code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def get_commit_from_tag(self, tag: str) -> Commit: """ Obtain the tagged commit. :param str tag: the tag :return: Commit commit: the commit the tag referred to """ try: selected_tag = self.repo.tags[tag] return self.get_commit(selected_tag.commit.hexsha) except (IndexError, AttributeError): logger.debug('Tag %s not found', tag) raise
def function[get_commit_from_tag, parameter[self, tag]]: constant[ Obtain the tagged commit. :param str tag: the tag :return: Commit commit: the commit the tag referred to ] <ast.Try object at 0x7da207f9b940>
keyword[def] identifier[get_commit_from_tag] ( identifier[self] , identifier[tag] : identifier[str] )-> identifier[Commit] : literal[string] keyword[try] : identifier[selected_tag] = identifier[self] . identifier[repo] . identifier[tags] [ identifier[tag] ] keyword[return] identifier[self] . identifier[get_commit] ( identifier[selected_tag] . identifier[commit] . identifier[hexsha] ) keyword[except] ( identifier[IndexError] , identifier[AttributeError] ): identifier[logger] . identifier[debug] ( literal[string] , identifier[tag] ) keyword[raise]
def get_commit_from_tag(self, tag: str) -> Commit: """ Obtain the tagged commit. :param str tag: the tag :return: Commit commit: the commit the tag referred to """ try: selected_tag = self.repo.tags[tag] return self.get_commit(selected_tag.commit.hexsha) # depends on [control=['try'], data=[]] except (IndexError, AttributeError): logger.debug('Tag %s not found', tag) raise # depends on [control=['except'], data=[]]
def upload_stream(stream, filename, metadata, access_token, base_url=OH_BASE_URL, remote_file_info=None, project_member_id=None, max_bytes=MAX_FILE_DEFAULT, file_identifier=None): """ Upload a file object using the "direct upload" feature, which uploads to an S3 bucket URL provided by the Open Humans API. To learn more about this API endpoint see: * https://www.openhumans.org/direct-sharing/on-site-data-upload/ * https://www.openhumans.org/direct-sharing/oauth2-data-upload/ :param stream: This field is the stream (or file object) to be uploaded. :param metadata: This field is the metadata associated with the file. Description and tags are compulsory fields of metadata. :param access_token: This is user specific access token/master token. :param base_url: It is this URL `https://www.openhumans.org`. :param remote_file_info: This field is for for checking if a file with matching name and file size already exists. Its default value is none. :param project_member_id: This field is the list of project member id of all members of a project. Its default value is None. :param max_bytes: This field is the maximum file size a user can upload. Its default value is 128m. :param max_bytes: If provided, this is used in logging output. Its default value is None (in which case, filename is used). """ if not file_identifier: file_identifier = filename # Determine a stream's size using seek. # f is a file-like object. old_position = stream.tell() stream.seek(0, os.SEEK_END) filesize = stream.tell() stream.seek(old_position, os.SEEK_SET) if filesize == 0: raise Exception('The submitted file is empty.') # Check size, and possibly remote file match. if _exceeds_size(filesize, max_bytes, file_identifier): raise ValueError("Maximum file size exceeded") if remote_file_info: response = requests.get(remote_file_info['download_url'], stream=True) remote_size = int(response.headers['Content-Length']) if remote_size == filesize: info_msg = ('Skipping {}, remote exists with matching ' 'file size'.format(file_identifier)) logging.info(info_msg) return(info_msg) url = urlparse.urljoin( base_url, '/api/direct-sharing/project/files/upload/direct/?{}'.format( urlparse.urlencode({'access_token': access_token}))) if not(project_member_id): response = exchange_oauth2_member(access_token, base_url=base_url) project_member_id = response['project_member_id'] data = {'project_member_id': project_member_id, 'metadata': json.dumps(metadata), 'filename': filename} r1 = requests.post(url, data=data) handle_error(r1, 201) r2 = requests.put(url=r1.json()['url'], data=stream) handle_error(r2, 200) done = urlparse.urljoin( base_url, '/api/direct-sharing/project/files/upload/complete/?{}'.format( urlparse.urlencode({'access_token': access_token}))) r3 = requests.post(done, data={'project_member_id': project_member_id, 'file_id': r1.json()['id']}) handle_error(r3, 200) logging.info('Upload complete: {}'.format(file_identifier)) return r3
def function[upload_stream, parameter[stream, filename, metadata, access_token, base_url, remote_file_info, project_member_id, max_bytes, file_identifier]]: constant[ Upload a file object using the "direct upload" feature, which uploads to an S3 bucket URL provided by the Open Humans API. To learn more about this API endpoint see: * https://www.openhumans.org/direct-sharing/on-site-data-upload/ * https://www.openhumans.org/direct-sharing/oauth2-data-upload/ :param stream: This field is the stream (or file object) to be uploaded. :param metadata: This field is the metadata associated with the file. Description and tags are compulsory fields of metadata. :param access_token: This is user specific access token/master token. :param base_url: It is this URL `https://www.openhumans.org`. :param remote_file_info: This field is for for checking if a file with matching name and file size already exists. Its default value is none. :param project_member_id: This field is the list of project member id of all members of a project. Its default value is None. :param max_bytes: This field is the maximum file size a user can upload. Its default value is 128m. :param max_bytes: If provided, this is used in logging output. Its default value is None (in which case, filename is used). ] if <ast.UnaryOp object at 0x7da1b1112500> begin[:] variable[file_identifier] assign[=] name[filename] variable[old_position] assign[=] call[name[stream].tell, parameter[]] call[name[stream].seek, parameter[constant[0], name[os].SEEK_END]] variable[filesize] assign[=] call[name[stream].tell, parameter[]] call[name[stream].seek, parameter[name[old_position], name[os].SEEK_SET]] if compare[name[filesize] equal[==] constant[0]] begin[:] <ast.Raise object at 0x7da1b1113dc0> if call[name[_exceeds_size], parameter[name[filesize], name[max_bytes], name[file_identifier]]] begin[:] <ast.Raise object at 0x7da1b11113f0> if name[remote_file_info] begin[:] variable[response] assign[=] call[name[requests].get, parameter[call[name[remote_file_info]][constant[download_url]]]] variable[remote_size] assign[=] call[name[int], parameter[call[name[response].headers][constant[Content-Length]]]] if compare[name[remote_size] equal[==] name[filesize]] begin[:] variable[info_msg] assign[=] call[constant[Skipping {}, remote exists with matching file size].format, parameter[name[file_identifier]]] call[name[logging].info, parameter[name[info_msg]]] return[name[info_msg]] variable[url] assign[=] call[name[urlparse].urljoin, parameter[name[base_url], call[constant[/api/direct-sharing/project/files/upload/direct/?{}].format, parameter[call[name[urlparse].urlencode, parameter[dictionary[[<ast.Constant object at 0x7da1b0f23850>], [<ast.Name object at 0x7da1b0f215a0>]]]]]]]] if <ast.UnaryOp object at 0x7da1b0f23820> begin[:] variable[response] assign[=] call[name[exchange_oauth2_member], parameter[name[access_token]]] variable[project_member_id] assign[=] call[name[response]][constant[project_member_id]] variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da1b0f20b50>, <ast.Constant object at 0x7da1b0f22830>, <ast.Constant object at 0x7da1b0f200d0>], [<ast.Name object at 0x7da1b0f23b50>, <ast.Call object at 0x7da1b0f237f0>, <ast.Name object at 0x7da1b0f20a30>]] variable[r1] assign[=] call[name[requests].post, parameter[name[url]]] call[name[handle_error], parameter[name[r1], constant[201]]] variable[r2] assign[=] call[name[requests].put, parameter[]] call[name[handle_error], parameter[name[r2], constant[200]]] variable[done] assign[=] call[name[urlparse].urljoin, parameter[name[base_url], call[constant[/api/direct-sharing/project/files/upload/complete/?{}].format, parameter[call[name[urlparse].urlencode, parameter[dictionary[[<ast.Constant object at 0x7da1b0f20df0>], [<ast.Name object at 0x7da1b0f23be0>]]]]]]]] variable[r3] assign[=] call[name[requests].post, parameter[name[done]]] call[name[handle_error], parameter[name[r3], constant[200]]] call[name[logging].info, parameter[call[constant[Upload complete: {}].format, parameter[name[file_identifier]]]]] return[name[r3]]
keyword[def] identifier[upload_stream] ( identifier[stream] , identifier[filename] , identifier[metadata] , identifier[access_token] , identifier[base_url] = identifier[OH_BASE_URL] , identifier[remote_file_info] = keyword[None] , identifier[project_member_id] = keyword[None] , identifier[max_bytes] = identifier[MAX_FILE_DEFAULT] , identifier[file_identifier] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[file_identifier] : identifier[file_identifier] = identifier[filename] identifier[old_position] = identifier[stream] . identifier[tell] () identifier[stream] . identifier[seek] ( literal[int] , identifier[os] . identifier[SEEK_END] ) identifier[filesize] = identifier[stream] . identifier[tell] () identifier[stream] . identifier[seek] ( identifier[old_position] , identifier[os] . identifier[SEEK_SET] ) keyword[if] identifier[filesize] == literal[int] : keyword[raise] identifier[Exception] ( literal[string] ) keyword[if] identifier[_exceeds_size] ( identifier[filesize] , identifier[max_bytes] , identifier[file_identifier] ): keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[remote_file_info] : identifier[response] = identifier[requests] . identifier[get] ( identifier[remote_file_info] [ literal[string] ], identifier[stream] = keyword[True] ) identifier[remote_size] = identifier[int] ( identifier[response] . identifier[headers] [ literal[string] ]) keyword[if] identifier[remote_size] == identifier[filesize] : identifier[info_msg] =( literal[string] literal[string] . identifier[format] ( identifier[file_identifier] )) identifier[logging] . identifier[info] ( identifier[info_msg] ) keyword[return] ( identifier[info_msg] ) identifier[url] = identifier[urlparse] . identifier[urljoin] ( identifier[base_url] , literal[string] . identifier[format] ( identifier[urlparse] . identifier[urlencode] ({ literal[string] : identifier[access_token] }))) keyword[if] keyword[not] ( identifier[project_member_id] ): identifier[response] = identifier[exchange_oauth2_member] ( identifier[access_token] , identifier[base_url] = identifier[base_url] ) identifier[project_member_id] = identifier[response] [ literal[string] ] identifier[data] ={ literal[string] : identifier[project_member_id] , literal[string] : identifier[json] . identifier[dumps] ( identifier[metadata] ), literal[string] : identifier[filename] } identifier[r1] = identifier[requests] . identifier[post] ( identifier[url] , identifier[data] = identifier[data] ) identifier[handle_error] ( identifier[r1] , literal[int] ) identifier[r2] = identifier[requests] . identifier[put] ( identifier[url] = identifier[r1] . identifier[json] ()[ literal[string] ], identifier[data] = identifier[stream] ) identifier[handle_error] ( identifier[r2] , literal[int] ) identifier[done] = identifier[urlparse] . identifier[urljoin] ( identifier[base_url] , literal[string] . identifier[format] ( identifier[urlparse] . identifier[urlencode] ({ literal[string] : identifier[access_token] }))) identifier[r3] = identifier[requests] . identifier[post] ( identifier[done] , identifier[data] ={ literal[string] : identifier[project_member_id] , literal[string] : identifier[r1] . identifier[json] ()[ literal[string] ]}) identifier[handle_error] ( identifier[r3] , literal[int] ) identifier[logging] . identifier[info] ( literal[string] . identifier[format] ( identifier[file_identifier] )) keyword[return] identifier[r3]
def upload_stream(stream, filename, metadata, access_token, base_url=OH_BASE_URL, remote_file_info=None, project_member_id=None, max_bytes=MAX_FILE_DEFAULT, file_identifier=None): """ Upload a file object using the "direct upload" feature, which uploads to an S3 bucket URL provided by the Open Humans API. To learn more about this API endpoint see: * https://www.openhumans.org/direct-sharing/on-site-data-upload/ * https://www.openhumans.org/direct-sharing/oauth2-data-upload/ :param stream: This field is the stream (or file object) to be uploaded. :param metadata: This field is the metadata associated with the file. Description and tags are compulsory fields of metadata. :param access_token: This is user specific access token/master token. :param base_url: It is this URL `https://www.openhumans.org`. :param remote_file_info: This field is for for checking if a file with matching name and file size already exists. Its default value is none. :param project_member_id: This field is the list of project member id of all members of a project. Its default value is None. :param max_bytes: This field is the maximum file size a user can upload. Its default value is 128m. :param max_bytes: If provided, this is used in logging output. Its default value is None (in which case, filename is used). """ if not file_identifier: file_identifier = filename # depends on [control=['if'], data=[]] # Determine a stream's size using seek. # f is a file-like object. old_position = stream.tell() stream.seek(0, os.SEEK_END) filesize = stream.tell() stream.seek(old_position, os.SEEK_SET) if filesize == 0: raise Exception('The submitted file is empty.') # depends on [control=['if'], data=[]] # Check size, and possibly remote file match. if _exceeds_size(filesize, max_bytes, file_identifier): raise ValueError('Maximum file size exceeded') # depends on [control=['if'], data=[]] if remote_file_info: response = requests.get(remote_file_info['download_url'], stream=True) remote_size = int(response.headers['Content-Length']) if remote_size == filesize: info_msg = 'Skipping {}, remote exists with matching file size'.format(file_identifier) logging.info(info_msg) return info_msg # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] url = urlparse.urljoin(base_url, '/api/direct-sharing/project/files/upload/direct/?{}'.format(urlparse.urlencode({'access_token': access_token}))) if not project_member_id: response = exchange_oauth2_member(access_token, base_url=base_url) project_member_id = response['project_member_id'] # depends on [control=['if'], data=[]] data = {'project_member_id': project_member_id, 'metadata': json.dumps(metadata), 'filename': filename} r1 = requests.post(url, data=data) handle_error(r1, 201) r2 = requests.put(url=r1.json()['url'], data=stream) handle_error(r2, 200) done = urlparse.urljoin(base_url, '/api/direct-sharing/project/files/upload/complete/?{}'.format(urlparse.urlencode({'access_token': access_token}))) r3 = requests.post(done, data={'project_member_id': project_member_id, 'file_id': r1.json()['id']}) handle_error(r3, 200) logging.info('Upload complete: {}'.format(file_identifier)) return r3
def _file_filter(cls, filename, include_patterns, exclude_patterns): """:returns: `True` if the file should be allowed through the filter.""" logger.debug('filename: {}'.format(filename)) for exclude_pattern in exclude_patterns: if exclude_pattern.match(filename): return False if include_patterns: found = False for include_pattern in include_patterns: if include_pattern.match(filename): found = True break if not found: return False return True
def function[_file_filter, parameter[cls, filename, include_patterns, exclude_patterns]]: constant[:returns: `True` if the file should be allowed through the filter.] call[name[logger].debug, parameter[call[constant[filename: {}].format, parameter[name[filename]]]]] for taget[name[exclude_pattern]] in starred[name[exclude_patterns]] begin[:] if call[name[exclude_pattern].match, parameter[name[filename]]] begin[:] return[constant[False]] if name[include_patterns] begin[:] variable[found] assign[=] constant[False] for taget[name[include_pattern]] in starred[name[include_patterns]] begin[:] if call[name[include_pattern].match, parameter[name[filename]]] begin[:] variable[found] assign[=] constant[True] break if <ast.UnaryOp object at 0x7da1b224b4c0> begin[:] return[constant[False]] return[constant[True]]
keyword[def] identifier[_file_filter] ( identifier[cls] , identifier[filename] , identifier[include_patterns] , identifier[exclude_patterns] ): literal[string] identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[filename] )) keyword[for] identifier[exclude_pattern] keyword[in] identifier[exclude_patterns] : keyword[if] identifier[exclude_pattern] . identifier[match] ( identifier[filename] ): keyword[return] keyword[False] keyword[if] identifier[include_patterns] : identifier[found] = keyword[False] keyword[for] identifier[include_pattern] keyword[in] identifier[include_patterns] : keyword[if] identifier[include_pattern] . identifier[match] ( identifier[filename] ): identifier[found] = keyword[True] keyword[break] keyword[if] keyword[not] identifier[found] : keyword[return] keyword[False] keyword[return] keyword[True]
def _file_filter(cls, filename, include_patterns, exclude_patterns): """:returns: `True` if the file should be allowed through the filter.""" logger.debug('filename: {}'.format(filename)) for exclude_pattern in exclude_patterns: if exclude_pattern.match(filename): return False # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['exclude_pattern']] if include_patterns: found = False for include_pattern in include_patterns: if include_pattern.match(filename): found = True break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['include_pattern']] if not found: return False # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return True
def _rolling_window(self, array, size): """ Compute rolling windows of width ``size`` of the given array. Return a numpy 2D stride array, where rows are the windows, each of ``size`` elements. :param array: the data array :type array: numpy 1D array (n) :param int size: the width of each window :rtype: numpy 2D stride array (n // size, size) """ shape = array.shape[:-1] + (array.shape[-1] - size + 1, size) strides = array.strides + (array.strides[-1],) return numpy.lib.stride_tricks.as_strided(array, shape=shape, strides=strides)
def function[_rolling_window, parameter[self, array, size]]: constant[ Compute rolling windows of width ``size`` of the given array. Return a numpy 2D stride array, where rows are the windows, each of ``size`` elements. :param array: the data array :type array: numpy 1D array (n) :param int size: the width of each window :rtype: numpy 2D stride array (n // size, size) ] variable[shape] assign[=] binary_operation[call[name[array].shape][<ast.Slice object at 0x7da1b18a3f10>] + tuple[[<ast.BinOp object at 0x7da1b18a3280>, <ast.Name object at 0x7da1b18a2290>]]] variable[strides] assign[=] binary_operation[name[array].strides + tuple[[<ast.Subscript object at 0x7da1b18a1ab0>]]] return[call[name[numpy].lib.stride_tricks.as_strided, parameter[name[array]]]]
keyword[def] identifier[_rolling_window] ( identifier[self] , identifier[array] , identifier[size] ): literal[string] identifier[shape] = identifier[array] . identifier[shape] [:- literal[int] ]+( identifier[array] . identifier[shape] [- literal[int] ]- identifier[size] + literal[int] , identifier[size] ) identifier[strides] = identifier[array] . identifier[strides] +( identifier[array] . identifier[strides] [- literal[int] ],) keyword[return] identifier[numpy] . identifier[lib] . identifier[stride_tricks] . identifier[as_strided] ( identifier[array] , identifier[shape] = identifier[shape] , identifier[strides] = identifier[strides] )
def _rolling_window(self, array, size): """ Compute rolling windows of width ``size`` of the given array. Return a numpy 2D stride array, where rows are the windows, each of ``size`` elements. :param array: the data array :type array: numpy 1D array (n) :param int size: the width of each window :rtype: numpy 2D stride array (n // size, size) """ shape = array.shape[:-1] + (array.shape[-1] - size + 1, size) strides = array.strides + (array.strides[-1],) return numpy.lib.stride_tricks.as_strided(array, shape=shape, strides=strides)
def _safe_read(path, length): """Read file contents.""" if not os.path.exists(os.path.join(HERE, path)): return '' file_handle = codecs.open(os.path.join(HERE, path), encoding='utf-8') contents = file_handle.read(length) file_handle.close() return contents
def function[_safe_read, parameter[path, length]]: constant[Read file contents.] if <ast.UnaryOp object at 0x7da1b28dc760> begin[:] return[constant[]] variable[file_handle] assign[=] call[name[codecs].open, parameter[call[name[os].path.join, parameter[name[HERE], name[path]]]]] variable[contents] assign[=] call[name[file_handle].read, parameter[name[length]]] call[name[file_handle].close, parameter[]] return[name[contents]]
keyword[def] identifier[_safe_read] ( identifier[path] , identifier[length] ): literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[os] . identifier[path] . identifier[join] ( identifier[HERE] , identifier[path] )): keyword[return] literal[string] identifier[file_handle] = identifier[codecs] . identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[HERE] , identifier[path] ), identifier[encoding] = literal[string] ) identifier[contents] = identifier[file_handle] . identifier[read] ( identifier[length] ) identifier[file_handle] . identifier[close] () keyword[return] identifier[contents]
def _safe_read(path, length): """Read file contents.""" if not os.path.exists(os.path.join(HERE, path)): return '' # depends on [control=['if'], data=[]] file_handle = codecs.open(os.path.join(HERE, path), encoding='utf-8') contents = file_handle.read(length) file_handle.close() return contents
def portfolio_performance(self, verbose=False, risk_free_rate=0.02): """ After optimising, calculate (and optionally print) the performance of the optimal portfolio. Currently calculates expected return, volatility, and the Sharpe ratio. :param verbose: whether performance should be printed, defaults to False :type verbose: bool, optional :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02 :type risk_free_rate: float, optional :raises ValueError: if weights have not been calcualted yet :return: expected return, volatility, Sharpe ratio. :rtype: (float, float, float) """ return base_optimizer.portfolio_performance( self.expected_returns, self.cov_matrix, self.weights, verbose, risk_free_rate, )
def function[portfolio_performance, parameter[self, verbose, risk_free_rate]]: constant[ After optimising, calculate (and optionally print) the performance of the optimal portfolio. Currently calculates expected return, volatility, and the Sharpe ratio. :param verbose: whether performance should be printed, defaults to False :type verbose: bool, optional :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02 :type risk_free_rate: float, optional :raises ValueError: if weights have not been calcualted yet :return: expected return, volatility, Sharpe ratio. :rtype: (float, float, float) ] return[call[name[base_optimizer].portfolio_performance, parameter[name[self].expected_returns, name[self].cov_matrix, name[self].weights, name[verbose], name[risk_free_rate]]]]
keyword[def] identifier[portfolio_performance] ( identifier[self] , identifier[verbose] = keyword[False] , identifier[risk_free_rate] = literal[int] ): literal[string] keyword[return] identifier[base_optimizer] . identifier[portfolio_performance] ( identifier[self] . identifier[expected_returns] , identifier[self] . identifier[cov_matrix] , identifier[self] . identifier[weights] , identifier[verbose] , identifier[risk_free_rate] , )
def portfolio_performance(self, verbose=False, risk_free_rate=0.02): """ After optimising, calculate (and optionally print) the performance of the optimal portfolio. Currently calculates expected return, volatility, and the Sharpe ratio. :param verbose: whether performance should be printed, defaults to False :type verbose: bool, optional :param risk_free_rate: risk-free rate of borrowing/lending, defaults to 0.02 :type risk_free_rate: float, optional :raises ValueError: if weights have not been calcualted yet :return: expected return, volatility, Sharpe ratio. :rtype: (float, float, float) """ return base_optimizer.portfolio_performance(self.expected_returns, self.cov_matrix, self.weights, verbose, risk_free_rate)
def iterable(self, iterable_name, *, collection, attribute, word, func=None, operation=None): """ Performs a filter with the OData 'iterable_name' keyword on the collection For example: q.iterable('any', collection='email_addresses', attribute='address', operation='eq', word='george@best.com') will transform to a filter such as: emailAddresses/any(a:a/address eq 'george@best.com') :param str iterable_name: the OData name of the iterable :param str collection: the collection to apply the any keyword on :param str attribute: the attribute of the collection to check :param str word: the word to check :param str func: the logical function to apply to the attribute inside the collection :param str operation: the logical operation to apply to the attribute inside the collection :rtype: Query """ if func is None and operation is None: raise ValueError('Provide a function or an operation to apply') elif func is not None and operation is not None: raise ValueError( 'Provide either a function or an operation but not both') current_att = self._attribute self._attribute = iterable_name word = self._parse_filter_word(word) collection = self._get_mapping(collection) attribute = self._get_mapping(attribute) if func is not None: sentence = self._prepare_function(func, attribute, word) else: sentence = self._prepare_sentence(attribute, operation, word) filter_str, attrs = sentence filter_data = '{}/{}(a:a/{})'.format(collection, iterable_name, filter_str), attrs self._add_filter(*filter_data) self._attribute = current_att return self
def function[iterable, parameter[self, iterable_name]]: constant[ Performs a filter with the OData 'iterable_name' keyword on the collection For example: q.iterable('any', collection='email_addresses', attribute='address', operation='eq', word='george@best.com') will transform to a filter such as: emailAddresses/any(a:a/address eq 'george@best.com') :param str iterable_name: the OData name of the iterable :param str collection: the collection to apply the any keyword on :param str attribute: the attribute of the collection to check :param str word: the word to check :param str func: the logical function to apply to the attribute inside the collection :param str operation: the logical operation to apply to the attribute inside the collection :rtype: Query ] if <ast.BoolOp object at 0x7da1b1baf790> begin[:] <ast.Raise object at 0x7da1b1bafb50> variable[current_att] assign[=] name[self]._attribute name[self]._attribute assign[=] name[iterable_name] variable[word] assign[=] call[name[self]._parse_filter_word, parameter[name[word]]] variable[collection] assign[=] call[name[self]._get_mapping, parameter[name[collection]]] variable[attribute] assign[=] call[name[self]._get_mapping, parameter[name[attribute]]] if compare[name[func] is_not constant[None]] begin[:] variable[sentence] assign[=] call[name[self]._prepare_function, parameter[name[func], name[attribute], name[word]]] <ast.Tuple object at 0x7da1b1b28520> assign[=] name[sentence] variable[filter_data] assign[=] tuple[[<ast.Call object at 0x7da1b1b2b640>, <ast.Name object at 0x7da1b1b2a080>]] call[name[self]._add_filter, parameter[<ast.Starred object at 0x7da1b1b28400>]] name[self]._attribute assign[=] name[current_att] return[name[self]]
keyword[def] identifier[iterable] ( identifier[self] , identifier[iterable_name] ,*, identifier[collection] , identifier[attribute] , identifier[word] , identifier[func] = keyword[None] , identifier[operation] = keyword[None] ): literal[string] keyword[if] identifier[func] keyword[is] keyword[None] keyword[and] identifier[operation] keyword[is] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[elif] identifier[func] keyword[is] keyword[not] keyword[None] keyword[and] identifier[operation] keyword[is] keyword[not] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[current_att] = identifier[self] . identifier[_attribute] identifier[self] . identifier[_attribute] = identifier[iterable_name] identifier[word] = identifier[self] . identifier[_parse_filter_word] ( identifier[word] ) identifier[collection] = identifier[self] . identifier[_get_mapping] ( identifier[collection] ) identifier[attribute] = identifier[self] . identifier[_get_mapping] ( identifier[attribute] ) keyword[if] identifier[func] keyword[is] keyword[not] keyword[None] : identifier[sentence] = identifier[self] . identifier[_prepare_function] ( identifier[func] , identifier[attribute] , identifier[word] ) keyword[else] : identifier[sentence] = identifier[self] . identifier[_prepare_sentence] ( identifier[attribute] , identifier[operation] , identifier[word] ) identifier[filter_str] , identifier[attrs] = identifier[sentence] identifier[filter_data] = literal[string] . identifier[format] ( identifier[collection] , identifier[iterable_name] , identifier[filter_str] ), identifier[attrs] identifier[self] . identifier[_add_filter] (* identifier[filter_data] ) identifier[self] . identifier[_attribute] = identifier[current_att] keyword[return] identifier[self]
def iterable(self, iterable_name, *, collection, attribute, word, func=None, operation=None): """ Performs a filter with the OData 'iterable_name' keyword on the collection For example: q.iterable('any', collection='email_addresses', attribute='address', operation='eq', word='george@best.com') will transform to a filter such as: emailAddresses/any(a:a/address eq 'george@best.com') :param str iterable_name: the OData name of the iterable :param str collection: the collection to apply the any keyword on :param str attribute: the attribute of the collection to check :param str word: the word to check :param str func: the logical function to apply to the attribute inside the collection :param str operation: the logical operation to apply to the attribute inside the collection :rtype: Query """ if func is None and operation is None: raise ValueError('Provide a function or an operation to apply') # depends on [control=['if'], data=[]] elif func is not None and operation is not None: raise ValueError('Provide either a function or an operation but not both') # depends on [control=['if'], data=[]] current_att = self._attribute self._attribute = iterable_name word = self._parse_filter_word(word) collection = self._get_mapping(collection) attribute = self._get_mapping(attribute) if func is not None: sentence = self._prepare_function(func, attribute, word) # depends on [control=['if'], data=['func']] else: sentence = self._prepare_sentence(attribute, operation, word) (filter_str, attrs) = sentence filter_data = ('{}/{}(a:a/{})'.format(collection, iterable_name, filter_str), attrs) self._add_filter(*filter_data) self._attribute = current_att return self
def disconnect(self, chassis_list): """Remove connection with one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names) """ self._check_session() if not isinstance(chassis_list, (list, tuple, set, dict, frozenset)): chassis_list = (chassis_list,) if len(chassis_list) == 1: self._rest.delete_request('connections', chassis_list[0]) else: params = {chassis: True for chassis in chassis_list} params['action'] = 'disconnect' self._rest.post_request('connections', None, params)
def function[disconnect, parameter[self, chassis_list]]: constant[Remove connection with one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names) ] call[name[self]._check_session, parameter[]] if <ast.UnaryOp object at 0x7da1b10d7ee0> begin[:] variable[chassis_list] assign[=] tuple[[<ast.Name object at 0x7da1b10414e0>]] if compare[call[name[len], parameter[name[chassis_list]]] equal[==] constant[1]] begin[:] call[name[self]._rest.delete_request, parameter[constant[connections], call[name[chassis_list]][constant[0]]]]
keyword[def] identifier[disconnect] ( identifier[self] , identifier[chassis_list] ): literal[string] identifier[self] . identifier[_check_session] () keyword[if] keyword[not] identifier[isinstance] ( identifier[chassis_list] ,( identifier[list] , identifier[tuple] , identifier[set] , identifier[dict] , identifier[frozenset] )): identifier[chassis_list] =( identifier[chassis_list] ,) keyword[if] identifier[len] ( identifier[chassis_list] )== literal[int] : identifier[self] . identifier[_rest] . identifier[delete_request] ( literal[string] , identifier[chassis_list] [ literal[int] ]) keyword[else] : identifier[params] ={ identifier[chassis] : keyword[True] keyword[for] identifier[chassis] keyword[in] identifier[chassis_list] } identifier[params] [ literal[string] ]= literal[string] identifier[self] . identifier[_rest] . identifier[post_request] ( literal[string] , keyword[None] , identifier[params] )
def disconnect(self, chassis_list): """Remove connection with one or more chassis. Arguments: chassis_list -- List of chassis (IP addresses or DNS names) """ self._check_session() if not isinstance(chassis_list, (list, tuple, set, dict, frozenset)): chassis_list = (chassis_list,) # depends on [control=['if'], data=[]] if len(chassis_list) == 1: self._rest.delete_request('connections', chassis_list[0]) # depends on [control=['if'], data=[]] else: params = {chassis: True for chassis in chassis_list} params['action'] = 'disconnect' self._rest.post_request('connections', None, params)
def list_build_configuration_sets(page_size=200, page_index=0, sort="", q=""): """ List all build configuration sets """ data = list_build_configuration_sets_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
def function[list_build_configuration_sets, parameter[page_size, page_index, sort, q]]: constant[ List all build configuration sets ] variable[data] assign[=] call[name[list_build_configuration_sets_raw], parameter[name[page_size], name[page_index], name[sort], name[q]]] if name[data] begin[:] return[call[name[utils].format_json_list, parameter[name[data]]]]
keyword[def] identifier[list_build_configuration_sets] ( identifier[page_size] = literal[int] , identifier[page_index] = literal[int] , identifier[sort] = literal[string] , identifier[q] = literal[string] ): literal[string] identifier[data] = identifier[list_build_configuration_sets_raw] ( identifier[page_size] , identifier[page_index] , identifier[sort] , identifier[q] ) keyword[if] identifier[data] : keyword[return] identifier[utils] . identifier[format_json_list] ( identifier[data] )
def list_build_configuration_sets(page_size=200, page_index=0, sort='', q=''): """ List all build configuration sets """ data = list_build_configuration_sets_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data) # depends on [control=['if'], data=[]]
def recommend_delete(self, num_iid, session): '''taobao.item.recommend.delete 取消橱窗推荐一个商品 取消当前用户指定商品的橱窗推荐状态 这个Item所属卖家从传入的session中获取,需要session绑定''' request = TOPRequest('taobao.item.recommend.delete') request['num_iid'] = num_iid self.create(self.execute(request, session)['item']) return self
def function[recommend_delete, parameter[self, num_iid, session]]: constant[taobao.item.recommend.delete 取消橱窗推荐一个商品 取消当前用户指定商品的橱窗推荐状态 这个Item所属卖家从传入的session中获取,需要session绑定] variable[request] assign[=] call[name[TOPRequest], parameter[constant[taobao.item.recommend.delete]]] call[name[request]][constant[num_iid]] assign[=] name[num_iid] call[name[self].create, parameter[call[call[name[self].execute, parameter[name[request], name[session]]]][constant[item]]]] return[name[self]]
keyword[def] identifier[recommend_delete] ( identifier[self] , identifier[num_iid] , identifier[session] ): literal[string] identifier[request] = identifier[TOPRequest] ( literal[string] ) identifier[request] [ literal[string] ]= identifier[num_iid] identifier[self] . identifier[create] ( identifier[self] . identifier[execute] ( identifier[request] , identifier[session] )[ literal[string] ]) keyword[return] identifier[self]
def recommend_delete(self, num_iid, session): """taobao.item.recommend.delete 取消橱窗推荐一个商品 取消当前用户指定商品的橱窗推荐状态 这个Item所属卖家从传入的session中获取,需要session绑定""" request = TOPRequest('taobao.item.recommend.delete') request['num_iid'] = num_iid self.create(self.execute(request, session)['item']) return self
def image(self): """ Read the loaded DICOM image data """ if self._image is None: self._image = Image(self.fname) return self._image
def function[image, parameter[self]]: constant[ Read the loaded DICOM image data ] if compare[name[self]._image is constant[None]] begin[:] name[self]._image assign[=] call[name[Image], parameter[name[self].fname]] return[name[self]._image]
keyword[def] identifier[image] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_image] keyword[is] keyword[None] : identifier[self] . identifier[_image] = identifier[Image] ( identifier[self] . identifier[fname] ) keyword[return] identifier[self] . identifier[_image]
def image(self): """ Read the loaded DICOM image data """ if self._image is None: self._image = Image(self.fname) # depends on [control=['if'], data=[]] return self._image
def query(query): ''' Send an ADQL query to the Gaia archive, wait for a response, and hang on to the results. ''' # send the query to the Gaia archive with warnings.catch_warnings() : warnings.filterwarnings("ignore") _gaia_job = astroquery.gaia.Gaia.launch_job(query) # return the table of results return _gaia_job.get_results()
def function[query, parameter[query]]: constant[ Send an ADQL query to the Gaia archive, wait for a response, and hang on to the results. ] with call[name[warnings].catch_warnings, parameter[]] begin[:] call[name[warnings].filterwarnings, parameter[constant[ignore]]] variable[_gaia_job] assign[=] call[name[astroquery].gaia.Gaia.launch_job, parameter[name[query]]] return[call[name[_gaia_job].get_results, parameter[]]]
keyword[def] identifier[query] ( identifier[query] ): literal[string] keyword[with] identifier[warnings] . identifier[catch_warnings] (): identifier[warnings] . identifier[filterwarnings] ( literal[string] ) identifier[_gaia_job] = identifier[astroquery] . identifier[gaia] . identifier[Gaia] . identifier[launch_job] ( identifier[query] ) keyword[return] identifier[_gaia_job] . identifier[get_results] ()
def query(query): """ Send an ADQL query to the Gaia archive, wait for a response, and hang on to the results. """ # send the query to the Gaia archive with warnings.catch_warnings(): warnings.filterwarnings('ignore') _gaia_job = astroquery.gaia.Gaia.launch_job(query) # return the table of results return _gaia_job.get_results() # depends on [control=['with'], data=[]]
def analyze(qpi, r0, method="edge", model="projection", edgekw={}, imagekw={}, ret_center=False, ret_pha_offset=False, ret_qpi=False): """Determine refractive index and radius of a spherical object Parameters ---------- qpi: qpimage.QPImage Quantitative phase image data r0: float Approximate radius of the sphere [m] method: str The method used to determine the refractive index can either be "edge" (determine the radius from the edge detected in the phase image) or "image" (perform a 2D phase image fit). model: str The light-scattering model used by `method`. If `method` is "edge", only "projection" is allowed. If `method` is "image", `model` can be one of "mie", "projection", "rytov", or "rytov-sc". edgekw: dict Keyword arguments for tuning the edge detection algorithm, see :func:`qpsphere.edgefit.contour_canny`. imagekw: dict Keyword arguments for tuning the image fitting algorithm, see :func:`qpsphere.imagefit.alg.match_phase` ret_center: bool If True, return the center coordinate of the sphere. ret_pha_offset: bool If True, return the phase image background offset. ret_qpi: bool If True, return the modeled data as a :class:`qpimage.QPImage`. Returns ------- n: float Computed refractive index r: float Computed radius [m] c: tuple of floats Only returned if `ret_center` is True; Center position of the sphere [px] pha_offset: float Only returned if `ret_pha_offset` is True; Phase image background offset qpi_sim: qpimage.QPImage Only returned if `ret_qpi` is True; Modeled data Notes ----- If `method` is "image", then the "edge" method is used as a first step to estimate initial parameters for radius, refractive index, and position of the sphere using `edgekw`. If this behavior is not desired, please make use of the method :func:`qpsphere.imagefit.analyze`. """ if method == "edge": if model != "projection": raise ValueError("`method='edge'` requires `model='projection'`!") n, r, c = edgefit.analyze(qpi=qpi, r0=r0, edgekw=edgekw, ret_center=True, ret_edge=False, ) res = [n, r] if ret_center: res.append(c) if ret_pha_offset: res.append(0) if ret_qpi: qpi_sim = simulate(radius=r, sphere_index=n, medium_index=qpi["medium index"], wavelength=qpi["wavelength"], grid_size=qpi.shape, model="projection", pixel_size=qpi["pixel size"], center=c) res.append(qpi_sim) elif method == "image": n0, r0, c0 = edgefit.analyze(qpi=qpi, r0=r0, edgekw=edgekw, ret_center=True, ret_edge=False, ) res = imagefit.analyze(qpi=qpi, model=model, n0=n0, r0=r0, c0=c0, imagekw=imagekw, ret_center=ret_center, ret_pha_offset=ret_pha_offset, ret_qpi=ret_qpi ) else: raise NotImplementedError("`method` must be 'edge' or 'image'!") return res
def function[analyze, parameter[qpi, r0, method, model, edgekw, imagekw, ret_center, ret_pha_offset, ret_qpi]]: constant[Determine refractive index and radius of a spherical object Parameters ---------- qpi: qpimage.QPImage Quantitative phase image data r0: float Approximate radius of the sphere [m] method: str The method used to determine the refractive index can either be "edge" (determine the radius from the edge detected in the phase image) or "image" (perform a 2D phase image fit). model: str The light-scattering model used by `method`. If `method` is "edge", only "projection" is allowed. If `method` is "image", `model` can be one of "mie", "projection", "rytov", or "rytov-sc". edgekw: dict Keyword arguments for tuning the edge detection algorithm, see :func:`qpsphere.edgefit.contour_canny`. imagekw: dict Keyword arguments for tuning the image fitting algorithm, see :func:`qpsphere.imagefit.alg.match_phase` ret_center: bool If True, return the center coordinate of the sphere. ret_pha_offset: bool If True, return the phase image background offset. ret_qpi: bool If True, return the modeled data as a :class:`qpimage.QPImage`. Returns ------- n: float Computed refractive index r: float Computed radius [m] c: tuple of floats Only returned if `ret_center` is True; Center position of the sphere [px] pha_offset: float Only returned if `ret_pha_offset` is True; Phase image background offset qpi_sim: qpimage.QPImage Only returned if `ret_qpi` is True; Modeled data Notes ----- If `method` is "image", then the "edge" method is used as a first step to estimate initial parameters for radius, refractive index, and position of the sphere using `edgekw`. If this behavior is not desired, please make use of the method :func:`qpsphere.imagefit.analyze`. ] if compare[name[method] equal[==] constant[edge]] begin[:] if compare[name[model] not_equal[!=] constant[projection]] begin[:] <ast.Raise object at 0x7da20c6ab310> <ast.Tuple object at 0x7da20c6aa620> assign[=] call[name[edgefit].analyze, parameter[]] variable[res] assign[=] list[[<ast.Name object at 0x7da20c6ab9d0>, <ast.Name object at 0x7da20c6a9e10>]] if name[ret_center] begin[:] call[name[res].append, parameter[name[c]]] if name[ret_pha_offset] begin[:] call[name[res].append, parameter[constant[0]]] if name[ret_qpi] begin[:] variable[qpi_sim] assign[=] call[name[simulate], parameter[]] call[name[res].append, parameter[name[qpi_sim]]] return[name[res]]
keyword[def] identifier[analyze] ( identifier[qpi] , identifier[r0] , identifier[method] = literal[string] , identifier[model] = literal[string] , identifier[edgekw] ={}, identifier[imagekw] ={}, identifier[ret_center] = keyword[False] , identifier[ret_pha_offset] = keyword[False] , identifier[ret_qpi] = keyword[False] ): literal[string] keyword[if] identifier[method] == literal[string] : keyword[if] identifier[model] != literal[string] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[n] , identifier[r] , identifier[c] = identifier[edgefit] . identifier[analyze] ( identifier[qpi] = identifier[qpi] , identifier[r0] = identifier[r0] , identifier[edgekw] = identifier[edgekw] , identifier[ret_center] = keyword[True] , identifier[ret_edge] = keyword[False] , ) identifier[res] =[ identifier[n] , identifier[r] ] keyword[if] identifier[ret_center] : identifier[res] . identifier[append] ( identifier[c] ) keyword[if] identifier[ret_pha_offset] : identifier[res] . identifier[append] ( literal[int] ) keyword[if] identifier[ret_qpi] : identifier[qpi_sim] = identifier[simulate] ( identifier[radius] = identifier[r] , identifier[sphere_index] = identifier[n] , identifier[medium_index] = identifier[qpi] [ literal[string] ], identifier[wavelength] = identifier[qpi] [ literal[string] ], identifier[grid_size] = identifier[qpi] . identifier[shape] , identifier[model] = literal[string] , identifier[pixel_size] = identifier[qpi] [ literal[string] ], identifier[center] = identifier[c] ) identifier[res] . identifier[append] ( identifier[qpi_sim] ) keyword[elif] identifier[method] == literal[string] : identifier[n0] , identifier[r0] , identifier[c0] = identifier[edgefit] . identifier[analyze] ( identifier[qpi] = identifier[qpi] , identifier[r0] = identifier[r0] , identifier[edgekw] = identifier[edgekw] , identifier[ret_center] = keyword[True] , identifier[ret_edge] = keyword[False] , ) identifier[res] = identifier[imagefit] . identifier[analyze] ( identifier[qpi] = identifier[qpi] , identifier[model] = identifier[model] , identifier[n0] = identifier[n0] , identifier[r0] = identifier[r0] , identifier[c0] = identifier[c0] , identifier[imagekw] = identifier[imagekw] , identifier[ret_center] = identifier[ret_center] , identifier[ret_pha_offset] = identifier[ret_pha_offset] , identifier[ret_qpi] = identifier[ret_qpi] ) keyword[else] : keyword[raise] identifier[NotImplementedError] ( literal[string] ) keyword[return] identifier[res]
def analyze(qpi, r0, method='edge', model='projection', edgekw={}, imagekw={}, ret_center=False, ret_pha_offset=False, ret_qpi=False): """Determine refractive index and radius of a spherical object Parameters ---------- qpi: qpimage.QPImage Quantitative phase image data r0: float Approximate radius of the sphere [m] method: str The method used to determine the refractive index can either be "edge" (determine the radius from the edge detected in the phase image) or "image" (perform a 2D phase image fit). model: str The light-scattering model used by `method`. If `method` is "edge", only "projection" is allowed. If `method` is "image", `model` can be one of "mie", "projection", "rytov", or "rytov-sc". edgekw: dict Keyword arguments for tuning the edge detection algorithm, see :func:`qpsphere.edgefit.contour_canny`. imagekw: dict Keyword arguments for tuning the image fitting algorithm, see :func:`qpsphere.imagefit.alg.match_phase` ret_center: bool If True, return the center coordinate of the sphere. ret_pha_offset: bool If True, return the phase image background offset. ret_qpi: bool If True, return the modeled data as a :class:`qpimage.QPImage`. Returns ------- n: float Computed refractive index r: float Computed radius [m] c: tuple of floats Only returned if `ret_center` is True; Center position of the sphere [px] pha_offset: float Only returned if `ret_pha_offset` is True; Phase image background offset qpi_sim: qpimage.QPImage Only returned if `ret_qpi` is True; Modeled data Notes ----- If `method` is "image", then the "edge" method is used as a first step to estimate initial parameters for radius, refractive index, and position of the sphere using `edgekw`. If this behavior is not desired, please make use of the method :func:`qpsphere.imagefit.analyze`. """ if method == 'edge': if model != 'projection': raise ValueError("`method='edge'` requires `model='projection'`!") # depends on [control=['if'], data=[]] (n, r, c) = edgefit.analyze(qpi=qpi, r0=r0, edgekw=edgekw, ret_center=True, ret_edge=False) res = [n, r] if ret_center: res.append(c) # depends on [control=['if'], data=[]] if ret_pha_offset: res.append(0) # depends on [control=['if'], data=[]] if ret_qpi: qpi_sim = simulate(radius=r, sphere_index=n, medium_index=qpi['medium index'], wavelength=qpi['wavelength'], grid_size=qpi.shape, model='projection', pixel_size=qpi['pixel size'], center=c) res.append(qpi_sim) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] elif method == 'image': (n0, r0, c0) = edgefit.analyze(qpi=qpi, r0=r0, edgekw=edgekw, ret_center=True, ret_edge=False) res = imagefit.analyze(qpi=qpi, model=model, n0=n0, r0=r0, c0=c0, imagekw=imagekw, ret_center=ret_center, ret_pha_offset=ret_pha_offset, ret_qpi=ret_qpi) # depends on [control=['if'], data=[]] else: raise NotImplementedError("`method` must be 'edge' or 'image'!") return res
def _get_origcache(self, graph, dest, branch, turn, tick, *, forward): """Return a set of origin nodes leading to ``dest``""" origcache, origcache_lru, get_keycachelike, predecessors, adds_dels_sucpred = self._get_origcache_stuff lru_append(origcache, origcache_lru, ((graph, dest, branch), turn, tick), KEYCACHE_MAXSIZE) return get_keycachelike( origcache, predecessors, adds_dels_sucpred, (graph, dest), branch, turn, tick, forward=forward )
def function[_get_origcache, parameter[self, graph, dest, branch, turn, tick]]: constant[Return a set of origin nodes leading to ``dest``] <ast.Tuple object at 0x7da1b0cb6770> assign[=] name[self]._get_origcache_stuff call[name[lru_append], parameter[name[origcache], name[origcache_lru], tuple[[<ast.Tuple object at 0x7da1b0cb78e0>, <ast.Name object at 0x7da1b0cb6cb0>, <ast.Name object at 0x7da1b0cb7bb0>]], name[KEYCACHE_MAXSIZE]]] return[call[name[get_keycachelike], parameter[name[origcache], name[predecessors], name[adds_dels_sucpred], tuple[[<ast.Name object at 0x7da1b0cb7e80>, <ast.Name object at 0x7da1b0cb4250>]], name[branch], name[turn], name[tick]]]]
keyword[def] identifier[_get_origcache] ( identifier[self] , identifier[graph] , identifier[dest] , identifier[branch] , identifier[turn] , identifier[tick] ,*, identifier[forward] ): literal[string] identifier[origcache] , identifier[origcache_lru] , identifier[get_keycachelike] , identifier[predecessors] , identifier[adds_dels_sucpred] = identifier[self] . identifier[_get_origcache_stuff] identifier[lru_append] ( identifier[origcache] , identifier[origcache_lru] ,(( identifier[graph] , identifier[dest] , identifier[branch] ), identifier[turn] , identifier[tick] ), identifier[KEYCACHE_MAXSIZE] ) keyword[return] identifier[get_keycachelike] ( identifier[origcache] , identifier[predecessors] , identifier[adds_dels_sucpred] ,( identifier[graph] , identifier[dest] ), identifier[branch] , identifier[turn] , identifier[tick] , identifier[forward] = identifier[forward] )
def _get_origcache(self, graph, dest, branch, turn, tick, *, forward): """Return a set of origin nodes leading to ``dest``""" (origcache, origcache_lru, get_keycachelike, predecessors, adds_dels_sucpred) = self._get_origcache_stuff lru_append(origcache, origcache_lru, ((graph, dest, branch), turn, tick), KEYCACHE_MAXSIZE) return get_keycachelike(origcache, predecessors, adds_dels_sucpred, (graph, dest), branch, turn, tick, forward=forward)
def run(self): """ Called by the process, it runs it. NEVER call this method directly. Instead call start() to start the separate process. If you don't want to use a second process, then call fetch() directly on this istance. To stop, call terminate() """ producer_deferred = defer.Deferred() producer_deferred.addCallback(self._request_finished) producer_deferred.addErrback(self._request_error) receiver_deferred = defer.Deferred() receiver_deferred.addCallback(self._response_finished) receiver_deferred.addErrback(self._response_error) self._producer = producer.MultiPartProducer( self._files, self._data, callback = self._request_progress, deferred = producer_deferred ) self._receiver = receiver.StringReceiver(receiver_deferred) headers = { 'Content-Type': "multipart/form-data; boundary=%s" % self._producer.boundary } self._reactor, request = self._connection.build_twisted_request( "POST", "room/%s/uploads" % self._room.id, extra_headers = headers, body_producer = self._producer ) request.addCallback(self._response) request.addErrback(self._shutdown) self._reactor.run()
def function[run, parameter[self]]: constant[ Called by the process, it runs it. NEVER call this method directly. Instead call start() to start the separate process. If you don't want to use a second process, then call fetch() directly on this istance. To stop, call terminate() ] variable[producer_deferred] assign[=] call[name[defer].Deferred, parameter[]] call[name[producer_deferred].addCallback, parameter[name[self]._request_finished]] call[name[producer_deferred].addErrback, parameter[name[self]._request_error]] variable[receiver_deferred] assign[=] call[name[defer].Deferred, parameter[]] call[name[receiver_deferred].addCallback, parameter[name[self]._response_finished]] call[name[receiver_deferred].addErrback, parameter[name[self]._response_error]] name[self]._producer assign[=] call[name[producer].MultiPartProducer, parameter[name[self]._files, name[self]._data]] name[self]._receiver assign[=] call[name[receiver].StringReceiver, parameter[name[receiver_deferred]]] variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da1b0088910>], [<ast.BinOp object at 0x7da1b00887c0>]] <ast.Tuple object at 0x7da1b008ad70> assign[=] call[name[self]._connection.build_twisted_request, parameter[constant[POST], binary_operation[constant[room/%s/uploads] <ast.Mod object at 0x7da2590d6920> name[self]._room.id]]] call[name[request].addCallback, parameter[name[self]._response]] call[name[request].addErrback, parameter[name[self]._shutdown]] call[name[self]._reactor.run, parameter[]]
keyword[def] identifier[run] ( identifier[self] ): literal[string] identifier[producer_deferred] = identifier[defer] . identifier[Deferred] () identifier[producer_deferred] . identifier[addCallback] ( identifier[self] . identifier[_request_finished] ) identifier[producer_deferred] . identifier[addErrback] ( identifier[self] . identifier[_request_error] ) identifier[receiver_deferred] = identifier[defer] . identifier[Deferred] () identifier[receiver_deferred] . identifier[addCallback] ( identifier[self] . identifier[_response_finished] ) identifier[receiver_deferred] . identifier[addErrback] ( identifier[self] . identifier[_response_error] ) identifier[self] . identifier[_producer] = identifier[producer] . identifier[MultiPartProducer] ( identifier[self] . identifier[_files] , identifier[self] . identifier[_data] , identifier[callback] = identifier[self] . identifier[_request_progress] , identifier[deferred] = identifier[producer_deferred] ) identifier[self] . identifier[_receiver] = identifier[receiver] . identifier[StringReceiver] ( identifier[receiver_deferred] ) identifier[headers] ={ literal[string] : literal[string] % identifier[self] . identifier[_producer] . identifier[boundary] } identifier[self] . identifier[_reactor] , identifier[request] = identifier[self] . identifier[_connection] . identifier[build_twisted_request] ( literal[string] , literal[string] % identifier[self] . identifier[_room] . identifier[id] , identifier[extra_headers] = identifier[headers] , identifier[body_producer] = identifier[self] . identifier[_producer] ) identifier[request] . identifier[addCallback] ( identifier[self] . identifier[_response] ) identifier[request] . identifier[addErrback] ( identifier[self] . identifier[_shutdown] ) identifier[self] . identifier[_reactor] . identifier[run] ()
def run(self): """ Called by the process, it runs it. NEVER call this method directly. Instead call start() to start the separate process. If you don't want to use a second process, then call fetch() directly on this istance. To stop, call terminate() """ producer_deferred = defer.Deferred() producer_deferred.addCallback(self._request_finished) producer_deferred.addErrback(self._request_error) receiver_deferred = defer.Deferred() receiver_deferred.addCallback(self._response_finished) receiver_deferred.addErrback(self._response_error) self._producer = producer.MultiPartProducer(self._files, self._data, callback=self._request_progress, deferred=producer_deferred) self._receiver = receiver.StringReceiver(receiver_deferred) headers = {'Content-Type': 'multipart/form-data; boundary=%s' % self._producer.boundary} (self._reactor, request) = self._connection.build_twisted_request('POST', 'room/%s/uploads' % self._room.id, extra_headers=headers, body_producer=self._producer) request.addCallback(self._response) request.addErrback(self._shutdown) self._reactor.run()
async def handle_token_async(self): """This coroutine is called periodically to check the status of the current token if there is one, and request a new one if needed. If the token request fails, it will be retried according to the retry policy. A token refresh will be attempted if the token will expire soon. This function will return a tuple of two booleans. The first represents whether the token authentication has not completed within it's given timeout window. The second indicates whether the token negotiation is still in progress. :raises: ~uamqp.errors.AuthenticationException if the token authentication fails. :raises: ~uamqp.errors.TokenExpired if the token has expired and cannot be refreshed. :rtype: tuple[bool, bool] """ # pylint: disable=protected-access timeout = False in_progress = False try: await self._connection.lock_async() if self._connection._closing or self._connection._error: return timeout, in_progress auth_status = self._cbs_auth.get_status() auth_status = constants.CBSAuthStatus(auth_status) if auth_status == constants.CBSAuthStatus.Error: if self.retries >= self._retry_policy.retries: # pylint: disable=no-member _logger.warning("Authentication Put-Token failed. Retries exhausted.") raise errors.TokenAuthFailure(*self._cbs_auth.get_failure_info()) error_code, error_description = self._cbs_auth.get_failure_info() _logger.info("Authentication status: %r, description: %r", error_code, error_description) _logger.info("Authentication Put-Token failed. Retrying.") self.retries += 1 # pylint: disable=no-member await asyncio.sleep(self._retry_policy.backoff) self._cbs_auth.authenticate() in_progress = True elif auth_status == constants.CBSAuthStatus.Failure: errors.AuthenticationException("Failed to open CBS authentication link.") elif auth_status == constants.CBSAuthStatus.Expired: raise errors.TokenExpired("CBS Authentication Expired.") elif auth_status == constants.CBSAuthStatus.Timeout: timeout = True elif auth_status == constants.CBSAuthStatus.InProgress: in_progress = True elif auth_status == constants.CBSAuthStatus.RefreshRequired: _logger.info("Token on connection %r will expire soon - attempting to refresh.", self._connection.container_id) self.update_token() self._cbs_auth.refresh(self.token, int(self.expires_at)) elif auth_status == constants.CBSAuthStatus.Idle: self._cbs_auth.authenticate() in_progress = True elif auth_status != constants.CBSAuthStatus.Ok: raise ValueError("Invalid auth state.") except asyncio.TimeoutError: _logger.debug("CBS auth timed out while waiting for lock acquisition.") return None, None except ValueError as e: raise errors.AuthenticationException( "Token authentication failed: {}".format(e)) finally: self._connection.release_async() return timeout, in_progress
<ast.AsyncFunctionDef object at 0x7da204961e70>
keyword[async] keyword[def] identifier[handle_token_async] ( identifier[self] ): literal[string] identifier[timeout] = keyword[False] identifier[in_progress] = keyword[False] keyword[try] : keyword[await] identifier[self] . identifier[_connection] . identifier[lock_async] () keyword[if] identifier[self] . identifier[_connection] . identifier[_closing] keyword[or] identifier[self] . identifier[_connection] . identifier[_error] : keyword[return] identifier[timeout] , identifier[in_progress] identifier[auth_status] = identifier[self] . identifier[_cbs_auth] . identifier[get_status] () identifier[auth_status] = identifier[constants] . identifier[CBSAuthStatus] ( identifier[auth_status] ) keyword[if] identifier[auth_status] == identifier[constants] . identifier[CBSAuthStatus] . identifier[Error] : keyword[if] identifier[self] . identifier[retries] >= identifier[self] . identifier[_retry_policy] . identifier[retries] : identifier[_logger] . identifier[warning] ( literal[string] ) keyword[raise] identifier[errors] . identifier[TokenAuthFailure] (* identifier[self] . identifier[_cbs_auth] . identifier[get_failure_info] ()) identifier[error_code] , identifier[error_description] = identifier[self] . identifier[_cbs_auth] . identifier[get_failure_info] () identifier[_logger] . identifier[info] ( literal[string] , identifier[error_code] , identifier[error_description] ) identifier[_logger] . identifier[info] ( literal[string] ) identifier[self] . identifier[retries] += literal[int] keyword[await] identifier[asyncio] . identifier[sleep] ( identifier[self] . identifier[_retry_policy] . identifier[backoff] ) identifier[self] . identifier[_cbs_auth] . identifier[authenticate] () identifier[in_progress] = keyword[True] keyword[elif] identifier[auth_status] == identifier[constants] . identifier[CBSAuthStatus] . identifier[Failure] : identifier[errors] . identifier[AuthenticationException] ( literal[string] ) keyword[elif] identifier[auth_status] == identifier[constants] . identifier[CBSAuthStatus] . identifier[Expired] : keyword[raise] identifier[errors] . identifier[TokenExpired] ( literal[string] ) keyword[elif] identifier[auth_status] == identifier[constants] . identifier[CBSAuthStatus] . identifier[Timeout] : identifier[timeout] = keyword[True] keyword[elif] identifier[auth_status] == identifier[constants] . identifier[CBSAuthStatus] . identifier[InProgress] : identifier[in_progress] = keyword[True] keyword[elif] identifier[auth_status] == identifier[constants] . identifier[CBSAuthStatus] . identifier[RefreshRequired] : identifier[_logger] . identifier[info] ( literal[string] , identifier[self] . identifier[_connection] . identifier[container_id] ) identifier[self] . identifier[update_token] () identifier[self] . identifier[_cbs_auth] . identifier[refresh] ( identifier[self] . identifier[token] , identifier[int] ( identifier[self] . identifier[expires_at] )) keyword[elif] identifier[auth_status] == identifier[constants] . identifier[CBSAuthStatus] . identifier[Idle] : identifier[self] . identifier[_cbs_auth] . identifier[authenticate] () identifier[in_progress] = keyword[True] keyword[elif] identifier[auth_status] != identifier[constants] . identifier[CBSAuthStatus] . identifier[Ok] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[except] identifier[asyncio] . identifier[TimeoutError] : identifier[_logger] . identifier[debug] ( literal[string] ) keyword[return] keyword[None] , keyword[None] keyword[except] identifier[ValueError] keyword[as] identifier[e] : keyword[raise] identifier[errors] . identifier[AuthenticationException] ( literal[string] . identifier[format] ( identifier[e] )) keyword[finally] : identifier[self] . identifier[_connection] . identifier[release_async] () keyword[return] identifier[timeout] , identifier[in_progress]
async def handle_token_async(self): """This coroutine is called periodically to check the status of the current token if there is one, and request a new one if needed. If the token request fails, it will be retried according to the retry policy. A token refresh will be attempted if the token will expire soon. This function will return a tuple of two booleans. The first represents whether the token authentication has not completed within it's given timeout window. The second indicates whether the token negotiation is still in progress. :raises: ~uamqp.errors.AuthenticationException if the token authentication fails. :raises: ~uamqp.errors.TokenExpired if the token has expired and cannot be refreshed. :rtype: tuple[bool, bool] """ # pylint: disable=protected-access timeout = False in_progress = False try: await self._connection.lock_async() if self._connection._closing or self._connection._error: return (timeout, in_progress) # depends on [control=['if'], data=[]] auth_status = self._cbs_auth.get_status() auth_status = constants.CBSAuthStatus(auth_status) if auth_status == constants.CBSAuthStatus.Error: if self.retries >= self._retry_policy.retries: # pylint: disable=no-member _logger.warning('Authentication Put-Token failed. Retries exhausted.') raise errors.TokenAuthFailure(*self._cbs_auth.get_failure_info()) # depends on [control=['if'], data=[]] (error_code, error_description) = self._cbs_auth.get_failure_info() _logger.info('Authentication status: %r, description: %r', error_code, error_description) _logger.info('Authentication Put-Token failed. Retrying.') self.retries += 1 # pylint: disable=no-member await asyncio.sleep(self._retry_policy.backoff) self._cbs_auth.authenticate() in_progress = True # depends on [control=['if'], data=[]] elif auth_status == constants.CBSAuthStatus.Failure: errors.AuthenticationException('Failed to open CBS authentication link.') # depends on [control=['if'], data=[]] elif auth_status == constants.CBSAuthStatus.Expired: raise errors.TokenExpired('CBS Authentication Expired.') # depends on [control=['if'], data=[]] elif auth_status == constants.CBSAuthStatus.Timeout: timeout = True # depends on [control=['if'], data=[]] elif auth_status == constants.CBSAuthStatus.InProgress: in_progress = True # depends on [control=['if'], data=[]] elif auth_status == constants.CBSAuthStatus.RefreshRequired: _logger.info('Token on connection %r will expire soon - attempting to refresh.', self._connection.container_id) self.update_token() self._cbs_auth.refresh(self.token, int(self.expires_at)) # depends on [control=['if'], data=[]] elif auth_status == constants.CBSAuthStatus.Idle: self._cbs_auth.authenticate() in_progress = True # depends on [control=['if'], data=[]] elif auth_status != constants.CBSAuthStatus.Ok: raise ValueError('Invalid auth state.') # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except asyncio.TimeoutError: _logger.debug('CBS auth timed out while waiting for lock acquisition.') return (None, None) # depends on [control=['except'], data=[]] except ValueError as e: raise errors.AuthenticationException('Token authentication failed: {}'.format(e)) # depends on [control=['except'], data=['e']] finally: self._connection.release_async() return (timeout, in_progress)
def load_ui_file(name): """loads interface from the glade file; sorts out the path business""" ui = gtk.Builder() ui.add_from_file(os.path.join(runtime.data_dir, name)) return ui
def function[load_ui_file, parameter[name]]: constant[loads interface from the glade file; sorts out the path business] variable[ui] assign[=] call[name[gtk].Builder, parameter[]] call[name[ui].add_from_file, parameter[call[name[os].path.join, parameter[name[runtime].data_dir, name[name]]]]] return[name[ui]]
keyword[def] identifier[load_ui_file] ( identifier[name] ): literal[string] identifier[ui] = identifier[gtk] . identifier[Builder] () identifier[ui] . identifier[add_from_file] ( identifier[os] . identifier[path] . identifier[join] ( identifier[runtime] . identifier[data_dir] , identifier[name] )) keyword[return] identifier[ui]
def load_ui_file(name): """loads interface from the glade file; sorts out the path business""" ui = gtk.Builder() ui.add_from_file(os.path.join(runtime.data_dir, name)) return ui
def receive_message(sock, request_id, max_message_size=MAX_MESSAGE_SIZE): """Receive a raw BSON message or raise socket.error.""" # Ignore the response's request id. length, _, response_to, op_code = _UNPACK_HEADER( _receive_data_on_socket(sock, 16)) # No request_id for exhaust cursor "getMore". if request_id is not None: if request_id != response_to: raise ProtocolError("Got response id %r but expected " "%r" % (response_to, request_id)) if length <= 16: raise ProtocolError("Message length (%r) not longer than standard " "message header size (16)" % (length,)) if length > max_message_size: raise ProtocolError("Message length (%r) is larger than server max " "message size (%r)" % (length, max_message_size)) if op_code == 2012: op_code, _, compressor_id = _UNPACK_COMPRESSION_HEADER( _receive_data_on_socket(sock, 9)) data = decompress( _receive_data_on_socket(sock, length - 25), compressor_id) else: data = _receive_data_on_socket(sock, length - 16) try: unpack_reply = _UNPACK_REPLY[op_code] except KeyError: raise ProtocolError("Got opcode %r but expected " "%r" % (op_code, _UNPACK_REPLY.keys())) return unpack_reply(data)
def function[receive_message, parameter[sock, request_id, max_message_size]]: constant[Receive a raw BSON message or raise socket.error.] <ast.Tuple object at 0x7da20c9926e0> assign[=] call[name[_UNPACK_HEADER], parameter[call[name[_receive_data_on_socket], parameter[name[sock], constant[16]]]]] if compare[name[request_id] is_not constant[None]] begin[:] if compare[name[request_id] not_equal[!=] name[response_to]] begin[:] <ast.Raise object at 0x7da20c993c10> if compare[name[length] less_or_equal[<=] constant[16]] begin[:] <ast.Raise object at 0x7da20c993220> if compare[name[length] greater[>] name[max_message_size]] begin[:] <ast.Raise object at 0x7da20c993970> if compare[name[op_code] equal[==] constant[2012]] begin[:] <ast.Tuple object at 0x7da20c993010> assign[=] call[name[_UNPACK_COMPRESSION_HEADER], parameter[call[name[_receive_data_on_socket], parameter[name[sock], constant[9]]]]] variable[data] assign[=] call[name[decompress], parameter[call[name[_receive_data_on_socket], parameter[name[sock], binary_operation[name[length] - constant[25]]]], name[compressor_id]]] <ast.Try object at 0x7da20c9920e0> return[call[name[unpack_reply], parameter[name[data]]]]
keyword[def] identifier[receive_message] ( identifier[sock] , identifier[request_id] , identifier[max_message_size] = identifier[MAX_MESSAGE_SIZE] ): literal[string] identifier[length] , identifier[_] , identifier[response_to] , identifier[op_code] = identifier[_UNPACK_HEADER] ( identifier[_receive_data_on_socket] ( identifier[sock] , literal[int] )) keyword[if] identifier[request_id] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[request_id] != identifier[response_to] : keyword[raise] identifier[ProtocolError] ( literal[string] literal[string] %( identifier[response_to] , identifier[request_id] )) keyword[if] identifier[length] <= literal[int] : keyword[raise] identifier[ProtocolError] ( literal[string] literal[string] %( identifier[length] ,)) keyword[if] identifier[length] > identifier[max_message_size] : keyword[raise] identifier[ProtocolError] ( literal[string] literal[string] %( identifier[length] , identifier[max_message_size] )) keyword[if] identifier[op_code] == literal[int] : identifier[op_code] , identifier[_] , identifier[compressor_id] = identifier[_UNPACK_COMPRESSION_HEADER] ( identifier[_receive_data_on_socket] ( identifier[sock] , literal[int] )) identifier[data] = identifier[decompress] ( identifier[_receive_data_on_socket] ( identifier[sock] , identifier[length] - literal[int] ), identifier[compressor_id] ) keyword[else] : identifier[data] = identifier[_receive_data_on_socket] ( identifier[sock] , identifier[length] - literal[int] ) keyword[try] : identifier[unpack_reply] = identifier[_UNPACK_REPLY] [ identifier[op_code] ] keyword[except] identifier[KeyError] : keyword[raise] identifier[ProtocolError] ( literal[string] literal[string] %( identifier[op_code] , identifier[_UNPACK_REPLY] . identifier[keys] ())) keyword[return] identifier[unpack_reply] ( identifier[data] )
def receive_message(sock, request_id, max_message_size=MAX_MESSAGE_SIZE): """Receive a raw BSON message or raise socket.error.""" # Ignore the response's request id. (length, _, response_to, op_code) = _UNPACK_HEADER(_receive_data_on_socket(sock, 16)) # No request_id for exhaust cursor "getMore". if request_id is not None: if request_id != response_to: raise ProtocolError('Got response id %r but expected %r' % (response_to, request_id)) # depends on [control=['if'], data=['request_id', 'response_to']] # depends on [control=['if'], data=['request_id']] if length <= 16: raise ProtocolError('Message length (%r) not longer than standard message header size (16)' % (length,)) # depends on [control=['if'], data=['length']] if length > max_message_size: raise ProtocolError('Message length (%r) is larger than server max message size (%r)' % (length, max_message_size)) # depends on [control=['if'], data=['length', 'max_message_size']] if op_code == 2012: (op_code, _, compressor_id) = _UNPACK_COMPRESSION_HEADER(_receive_data_on_socket(sock, 9)) data = decompress(_receive_data_on_socket(sock, length - 25), compressor_id) # depends on [control=['if'], data=['op_code']] else: data = _receive_data_on_socket(sock, length - 16) try: unpack_reply = _UNPACK_REPLY[op_code] # depends on [control=['try'], data=[]] except KeyError: raise ProtocolError('Got opcode %r but expected %r' % (op_code, _UNPACK_REPLY.keys())) # depends on [control=['except'], data=[]] return unpack_reply(data)
def _recursively_freeze(value): """ Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively. """ if isinstance(value, Mapping): return _FrozenOrderedDict(((k, _recursively_freeze(v)) for k, v in value.items())) elif isinstance(value, list) or isinstance(value, tuple): return tuple(_recursively_freeze(v) for v in value) return value
def function[_recursively_freeze, parameter[value]]: constant[ Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively. ] if call[name[isinstance], parameter[name[value], name[Mapping]]] begin[:] return[call[name[_FrozenOrderedDict], parameter[<ast.GeneratorExp object at 0x7da2041d9150>]]] return[name[value]]
keyword[def] identifier[_recursively_freeze] ( identifier[value] ): literal[string] keyword[if] identifier[isinstance] ( identifier[value] , identifier[Mapping] ): keyword[return] identifier[_FrozenOrderedDict] ((( identifier[k] , identifier[_recursively_freeze] ( identifier[v] )) keyword[for] identifier[k] , identifier[v] keyword[in] identifier[value] . identifier[items] ())) keyword[elif] identifier[isinstance] ( identifier[value] , identifier[list] ) keyword[or] identifier[isinstance] ( identifier[value] , identifier[tuple] ): keyword[return] identifier[tuple] ( identifier[_recursively_freeze] ( identifier[v] ) keyword[for] identifier[v] keyword[in] identifier[value] ) keyword[return] identifier[value]
def _recursively_freeze(value): """ Recursively walks ``Mapping``s and ``list``s and converts them to ``_FrozenOrderedDict`` and ``tuples``, respectively. """ if isinstance(value, Mapping): return _FrozenOrderedDict(((k, _recursively_freeze(v)) for (k, v) in value.items())) # depends on [control=['if'], data=[]] elif isinstance(value, list) or isinstance(value, tuple): return tuple((_recursively_freeze(v) for v in value)) # depends on [control=['if'], data=[]] return value
def write_utf8_string(self, u): """ Writes a unicode object to the stream in UTF-8. @param u: unicode object @raise TypeError: Unexpected type for str C{u}. """ if not isinstance(u, python.str_types): raise TypeError('Expected %r, got %r' % (python.str_types, u)) bytes = u if isinstance(bytes, unicode): bytes = u.encode("utf8") self.write(struct.pack("%s%ds" % (self.endian, len(bytes)), bytes))
def function[write_utf8_string, parameter[self, u]]: constant[ Writes a unicode object to the stream in UTF-8. @param u: unicode object @raise TypeError: Unexpected type for str C{u}. ] if <ast.UnaryOp object at 0x7da1b135d6c0> begin[:] <ast.Raise object at 0x7da1b135e200> variable[bytes] assign[=] name[u] if call[name[isinstance], parameter[name[bytes], name[unicode]]] begin[:] variable[bytes] assign[=] call[name[u].encode, parameter[constant[utf8]]] call[name[self].write, parameter[call[name[struct].pack, parameter[binary_operation[constant[%s%ds] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b135c400>, <ast.Call object at 0x7da1b135f340>]]], name[bytes]]]]]
keyword[def] identifier[write_utf8_string] ( identifier[self] , identifier[u] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[u] , identifier[python] . identifier[str_types] ): keyword[raise] identifier[TypeError] ( literal[string] %( identifier[python] . identifier[str_types] , identifier[u] )) identifier[bytes] = identifier[u] keyword[if] identifier[isinstance] ( identifier[bytes] , identifier[unicode] ): identifier[bytes] = identifier[u] . identifier[encode] ( literal[string] ) identifier[self] . identifier[write] ( identifier[struct] . identifier[pack] ( literal[string] %( identifier[self] . identifier[endian] , identifier[len] ( identifier[bytes] )), identifier[bytes] ))
def write_utf8_string(self, u): """ Writes a unicode object to the stream in UTF-8. @param u: unicode object @raise TypeError: Unexpected type for str C{u}. """ if not isinstance(u, python.str_types): raise TypeError('Expected %r, got %r' % (python.str_types, u)) # depends on [control=['if'], data=[]] bytes = u if isinstance(bytes, unicode): bytes = u.encode('utf8') # depends on [control=['if'], data=[]] self.write(struct.pack('%s%ds' % (self.endian, len(bytes)), bytes))
def load_profiles_from_file(self, fqfn): """Load profiles from file. Args: fqfn (str): Fully qualified file name. """ if self.args.verbose: print('Loading profiles from File: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, fqfn)) with open(fqfn, 'r+') as fh: data = json.load(fh) for profile in data: # force update old profiles self.profile_update(profile) if self.args.action == 'validate': self.validate(profile) fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate() for d in data: if d.get('profile_name') in self.profiles: self.handle_error( 'Found a duplicate profile name ({}).'.format(d.get('profile_name')) ) self.profiles.setdefault( d.get('profile_name'), {'data': d, 'ij_filename': d.get('install_json'), 'fqfn': fqfn}, )
def function[load_profiles_from_file, parameter[self, fqfn]]: constant[Load profiles from file. Args: fqfn (str): Fully qualified file name. ] if name[self].args.verbose begin[:] call[name[print], parameter[call[constant[Loading profiles from File: {}{}{}].format, parameter[name[c].Style.BRIGHT, name[c].Fore.MAGENTA, name[fqfn]]]]] with call[name[open], parameter[name[fqfn], constant[r+]]] begin[:] variable[data] assign[=] call[name[json].load, parameter[name[fh]]] for taget[name[profile]] in starred[name[data]] begin[:] call[name[self].profile_update, parameter[name[profile]]] if compare[name[self].args.action equal[==] constant[validate]] begin[:] call[name[self].validate, parameter[name[profile]]] call[name[fh].seek, parameter[constant[0]]] call[name[fh].write, parameter[call[name[json].dumps, parameter[name[data]]]]] call[name[fh].truncate, parameter[]] for taget[name[d]] in starred[name[data]] begin[:] if compare[call[name[d].get, parameter[constant[profile_name]]] in name[self].profiles] begin[:] call[name[self].handle_error, parameter[call[constant[Found a duplicate profile name ({}).].format, parameter[call[name[d].get, parameter[constant[profile_name]]]]]]] call[name[self].profiles.setdefault, parameter[call[name[d].get, parameter[constant[profile_name]]], dictionary[[<ast.Constant object at 0x7da1b2345090>, <ast.Constant object at 0x7da1b2346d40>, <ast.Constant object at 0x7da1b2346ef0>], [<ast.Name object at 0x7da1b2347430>, <ast.Call object at 0x7da1b23462c0>, <ast.Name object at 0x7da1b23478b0>]]]]
keyword[def] identifier[load_profiles_from_file] ( identifier[self] , identifier[fqfn] ): literal[string] keyword[if] identifier[self] . identifier[args] . identifier[verbose] : identifier[print] ( literal[string] . identifier[format] ( identifier[c] . identifier[Style] . identifier[BRIGHT] , identifier[c] . identifier[Fore] . identifier[MAGENTA] , identifier[fqfn] )) keyword[with] identifier[open] ( identifier[fqfn] , literal[string] ) keyword[as] identifier[fh] : identifier[data] = identifier[json] . identifier[load] ( identifier[fh] ) keyword[for] identifier[profile] keyword[in] identifier[data] : identifier[self] . identifier[profile_update] ( identifier[profile] ) keyword[if] identifier[self] . identifier[args] . identifier[action] == literal[string] : identifier[self] . identifier[validate] ( identifier[profile] ) identifier[fh] . identifier[seek] ( literal[int] ) identifier[fh] . identifier[write] ( identifier[json] . identifier[dumps] ( identifier[data] , identifier[indent] = literal[int] , identifier[sort_keys] = keyword[True] )) identifier[fh] . identifier[truncate] () keyword[for] identifier[d] keyword[in] identifier[data] : keyword[if] identifier[d] . identifier[get] ( literal[string] ) keyword[in] identifier[self] . identifier[profiles] : identifier[self] . identifier[handle_error] ( literal[string] . identifier[format] ( identifier[d] . identifier[get] ( literal[string] )) ) identifier[self] . identifier[profiles] . identifier[setdefault] ( identifier[d] . identifier[get] ( literal[string] ), { literal[string] : identifier[d] , literal[string] : identifier[d] . identifier[get] ( literal[string] ), literal[string] : identifier[fqfn] }, )
def load_profiles_from_file(self, fqfn): """Load profiles from file. Args: fqfn (str): Fully qualified file name. """ if self.args.verbose: print('Loading profiles from File: {}{}{}'.format(c.Style.BRIGHT, c.Fore.MAGENTA, fqfn)) # depends on [control=['if'], data=[]] with open(fqfn, 'r+') as fh: data = json.load(fh) for profile in data: # force update old profiles self.profile_update(profile) if self.args.action == 'validate': self.validate(profile) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['profile']] fh.seek(0) fh.write(json.dumps(data, indent=2, sort_keys=True)) fh.truncate() # depends on [control=['with'], data=['fh']] for d in data: if d.get('profile_name') in self.profiles: self.handle_error('Found a duplicate profile name ({}).'.format(d.get('profile_name'))) # depends on [control=['if'], data=[]] self.profiles.setdefault(d.get('profile_name'), {'data': d, 'ij_filename': d.get('install_json'), 'fqfn': fqfn}) # depends on [control=['for'], data=['d']]
def get_instance(self, payload): """ Build an instance of DependentHostedNumberOrderInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance """ return DependentHostedNumberOrderInstance( self._version, payload, signing_document_sid=self._solution['signing_document_sid'], )
def function[get_instance, parameter[self, payload]]: constant[ Build an instance of DependentHostedNumberOrderInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance ] return[call[name[DependentHostedNumberOrderInstance], parameter[name[self]._version, name[payload]]]]
keyword[def] identifier[get_instance] ( identifier[self] , identifier[payload] ): literal[string] keyword[return] identifier[DependentHostedNumberOrderInstance] ( identifier[self] . identifier[_version] , identifier[payload] , identifier[signing_document_sid] = identifier[self] . identifier[_solution] [ literal[string] ], )
def get_instance(self, payload): """ Build an instance of DependentHostedNumberOrderInstance :param dict payload: Payload response from the API :returns: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance :rtype: twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order.DependentHostedNumberOrderInstance """ return DependentHostedNumberOrderInstance(self._version, payload, signing_document_sid=self._solution['signing_document_sid'])
def peek(self): """ Returns PeekableIterator.Nothing when the iterator is exhausted. """ try: v = next(self._iter) self._iter = itertools.chain((v,), self._iter) return v except StopIteration: return PeekableIterator.Nothing
def function[peek, parameter[self]]: constant[ Returns PeekableIterator.Nothing when the iterator is exhausted. ] <ast.Try object at 0x7da18eb56770>
keyword[def] identifier[peek] ( identifier[self] ): literal[string] keyword[try] : identifier[v] = identifier[next] ( identifier[self] . identifier[_iter] ) identifier[self] . identifier[_iter] = identifier[itertools] . identifier[chain] (( identifier[v] ,), identifier[self] . identifier[_iter] ) keyword[return] identifier[v] keyword[except] identifier[StopIteration] : keyword[return] identifier[PeekableIterator] . identifier[Nothing]
def peek(self): """ Returns PeekableIterator.Nothing when the iterator is exhausted. """ try: v = next(self._iter) self._iter = itertools.chain((v,), self._iter) return v # depends on [control=['try'], data=[]] except StopIteration: return PeekableIterator.Nothing # depends on [control=['except'], data=[]]
def solve_resolve(expr, vars): """Use IStructured.resolve to get member (rhs) from the object (lhs). This operation supports both scalars and repeated values on the LHS - resolving from a repeated value implies a map-like operation and returns a new repeated values. """ objs, _ = __solve_for_repeated(expr.lhs, vars) member = solve(expr.rhs, vars).value try: results = [structured.resolve(o, member) for o in repeated.getvalues(objs)] except (KeyError, AttributeError): # Raise a better exception for the non-existent member. raise errors.EfilterKeyError(root=expr.rhs, key=member, query=expr.source) except (TypeError, ValueError): # Is this a null object error? if vars.locals is None: raise errors.EfilterNoneError( root=expr, query=expr.source, message="Cannot resolve member %r from a null." % member) else: raise except NotImplementedError: raise errors.EfilterError( root=expr, query=expr.source, message="Cannot resolve members from a non-structured value.") return Result(repeated.meld(*results), ())
def function[solve_resolve, parameter[expr, vars]]: constant[Use IStructured.resolve to get member (rhs) from the object (lhs). This operation supports both scalars and repeated values on the LHS - resolving from a repeated value implies a map-like operation and returns a new repeated values. ] <ast.Tuple object at 0x7da1b0e7e260> assign[=] call[name[__solve_for_repeated], parameter[name[expr].lhs, name[vars]]] variable[member] assign[=] call[name[solve], parameter[name[expr].rhs, name[vars]]].value <ast.Try object at 0x7da1b0e7e740> return[call[name[Result], parameter[call[name[repeated].meld, parameter[<ast.Starred object at 0x7da1b0ff9810>]], tuple[[]]]]]
keyword[def] identifier[solve_resolve] ( identifier[expr] , identifier[vars] ): literal[string] identifier[objs] , identifier[_] = identifier[__solve_for_repeated] ( identifier[expr] . identifier[lhs] , identifier[vars] ) identifier[member] = identifier[solve] ( identifier[expr] . identifier[rhs] , identifier[vars] ). identifier[value] keyword[try] : identifier[results] =[ identifier[structured] . identifier[resolve] ( identifier[o] , identifier[member] ) keyword[for] identifier[o] keyword[in] identifier[repeated] . identifier[getvalues] ( identifier[objs] )] keyword[except] ( identifier[KeyError] , identifier[AttributeError] ): keyword[raise] identifier[errors] . identifier[EfilterKeyError] ( identifier[root] = identifier[expr] . identifier[rhs] , identifier[key] = identifier[member] , identifier[query] = identifier[expr] . identifier[source] ) keyword[except] ( identifier[TypeError] , identifier[ValueError] ): keyword[if] identifier[vars] . identifier[locals] keyword[is] keyword[None] : keyword[raise] identifier[errors] . identifier[EfilterNoneError] ( identifier[root] = identifier[expr] , identifier[query] = identifier[expr] . identifier[source] , identifier[message] = literal[string] % identifier[member] ) keyword[else] : keyword[raise] keyword[except] identifier[NotImplementedError] : keyword[raise] identifier[errors] . identifier[EfilterError] ( identifier[root] = identifier[expr] , identifier[query] = identifier[expr] . identifier[source] , identifier[message] = literal[string] ) keyword[return] identifier[Result] ( identifier[repeated] . identifier[meld] (* identifier[results] ),())
def solve_resolve(expr, vars): """Use IStructured.resolve to get member (rhs) from the object (lhs). This operation supports both scalars and repeated values on the LHS - resolving from a repeated value implies a map-like operation and returns a new repeated values. """ (objs, _) = __solve_for_repeated(expr.lhs, vars) member = solve(expr.rhs, vars).value try: results = [structured.resolve(o, member) for o in repeated.getvalues(objs)] # depends on [control=['try'], data=[]] except (KeyError, AttributeError): # Raise a better exception for the non-existent member. raise errors.EfilterKeyError(root=expr.rhs, key=member, query=expr.source) # depends on [control=['except'], data=[]] except (TypeError, ValueError): # Is this a null object error? if vars.locals is None: raise errors.EfilterNoneError(root=expr, query=expr.source, message='Cannot resolve member %r from a null.' % member) # depends on [control=['if'], data=[]] else: raise # depends on [control=['except'], data=[]] except NotImplementedError: raise errors.EfilterError(root=expr, query=expr.source, message='Cannot resolve members from a non-structured value.') # depends on [control=['except'], data=[]] return Result(repeated.meld(*results), ())
def to_ising(self): """Converts a binary quadratic model to Ising format. If the binary quadratic model's vartype is not :class:`.Vartype.SPIN`, values are converted. Returns: tuple: 3-tuple of form (`linear`, `quadratic`, `offset`), where `linear` is a dict of linear biases, `quadratic` is a dict of quadratic biases, and `offset` is a number that represents the constant offset of the binary quadratic model. Examples: This example converts a binary quadratic model to an Ising problem. >>> import dimod >>> model = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5}, ... {(0, 1): .5, (1, 2): 1.5}, ... 1.4, ... dimod.SPIN) >>> model.to_ising() # doctest: +SKIP ({0: 1, 1: -1, 2: 0.5}, {(0, 1): 0.5, (1, 2): 1.5}, 1.4) """ # cast to a dict return dict(self.spin.linear), dict(self.spin.quadratic), self.spin.offset
def function[to_ising, parameter[self]]: constant[Converts a binary quadratic model to Ising format. If the binary quadratic model's vartype is not :class:`.Vartype.SPIN`, values are converted. Returns: tuple: 3-tuple of form (`linear`, `quadratic`, `offset`), where `linear` is a dict of linear biases, `quadratic` is a dict of quadratic biases, and `offset` is a number that represents the constant offset of the binary quadratic model. Examples: This example converts a binary quadratic model to an Ising problem. >>> import dimod >>> model = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5}, ... {(0, 1): .5, (1, 2): 1.5}, ... 1.4, ... dimod.SPIN) >>> model.to_ising() # doctest: +SKIP ({0: 1, 1: -1, 2: 0.5}, {(0, 1): 0.5, (1, 2): 1.5}, 1.4) ] return[tuple[[<ast.Call object at 0x7da1b072f4c0>, <ast.Call object at 0x7da1b072f6a0>, <ast.Attribute object at 0x7da1b072ee90>]]]
keyword[def] identifier[to_ising] ( identifier[self] ): literal[string] keyword[return] identifier[dict] ( identifier[self] . identifier[spin] . identifier[linear] ), identifier[dict] ( identifier[self] . identifier[spin] . identifier[quadratic] ), identifier[self] . identifier[spin] . identifier[offset]
def to_ising(self): """Converts a binary quadratic model to Ising format. If the binary quadratic model's vartype is not :class:`.Vartype.SPIN`, values are converted. Returns: tuple: 3-tuple of form (`linear`, `quadratic`, `offset`), where `linear` is a dict of linear biases, `quadratic` is a dict of quadratic biases, and `offset` is a number that represents the constant offset of the binary quadratic model. Examples: This example converts a binary quadratic model to an Ising problem. >>> import dimod >>> model = dimod.BinaryQuadraticModel({0: 1, 1: -1, 2: .5}, ... {(0, 1): .5, (1, 2): 1.5}, ... 1.4, ... dimod.SPIN) >>> model.to_ising() # doctest: +SKIP ({0: 1, 1: -1, 2: 0.5}, {(0, 1): 0.5, (1, 2): 1.5}, 1.4) """ # cast to a dict return (dict(self.spin.linear), dict(self.spin.quadratic), self.spin.offset)
def parse_dsn(dsn, default_port=5432, protocol='http://'): """ Разбирает строку подключения к БД и возвращает список из (host, port, username, password, dbname) :param dsn: Строка подключения. Например: username@localhost:5432/dname :type: str :param default_port: Порт по-умолчанию :type default_port: int :params protocol :type protocol str :return: [host, port, username, password, dbname] :rtype: list """ parsed = urlparse(protocol + dsn) return [ parsed.hostname or 'localhost', parsed.port or default_port, unquote(parsed.username) if parsed.username is not None else getuser(), unquote(parsed.password) if parsed.password is not None else None, parsed.path.lstrip('/'), ]
def function[parse_dsn, parameter[dsn, default_port, protocol]]: constant[ Разбирает строку подключения к БД и возвращает список из (host, port, username, password, dbname) :param dsn: Строка подключения. Например: username@localhost:5432/dname :type: str :param default_port: Порт по-умолчанию :type default_port: int :params protocol :type protocol str :return: [host, port, username, password, dbname] :rtype: list ] variable[parsed] assign[=] call[name[urlparse], parameter[binary_operation[name[protocol] + name[dsn]]]] return[list[[<ast.BoolOp object at 0x7da1b10d6ec0>, <ast.BoolOp object at 0x7da1b10d7190>, <ast.IfExp object at 0x7da1b10d4340>, <ast.IfExp object at 0x7da20c76cf40>, <ast.Call object at 0x7da20c76f9d0>]]]
keyword[def] identifier[parse_dsn] ( identifier[dsn] , identifier[default_port] = literal[int] , identifier[protocol] = literal[string] ): literal[string] identifier[parsed] = identifier[urlparse] ( identifier[protocol] + identifier[dsn] ) keyword[return] [ identifier[parsed] . identifier[hostname] keyword[or] literal[string] , identifier[parsed] . identifier[port] keyword[or] identifier[default_port] , identifier[unquote] ( identifier[parsed] . identifier[username] ) keyword[if] identifier[parsed] . identifier[username] keyword[is] keyword[not] keyword[None] keyword[else] identifier[getuser] (), identifier[unquote] ( identifier[parsed] . identifier[password] ) keyword[if] identifier[parsed] . identifier[password] keyword[is] keyword[not] keyword[None] keyword[else] keyword[None] , identifier[parsed] . identifier[path] . identifier[lstrip] ( literal[string] ), ]
def parse_dsn(dsn, default_port=5432, protocol='http://'): """ Разбирает строку подключения к БД и возвращает список из (host, port, username, password, dbname) :param dsn: Строка подключения. Например: username@localhost:5432/dname :type: str :param default_port: Порт по-умолчанию :type default_port: int :params protocol :type protocol str :return: [host, port, username, password, dbname] :rtype: list """ parsed = urlparse(protocol + dsn) return [parsed.hostname or 'localhost', parsed.port or default_port, unquote(parsed.username) if parsed.username is not None else getuser(), unquote(parsed.password) if parsed.password is not None else None, parsed.path.lstrip('/')]
def main(): """ Main *boilerplate* function to start simulation """ # Now let's make use of logging logger = logging.getLogger() # Create folders for data and plots folder = os.path.join(os.getcwd(), 'experiments', 'ca_patterns_pypet') if not os.path.isdir(folder): os.makedirs(folder) filename = os.path.join(folder, 'all_patterns.hdf5') # Create an environment env = Environment(trajectory='cellular_automata', multiproc=True, ncores=4, wrap_mode='QUEUE', filename=filename, overwrite_file=True) # extract the trajectory traj = env.traj traj.par.ncells = Parameter('ncells', 400, 'Number of cells') traj.par.steps = Parameter('steps', 250, 'Number of timesteps') traj.par.rule_number = Parameter('rule_number', 30, 'The ca rule') traj.par.initial_name = Parameter('initial_name', 'random', 'The type of initial state') traj.par.seed = Parameter('seed', 100042, 'RNG Seed') # Explore exp_dict = {'rule_number' : [10, 30, 90, 110, 184], 'initial_name' : ['single', 'random'],} # # You can uncomment the ``exp_dict`` below to see that changing the # # exploration scheme is now really easy: # exp_dict = {'rule_number' : [10, 30, 90, 110, 184], # 'ncells' : [100, 200, 300], # 'seed': [333444555, 123456]} exp_dict = cartesian_product(exp_dict) traj.f_explore(exp_dict) # Run the simulation logger.info('Starting Simulation') env.run(wrap_automaton) # Load all data traj.f_load(load_data=2) logger.info('Printing data') for idx, run_name in enumerate(traj.f_iter_runs()): # Plot all patterns filename = os.path.join(folder, make_filename(traj)) plot_pattern(traj.crun.pattern, traj.rule_number, filename) progressbar(idx, len(traj), logger=logger) # Finally disable logging and close all log-files env.disable_logging()
def function[main, parameter[]]: constant[ Main *boilerplate* function to start simulation ] variable[logger] assign[=] call[name[logging].getLogger, parameter[]] variable[folder] assign[=] call[name[os].path.join, parameter[call[name[os].getcwd, parameter[]], constant[experiments], constant[ca_patterns_pypet]]] if <ast.UnaryOp object at 0x7da1b034ad40> begin[:] call[name[os].makedirs, parameter[name[folder]]] variable[filename] assign[=] call[name[os].path.join, parameter[name[folder], constant[all_patterns.hdf5]]] variable[env] assign[=] call[name[Environment], parameter[]] variable[traj] assign[=] name[env].traj name[traj].par.ncells assign[=] call[name[Parameter], parameter[constant[ncells], constant[400], constant[Number of cells]]] name[traj].par.steps assign[=] call[name[Parameter], parameter[constant[steps], constant[250], constant[Number of timesteps]]] name[traj].par.rule_number assign[=] call[name[Parameter], parameter[constant[rule_number], constant[30], constant[The ca rule]]] name[traj].par.initial_name assign[=] call[name[Parameter], parameter[constant[initial_name], constant[random], constant[The type of initial state]]] name[traj].par.seed assign[=] call[name[Parameter], parameter[constant[seed], constant[100042], constant[RNG Seed]]] variable[exp_dict] assign[=] dictionary[[<ast.Constant object at 0x7da1b034b8e0>, <ast.Constant object at 0x7da1b0348f40>], [<ast.List object at 0x7da1b0348b50>, <ast.List object at 0x7da1b03488e0>]] variable[exp_dict] assign[=] call[name[cartesian_product], parameter[name[exp_dict]]] call[name[traj].f_explore, parameter[name[exp_dict]]] call[name[logger].info, parameter[constant[Starting Simulation]]] call[name[env].run, parameter[name[wrap_automaton]]] call[name[traj].f_load, parameter[]] call[name[logger].info, parameter[constant[Printing data]]] for taget[tuple[[<ast.Name object at 0x7da1b0349030>, <ast.Name object at 0x7da1b034a830>]]] in starred[call[name[enumerate], parameter[call[name[traj].f_iter_runs, parameter[]]]]] begin[:] variable[filename] assign[=] call[name[os].path.join, parameter[name[folder], call[name[make_filename], parameter[name[traj]]]]] call[name[plot_pattern], parameter[name[traj].crun.pattern, name[traj].rule_number, name[filename]]] call[name[progressbar], parameter[name[idx], call[name[len], parameter[name[traj]]]]] call[name[env].disable_logging, parameter[]]
keyword[def] identifier[main] (): literal[string] identifier[logger] = identifier[logging] . identifier[getLogger] () identifier[folder] = identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[getcwd] (), literal[string] , literal[string] ) keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier[folder] ): identifier[os] . identifier[makedirs] ( identifier[folder] ) identifier[filename] = identifier[os] . identifier[path] . identifier[join] ( identifier[folder] , literal[string] ) identifier[env] = identifier[Environment] ( identifier[trajectory] = literal[string] , identifier[multiproc] = keyword[True] , identifier[ncores] = literal[int] , identifier[wrap_mode] = literal[string] , identifier[filename] = identifier[filename] , identifier[overwrite_file] = keyword[True] ) identifier[traj] = identifier[env] . identifier[traj] identifier[traj] . identifier[par] . identifier[ncells] = identifier[Parameter] ( literal[string] , literal[int] , literal[string] ) identifier[traj] . identifier[par] . identifier[steps] = identifier[Parameter] ( literal[string] , literal[int] , literal[string] ) identifier[traj] . identifier[par] . identifier[rule_number] = identifier[Parameter] ( literal[string] , literal[int] , literal[string] ) identifier[traj] . identifier[par] . identifier[initial_name] = identifier[Parameter] ( literal[string] , literal[string] , literal[string] ) identifier[traj] . identifier[par] . identifier[seed] = identifier[Parameter] ( literal[string] , literal[int] , literal[string] ) identifier[exp_dict] ={ literal[string] :[ literal[int] , literal[int] , literal[int] , literal[int] , literal[int] ], literal[string] :[ literal[string] , literal[string] ],} identifier[exp_dict] = identifier[cartesian_product] ( identifier[exp_dict] ) identifier[traj] . identifier[f_explore] ( identifier[exp_dict] ) identifier[logger] . identifier[info] ( literal[string] ) identifier[env] . identifier[run] ( identifier[wrap_automaton] ) identifier[traj] . identifier[f_load] ( identifier[load_data] = literal[int] ) identifier[logger] . identifier[info] ( literal[string] ) keyword[for] identifier[idx] , identifier[run_name] keyword[in] identifier[enumerate] ( identifier[traj] . identifier[f_iter_runs] ()): identifier[filename] = identifier[os] . identifier[path] . identifier[join] ( identifier[folder] , identifier[make_filename] ( identifier[traj] )) identifier[plot_pattern] ( identifier[traj] . identifier[crun] . identifier[pattern] , identifier[traj] . identifier[rule_number] , identifier[filename] ) identifier[progressbar] ( identifier[idx] , identifier[len] ( identifier[traj] ), identifier[logger] = identifier[logger] ) identifier[env] . identifier[disable_logging] ()
def main(): """ Main *boilerplate* function to start simulation """ # Now let's make use of logging logger = logging.getLogger() # Create folders for data and plots folder = os.path.join(os.getcwd(), 'experiments', 'ca_patterns_pypet') if not os.path.isdir(folder): os.makedirs(folder) # depends on [control=['if'], data=[]] filename = os.path.join(folder, 'all_patterns.hdf5') # Create an environment env = Environment(trajectory='cellular_automata', multiproc=True, ncores=4, wrap_mode='QUEUE', filename=filename, overwrite_file=True) # extract the trajectory traj = env.traj traj.par.ncells = Parameter('ncells', 400, 'Number of cells') traj.par.steps = Parameter('steps', 250, 'Number of timesteps') traj.par.rule_number = Parameter('rule_number', 30, 'The ca rule') traj.par.initial_name = Parameter('initial_name', 'random', 'The type of initial state') traj.par.seed = Parameter('seed', 100042, 'RNG Seed') # Explore exp_dict = {'rule_number': [10, 30, 90, 110, 184], 'initial_name': ['single', 'random']} # # You can uncomment the ``exp_dict`` below to see that changing the # # exploration scheme is now really easy: # exp_dict = {'rule_number' : [10, 30, 90, 110, 184], # 'ncells' : [100, 200, 300], # 'seed': [333444555, 123456]} exp_dict = cartesian_product(exp_dict) traj.f_explore(exp_dict) # Run the simulation logger.info('Starting Simulation') env.run(wrap_automaton) # Load all data traj.f_load(load_data=2) logger.info('Printing data') for (idx, run_name) in enumerate(traj.f_iter_runs()): # Plot all patterns filename = os.path.join(folder, make_filename(traj)) plot_pattern(traj.crun.pattern, traj.rule_number, filename) progressbar(idx, len(traj), logger=logger) # depends on [control=['for'], data=[]] # Finally disable logging and close all log-files env.disable_logging()
def merge(self, other, reference_seq): '''Tries to merge this VcfRecord with other VcfRecord. Simple example (working in 0-based coords): ref = ACGT var1 = SNP at position 1, C->G var2 = SNP at position 3, T->A then this returns new variant, position=1, REF=CGT, ALT=GGA. If there is any kind of conflict, eg two SNPs in same position, then returns None. Also assumes there is only one ALT, otherwise returns None.''' if self.CHROM != other.CHROM or self.intersects(other) or len(self.ALT) != 1 or len(other.ALT) != 1: return None ref_start = min(self.POS, other.POS) ref_end = max(self.ref_end_pos(), other.ref_end_pos()) ref_seq_for_vcf = reference_seq[ref_start:ref_end + 1] sorted_records = sorted([self, other], key=operator.attrgetter('POS')) alt_seq = [] gt_confs = [] current_ref_pos = ref_start for record in sorted_records: assert record.REF != '.' and record.ALT[0] != '.' alt_seq.append(reference_seq[current_ref_pos:record.POS]) alt_seq.append(record.ALT[0]) current_ref_pos += len(record.REF) if record.FORMAT is not None and 'GT_CONF' in record.FORMAT: gt_confs.append(record.FORMAT['GT_CONF']) gt_conf = 0 format = "GT" gt_1 = '1/1' if len(gt_confs) > 0: gt_conf = min(gt_confs) format = 'GT:GT_CONF' gt_1 = '1/1:' + str(gt_conf) return VcfRecord('\t'.join([ self.CHROM, str(ref_start + 1), '.', ref_seq_for_vcf, ''.join(alt_seq), '.', '.', 'SVTYPE=MERGED', format, gt_1, ]))
def function[merge, parameter[self, other, reference_seq]]: constant[Tries to merge this VcfRecord with other VcfRecord. Simple example (working in 0-based coords): ref = ACGT var1 = SNP at position 1, C->G var2 = SNP at position 3, T->A then this returns new variant, position=1, REF=CGT, ALT=GGA. If there is any kind of conflict, eg two SNPs in same position, then returns None. Also assumes there is only one ALT, otherwise returns None.] if <ast.BoolOp object at 0x7da1b1da1d20> begin[:] return[constant[None]] variable[ref_start] assign[=] call[name[min], parameter[name[self].POS, name[other].POS]] variable[ref_end] assign[=] call[name[max], parameter[call[name[self].ref_end_pos, parameter[]], call[name[other].ref_end_pos, parameter[]]]] variable[ref_seq_for_vcf] assign[=] call[name[reference_seq]][<ast.Slice object at 0x7da1b1da1de0>] variable[sorted_records] assign[=] call[name[sorted], parameter[list[[<ast.Name object at 0x7da1b1da3820>, <ast.Name object at 0x7da1b1da04c0>]]]] variable[alt_seq] assign[=] list[[]] variable[gt_confs] assign[=] list[[]] variable[current_ref_pos] assign[=] name[ref_start] for taget[name[record]] in starred[name[sorted_records]] begin[:] assert[<ast.BoolOp object at 0x7da1b1da2560>] call[name[alt_seq].append, parameter[call[name[reference_seq]][<ast.Slice object at 0x7da1b1da06a0>]]] call[name[alt_seq].append, parameter[call[name[record].ALT][constant[0]]]] <ast.AugAssign object at 0x7da1b1da11e0> if <ast.BoolOp object at 0x7da1b1da2b60> begin[:] call[name[gt_confs].append, parameter[call[name[record].FORMAT][constant[GT_CONF]]]] variable[gt_conf] assign[=] constant[0] variable[format] assign[=] constant[GT] variable[gt_1] assign[=] constant[1/1] if compare[call[name[len], parameter[name[gt_confs]]] greater[>] constant[0]] begin[:] variable[gt_conf] assign[=] call[name[min], parameter[name[gt_confs]]] variable[format] assign[=] constant[GT:GT_CONF] variable[gt_1] assign[=] binary_operation[constant[1/1:] + call[name[str], parameter[name[gt_conf]]]] return[call[name[VcfRecord], parameter[call[constant[ ].join, parameter[list[[<ast.Attribute object at 0x7da1b1da1420>, <ast.Call object at 0x7da1b1da1450>, <ast.Constant object at 0x7da1b1da2980>, <ast.Name object at 0x7da1b1da2aa0>, <ast.Call object at 0x7da1b1da2a10>, <ast.Constant object at 0x7da1b1da3430>, <ast.Constant object at 0x7da1b1da2320>, <ast.Constant object at 0x7da1b1da2b30>, <ast.Name object at 0x7da1b1da29e0>, <ast.Name object at 0x7da1b1da3400>]]]]]]]
keyword[def] identifier[merge] ( identifier[self] , identifier[other] , identifier[reference_seq] ): literal[string] keyword[if] identifier[self] . identifier[CHROM] != identifier[other] . identifier[CHROM] keyword[or] identifier[self] . identifier[intersects] ( identifier[other] ) keyword[or] identifier[len] ( identifier[self] . identifier[ALT] )!= literal[int] keyword[or] identifier[len] ( identifier[other] . identifier[ALT] )!= literal[int] : keyword[return] keyword[None] identifier[ref_start] = identifier[min] ( identifier[self] . identifier[POS] , identifier[other] . identifier[POS] ) identifier[ref_end] = identifier[max] ( identifier[self] . identifier[ref_end_pos] (), identifier[other] . identifier[ref_end_pos] ()) identifier[ref_seq_for_vcf] = identifier[reference_seq] [ identifier[ref_start] : identifier[ref_end] + literal[int] ] identifier[sorted_records] = identifier[sorted] ([ identifier[self] , identifier[other] ], identifier[key] = identifier[operator] . identifier[attrgetter] ( literal[string] )) identifier[alt_seq] =[] identifier[gt_confs] =[] identifier[current_ref_pos] = identifier[ref_start] keyword[for] identifier[record] keyword[in] identifier[sorted_records] : keyword[assert] identifier[record] . identifier[REF] != literal[string] keyword[and] identifier[record] . identifier[ALT] [ literal[int] ]!= literal[string] identifier[alt_seq] . identifier[append] ( identifier[reference_seq] [ identifier[current_ref_pos] : identifier[record] . identifier[POS] ]) identifier[alt_seq] . identifier[append] ( identifier[record] . identifier[ALT] [ literal[int] ]) identifier[current_ref_pos] += identifier[len] ( identifier[record] . identifier[REF] ) keyword[if] identifier[record] . identifier[FORMAT] keyword[is] keyword[not] keyword[None] keyword[and] literal[string] keyword[in] identifier[record] . identifier[FORMAT] : identifier[gt_confs] . identifier[append] ( identifier[record] . identifier[FORMAT] [ literal[string] ]) identifier[gt_conf] = literal[int] identifier[format] = literal[string] identifier[gt_1] = literal[string] keyword[if] identifier[len] ( identifier[gt_confs] )> literal[int] : identifier[gt_conf] = identifier[min] ( identifier[gt_confs] ) identifier[format] = literal[string] identifier[gt_1] = literal[string] + identifier[str] ( identifier[gt_conf] ) keyword[return] identifier[VcfRecord] ( literal[string] . identifier[join] ([ identifier[self] . identifier[CHROM] , identifier[str] ( identifier[ref_start] + literal[int] ), literal[string] , identifier[ref_seq_for_vcf] , literal[string] . identifier[join] ( identifier[alt_seq] ), literal[string] , literal[string] , literal[string] , identifier[format] , identifier[gt_1] , ]))
def merge(self, other, reference_seq): """Tries to merge this VcfRecord with other VcfRecord. Simple example (working in 0-based coords): ref = ACGT var1 = SNP at position 1, C->G var2 = SNP at position 3, T->A then this returns new variant, position=1, REF=CGT, ALT=GGA. If there is any kind of conflict, eg two SNPs in same position, then returns None. Also assumes there is only one ALT, otherwise returns None.""" if self.CHROM != other.CHROM or self.intersects(other) or len(self.ALT) != 1 or (len(other.ALT) != 1): return None # depends on [control=['if'], data=[]] ref_start = min(self.POS, other.POS) ref_end = max(self.ref_end_pos(), other.ref_end_pos()) ref_seq_for_vcf = reference_seq[ref_start:ref_end + 1] sorted_records = sorted([self, other], key=operator.attrgetter('POS')) alt_seq = [] gt_confs = [] current_ref_pos = ref_start for record in sorted_records: assert record.REF != '.' and record.ALT[0] != '.' alt_seq.append(reference_seq[current_ref_pos:record.POS]) alt_seq.append(record.ALT[0]) current_ref_pos += len(record.REF) if record.FORMAT is not None and 'GT_CONF' in record.FORMAT: gt_confs.append(record.FORMAT['GT_CONF']) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['record']] gt_conf = 0 format = 'GT' gt_1 = '1/1' if len(gt_confs) > 0: gt_conf = min(gt_confs) format = 'GT:GT_CONF' gt_1 = '1/1:' + str(gt_conf) # depends on [control=['if'], data=[]] return VcfRecord('\t'.join([self.CHROM, str(ref_start + 1), '.', ref_seq_for_vcf, ''.join(alt_seq), '.', '.', 'SVTYPE=MERGED', format, gt_1]))
def tone_marks(): """Keep tone-modifying punctuation by matching following character. Assumes the `tone_marks` pre-processor was run for cases where there might not be any space after a tone-modifying punctuation mark. """ return RegexBuilder( pattern_args=symbols.TONE_MARKS, pattern_func=lambda x: u"(?<={}).".format(x)).regex
def function[tone_marks, parameter[]]: constant[Keep tone-modifying punctuation by matching following character. Assumes the `tone_marks` pre-processor was run for cases where there might not be any space after a tone-modifying punctuation mark. ] return[call[name[RegexBuilder], parameter[]].regex]
keyword[def] identifier[tone_marks] (): literal[string] keyword[return] identifier[RegexBuilder] ( identifier[pattern_args] = identifier[symbols] . identifier[TONE_MARKS] , identifier[pattern_func] = keyword[lambda] identifier[x] : literal[string] . identifier[format] ( identifier[x] )). identifier[regex]
def tone_marks(): """Keep tone-modifying punctuation by matching following character. Assumes the `tone_marks` pre-processor was run for cases where there might not be any space after a tone-modifying punctuation mark. """ return RegexBuilder(pattern_args=symbols.TONE_MARKS, pattern_func=lambda x: u'(?<={}).'.format(x)).regex
def html_error_template(): """Provides a template that renders a stack trace in an HTML format, providing an excerpt of code as well as substituting source template filenames, line numbers and code for that of the originating source template, as applicable. The template's default ``encoding_errors`` value is ``'htmlentityreplace'``. The template has two options. With the ``full`` option disabled, only a section of an HTML document is returned. With the ``css`` option disabled, the default stylesheet won't be included. """ import mako.template return mako.template.Template(r""" <%! from mako.exceptions import RichTraceback, syntax_highlight,\ pygments_html_formatter %> <%page args="full=True, css=True, error=None, traceback=None"/> % if full: <html> <head> <title>Mako Runtime Error</title> % endif % if css: <style> body { font-family:verdana; margin:10px 30px 10px 30px;} .stacktrace { margin:5px 5px 5px 5px; } .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; } .nonhighlight { padding:0px; background-color:#DFDFDF; } .sample { padding:10px; margin:10px 10px 10px 10px; font-family:monospace; } .sampleline { padding:0px 10px 0px 10px; } .sourceline { margin:5px 5px 10px 5px; font-family:monospace;} .location { font-size:80%; } .highlight { white-space:pre; } .sampleline { white-space:pre; } % if pygments_html_formatter: ${pygments_html_formatter.get_style_defs()} .linenos { min-width: 2.5em; text-align: right; } pre { margin: 0; } .syntax-highlighted { padding: 0 10px; } .syntax-highlightedtable { border-spacing: 1px; } .nonhighlight { border-top: 1px solid #DFDFDF; border-bottom: 1px solid #DFDFDF; } .stacktrace .nonhighlight { margin: 5px 15px 10px; } .sourceline { margin: 0 0; font-family:monospace; } .code { background-color: #F8F8F8; width: 100%; } .error .code { background-color: #FFBDBD; } .error .syntax-highlighted { background-color: #FFBDBD; } % endif </style> % endif % if full: </head> <body> % endif <h2>Error !</h2> <% tback = RichTraceback(error=error, traceback=traceback) src = tback.source line = tback.lineno if src: lines = src.split('\n') else: lines = None %> <h3>${tback.errorname}: ${tback.message|h}</h3> % if lines: <div class="sample"> <div class="nonhighlight"> % for index in range(max(0, line-4),min(len(lines), line+5)): <% if pygments_html_formatter: pygments_html_formatter.linenostart = index + 1 %> % if index + 1 == line: <% if pygments_html_formatter: old_cssclass = pygments_html_formatter.cssclass pygments_html_formatter.cssclass = 'error ' + old_cssclass %> ${lines[index] | syntax_highlight(language='mako')} <% if pygments_html_formatter: pygments_html_formatter.cssclass = old_cssclass %> % else: ${lines[index] | syntax_highlight(language='mako')} % endif % endfor </div> </div> % endif <div class="stacktrace"> % for (filename, lineno, function, line) in tback.reverse_traceback: <div class="location">${filename}, line ${lineno}:</div> <div class="nonhighlight"> <% if pygments_html_formatter: pygments_html_formatter.linenostart = lineno %> <div class="sourceline">${line | syntax_highlight(filename)}</div> </div> % endfor </div> % if full: </body> </html> % endif """, output_encoding=sys.getdefaultencoding(), encoding_errors='htmlentityreplace')
def function[html_error_template, parameter[]]: constant[Provides a template that renders a stack trace in an HTML format, providing an excerpt of code as well as substituting source template filenames, line numbers and code for that of the originating source template, as applicable. The template's default ``encoding_errors`` value is ``'htmlentityreplace'``. The template has two options. With the ``full`` option disabled, only a section of an HTML document is returned. With the ``css`` option disabled, the default stylesheet won't be included. ] import module[mako.template] return[call[name[mako].template.Template, parameter[constant[ <%! from mako.exceptions import RichTraceback, syntax_highlight,\ pygments_html_formatter %> <%page args="full=True, css=True, error=None, traceback=None"/> % if full: <html> <head> <title>Mako Runtime Error</title> % endif % if css: <style> body { font-family:verdana; margin:10px 30px 10px 30px;} .stacktrace { margin:5px 5px 5px 5px; } .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; } .nonhighlight { padding:0px; background-color:#DFDFDF; } .sample { padding:10px; margin:10px 10px 10px 10px; font-family:monospace; } .sampleline { padding:0px 10px 0px 10px; } .sourceline { margin:5px 5px 10px 5px; font-family:monospace;} .location { font-size:80%; } .highlight { white-space:pre; } .sampleline { white-space:pre; } % if pygments_html_formatter: ${pygments_html_formatter.get_style_defs()} .linenos { min-width: 2.5em; text-align: right; } pre { margin: 0; } .syntax-highlighted { padding: 0 10px; } .syntax-highlightedtable { border-spacing: 1px; } .nonhighlight { border-top: 1px solid #DFDFDF; border-bottom: 1px solid #DFDFDF; } .stacktrace .nonhighlight { margin: 5px 15px 10px; } .sourceline { margin: 0 0; font-family:monospace; } .code { background-color: #F8F8F8; width: 100%; } .error .code { background-color: #FFBDBD; } .error .syntax-highlighted { background-color: #FFBDBD; } % endif </style> % endif % if full: </head> <body> % endif <h2>Error !</h2> <% tback = RichTraceback(error=error, traceback=traceback) src = tback.source line = tback.lineno if src: lines = src.split('\n') else: lines = None %> <h3>${tback.errorname}: ${tback.message|h}</h3> % if lines: <div class="sample"> <div class="nonhighlight"> % for index in range(max(0, line-4),min(len(lines), line+5)): <% if pygments_html_formatter: pygments_html_formatter.linenostart = index + 1 %> % if index + 1 == line: <% if pygments_html_formatter: old_cssclass = pygments_html_formatter.cssclass pygments_html_formatter.cssclass = 'error ' + old_cssclass %> ${lines[index] | syntax_highlight(language='mako')} <% if pygments_html_formatter: pygments_html_formatter.cssclass = old_cssclass %> % else: ${lines[index] | syntax_highlight(language='mako')} % endif % endfor </div> </div> % endif <div class="stacktrace"> % for (filename, lineno, function, line) in tback.reverse_traceback: <div class="location">${filename}, line ${lineno}:</div> <div class="nonhighlight"> <% if pygments_html_formatter: pygments_html_formatter.linenostart = lineno %> <div class="sourceline">${line | syntax_highlight(filename)}</div> </div> % endfor </div> % if full: </body> </html> % endif ]]]]
keyword[def] identifier[html_error_template] (): literal[string] keyword[import] identifier[mako] . identifier[template] keyword[return] identifier[mako] . identifier[template] . identifier[Template] ( literal[string] , identifier[output_encoding] = identifier[sys] . identifier[getdefaultencoding] (), identifier[encoding_errors] = literal[string] )
def html_error_template(): """Provides a template that renders a stack trace in an HTML format, providing an excerpt of code as well as substituting source template filenames, line numbers and code for that of the originating source template, as applicable. The template's default ``encoding_errors`` value is ``'htmlentityreplace'``. The template has two options. With the ``full`` option disabled, only a section of an HTML document is returned. With the ``css`` option disabled, the default stylesheet won't be included. """ import mako.template return mako.template.Template('\n<%!\n from mako.exceptions import RichTraceback, syntax_highlight,\\\n pygments_html_formatter\n%>\n<%page args="full=True, css=True, error=None, traceback=None"/>\n% if full:\n<html>\n<head>\n <title>Mako Runtime Error</title>\n% endif\n% if css:\n <style>\n body { font-family:verdana; margin:10px 30px 10px 30px;}\n .stacktrace { margin:5px 5px 5px 5px; }\n .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; }\n .nonhighlight { padding:0px; background-color:#DFDFDF; }\n .sample { padding:10px; margin:10px 10px 10px 10px;\n font-family:monospace; }\n .sampleline { padding:0px 10px 0px 10px; }\n .sourceline { margin:5px 5px 10px 5px; font-family:monospace;}\n .location { font-size:80%; }\n .highlight { white-space:pre; }\n .sampleline { white-space:pre; }\n\n % if pygments_html_formatter:\n ${pygments_html_formatter.get_style_defs()}\n .linenos { min-width: 2.5em; text-align: right; }\n pre { margin: 0; }\n .syntax-highlighted { padding: 0 10px; }\n .syntax-highlightedtable { border-spacing: 1px; }\n .nonhighlight { border-top: 1px solid #DFDFDF;\n border-bottom: 1px solid #DFDFDF; }\n .stacktrace .nonhighlight { margin: 5px 15px 10px; }\n .sourceline { margin: 0 0; font-family:monospace; }\n .code { background-color: #F8F8F8; width: 100%; }\n .error .code { background-color: #FFBDBD; }\n .error .syntax-highlighted { background-color: #FFBDBD; }\n % endif\n\n </style>\n% endif\n% if full:\n</head>\n<body>\n% endif\n\n<h2>Error !</h2>\n<%\n tback = RichTraceback(error=error, traceback=traceback)\n src = tback.source\n line = tback.lineno\n if src:\n lines = src.split(\'\\n\')\n else:\n lines = None\n%>\n<h3>${tback.errorname}: ${tback.message|h}</h3>\n\n% if lines:\n <div class="sample">\n <div class="nonhighlight">\n% for index in range(max(0, line-4),min(len(lines), line+5)):\n <%\n if pygments_html_formatter:\n pygments_html_formatter.linenostart = index + 1\n %>\n % if index + 1 == line:\n <%\n if pygments_html_formatter:\n old_cssclass = pygments_html_formatter.cssclass\n pygments_html_formatter.cssclass = \'error \' + old_cssclass\n %>\n ${lines[index] | syntax_highlight(language=\'mako\')}\n <%\n if pygments_html_formatter:\n pygments_html_formatter.cssclass = old_cssclass\n %>\n % else:\n ${lines[index] | syntax_highlight(language=\'mako\')}\n % endif\n% endfor\n </div>\n </div>\n% endif\n\n<div class="stacktrace">\n% for (filename, lineno, function, line) in tback.reverse_traceback:\n <div class="location">${filename}, line ${lineno}:</div>\n <div class="nonhighlight">\n <%\n if pygments_html_formatter:\n pygments_html_formatter.linenostart = lineno\n %>\n <div class="sourceline">${line | syntax_highlight(filename)}</div>\n </div>\n% endfor\n</div>\n\n% if full:\n</body>\n</html>\n% endif\n', output_encoding=sys.getdefaultencoding(), encoding_errors='htmlentityreplace')
def dtpool(name): """ Return the data about a kernel pool variable. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dtpool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :return: Number of values returned for name, Type of the variable "C", "N", or "X". :rtype: tuple """ name = stypes.stringToCharP(name) found = ctypes.c_int() n = ctypes.c_int() typeout = ctypes.c_char() libspice.dtpool_c(name, ctypes.byref(found), ctypes.byref(n), ctypes.byref(typeout)) return n.value, stypes.toPythonString(typeout.value), bool(found.value)
def function[dtpool, parameter[name]]: constant[ Return the data about a kernel pool variable. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dtpool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :return: Number of values returned for name, Type of the variable "C", "N", or "X". :rtype: tuple ] variable[name] assign[=] call[name[stypes].stringToCharP, parameter[name[name]]] variable[found] assign[=] call[name[ctypes].c_int, parameter[]] variable[n] assign[=] call[name[ctypes].c_int, parameter[]] variable[typeout] assign[=] call[name[ctypes].c_char, parameter[]] call[name[libspice].dtpool_c, parameter[name[name], call[name[ctypes].byref, parameter[name[found]]], call[name[ctypes].byref, parameter[name[n]]], call[name[ctypes].byref, parameter[name[typeout]]]]] return[tuple[[<ast.Attribute object at 0x7da18f09ca30>, <ast.Call object at 0x7da18f09cac0>, <ast.Call object at 0x7da18f09c520>]]]
keyword[def] identifier[dtpool] ( identifier[name] ): literal[string] identifier[name] = identifier[stypes] . identifier[stringToCharP] ( identifier[name] ) identifier[found] = identifier[ctypes] . identifier[c_int] () identifier[n] = identifier[ctypes] . identifier[c_int] () identifier[typeout] = identifier[ctypes] . identifier[c_char] () identifier[libspice] . identifier[dtpool_c] ( identifier[name] , identifier[ctypes] . identifier[byref] ( identifier[found] ), identifier[ctypes] . identifier[byref] ( identifier[n] ), identifier[ctypes] . identifier[byref] ( identifier[typeout] )) keyword[return] identifier[n] . identifier[value] , identifier[stypes] . identifier[toPythonString] ( identifier[typeout] . identifier[value] ), identifier[bool] ( identifier[found] . identifier[value] )
def dtpool(name): """ Return the data about a kernel pool variable. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dtpool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :return: Number of values returned for name, Type of the variable "C", "N", or "X". :rtype: tuple """ name = stypes.stringToCharP(name) found = ctypes.c_int() n = ctypes.c_int() typeout = ctypes.c_char() libspice.dtpool_c(name, ctypes.byref(found), ctypes.byref(n), ctypes.byref(typeout)) return (n.value, stypes.toPythonString(typeout.value), bool(found.value))
def add_editor(self, username, _delete=False, *args, **kwargs): """Add an editor to this wiki page. :param username: The name or Redditor object of the user to add. :param _delete: If True, remove the user as an editor instead. Please use :meth:`remove_editor` rather than setting it manually. Additional parameters are passed into :meth:`~praw.__init__.BaseReddit.request_json`. """ url = self.reddit_session.config['wiki_page_editor'] url = url.format(subreddit=six.text_type(self.subreddit), method='del' if _delete else 'add') data = {'page': self.page, 'username': six.text_type(username)} return self.reddit_session.request_json(url, data=data, *args, **kwargs)
def function[add_editor, parameter[self, username, _delete]]: constant[Add an editor to this wiki page. :param username: The name or Redditor object of the user to add. :param _delete: If True, remove the user as an editor instead. Please use :meth:`remove_editor` rather than setting it manually. Additional parameters are passed into :meth:`~praw.__init__.BaseReddit.request_json`. ] variable[url] assign[=] call[name[self].reddit_session.config][constant[wiki_page_editor]] variable[url] assign[=] call[name[url].format, parameter[]] variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da20c76d360>, <ast.Constant object at 0x7da20c76f430>], [<ast.Attribute object at 0x7da20c76e8f0>, <ast.Call object at 0x7da20c76fa00>]] return[call[name[self].reddit_session.request_json, parameter[name[url], <ast.Starred object at 0x7da20c76ca00>]]]
keyword[def] identifier[add_editor] ( identifier[self] , identifier[username] , identifier[_delete] = keyword[False] ,* identifier[args] ,** identifier[kwargs] ): literal[string] identifier[url] = identifier[self] . identifier[reddit_session] . identifier[config] [ literal[string] ] identifier[url] = identifier[url] . identifier[format] ( identifier[subreddit] = identifier[six] . identifier[text_type] ( identifier[self] . identifier[subreddit] ), identifier[method] = literal[string] keyword[if] identifier[_delete] keyword[else] literal[string] ) identifier[data] ={ literal[string] : identifier[self] . identifier[page] , literal[string] : identifier[six] . identifier[text_type] ( identifier[username] )} keyword[return] identifier[self] . identifier[reddit_session] . identifier[request_json] ( identifier[url] , identifier[data] = identifier[data] ,* identifier[args] , ** identifier[kwargs] )
def add_editor(self, username, _delete=False, *args, **kwargs): """Add an editor to this wiki page. :param username: The name or Redditor object of the user to add. :param _delete: If True, remove the user as an editor instead. Please use :meth:`remove_editor` rather than setting it manually. Additional parameters are passed into :meth:`~praw.__init__.BaseReddit.request_json`. """ url = self.reddit_session.config['wiki_page_editor'] url = url.format(subreddit=six.text_type(self.subreddit), method='del' if _delete else 'add') data = {'page': self.page, 'username': six.text_type(username)} return self.reddit_session.request_json(url, *args, data=data, **kwargs)
def ITS90_68_difference(T): r'''Calculates the difference between ITS-90 and ITS-68 scales using a series of models listed in [1]_, [2]_, and [3]_. The temperature difference is given by the following equations: From 13.8 K to 73.15 K: .. math:: T_{90} - T_{68} = a_0 + \sum_{i=1}^{12} a_i[(T_{90}/K-40)/40]^i From 83.8 K to 903.75 K: .. math:: T_{90} - T_{68} = \sum_{i=1}^8 b_i[(T_{90}/K - 273.15)/630]^i From 903.75 K to 1337.33 K: .. math:: T_{90} - T_{68} = \sum_{i=0}^5 c_i[T_{90}/^\circ C]^i Above 1337.33 K: .. math:: T_{90} - T_{68} = -1.398\cdot 10^{-7}\left(\frac{T_{90}}{K}\right)^2 Parameters ---------- T : float Temperature, ITS-90, or approximately ITS-68 [K] Returns ------- dT : float Temperature, difference between ITS-90 and ITS-68 at T [K] Notes ----- The conversion is straightforward when T90 is known. Theoretically, the model should be solved numerically to convert the reverse way. However, according to [4]_, the difference is under 0.05 mK from 73.15 K to 903.15 K, and under 0.26 mK up to 1337.33 K. For temperatures under 13.8 K, no conversion is performed. The first set of coefficients are: -0.005903, 0.008174, -0.061924, -0.193388, 1.490793, 1.252347, -9.835868, 1.411912, 25.277595, -19.183815, -18.437089, 27.000895, -8.716324. The second set of coefficients are: 0, -0.148759, -0.267408, 1.08076, 1.269056, -4.089591, -1.871251, 7.438081, -3.536296. The third set of coefficients are: 7.8687209E1, -4.7135991E-1, 1.0954715E-3, -1.2357884E-6, 6.7736583E-10, -1.4458081E-13. These last coefficients use the temperature in degrees Celcius. A slightly older model used the following coefficients but a different equation over the same range: -0.00317, -0.97737, 1.2559, 2.03295, -5.91887, -3.23561, 7.23364, 5.04151. The model for these coefficients was: .. math:: T_{90} - T_{68} = c_0 + \sum_{i=1}^7 c_i[(T_{90}/K - 1173.15)/300]^i For temperatures larger than several thousand K, the differences have no meaning and grows quadratically. Examples -------- >>> ITS90_68_difference(1000.) 0.01231818956580355 References ---------- .. [1] Bedford, R. E., G. Bonnier, H. Maas, and F. Pavese. "Techniques for Approximating the International Temperature Scale of 1990." Bureau International Des Poids et Mesures, Sfievres, 1990. .. [2] Wier, Ron D., and Robert N. Goldberg. "On the Conversion of Thermodynamic Properties to the Basis of the International Temperature Scale of 1990." The Journal of Chemical Thermodynamics 28, no. 3 (March 1996): 261-76. doi:10.1006/jcht.1996.0026. .. [3] Goldberg, Robert N., and R. D. Weir. "Conversion of Temperatures and Thermodynamic Properties to the Basis of the International Temperature Scale of 1990 (Technical Report)." Pure and Applied Chemistry 64, no. 10 (1992): 1545-1562. doi:10.1351/pac199264101545. .. [4] Code10.info. "Conversions among International Temperature Scales." Accessed May 22, 2016. http://www.code10.info/index.php%3Foption%3Dcom_content%26view%3Darticle%26id%3D83:conversions-among-international-temperature-scales%26catid%3D60:temperature%26Itemid%3D83. ''' ais = [-0.005903, 0.008174, -0.061924, -0.193388, 1.490793, 1.252347, -9.835868, 1.411912, 25.277595, -19.183815, -18.437089, 27.000895, -8.716324] bis = [0, -0.148759, -0.267408, 1.08076, 1.269056, -4.089591, -1.871251, 7.438081, -3.536296] # cis = [-0.00317, -0.97737, 1.2559, 2.03295, -5.91887, -3.23561, 7.23364, # 5.04151] new_cs = [7.8687209E1, -4.7135991E-1, 1.0954715E-3, -1.2357884E-6, 6.7736583E-10, -1.4458081E-13] dT = 0 if T < 13.8: dT = 0 elif T >= 13.8 and T <= 73.15: for i in range(13): dT += ais[i]*((T - 40.)/40.)**i elif T > 73.15 and T < 83.8: dT = 0 elif T >= 83.8 and T <= 903.75: for i in range(9): dT += bis[i]*((T - 273.15)/630.)**i elif T > 903.75 and T <= 1337.33: # Revised function exists, but does not match the tabulated data # for i in range(8): # dT += cis[i]*((T - 1173.15)/300.)**i for i in range(6): dT += new_cs[i]*(T-273.15)**i elif T > 1337.33: dT = -1.398E-7*T**2 return dT
def function[ITS90_68_difference, parameter[T]]: constant[Calculates the difference between ITS-90 and ITS-68 scales using a series of models listed in [1]_, [2]_, and [3]_. The temperature difference is given by the following equations: From 13.8 K to 73.15 K: .. math:: T_{90} - T_{68} = a_0 + \sum_{i=1}^{12} a_i[(T_{90}/K-40)/40]^i From 83.8 K to 903.75 K: .. math:: T_{90} - T_{68} = \sum_{i=1}^8 b_i[(T_{90}/K - 273.15)/630]^i From 903.75 K to 1337.33 K: .. math:: T_{90} - T_{68} = \sum_{i=0}^5 c_i[T_{90}/^\circ C]^i Above 1337.33 K: .. math:: T_{90} - T_{68} = -1.398\cdot 10^{-7}\left(\frac{T_{90}}{K}\right)^2 Parameters ---------- T : float Temperature, ITS-90, or approximately ITS-68 [K] Returns ------- dT : float Temperature, difference between ITS-90 and ITS-68 at T [K] Notes ----- The conversion is straightforward when T90 is known. Theoretically, the model should be solved numerically to convert the reverse way. However, according to [4]_, the difference is under 0.05 mK from 73.15 K to 903.15 K, and under 0.26 mK up to 1337.33 K. For temperatures under 13.8 K, no conversion is performed. The first set of coefficients are: -0.005903, 0.008174, -0.061924, -0.193388, 1.490793, 1.252347, -9.835868, 1.411912, 25.277595, -19.183815, -18.437089, 27.000895, -8.716324. The second set of coefficients are: 0, -0.148759, -0.267408, 1.08076, 1.269056, -4.089591, -1.871251, 7.438081, -3.536296. The third set of coefficients are: 7.8687209E1, -4.7135991E-1, 1.0954715E-3, -1.2357884E-6, 6.7736583E-10, -1.4458081E-13. These last coefficients use the temperature in degrees Celcius. A slightly older model used the following coefficients but a different equation over the same range: -0.00317, -0.97737, 1.2559, 2.03295, -5.91887, -3.23561, 7.23364, 5.04151. The model for these coefficients was: .. math:: T_{90} - T_{68} = c_0 + \sum_{i=1}^7 c_i[(T_{90}/K - 1173.15)/300]^i For temperatures larger than several thousand K, the differences have no meaning and grows quadratically. Examples -------- >>> ITS90_68_difference(1000.) 0.01231818956580355 References ---------- .. [1] Bedford, R. E., G. Bonnier, H. Maas, and F. Pavese. "Techniques for Approximating the International Temperature Scale of 1990." Bureau International Des Poids et Mesures, Sfievres, 1990. .. [2] Wier, Ron D., and Robert N. Goldberg. "On the Conversion of Thermodynamic Properties to the Basis of the International Temperature Scale of 1990." The Journal of Chemical Thermodynamics 28, no. 3 (March 1996): 261-76. doi:10.1006/jcht.1996.0026. .. [3] Goldberg, Robert N., and R. D. Weir. "Conversion of Temperatures and Thermodynamic Properties to the Basis of the International Temperature Scale of 1990 (Technical Report)." Pure and Applied Chemistry 64, no. 10 (1992): 1545-1562. doi:10.1351/pac199264101545. .. [4] Code10.info. "Conversions among International Temperature Scales." Accessed May 22, 2016. http://www.code10.info/index.php%3Foption%3Dcom_content%26view%3Darticle%26id%3D83:conversions-among-international-temperature-scales%26catid%3D60:temperature%26Itemid%3D83. ] variable[ais] assign[=] list[[<ast.UnaryOp object at 0x7da204961c30>, <ast.Constant object at 0x7da204962650>, <ast.UnaryOp object at 0x7da2049610f0>, <ast.UnaryOp object at 0x7da204963ca0>, <ast.Constant object at 0x7da204960c70>, <ast.Constant object at 0x7da204963430>, <ast.UnaryOp object at 0x7da204961300>, <ast.Constant object at 0x7da2049601c0>, <ast.Constant object at 0x7da204962920>, <ast.UnaryOp object at 0x7da2049630d0>, <ast.UnaryOp object at 0x7da204960ac0>, <ast.Constant object at 0x7da2049628f0>, <ast.UnaryOp object at 0x7da204962ce0>]] variable[bis] assign[=] list[[<ast.Constant object at 0x7da204961390>, <ast.UnaryOp object at 0x7da204963d00>, <ast.UnaryOp object at 0x7da2049605b0>, <ast.Constant object at 0x7da204960df0>, <ast.Constant object at 0x7da204960b20>, <ast.UnaryOp object at 0x7da204961900>, <ast.UnaryOp object at 0x7da204962fb0>, <ast.Constant object at 0x7da2049608b0>, <ast.UnaryOp object at 0x7da204963a00>]] variable[new_cs] assign[=] list[[<ast.Constant object at 0x7da2049623e0>, <ast.UnaryOp object at 0x7da204962830>, <ast.Constant object at 0x7da204961e40>, <ast.UnaryOp object at 0x7da204962e00>, <ast.Constant object at 0x7da204961c00>, <ast.UnaryOp object at 0x7da204961150>]] variable[dT] assign[=] constant[0] if compare[name[T] less[<] constant[13.8]] begin[:] variable[dT] assign[=] constant[0] return[name[dT]]
keyword[def] identifier[ITS90_68_difference] ( identifier[T] ): literal[string] identifier[ais] =[- literal[int] , literal[int] ,- literal[int] ,- literal[int] , literal[int] , literal[int] , - literal[int] , literal[int] , literal[int] ,- literal[int] ,- literal[int] , literal[int] , - literal[int] ] identifier[bis] =[ literal[int] ,- literal[int] ,- literal[int] , literal[int] , literal[int] ,- literal[int] ,- literal[int] , literal[int] ,- literal[int] ] identifier[new_cs] =[ literal[int] ,- literal[int] , literal[int] ,- literal[int] , literal[int] ,- literal[int] ] identifier[dT] = literal[int] keyword[if] identifier[T] < literal[int] : identifier[dT] = literal[int] keyword[elif] identifier[T] >= literal[int] keyword[and] identifier[T] <= literal[int] : keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] ): identifier[dT] += identifier[ais] [ identifier[i] ]*(( identifier[T] - literal[int] )/ literal[int] )** identifier[i] keyword[elif] identifier[T] > literal[int] keyword[and] identifier[T] < literal[int] : identifier[dT] = literal[int] keyword[elif] identifier[T] >= literal[int] keyword[and] identifier[T] <= literal[int] : keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] ): identifier[dT] += identifier[bis] [ identifier[i] ]*(( identifier[T] - literal[int] )/ literal[int] )** identifier[i] keyword[elif] identifier[T] > literal[int] keyword[and] identifier[T] <= literal[int] : keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] ): identifier[dT] += identifier[new_cs] [ identifier[i] ]*( identifier[T] - literal[int] )** identifier[i] keyword[elif] identifier[T] > literal[int] : identifier[dT] =- literal[int] * identifier[T] ** literal[int] keyword[return] identifier[dT]
def ITS90_68_difference(T): """Calculates the difference between ITS-90 and ITS-68 scales using a series of models listed in [1]_, [2]_, and [3]_. The temperature difference is given by the following equations: From 13.8 K to 73.15 K: .. math:: T_{90} - T_{68} = a_0 + \\sum_{i=1}^{12} a_i[(T_{90}/K-40)/40]^i From 83.8 K to 903.75 K: .. math:: T_{90} - T_{68} = \\sum_{i=1}^8 b_i[(T_{90}/K - 273.15)/630]^i From 903.75 K to 1337.33 K: .. math:: T_{90} - T_{68} = \\sum_{i=0}^5 c_i[T_{90}/^\\circ C]^i Above 1337.33 K: .. math:: T_{90} - T_{68} = -1.398\\cdot 10^{-7}\\left(\\frac{T_{90}}{K}\\right)^2 Parameters ---------- T : float Temperature, ITS-90, or approximately ITS-68 [K] Returns ------- dT : float Temperature, difference between ITS-90 and ITS-68 at T [K] Notes ----- The conversion is straightforward when T90 is known. Theoretically, the model should be solved numerically to convert the reverse way. However, according to [4]_, the difference is under 0.05 mK from 73.15 K to 903.15 K, and under 0.26 mK up to 1337.33 K. For temperatures under 13.8 K, no conversion is performed. The first set of coefficients are: -0.005903, 0.008174, -0.061924, -0.193388, 1.490793, 1.252347, -9.835868, 1.411912, 25.277595, -19.183815, -18.437089, 27.000895, -8.716324. The second set of coefficients are: 0, -0.148759, -0.267408, 1.08076, 1.269056, -4.089591, -1.871251, 7.438081, -3.536296. The third set of coefficients are: 7.8687209E1, -4.7135991E-1, 1.0954715E-3, -1.2357884E-6, 6.7736583E-10, -1.4458081E-13. These last coefficients use the temperature in degrees Celcius. A slightly older model used the following coefficients but a different equation over the same range: -0.00317, -0.97737, 1.2559, 2.03295, -5.91887, -3.23561, 7.23364, 5.04151. The model for these coefficients was: .. math:: T_{90} - T_{68} = c_0 + \\sum_{i=1}^7 c_i[(T_{90}/K - 1173.15)/300]^i For temperatures larger than several thousand K, the differences have no meaning and grows quadratically. Examples -------- >>> ITS90_68_difference(1000.) 0.01231818956580355 References ---------- .. [1] Bedford, R. E., G. Bonnier, H. Maas, and F. Pavese. "Techniques for Approximating the International Temperature Scale of 1990." Bureau International Des Poids et Mesures, Sfievres, 1990. .. [2] Wier, Ron D., and Robert N. Goldberg. "On the Conversion of Thermodynamic Properties to the Basis of the International Temperature Scale of 1990." The Journal of Chemical Thermodynamics 28, no. 3 (March 1996): 261-76. doi:10.1006/jcht.1996.0026. .. [3] Goldberg, Robert N., and R. D. Weir. "Conversion of Temperatures and Thermodynamic Properties to the Basis of the International Temperature Scale of 1990 (Technical Report)." Pure and Applied Chemistry 64, no. 10 (1992): 1545-1562. doi:10.1351/pac199264101545. .. [4] Code10.info. "Conversions among International Temperature Scales." Accessed May 22, 2016. http://www.code10.info/index.php%3Foption%3Dcom_content%26view%3Darticle%26id%3D83:conversions-among-international-temperature-scales%26catid%3D60:temperature%26Itemid%3D83. """ ais = [-0.005903, 0.008174, -0.061924, -0.193388, 1.490793, 1.252347, -9.835868, 1.411912, 25.277595, -19.183815, -18.437089, 27.000895, -8.716324] bis = [0, -0.148759, -0.267408, 1.08076, 1.269056, -4.089591, -1.871251, 7.438081, -3.536296] # cis = [-0.00317, -0.97737, 1.2559, 2.03295, -5.91887, -3.23561, 7.23364, # 5.04151] new_cs = [78.687209, -0.47135991, 0.0010954715, -1.2357884e-06, 6.7736583e-10, -1.4458081e-13] dT = 0 if T < 13.8: dT = 0 # depends on [control=['if'], data=[]] elif T >= 13.8 and T <= 73.15: for i in range(13): dT += ais[i] * ((T - 40.0) / 40.0) ** i # depends on [control=['for'], data=['i']] # depends on [control=['if'], data=[]] elif T > 73.15 and T < 83.8: dT = 0 # depends on [control=['if'], data=[]] elif T >= 83.8 and T <= 903.75: for i in range(9): dT += bis[i] * ((T - 273.15) / 630.0) ** i # depends on [control=['for'], data=['i']] # depends on [control=['if'], data=[]] elif T > 903.75 and T <= 1337.33: # Revised function exists, but does not match the tabulated data # for i in range(8): # dT += cis[i]*((T - 1173.15)/300.)**i for i in range(6): dT += new_cs[i] * (T - 273.15) ** i # depends on [control=['for'], data=['i']] # depends on [control=['if'], data=[]] elif T > 1337.33: dT = -1.398e-07 * T ** 2 # depends on [control=['if'], data=['T']] return dT
def get(self, name, default=NO_DEFAULT): """ Return the specified name from the root section. Parameters: name (str): The name of the requested value. default (optional): If set, the default value to use instead of raising :class:`LoggedFailure` for unknown names. Returns: The value for `name`. Raises: LoggedFailure: The requested `name` was not found. """ values = self.load() try: return values[name] except KeyError: if default is self.NO_DEFAULT: raise LoggedFailure("Configuration value '{}' not found in root section!".format(name)) return default
def function[get, parameter[self, name, default]]: constant[ Return the specified name from the root section. Parameters: name (str): The name of the requested value. default (optional): If set, the default value to use instead of raising :class:`LoggedFailure` for unknown names. Returns: The value for `name`. Raises: LoggedFailure: The requested `name` was not found. ] variable[values] assign[=] call[name[self].load, parameter[]] <ast.Try object at 0x7da20c6a8490>
keyword[def] identifier[get] ( identifier[self] , identifier[name] , identifier[default] = identifier[NO_DEFAULT] ): literal[string] identifier[values] = identifier[self] . identifier[load] () keyword[try] : keyword[return] identifier[values] [ identifier[name] ] keyword[except] identifier[KeyError] : keyword[if] identifier[default] keyword[is] identifier[self] . identifier[NO_DEFAULT] : keyword[raise] identifier[LoggedFailure] ( literal[string] . identifier[format] ( identifier[name] )) keyword[return] identifier[default]
def get(self, name, default=NO_DEFAULT): """ Return the specified name from the root section. Parameters: name (str): The name of the requested value. default (optional): If set, the default value to use instead of raising :class:`LoggedFailure` for unknown names. Returns: The value for `name`. Raises: LoggedFailure: The requested `name` was not found. """ values = self.load() try: return values[name] # depends on [control=['try'], data=[]] except KeyError: if default is self.NO_DEFAULT: raise LoggedFailure("Configuration value '{}' not found in root section!".format(name)) # depends on [control=['if'], data=[]] return default # depends on [control=['except'], data=[]]
def addLadder(settings): """define a new Ladder setting and save to disk file""" ladder = Ladder(settings) ladder.save() getKnownLadders()[ladder.name] = ladder return ladder
def function[addLadder, parameter[settings]]: constant[define a new Ladder setting and save to disk file] variable[ladder] assign[=] call[name[Ladder], parameter[name[settings]]] call[name[ladder].save, parameter[]] call[call[name[getKnownLadders], parameter[]]][name[ladder].name] assign[=] name[ladder] return[name[ladder]]
keyword[def] identifier[addLadder] ( identifier[settings] ): literal[string] identifier[ladder] = identifier[Ladder] ( identifier[settings] ) identifier[ladder] . identifier[save] () identifier[getKnownLadders] ()[ identifier[ladder] . identifier[name] ]= identifier[ladder] keyword[return] identifier[ladder]
def addLadder(settings): """define a new Ladder setting and save to disk file""" ladder = Ladder(settings) ladder.save() getKnownLadders()[ladder.name] = ladder return ladder
def tf_loss_per_instance(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): """ Creates the TensorFlow operations for calculating the loss per batch instance. Args: states: Dict of state tensors. internals: Dict of prior internal state tensors. actions: Dict of action tensors. terminal: Terminal boolean tensor. reward: Reward tensor. next_states: Dict of successor state tensors. next_internals: List of posterior internal state tensors. update: Boolean tensor indicating whether this call happens during an update. reference: Optional reference tensor(s), in case of a comparative loss. Returns: Loss per instance tensor. """ raise NotImplementedError
def function[tf_loss_per_instance, parameter[self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference]]: constant[ Creates the TensorFlow operations for calculating the loss per batch instance. Args: states: Dict of state tensors. internals: Dict of prior internal state tensors. actions: Dict of action tensors. terminal: Terminal boolean tensor. reward: Reward tensor. next_states: Dict of successor state tensors. next_internals: List of posterior internal state tensors. update: Boolean tensor indicating whether this call happens during an update. reference: Optional reference tensor(s), in case of a comparative loss. Returns: Loss per instance tensor. ] <ast.Raise object at 0x7da2041da0e0>
keyword[def] identifier[tf_loss_per_instance] ( identifier[self] , identifier[states] , identifier[internals] , identifier[actions] , identifier[terminal] , identifier[reward] , identifier[next_states] , identifier[next_internals] , identifier[update] , identifier[reference] = keyword[None] ): literal[string] keyword[raise] identifier[NotImplementedError]
def tf_loss_per_instance(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): """ Creates the TensorFlow operations for calculating the loss per batch instance. Args: states: Dict of state tensors. internals: Dict of prior internal state tensors. actions: Dict of action tensors. terminal: Terminal boolean tensor. reward: Reward tensor. next_states: Dict of successor state tensors. next_internals: List of posterior internal state tensors. update: Boolean tensor indicating whether this call happens during an update. reference: Optional reference tensor(s), in case of a comparative loss. Returns: Loss per instance tensor. """ raise NotImplementedError
def from_path(cls, path: pathlib.Path) -> 'File': """ Create a file entity from a file path. :param path: The path of the file. :return: A file entity instance representing the file. :raises ValueError: If the path does not point to a file. """ if not path.is_file(): raise ValueError('Path does not point to a file') return File(path.name, path.stat().st_size, cls._md5(path))
def function[from_path, parameter[cls, path]]: constant[ Create a file entity from a file path. :param path: The path of the file. :return: A file entity instance representing the file. :raises ValueError: If the path does not point to a file. ] if <ast.UnaryOp object at 0x7da1b2241c00> begin[:] <ast.Raise object at 0x7da1b2240820> return[call[name[File], parameter[name[path].name, call[name[path].stat, parameter[]].st_size, call[name[cls]._md5, parameter[name[path]]]]]]
keyword[def] identifier[from_path] ( identifier[cls] , identifier[path] : identifier[pathlib] . identifier[Path] )-> literal[string] : literal[string] keyword[if] keyword[not] identifier[path] . identifier[is_file] (): keyword[raise] identifier[ValueError] ( literal[string] ) keyword[return] identifier[File] ( identifier[path] . identifier[name] , identifier[path] . identifier[stat] (). identifier[st_size] , identifier[cls] . identifier[_md5] ( identifier[path] ))
def from_path(cls, path: pathlib.Path) -> 'File': """ Create a file entity from a file path. :param path: The path of the file. :return: A file entity instance representing the file. :raises ValueError: If the path does not point to a file. """ if not path.is_file(): raise ValueError('Path does not point to a file') # depends on [control=['if'], data=[]] return File(path.name, path.stat().st_size, cls._md5(path))
def add_page(self, page, default = True): r""" Add a display page to the display. :param page: Page to be added :type display_id: ``DisplayPage`` :param default: True if this page should be shown upon initialization. :type name: ``bool`` """ self._pages[page.page_id] = page page._add_display(self) if default or not self._active_page: self._active_page = page
def function[add_page, parameter[self, page, default]]: constant[ Add a display page to the display. :param page: Page to be added :type display_id: ``DisplayPage`` :param default: True if this page should be shown upon initialization. :type name: ``bool`` ] call[name[self]._pages][name[page].page_id] assign[=] name[page] call[name[page]._add_display, parameter[name[self]]] if <ast.BoolOp object at 0x7da1b15f2c50> begin[:] name[self]._active_page assign[=] name[page]
keyword[def] identifier[add_page] ( identifier[self] , identifier[page] , identifier[default] = keyword[True] ): literal[string] identifier[self] . identifier[_pages] [ identifier[page] . identifier[page_id] ]= identifier[page] identifier[page] . identifier[_add_display] ( identifier[self] ) keyword[if] identifier[default] keyword[or] keyword[not] identifier[self] . identifier[_active_page] : identifier[self] . identifier[_active_page] = identifier[page]
def add_page(self, page, default=True): """ Add a display page to the display. :param page: Page to be added :type display_id: ``DisplayPage`` :param default: True if this page should be shown upon initialization. :type name: ``bool`` """ self._pages[page.page_id] = page page._add_display(self) if default or not self._active_page: self._active_page = page # depends on [control=['if'], data=[]]
def _make_absolute(self, link): """Makes a given link absolute.""" # Parse the link with stdlib. parsed = urlparse(link)._asdict() # If link is relative, then join it with base_url. if not parsed['netloc']: return urljoin(self.base_url, link) # Link is absolute; if it lacks a scheme, add one from base_url. if not parsed['scheme']: parsed['scheme'] = urlparse(self.base_url).scheme # Reconstruct the URL to incorporate the new scheme. parsed = (v for v in parsed.values()) return urlunparse(parsed) # Link is absolute and complete with scheme; nothing to be done here. return link
def function[_make_absolute, parameter[self, link]]: constant[Makes a given link absolute.] variable[parsed] assign[=] call[call[name[urlparse], parameter[name[link]]]._asdict, parameter[]] if <ast.UnaryOp object at 0x7da1b1f2e410> begin[:] return[call[name[urljoin], parameter[name[self].base_url, name[link]]]] if <ast.UnaryOp object at 0x7da1b1f2ee00> begin[:] call[name[parsed]][constant[scheme]] assign[=] call[name[urlparse], parameter[name[self].base_url]].scheme variable[parsed] assign[=] <ast.GeneratorExp object at 0x7da1b1f2df90> return[call[name[urlunparse], parameter[name[parsed]]]] return[name[link]]
keyword[def] identifier[_make_absolute] ( identifier[self] , identifier[link] ): literal[string] identifier[parsed] = identifier[urlparse] ( identifier[link] ). identifier[_asdict] () keyword[if] keyword[not] identifier[parsed] [ literal[string] ]: keyword[return] identifier[urljoin] ( identifier[self] . identifier[base_url] , identifier[link] ) keyword[if] keyword[not] identifier[parsed] [ literal[string] ]: identifier[parsed] [ literal[string] ]= identifier[urlparse] ( identifier[self] . identifier[base_url] ). identifier[scheme] identifier[parsed] =( identifier[v] keyword[for] identifier[v] keyword[in] identifier[parsed] . identifier[values] ()) keyword[return] identifier[urlunparse] ( identifier[parsed] ) keyword[return] identifier[link]
def _make_absolute(self, link): """Makes a given link absolute.""" # Parse the link with stdlib. parsed = urlparse(link)._asdict() # If link is relative, then join it with base_url. if not parsed['netloc']: return urljoin(self.base_url, link) # depends on [control=['if'], data=[]] # Link is absolute; if it lacks a scheme, add one from base_url. if not parsed['scheme']: parsed['scheme'] = urlparse(self.base_url).scheme # Reconstruct the URL to incorporate the new scheme. parsed = (v for v in parsed.values()) return urlunparse(parsed) # depends on [control=['if'], data=[]] # Link is absolute and complete with scheme; nothing to be done here. return link
def _notify(p, **data): """The callback func that will be hooked to the ``notify`` command""" message = data.get("message") if not message and not sys.stdin.isatty(): message = click.get_text_stream("stdin").read() data["message"] = message data = clean_data(data) ctx = click.get_current_context() if ctx.obj.get("env_prefix"): data["env_prefix"] = ctx.obj["env_prefix"] rsp = p.notify(**data) rsp.raise_on_errors() click.secho(f"Succesfully sent a notification to {p.name}!", fg="green")
def function[_notify, parameter[p]]: constant[The callback func that will be hooked to the ``notify`` command] variable[message] assign[=] call[name[data].get, parameter[constant[message]]] if <ast.BoolOp object at 0x7da1b2095ab0> begin[:] variable[message] assign[=] call[call[name[click].get_text_stream, parameter[constant[stdin]]].read, parameter[]] call[name[data]][constant[message]] assign[=] name[message] variable[data] assign[=] call[name[clean_data], parameter[name[data]]] variable[ctx] assign[=] call[name[click].get_current_context, parameter[]] if call[name[ctx].obj.get, parameter[constant[env_prefix]]] begin[:] call[name[data]][constant[env_prefix]] assign[=] call[name[ctx].obj][constant[env_prefix]] variable[rsp] assign[=] call[name[p].notify, parameter[]] call[name[rsp].raise_on_errors, parameter[]] call[name[click].secho, parameter[<ast.JoinedStr object at 0x7da1b1e92350>]]
keyword[def] identifier[_notify] ( identifier[p] ,** identifier[data] ): literal[string] identifier[message] = identifier[data] . identifier[get] ( literal[string] ) keyword[if] keyword[not] identifier[message] keyword[and] keyword[not] identifier[sys] . identifier[stdin] . identifier[isatty] (): identifier[message] = identifier[click] . identifier[get_text_stream] ( literal[string] ). identifier[read] () identifier[data] [ literal[string] ]= identifier[message] identifier[data] = identifier[clean_data] ( identifier[data] ) identifier[ctx] = identifier[click] . identifier[get_current_context] () keyword[if] identifier[ctx] . identifier[obj] . identifier[get] ( literal[string] ): identifier[data] [ literal[string] ]= identifier[ctx] . identifier[obj] [ literal[string] ] identifier[rsp] = identifier[p] . identifier[notify] (** identifier[data] ) identifier[rsp] . identifier[raise_on_errors] () identifier[click] . identifier[secho] ( literal[string] , identifier[fg] = literal[string] )
def _notify(p, **data): """The callback func that will be hooked to the ``notify`` command""" message = data.get('message') if not message and (not sys.stdin.isatty()): message = click.get_text_stream('stdin').read() # depends on [control=['if'], data=[]] data['message'] = message data = clean_data(data) ctx = click.get_current_context() if ctx.obj.get('env_prefix'): data['env_prefix'] = ctx.obj['env_prefix'] # depends on [control=['if'], data=[]] rsp = p.notify(**data) rsp.raise_on_errors() click.secho(f'Succesfully sent a notification to {p.name}!', fg='green')
def __write(self, output, binary=False): """write data on the nodemcu port. If 'binary' is True the debug log will show the intended output as hex, otherwise as string""" if not binary: log.debug('write: %s', output) else: log.debug('write binary: %s', hexify(output)) self._port.write(output) self._port.flush()
def function[__write, parameter[self, output, binary]]: constant[write data on the nodemcu port. If 'binary' is True the debug log will show the intended output as hex, otherwise as string] if <ast.UnaryOp object at 0x7da1b00f64a0> begin[:] call[name[log].debug, parameter[constant[write: %s], name[output]]] call[name[self]._port.write, parameter[name[output]]] call[name[self]._port.flush, parameter[]]
keyword[def] identifier[__write] ( identifier[self] , identifier[output] , identifier[binary] = keyword[False] ): literal[string] keyword[if] keyword[not] identifier[binary] : identifier[log] . identifier[debug] ( literal[string] , identifier[output] ) keyword[else] : identifier[log] . identifier[debug] ( literal[string] , identifier[hexify] ( identifier[output] )) identifier[self] . identifier[_port] . identifier[write] ( identifier[output] ) identifier[self] . identifier[_port] . identifier[flush] ()
def __write(self, output, binary=False): """write data on the nodemcu port. If 'binary' is True the debug log will show the intended output as hex, otherwise as string""" if not binary: log.debug('write: %s', output) # depends on [control=['if'], data=[]] else: log.debug('write binary: %s', hexify(output)) self._port.write(output) self._port.flush()
def forall(self, method): """ TODO: I AM NOT HAPPY THAT THIS WILL NOT WORK WELL WITH WINDOW FUNCTIONS THE parts GIVE NO INDICATION OF NEXT ITEM OR PREVIOUS ITEM LIKE rownum DOES. MAYBE ALGEBRAIC EDGES SHOULD BE LOOPED DIFFERENTLY? ON THE OTHER HAND, MAYBE WINDOW FUNCTIONS ARE RESPONSIBLE FOR THIS COMPLICATION MAR 2015: THE ISSUE IS parts, IT SHOULD BE coord INSTEAD IT IS EXPECTED THE method ACCEPTS (value, coord, cube), WHERE value - VALUE FOUND AT ELEMENT parts - THE ONE PART CORRESPONDING TO EACH EDGE cube - THE WHOLE CUBE, FOR USE IN WINDOW FUNCTIONS """ if not self.is_value: Log.error("Not dealing with this case yet") matrix = self.data.values()[0] parts = [e.domain.partitions for e in self.edges] for c in matrix._all_combos(): method(matrix[c], [parts[i][cc] for i, cc in enumerate(c)], self)
def function[forall, parameter[self, method]]: constant[ TODO: I AM NOT HAPPY THAT THIS WILL NOT WORK WELL WITH WINDOW FUNCTIONS THE parts GIVE NO INDICATION OF NEXT ITEM OR PREVIOUS ITEM LIKE rownum DOES. MAYBE ALGEBRAIC EDGES SHOULD BE LOOPED DIFFERENTLY? ON THE OTHER HAND, MAYBE WINDOW FUNCTIONS ARE RESPONSIBLE FOR THIS COMPLICATION MAR 2015: THE ISSUE IS parts, IT SHOULD BE coord INSTEAD IT IS EXPECTED THE method ACCEPTS (value, coord, cube), WHERE value - VALUE FOUND AT ELEMENT parts - THE ONE PART CORRESPONDING TO EACH EDGE cube - THE WHOLE CUBE, FOR USE IN WINDOW FUNCTIONS ] if <ast.UnaryOp object at 0x7da1b0ba9540> begin[:] call[name[Log].error, parameter[constant[Not dealing with this case yet]]] variable[matrix] assign[=] call[call[name[self].data.values, parameter[]]][constant[0]] variable[parts] assign[=] <ast.ListComp object at 0x7da1b0b72e90> for taget[name[c]] in starred[call[name[matrix]._all_combos, parameter[]]] begin[:] call[name[method], parameter[call[name[matrix]][name[c]], <ast.ListComp object at 0x7da1b0aed150>, name[self]]]
keyword[def] identifier[forall] ( identifier[self] , identifier[method] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[is_value] : identifier[Log] . identifier[error] ( literal[string] ) identifier[matrix] = identifier[self] . identifier[data] . identifier[values] ()[ literal[int] ] identifier[parts] =[ identifier[e] . identifier[domain] . identifier[partitions] keyword[for] identifier[e] keyword[in] identifier[self] . identifier[edges] ] keyword[for] identifier[c] keyword[in] identifier[matrix] . identifier[_all_combos] (): identifier[method] ( identifier[matrix] [ identifier[c] ],[ identifier[parts] [ identifier[i] ][ identifier[cc] ] keyword[for] identifier[i] , identifier[cc] keyword[in] identifier[enumerate] ( identifier[c] )], identifier[self] )
def forall(self, method): """ TODO: I AM NOT HAPPY THAT THIS WILL NOT WORK WELL WITH WINDOW FUNCTIONS THE parts GIVE NO INDICATION OF NEXT ITEM OR PREVIOUS ITEM LIKE rownum DOES. MAYBE ALGEBRAIC EDGES SHOULD BE LOOPED DIFFERENTLY? ON THE OTHER HAND, MAYBE WINDOW FUNCTIONS ARE RESPONSIBLE FOR THIS COMPLICATION MAR 2015: THE ISSUE IS parts, IT SHOULD BE coord INSTEAD IT IS EXPECTED THE method ACCEPTS (value, coord, cube), WHERE value - VALUE FOUND AT ELEMENT parts - THE ONE PART CORRESPONDING TO EACH EDGE cube - THE WHOLE CUBE, FOR USE IN WINDOW FUNCTIONS """ if not self.is_value: Log.error('Not dealing with this case yet') # depends on [control=['if'], data=[]] matrix = self.data.values()[0] parts = [e.domain.partitions for e in self.edges] for c in matrix._all_combos(): method(matrix[c], [parts[i][cc] for (i, cc) in enumerate(c)], self) # depends on [control=['for'], data=['c']]
def get_gcloud_pricelist(): """Retrieve latest pricelist from Google Cloud, or use cached copy if not reachable. """ try: r = requests.get('http://cloudpricingcalculator.appspot.com' '/static/data/pricelist.json') content = json.loads(r.content) except ConnectionError: logger.warning( "Couldn't get updated pricelist from " "http://cloudpricingcalculator.appspot.com" "/static/data/pricelist.json. Falling back to cached " "copy, but prices may be out of date.") with open('gcloudpricelist.json') as infile: content = json.load(infile) pricelist = content['gcp_price_list'] return pricelist
def function[get_gcloud_pricelist, parameter[]]: constant[Retrieve latest pricelist from Google Cloud, or use cached copy if not reachable. ] <ast.Try object at 0x7da1b10c0f70> variable[pricelist] assign[=] call[name[content]][constant[gcp_price_list]] return[name[pricelist]]
keyword[def] identifier[get_gcloud_pricelist] (): literal[string] keyword[try] : identifier[r] = identifier[requests] . identifier[get] ( literal[string] literal[string] ) identifier[content] = identifier[json] . identifier[loads] ( identifier[r] . identifier[content] ) keyword[except] identifier[ConnectionError] : identifier[logger] . identifier[warning] ( literal[string] literal[string] literal[string] literal[string] ) keyword[with] identifier[open] ( literal[string] ) keyword[as] identifier[infile] : identifier[content] = identifier[json] . identifier[load] ( identifier[infile] ) identifier[pricelist] = identifier[content] [ literal[string] ] keyword[return] identifier[pricelist]
def get_gcloud_pricelist(): """Retrieve latest pricelist from Google Cloud, or use cached copy if not reachable. """ try: r = requests.get('http://cloudpricingcalculator.appspot.com/static/data/pricelist.json') content = json.loads(r.content) # depends on [control=['try'], data=[]] except ConnectionError: logger.warning("Couldn't get updated pricelist from http://cloudpricingcalculator.appspot.com/static/data/pricelist.json. Falling back to cached copy, but prices may be out of date.") with open('gcloudpricelist.json') as infile: content = json.load(infile) # depends on [control=['with'], data=['infile']] # depends on [control=['except'], data=[]] pricelist = content['gcp_price_list'] return pricelist
def get_metainfo(scriptfile, keywords=['author', 'contact', 'copyright', 'download', 'git', 'subversion', 'version', 'website'], special={}, first_line_pattern=r'^(?P<progname>.+)(\s+v(?P<version>\S+))?', keyword_pattern_template=r'^\s*%(pretty)s:\s*(?P<%(keyword)s>\S.+?)\s*$', prettify = lambda kw: kw.capitalize().replace('_', ' ')): """Dumb helper for pulling metainfo from a script __doc__ string. Returns a metainfo dict with command, description, progname and the given keywords (if present). This function will only make minimal efforts to succeed. If you need anything else: roll your own. The docstring needs to be multiline and the closing quotes need to be first on a line, optionally preceeded by whitespace. The first non-whitespace line is re.search'ed using first_line_pattern, default e.g (version optional, contains no whitespace): PROGNAME [vVERSION] The next non-whitespace, non-keyword line is expected to be the program description. The following lines are re.search'ed against a keyword:pattern dict which is constructed using keyword_pattern % dict(pretty=prettify(keyword), keyword=keyword) Default prettify is keyword.capitalize().replace('_', ' '). Example, for the keyword "licence" will match the following line: License: The MIT license. and set the license metainfo to "The MIT license.". Any keyword:pattern pairs that need special treatment can be supplied with special. """ patterns = dict((kw, re.compile(keyword_pattern_template % dict(pretty=prettify(kw), keyword=kw))) for kw in keywords) patterns.update(special) metainfo = dict() if scriptfile[-4:] in ['.pyc', '.pyo']: scriptfile = scriptfile[:-1] script = open(scriptfile) closer = '' for line in script: line = line.strip() if not line or line.startswith('#'): continue if line[:3] in ('"""', "'''"): closer = line[:3] break raise ValueError('file contains no docstring') if not line: for line in script: line = line.strip() if line: break g = re.search(first_line_pattern, line[3:]).groupdict() metainfo['progname'] = g['progname'] if g['version']: metainfo['version'] = g['version'] for line in script: if line.strip().startswith(closer): break for keyword, pattern in patterns.items(): m = pattern.search(line) if m: metainfo[keyword] = m.group(keyword) break if line.strip() and not 'description' in metainfo: metainfo['description'] = line.strip() return metainfo
def function[get_metainfo, parameter[scriptfile, keywords, special, first_line_pattern, keyword_pattern_template, prettify]]: constant[Dumb helper for pulling metainfo from a script __doc__ string. Returns a metainfo dict with command, description, progname and the given keywords (if present). This function will only make minimal efforts to succeed. If you need anything else: roll your own. The docstring needs to be multiline and the closing quotes need to be first on a line, optionally preceeded by whitespace. The first non-whitespace line is re.search'ed using first_line_pattern, default e.g (version optional, contains no whitespace): PROGNAME [vVERSION] The next non-whitespace, non-keyword line is expected to be the program description. The following lines are re.search'ed against a keyword:pattern dict which is constructed using keyword_pattern % dict(pretty=prettify(keyword), keyword=keyword) Default prettify is keyword.capitalize().replace('_', ' '). Example, for the keyword "licence" will match the following line: License: The MIT license. and set the license metainfo to "The MIT license.". Any keyword:pattern pairs that need special treatment can be supplied with special. ] variable[patterns] assign[=] call[name[dict], parameter[<ast.GeneratorExp object at 0x7da20e9b08b0>]] call[name[patterns].update, parameter[name[special]]] variable[metainfo] assign[=] call[name[dict], parameter[]] if compare[call[name[scriptfile]][<ast.Slice object at 0x7da20e9b2cb0>] in list[[<ast.Constant object at 0x7da20e9b08e0>, <ast.Constant object at 0x7da20e9b2c50>]]] begin[:] variable[scriptfile] assign[=] call[name[scriptfile]][<ast.Slice object at 0x7da20e9b2e60>] variable[script] assign[=] call[name[open], parameter[name[scriptfile]]] variable[closer] assign[=] constant[] for taget[name[line]] in starred[name[script]] begin[:] variable[line] assign[=] call[name[line].strip, parameter[]] if <ast.BoolOp object at 0x7da20e9b22f0> begin[:] continue if compare[call[name[line]][<ast.Slice object at 0x7da20e9b3370>] in tuple[[<ast.Constant object at 0x7da2054a4af0>, <ast.Constant object at 0x7da2054a4160>]]] begin[:] variable[closer] assign[=] call[name[line]][<ast.Slice object at 0x7da2054a4f10>] break <ast.Raise object at 0x7da2054a4790> if <ast.UnaryOp object at 0x7da2054a46d0> begin[:] for taget[name[line]] in starred[name[script]] begin[:] variable[line] assign[=] call[name[line].strip, parameter[]] if name[line] begin[:] break variable[g] assign[=] call[call[name[re].search, parameter[name[first_line_pattern], call[name[line]][<ast.Slice object at 0x7da2044c3bb0>]]].groupdict, parameter[]] call[name[metainfo]][constant[progname]] assign[=] call[name[g]][constant[progname]] if call[name[g]][constant[version]] begin[:] call[name[metainfo]][constant[version]] assign[=] call[name[g]][constant[version]] for taget[name[line]] in starred[name[script]] begin[:] if call[call[name[line].strip, parameter[]].startswith, parameter[name[closer]]] begin[:] break for taget[tuple[[<ast.Name object at 0x7da2044c1660>, <ast.Name object at 0x7da2044c28c0>]]] in starred[call[name[patterns].items, parameter[]]] begin[:] variable[m] assign[=] call[name[pattern].search, parameter[name[line]]] if name[m] begin[:] call[name[metainfo]][name[keyword]] assign[=] call[name[m].group, parameter[name[keyword]]] break if <ast.BoolOp object at 0x7da2054a5840> begin[:] call[name[metainfo]][constant[description]] assign[=] call[name[line].strip, parameter[]] return[name[metainfo]]
keyword[def] identifier[get_metainfo] ( identifier[scriptfile] , identifier[keywords] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ], identifier[special] ={}, identifier[first_line_pattern] = literal[string] , identifier[keyword_pattern_template] = literal[string] , identifier[prettify] = keyword[lambda] identifier[kw] : identifier[kw] . identifier[capitalize] (). identifier[replace] ( literal[string] , literal[string] )): literal[string] identifier[patterns] = identifier[dict] (( identifier[kw] , identifier[re] . identifier[compile] ( identifier[keyword_pattern_template] % identifier[dict] ( identifier[pretty] = identifier[prettify] ( identifier[kw] ), identifier[keyword] = identifier[kw] ))) keyword[for] identifier[kw] keyword[in] identifier[keywords] ) identifier[patterns] . identifier[update] ( identifier[special] ) identifier[metainfo] = identifier[dict] () keyword[if] identifier[scriptfile] [- literal[int] :] keyword[in] [ literal[string] , literal[string] ]: identifier[scriptfile] = identifier[scriptfile] [:- literal[int] ] identifier[script] = identifier[open] ( identifier[scriptfile] ) identifier[closer] = literal[string] keyword[for] identifier[line] keyword[in] identifier[script] : identifier[line] = identifier[line] . identifier[strip] () keyword[if] keyword[not] identifier[line] keyword[or] identifier[line] . identifier[startswith] ( literal[string] ): keyword[continue] keyword[if] identifier[line] [: literal[int] ] keyword[in] ( literal[string] , literal[string] ): identifier[closer] = identifier[line] [: literal[int] ] keyword[break] keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] keyword[not] identifier[line] : keyword[for] identifier[line] keyword[in] identifier[script] : identifier[line] = identifier[line] . identifier[strip] () keyword[if] identifier[line] : keyword[break] identifier[g] = identifier[re] . identifier[search] ( identifier[first_line_pattern] , identifier[line] [ literal[int] :]). identifier[groupdict] () identifier[metainfo] [ literal[string] ]= identifier[g] [ literal[string] ] keyword[if] identifier[g] [ literal[string] ]: identifier[metainfo] [ literal[string] ]= identifier[g] [ literal[string] ] keyword[for] identifier[line] keyword[in] identifier[script] : keyword[if] identifier[line] . identifier[strip] (). identifier[startswith] ( identifier[closer] ): keyword[break] keyword[for] identifier[keyword] , identifier[pattern] keyword[in] identifier[patterns] . identifier[items] (): identifier[m] = identifier[pattern] . identifier[search] ( identifier[line] ) keyword[if] identifier[m] : identifier[metainfo] [ identifier[keyword] ]= identifier[m] . identifier[group] ( identifier[keyword] ) keyword[break] keyword[if] identifier[line] . identifier[strip] () keyword[and] keyword[not] literal[string] keyword[in] identifier[metainfo] : identifier[metainfo] [ literal[string] ]= identifier[line] . identifier[strip] () keyword[return] identifier[metainfo]
def get_metainfo(scriptfile, keywords=['author', 'contact', 'copyright', 'download', 'git', 'subversion', 'version', 'website'], special={}, first_line_pattern='^(?P<progname>.+)(\\s+v(?P<version>\\S+))?', keyword_pattern_template='^\\s*%(pretty)s:\\s*(?P<%(keyword)s>\\S.+?)\\s*$', prettify=lambda kw: kw.capitalize().replace('_', ' ')): """Dumb helper for pulling metainfo from a script __doc__ string. Returns a metainfo dict with command, description, progname and the given keywords (if present). This function will only make minimal efforts to succeed. If you need anything else: roll your own. The docstring needs to be multiline and the closing quotes need to be first on a line, optionally preceeded by whitespace. The first non-whitespace line is re.search'ed using first_line_pattern, default e.g (version optional, contains no whitespace): PROGNAME [vVERSION] The next non-whitespace, non-keyword line is expected to be the program description. The following lines are re.search'ed against a keyword:pattern dict which is constructed using keyword_pattern % dict(pretty=prettify(keyword), keyword=keyword) Default prettify is keyword.capitalize().replace('_', ' '). Example, for the keyword "licence" will match the following line: License: The MIT license. and set the license metainfo to "The MIT license.". Any keyword:pattern pairs that need special treatment can be supplied with special. """ patterns = dict(((kw, re.compile(keyword_pattern_template % dict(pretty=prettify(kw), keyword=kw))) for kw in keywords)) patterns.update(special) metainfo = dict() if scriptfile[-4:] in ['.pyc', '.pyo']: scriptfile = scriptfile[:-1] # depends on [control=['if'], data=[]] script = open(scriptfile) closer = '' for line in script: line = line.strip() if not line or line.startswith('#'): continue # depends on [control=['if'], data=[]] if line[:3] in ('"""', "'''"): closer = line[:3] break # depends on [control=['if'], data=[]] raise ValueError('file contains no docstring') # depends on [control=['for'], data=['line']] if not line: for line in script: line = line.strip() if line: break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']] # depends on [control=['if'], data=[]] g = re.search(first_line_pattern, line[3:]).groupdict() metainfo['progname'] = g['progname'] if g['version']: metainfo['version'] = g['version'] # depends on [control=['if'], data=[]] for line in script: if line.strip().startswith(closer): break # depends on [control=['if'], data=[]] for (keyword, pattern) in patterns.items(): m = pattern.search(line) if m: metainfo[keyword] = m.group(keyword) break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] if line.strip() and (not 'description' in metainfo): metainfo['description'] = line.strip() # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']] return metainfo
def direct(ctx, path): """Make direct call to RWS, bypassing rwslib""" try: url = make_url(ctx.obj['RWS'].base_url, path) resp = requests.get(url, auth=HTTPBasicAuth(ctx.obj['USERNAME'], ctx.obj['PASSWORD'])) click.echo(resp.text) except RWSException as e: click.echo(e.message) except requests.exceptions.HTTPError as e: click.echo(e.message)
def function[direct, parameter[ctx, path]]: constant[Make direct call to RWS, bypassing rwslib] <ast.Try object at 0x7da1b18013f0>
keyword[def] identifier[direct] ( identifier[ctx] , identifier[path] ): literal[string] keyword[try] : identifier[url] = identifier[make_url] ( identifier[ctx] . identifier[obj] [ literal[string] ]. identifier[base_url] , identifier[path] ) identifier[resp] = identifier[requests] . identifier[get] ( identifier[url] , identifier[auth] = identifier[HTTPBasicAuth] ( identifier[ctx] . identifier[obj] [ literal[string] ], identifier[ctx] . identifier[obj] [ literal[string] ])) identifier[click] . identifier[echo] ( identifier[resp] . identifier[text] ) keyword[except] identifier[RWSException] keyword[as] identifier[e] : identifier[click] . identifier[echo] ( identifier[e] . identifier[message] ) keyword[except] identifier[requests] . identifier[exceptions] . identifier[HTTPError] keyword[as] identifier[e] : identifier[click] . identifier[echo] ( identifier[e] . identifier[message] )
def direct(ctx, path): """Make direct call to RWS, bypassing rwslib""" try: url = make_url(ctx.obj['RWS'].base_url, path) resp = requests.get(url, auth=HTTPBasicAuth(ctx.obj['USERNAME'], ctx.obj['PASSWORD'])) click.echo(resp.text) # depends on [control=['try'], data=[]] except RWSException as e: click.echo(e.message) # depends on [control=['except'], data=['e']] except requests.exceptions.HTTPError as e: click.echo(e.message) # depends on [control=['except'], data=['e']]
def p_simple_command_element(p): '''simple_command_element : WORD | ASSIGNMENT_WORD | redirection''' if isinstance(p[1], ast.node): p[0] = [p[1]] return parserobj = p.context p[0] = [_expandword(parserobj, p.slice[1])] # change the word node to an assignment if necessary if p.slice[1].ttype == tokenizer.tokentype.ASSIGNMENT_WORD: p[0][0].kind = 'assignment'
def function[p_simple_command_element, parameter[p]]: constant[simple_command_element : WORD | ASSIGNMENT_WORD | redirection] if call[name[isinstance], parameter[call[name[p]][constant[1]], name[ast].node]] begin[:] call[name[p]][constant[0]] assign[=] list[[<ast.Subscript object at 0x7da1b20f84f0>]] return[None] variable[parserobj] assign[=] name[p].context call[name[p]][constant[0]] assign[=] list[[<ast.Call object at 0x7da1b20fbdf0>]] if compare[call[name[p].slice][constant[1]].ttype equal[==] name[tokenizer].tokentype.ASSIGNMENT_WORD] begin[:] call[call[name[p]][constant[0]]][constant[0]].kind assign[=] constant[assignment]
keyword[def] identifier[p_simple_command_element] ( identifier[p] ): literal[string] keyword[if] identifier[isinstance] ( identifier[p] [ literal[int] ], identifier[ast] . identifier[node] ): identifier[p] [ literal[int] ]=[ identifier[p] [ literal[int] ]] keyword[return] identifier[parserobj] = identifier[p] . identifier[context] identifier[p] [ literal[int] ]=[ identifier[_expandword] ( identifier[parserobj] , identifier[p] . identifier[slice] [ literal[int] ])] keyword[if] identifier[p] . identifier[slice] [ literal[int] ]. identifier[ttype] == identifier[tokenizer] . identifier[tokentype] . identifier[ASSIGNMENT_WORD] : identifier[p] [ literal[int] ][ literal[int] ]. identifier[kind] = literal[string]
def p_simple_command_element(p): """simple_command_element : WORD | ASSIGNMENT_WORD | redirection""" if isinstance(p[1], ast.node): p[0] = [p[1]] return # depends on [control=['if'], data=[]] parserobj = p.context p[0] = [_expandword(parserobj, p.slice[1])] # change the word node to an assignment if necessary if p.slice[1].ttype == tokenizer.tokentype.ASSIGNMENT_WORD: p[0][0].kind = 'assignment' # depends on [control=['if'], data=[]]
def properties_observer(instance, prop, callback, **kwargs): """Adds properties callback handler""" change_only = kwargs.get('change_only', True) observer(instance, prop, callback, change_only=change_only)
def function[properties_observer, parameter[instance, prop, callback]]: constant[Adds properties callback handler] variable[change_only] assign[=] call[name[kwargs].get, parameter[constant[change_only], constant[True]]] call[name[observer], parameter[name[instance], name[prop], name[callback]]]
keyword[def] identifier[properties_observer] ( identifier[instance] , identifier[prop] , identifier[callback] ,** identifier[kwargs] ): literal[string] identifier[change_only] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[True] ) identifier[observer] ( identifier[instance] , identifier[prop] , identifier[callback] , identifier[change_only] = identifier[change_only] )
def properties_observer(instance, prop, callback, **kwargs): """Adds properties callback handler""" change_only = kwargs.get('change_only', True) observer(instance, prop, callback, change_only=change_only)
async def full_dispatch_request( self, request_context: Optional[RequestContext]=None, ) -> Response: """Adds pre and post processing to the request dispatching. Arguments: request_context: The request context, optional as Flask omits this argument. """ await self.try_trigger_before_first_request_functions() await request_started.send(self) try: result = await self.preprocess_request(request_context) if result is None: result = await self.dispatch_request(request_context) except Exception as error: result = await self.handle_user_exception(error) return await self.finalize_request(result, request_context)
<ast.AsyncFunctionDef object at 0x7da207f01330>
keyword[async] keyword[def] identifier[full_dispatch_request] ( identifier[self] , identifier[request_context] : identifier[Optional] [ identifier[RequestContext] ]= keyword[None] , )-> identifier[Response] : literal[string] keyword[await] identifier[self] . identifier[try_trigger_before_first_request_functions] () keyword[await] identifier[request_started] . identifier[send] ( identifier[self] ) keyword[try] : identifier[result] = keyword[await] identifier[self] . identifier[preprocess_request] ( identifier[request_context] ) keyword[if] identifier[result] keyword[is] keyword[None] : identifier[result] = keyword[await] identifier[self] . identifier[dispatch_request] ( identifier[request_context] ) keyword[except] identifier[Exception] keyword[as] identifier[error] : identifier[result] = keyword[await] identifier[self] . identifier[handle_user_exception] ( identifier[error] ) keyword[return] keyword[await] identifier[self] . identifier[finalize_request] ( identifier[result] , identifier[request_context] )
async def full_dispatch_request(self, request_context: Optional[RequestContext]=None) -> Response: """Adds pre and post processing to the request dispatching. Arguments: request_context: The request context, optional as Flask omits this argument. """ await self.try_trigger_before_first_request_functions() await request_started.send(self) try: result = await self.preprocess_request(request_context) if result is None: result = await self.dispatch_request(request_context) # depends on [control=['if'], data=['result']] # depends on [control=['try'], data=[]] except Exception as error: result = await self.handle_user_exception(error) # depends on [control=['except'], data=['error']] return await self.finalize_request(result, request_context)
def check_update(): """ Check for app updates and print/log them. """ logging.info('Check for app updates.') try: update = updater.check_for_app_updates() except Exception: logging.exception('Check for updates failed.') return if update: print("!!! UPDATE AVAILABLE !!!\n" "" + static_data.PROJECT_URL + "\n\n") logging.info("Update available: " + static_data.PROJECT_URL) else: logging.info("No update available.")
def function[check_update, parameter[]]: constant[ Check for app updates and print/log them. ] call[name[logging].info, parameter[constant[Check for app updates.]]] <ast.Try object at 0x7da1b11a51b0> if name[update] begin[:] call[name[print], parameter[binary_operation[binary_operation[constant[!!! UPDATE AVAILABLE !!! ] + name[static_data].PROJECT_URL] + constant[ ]]]] call[name[logging].info, parameter[binary_operation[constant[Update available: ] + name[static_data].PROJECT_URL]]]
keyword[def] identifier[check_update] (): literal[string] identifier[logging] . identifier[info] ( literal[string] ) keyword[try] : identifier[update] = identifier[updater] . identifier[check_for_app_updates] () keyword[except] identifier[Exception] : identifier[logging] . identifier[exception] ( literal[string] ) keyword[return] keyword[if] identifier[update] : identifier[print] ( literal[string] literal[string] + identifier[static_data] . identifier[PROJECT_URL] + literal[string] ) identifier[logging] . identifier[info] ( literal[string] + identifier[static_data] . identifier[PROJECT_URL] ) keyword[else] : identifier[logging] . identifier[info] ( literal[string] )
def check_update(): """ Check for app updates and print/log them. """ logging.info('Check for app updates.') try: update = updater.check_for_app_updates() # depends on [control=['try'], data=[]] except Exception: logging.exception('Check for updates failed.') return # depends on [control=['except'], data=[]] if update: print('!!! UPDATE AVAILABLE !!!\n' + static_data.PROJECT_URL + '\n\n') logging.info('Update available: ' + static_data.PROJECT_URL) # depends on [control=['if'], data=[]] else: logging.info('No update available.')
def auth_view(method): ''' role for view. ''' def wrapper(self, *args, **kwargs): ''' wrapper. ''' if ROLE_CFG['view'] == '': return method(self, *args, **kwargs) elif self.current_user: if is_prived(self.userinfo.role, ROLE_CFG['view']): return method(self, *args, **kwargs) else: kwd = { 'info': 'No role', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) else: kwd = { 'info': 'No role', } self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) return wrapper
def function[auth_view, parameter[method]]: constant[ role for view. ] def function[wrapper, parameter[self]]: constant[ wrapper. ] if compare[call[name[ROLE_CFG]][constant[view]] equal[==] constant[]] begin[:] return[call[name[method], parameter[name[self], <ast.Starred object at 0x7da1b04f90f0>]]] return[name[wrapper]]
keyword[def] identifier[auth_view] ( identifier[method] ): literal[string] keyword[def] identifier[wrapper] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[ROLE_CFG] [ literal[string] ]== literal[string] : keyword[return] identifier[method] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ) keyword[elif] identifier[self] . identifier[current_user] : keyword[if] identifier[is_prived] ( identifier[self] . identifier[userinfo] . identifier[role] , identifier[ROLE_CFG] [ literal[string] ]): keyword[return] identifier[method] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ) keyword[else] : identifier[kwd] ={ literal[string] : literal[string] , } identifier[self] . identifier[render] ( literal[string] , identifier[kwd] = identifier[kwd] , identifier[userinfo] = identifier[self] . identifier[userinfo] ) keyword[else] : identifier[kwd] ={ literal[string] : literal[string] , } identifier[self] . identifier[render] ( literal[string] , identifier[kwd] = identifier[kwd] , identifier[userinfo] = identifier[self] . identifier[userinfo] ) keyword[return] identifier[wrapper]
def auth_view(method): """ role for view. """ def wrapper(self, *args, **kwargs): """ wrapper. """ if ROLE_CFG['view'] == '': return method(self, *args, **kwargs) # depends on [control=['if'], data=[]] elif self.current_user: if is_prived(self.userinfo.role, ROLE_CFG['view']): return method(self, *args, **kwargs) # depends on [control=['if'], data=[]] else: kwd = {'info': 'No role'} self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) # depends on [control=['if'], data=[]] else: kwd = {'info': 'No role'} self.render('misc/html/404.html', kwd=kwd, userinfo=self.userinfo) return wrapper
async def _make_connection(self): """Construct a connection to Redis.""" return await aioredis.create_redis( 'redis://{}:{}'.format( self._redis_params.get('host', 'localhost'), self._redis_params.get('port', 6379) ), db=int(self._redis_params.get('db', 1)) )
<ast.AsyncFunctionDef object at 0x7da18dc07970>
keyword[async] keyword[def] identifier[_make_connection] ( identifier[self] ): literal[string] keyword[return] keyword[await] identifier[aioredis] . identifier[create_redis] ( literal[string] . identifier[format] ( identifier[self] . identifier[_redis_params] . identifier[get] ( literal[string] , literal[string] ), identifier[self] . identifier[_redis_params] . identifier[get] ( literal[string] , literal[int] ) ), identifier[db] = identifier[int] ( identifier[self] . identifier[_redis_params] . identifier[get] ( literal[string] , literal[int] )) )
async def _make_connection(self): """Construct a connection to Redis.""" return await aioredis.create_redis('redis://{}:{}'.format(self._redis_params.get('host', 'localhost'), self._redis_params.get('port', 6379)), db=int(self._redis_params.get('db', 1)))
def buildCliString(self): """ Collect all of the required information from the config screen and build a CLI string which can be used to invoke the client program """ config = self.navbar.getActiveConfig() group = self.buildSpec['widgets'][self.navbar.getSelectedGroup()] positional = config.getPositionalArgs() optional = config.getOptionalArgs() print(cli.buildCliString( self.buildSpec['target'], group['command'], positional, optional )) return cli.buildCliString( self.buildSpec['target'], group['command'], positional, optional )
def function[buildCliString, parameter[self]]: constant[ Collect all of the required information from the config screen and build a CLI string which can be used to invoke the client program ] variable[config] assign[=] call[name[self].navbar.getActiveConfig, parameter[]] variable[group] assign[=] call[call[name[self].buildSpec][constant[widgets]]][call[name[self].navbar.getSelectedGroup, parameter[]]] variable[positional] assign[=] call[name[config].getPositionalArgs, parameter[]] variable[optional] assign[=] call[name[config].getOptionalArgs, parameter[]] call[name[print], parameter[call[name[cli].buildCliString, parameter[call[name[self].buildSpec][constant[target]], call[name[group]][constant[command]], name[positional], name[optional]]]]] return[call[name[cli].buildCliString, parameter[call[name[self].buildSpec][constant[target]], call[name[group]][constant[command]], name[positional], name[optional]]]]
keyword[def] identifier[buildCliString] ( identifier[self] ): literal[string] identifier[config] = identifier[self] . identifier[navbar] . identifier[getActiveConfig] () identifier[group] = identifier[self] . identifier[buildSpec] [ literal[string] ][ identifier[self] . identifier[navbar] . identifier[getSelectedGroup] ()] identifier[positional] = identifier[config] . identifier[getPositionalArgs] () identifier[optional] = identifier[config] . identifier[getOptionalArgs] () identifier[print] ( identifier[cli] . identifier[buildCliString] ( identifier[self] . identifier[buildSpec] [ literal[string] ], identifier[group] [ literal[string] ], identifier[positional] , identifier[optional] )) keyword[return] identifier[cli] . identifier[buildCliString] ( identifier[self] . identifier[buildSpec] [ literal[string] ], identifier[group] [ literal[string] ], identifier[positional] , identifier[optional] )
def buildCliString(self): """ Collect all of the required information from the config screen and build a CLI string which can be used to invoke the client program """ config = self.navbar.getActiveConfig() group = self.buildSpec['widgets'][self.navbar.getSelectedGroup()] positional = config.getPositionalArgs() optional = config.getOptionalArgs() print(cli.buildCliString(self.buildSpec['target'], group['command'], positional, optional)) return cli.buildCliString(self.buildSpec['target'], group['command'], positional, optional)
def xml(self, indent = ""): """Produce XML output for the profile""" xml = "\n" + indent + "<profile>\n" xml += indent + " <input>\n" for inputtemplate in self.input: xml += inputtemplate.xml(indent +" ") + "\n" xml += indent + " </input>\n" xml += indent + " <output>\n" for outputtemplate in self.output: xml += outputtemplate.xml(indent +" ") + "\n" #works for ParameterCondition as well! xml += indent + " </output>\n" xml += indent + "</profile>\n" return xml
def function[xml, parameter[self, indent]]: constant[Produce XML output for the profile] variable[xml] assign[=] binary_operation[binary_operation[constant[ ] + name[indent]] + constant[<profile> ]] <ast.AugAssign object at 0x7da20c6c4d30> for taget[name[inputtemplate]] in starred[name[self].input] begin[:] <ast.AugAssign object at 0x7da20c6c61a0> <ast.AugAssign object at 0x7da20c6c4d00> <ast.AugAssign object at 0x7da20c6c66e0> for taget[name[outputtemplate]] in starred[name[self].output] begin[:] <ast.AugAssign object at 0x7da20c6c5840> <ast.AugAssign object at 0x7da20c6c6680> <ast.AugAssign object at 0x7da20c6c5c00> return[name[xml]]
keyword[def] identifier[xml] ( identifier[self] , identifier[indent] = literal[string] ): literal[string] identifier[xml] = literal[string] + identifier[indent] + literal[string] identifier[xml] += identifier[indent] + literal[string] keyword[for] identifier[inputtemplate] keyword[in] identifier[self] . identifier[input] : identifier[xml] += identifier[inputtemplate] . identifier[xml] ( identifier[indent] + literal[string] )+ literal[string] identifier[xml] += identifier[indent] + literal[string] identifier[xml] += identifier[indent] + literal[string] keyword[for] identifier[outputtemplate] keyword[in] identifier[self] . identifier[output] : identifier[xml] += identifier[outputtemplate] . identifier[xml] ( identifier[indent] + literal[string] )+ literal[string] identifier[xml] += identifier[indent] + literal[string] identifier[xml] += identifier[indent] + literal[string] keyword[return] identifier[xml]
def xml(self, indent=''): """Produce XML output for the profile""" xml = '\n' + indent + '<profile>\n' xml += indent + ' <input>\n' for inputtemplate in self.input: xml += inputtemplate.xml(indent + ' ') + '\n' # depends on [control=['for'], data=['inputtemplate']] xml += indent + ' </input>\n' xml += indent + ' <output>\n' for outputtemplate in self.output: xml += outputtemplate.xml(indent + ' ') + '\n' #works for ParameterCondition as well! # depends on [control=['for'], data=['outputtemplate']] xml += indent + ' </output>\n' xml += indent + '</profile>\n' return xml
def roc(clss, vals, reverse=False): """ Reciever Operator Characteristic :param clss: known classes. 1 if positive case, -1 if the negative case :type class: list of boolean :param vals: classification probabilites etc... :type vals: list of real numbers :param bool reverse: whether the values should be sorted in reverse order """ assert len(clss) == len(vals) global X, Y, A, T, M, B order = numpy.argsort(vals) if reverse: order = order[::-1] clss = numpy.array(clss)[order] vals = numpy.array(vals)[order] length = len(clss) + 1 data = numpy.empty((length, 6), dtype=numpy.float32) data[0, X], data[0, Y], data[0, A] = 0 data[0, T] = vals[0] for i in range(length-1): if clss[i] == 1: data[i+1, X] = data[i, X] data[i+1, Y] = data[i, Y] + 1 data[i+1, A] = data[i, A] else: data[i+1, X] = data[i, X] + 1 data[i+1, Y] = data[i, Y] data[i+1, A] = data[i, A] + data[i+1, Y] data[i+1, T] = vals[i] # Incorporate accuracy scores data[0, M] = 0 for i in range(1, length-1): fp = data[i, X] tp = data[i, Y] tn = data[-1, X] - fp fn = data[-1, Y] - tp data[i, M] = mcc(tp, tn, fp, fn) data[i, B] = ber(tp, tn, fp, fn) data[-1, M] = 0 return data
def function[roc, parameter[clss, vals, reverse]]: constant[ Reciever Operator Characteristic :param clss: known classes. 1 if positive case, -1 if the negative case :type class: list of boolean :param vals: classification probabilites etc... :type vals: list of real numbers :param bool reverse: whether the values should be sorted in reverse order ] assert[compare[call[name[len], parameter[name[clss]]] equal[==] call[name[len], parameter[name[vals]]]]] <ast.Global object at 0x7da2041d82b0> variable[order] assign[=] call[name[numpy].argsort, parameter[name[vals]]] if name[reverse] begin[:] variable[order] assign[=] call[name[order]][<ast.Slice object at 0x7da2041da650>] variable[clss] assign[=] call[call[name[numpy].array, parameter[name[clss]]]][name[order]] variable[vals] assign[=] call[call[name[numpy].array, parameter[name[vals]]]][name[order]] variable[length] assign[=] binary_operation[call[name[len], parameter[name[clss]]] + constant[1]] variable[data] assign[=] call[name[numpy].empty, parameter[tuple[[<ast.Name object at 0x7da1b27e2bf0>, <ast.Constant object at 0x7da1b27e3910>]]]] <ast.Tuple object at 0x7da1b27e11b0> assign[=] constant[0] call[name[data]][tuple[[<ast.Constant object at 0x7da1b27e3a90>, <ast.Name object at 0x7da1b27e10c0>]]] assign[=] call[name[vals]][constant[0]] for taget[name[i]] in starred[call[name[range], parameter[binary_operation[name[length] - constant[1]]]]] begin[:] if compare[call[name[clss]][name[i]] equal[==] constant[1]] begin[:] call[name[data]][tuple[[<ast.BinOp object at 0x7da1b27e2c20>, <ast.Name object at 0x7da1b27e2680>]]] assign[=] call[name[data]][tuple[[<ast.Name object at 0x7da1b27e26e0>, <ast.Name object at 0x7da1b27e0eb0>]]] call[name[data]][tuple[[<ast.BinOp object at 0x7da1b27e1ae0>, <ast.Name object at 0x7da1b28e9270>]]] assign[=] binary_operation[call[name[data]][tuple[[<ast.Name object at 0x7da1b28ead10>, <ast.Name object at 0x7da1b28eada0>]]] + constant[1]] call[name[data]][tuple[[<ast.BinOp object at 0x7da1b28ead40>, <ast.Name object at 0x7da1b28ead70>]]] assign[=] call[name[data]][tuple[[<ast.Name object at 0x7da1b28eab00>, <ast.Name object at 0x7da1b28eae30>]]] call[name[data]][tuple[[<ast.BinOp object at 0x7da1b28e9450>, <ast.Name object at 0x7da1b28eb130>]]] assign[=] call[name[vals]][name[i]] call[name[data]][tuple[[<ast.Constant object at 0x7da1b28e83d0>, <ast.Name object at 0x7da1b28e9330>]]] assign[=] constant[0] for taget[name[i]] in starred[call[name[range], parameter[constant[1], binary_operation[name[length] - constant[1]]]]] begin[:] variable[fp] assign[=] call[name[data]][tuple[[<ast.Name object at 0x7da1b28eb2e0>, <ast.Name object at 0x7da1b28eb190>]]] variable[tp] assign[=] call[name[data]][tuple[[<ast.Name object at 0x7da1b28e8490>, <ast.Name object at 0x7da1b28e87c0>]]] variable[tn] assign[=] binary_operation[call[name[data]][tuple[[<ast.UnaryOp object at 0x7da1b28e8c10>, <ast.Name object at 0x7da1b28e9a20>]]] - name[fp]] variable[fn] assign[=] binary_operation[call[name[data]][tuple[[<ast.UnaryOp object at 0x7da1b28e9ed0>, <ast.Name object at 0x7da1b28e9ab0>]]] - name[tp]] call[name[data]][tuple[[<ast.Name object at 0x7da1b28ea710>, <ast.Name object at 0x7da1b28ea650>]]] assign[=] call[name[mcc], parameter[name[tp], name[tn], name[fp], name[fn]]] call[name[data]][tuple[[<ast.Name object at 0x7da1b28e9de0>, <ast.Name object at 0x7da1b28e8850>]]] assign[=] call[name[ber], parameter[name[tp], name[tn], name[fp], name[fn]]] call[name[data]][tuple[[<ast.UnaryOp object at 0x7da1b28eb6d0>, <ast.Name object at 0x7da1b28eb670>]]] assign[=] constant[0] return[name[data]]
keyword[def] identifier[roc] ( identifier[clss] , identifier[vals] , identifier[reverse] = keyword[False] ): literal[string] keyword[assert] identifier[len] ( identifier[clss] )== identifier[len] ( identifier[vals] ) keyword[global] identifier[X] , identifier[Y] , identifier[A] , identifier[T] , identifier[M] , identifier[B] identifier[order] = identifier[numpy] . identifier[argsort] ( identifier[vals] ) keyword[if] identifier[reverse] : identifier[order] = identifier[order] [::- literal[int] ] identifier[clss] = identifier[numpy] . identifier[array] ( identifier[clss] )[ identifier[order] ] identifier[vals] = identifier[numpy] . identifier[array] ( identifier[vals] )[ identifier[order] ] identifier[length] = identifier[len] ( identifier[clss] )+ literal[int] identifier[data] = identifier[numpy] . identifier[empty] (( identifier[length] , literal[int] ), identifier[dtype] = identifier[numpy] . identifier[float32] ) identifier[data] [ literal[int] , identifier[X] ], identifier[data] [ literal[int] , identifier[Y] ], identifier[data] [ literal[int] , identifier[A] ]= literal[int] identifier[data] [ literal[int] , identifier[T] ]= identifier[vals] [ literal[int] ] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[length] - literal[int] ): keyword[if] identifier[clss] [ identifier[i] ]== literal[int] : identifier[data] [ identifier[i] + literal[int] , identifier[X] ]= identifier[data] [ identifier[i] , identifier[X] ] identifier[data] [ identifier[i] + literal[int] , identifier[Y] ]= identifier[data] [ identifier[i] , identifier[Y] ]+ literal[int] identifier[data] [ identifier[i] + literal[int] , identifier[A] ]= identifier[data] [ identifier[i] , identifier[A] ] keyword[else] : identifier[data] [ identifier[i] + literal[int] , identifier[X] ]= identifier[data] [ identifier[i] , identifier[X] ]+ literal[int] identifier[data] [ identifier[i] + literal[int] , identifier[Y] ]= identifier[data] [ identifier[i] , identifier[Y] ] identifier[data] [ identifier[i] + literal[int] , identifier[A] ]= identifier[data] [ identifier[i] , identifier[A] ]+ identifier[data] [ identifier[i] + literal[int] , identifier[Y] ] identifier[data] [ identifier[i] + literal[int] , identifier[T] ]= identifier[vals] [ identifier[i] ] identifier[data] [ literal[int] , identifier[M] ]= literal[int] keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[length] - literal[int] ): identifier[fp] = identifier[data] [ identifier[i] , identifier[X] ] identifier[tp] = identifier[data] [ identifier[i] , identifier[Y] ] identifier[tn] = identifier[data] [- literal[int] , identifier[X] ]- identifier[fp] identifier[fn] = identifier[data] [- literal[int] , identifier[Y] ]- identifier[tp] identifier[data] [ identifier[i] , identifier[M] ]= identifier[mcc] ( identifier[tp] , identifier[tn] , identifier[fp] , identifier[fn] ) identifier[data] [ identifier[i] , identifier[B] ]= identifier[ber] ( identifier[tp] , identifier[tn] , identifier[fp] , identifier[fn] ) identifier[data] [- literal[int] , identifier[M] ]= literal[int] keyword[return] identifier[data]
def roc(clss, vals, reverse=False): """ Reciever Operator Characteristic :param clss: known classes. 1 if positive case, -1 if the negative case :type class: list of boolean :param vals: classification probabilites etc... :type vals: list of real numbers :param bool reverse: whether the values should be sorted in reverse order """ assert len(clss) == len(vals) global X, Y, A, T, M, B order = numpy.argsort(vals) if reverse: order = order[::-1] # depends on [control=['if'], data=[]] clss = numpy.array(clss)[order] vals = numpy.array(vals)[order] length = len(clss) + 1 data = numpy.empty((length, 6), dtype=numpy.float32) (data[0, X], data[0, Y], data[0, A]) = 0 data[0, T] = vals[0] for i in range(length - 1): if clss[i] == 1: data[i + 1, X] = data[i, X] data[i + 1, Y] = data[i, Y] + 1 data[i + 1, A] = data[i, A] # depends on [control=['if'], data=[]] else: data[i + 1, X] = data[i, X] + 1 data[i + 1, Y] = data[i, Y] data[i + 1, A] = data[i, A] + data[i + 1, Y] data[i + 1, T] = vals[i] # depends on [control=['for'], data=['i']] # Incorporate accuracy scores data[0, M] = 0 for i in range(1, length - 1): fp = data[i, X] tp = data[i, Y] tn = data[-1, X] - fp fn = data[-1, Y] - tp data[i, M] = mcc(tp, tn, fp, fn) data[i, B] = ber(tp, tn, fp, fn) # depends on [control=['for'], data=['i']] data[-1, M] = 0 return data
def convert_ints_to_bytes(in_ints, num): """Convert an integer array into a byte arrays. The number of bytes forming an integer is defined by num :param in_ints: the input integers :param num: the number of bytes per int :return the integer array""" out_bytes= b"" for val in in_ints: out_bytes+=struct.pack(mmtf.utils.constants.NUM_DICT[num], val) return out_bytes
def function[convert_ints_to_bytes, parameter[in_ints, num]]: constant[Convert an integer array into a byte arrays. The number of bytes forming an integer is defined by num :param in_ints: the input integers :param num: the number of bytes per int :return the integer array] variable[out_bytes] assign[=] constant[b''] for taget[name[val]] in starred[name[in_ints]] begin[:] <ast.AugAssign object at 0x7da1b10985b0> return[name[out_bytes]]
keyword[def] identifier[convert_ints_to_bytes] ( identifier[in_ints] , identifier[num] ): literal[string] identifier[out_bytes] = literal[string] keyword[for] identifier[val] keyword[in] identifier[in_ints] : identifier[out_bytes] += identifier[struct] . identifier[pack] ( identifier[mmtf] . identifier[utils] . identifier[constants] . identifier[NUM_DICT] [ identifier[num] ], identifier[val] ) keyword[return] identifier[out_bytes]
def convert_ints_to_bytes(in_ints, num): """Convert an integer array into a byte arrays. The number of bytes forming an integer is defined by num :param in_ints: the input integers :param num: the number of bytes per int :return the integer array""" out_bytes = b'' for val in in_ints: out_bytes += struct.pack(mmtf.utils.constants.NUM_DICT[num], val) # depends on [control=['for'], data=['val']] return out_bytes
def _build_dict( cls, parser_dict, delimiter=DEFAULT_DELIMITER, dict_type=collections.OrderedDict ): """ Builds a dictionary of ``dict_type`` given the ``parser._sections`` dict. :param dict parser_dict: The ``parser._sections`` mapping :param str delimiter: The delimiter for nested dictionaries, defaults to ":", optional :param class dict_type: The dictionary type to use for building the dict, defaults to :class:`collections.OrderedDict`, optional :return: The resulting dictionary :rtype: dict """ result = dict_type() for (key, value) in parser_dict.items(): if isinstance(value, dict): nestings = key.split(delimiter) # build nested dictionaries if they don't exist (up to 2nd to last key) base_dict = result for nested_key in nestings[:-1]: if nested_key not in base_dict: base_dict[nested_key] = dict_type() base_dict = base_dict[nested_key] base_dict[nestings[-1]] = cls._build_dict( parser_dict.get(key), delimiter=delimiter, dict_type=dict_type ) else: if "\n" in value: result[key] = [ cls._decode_var(_) for _ in value.lstrip("\n").split("\n") ] else: result[key] = cls._decode_var(value) return result
def function[_build_dict, parameter[cls, parser_dict, delimiter, dict_type]]: constant[ Builds a dictionary of ``dict_type`` given the ``parser._sections`` dict. :param dict parser_dict: The ``parser._sections`` mapping :param str delimiter: The delimiter for nested dictionaries, defaults to ":", optional :param class dict_type: The dictionary type to use for building the dict, defaults to :class:`collections.OrderedDict`, optional :return: The resulting dictionary :rtype: dict ] variable[result] assign[=] call[name[dict_type], parameter[]] for taget[tuple[[<ast.Name object at 0x7da18eb574f0>, <ast.Name object at 0x7da18eb540a0>]]] in starred[call[name[parser_dict].items, parameter[]]] begin[:] if call[name[isinstance], parameter[name[value], name[dict]]] begin[:] variable[nestings] assign[=] call[name[key].split, parameter[name[delimiter]]] variable[base_dict] assign[=] name[result] for taget[name[nested_key]] in starred[call[name[nestings]][<ast.Slice object at 0x7da18eb55a80>]] begin[:] if compare[name[nested_key] <ast.NotIn object at 0x7da2590d7190> name[base_dict]] begin[:] call[name[base_dict]][name[nested_key]] assign[=] call[name[dict_type], parameter[]] variable[base_dict] assign[=] call[name[base_dict]][name[nested_key]] call[name[base_dict]][call[name[nestings]][<ast.UnaryOp object at 0x7da204567a00>]] assign[=] call[name[cls]._build_dict, parameter[call[name[parser_dict].get, parameter[name[key]]]]] return[name[result]]
keyword[def] identifier[_build_dict] ( identifier[cls] , identifier[parser_dict] , identifier[delimiter] = identifier[DEFAULT_DELIMITER] , identifier[dict_type] = identifier[collections] . identifier[OrderedDict] ): literal[string] identifier[result] = identifier[dict_type] () keyword[for] ( identifier[key] , identifier[value] ) keyword[in] identifier[parser_dict] . identifier[items] (): keyword[if] identifier[isinstance] ( identifier[value] , identifier[dict] ): identifier[nestings] = identifier[key] . identifier[split] ( identifier[delimiter] ) identifier[base_dict] = identifier[result] keyword[for] identifier[nested_key] keyword[in] identifier[nestings] [:- literal[int] ]: keyword[if] identifier[nested_key] keyword[not] keyword[in] identifier[base_dict] : identifier[base_dict] [ identifier[nested_key] ]= identifier[dict_type] () identifier[base_dict] = identifier[base_dict] [ identifier[nested_key] ] identifier[base_dict] [ identifier[nestings] [- literal[int] ]]= identifier[cls] . identifier[_build_dict] ( identifier[parser_dict] . identifier[get] ( identifier[key] ), identifier[delimiter] = identifier[delimiter] , identifier[dict_type] = identifier[dict_type] ) keyword[else] : keyword[if] literal[string] keyword[in] identifier[value] : identifier[result] [ identifier[key] ]=[ identifier[cls] . identifier[_decode_var] ( identifier[_] ) keyword[for] identifier[_] keyword[in] identifier[value] . identifier[lstrip] ( literal[string] ). identifier[split] ( literal[string] ) ] keyword[else] : identifier[result] [ identifier[key] ]= identifier[cls] . identifier[_decode_var] ( identifier[value] ) keyword[return] identifier[result]
def _build_dict(cls, parser_dict, delimiter=DEFAULT_DELIMITER, dict_type=collections.OrderedDict): """ Builds a dictionary of ``dict_type`` given the ``parser._sections`` dict. :param dict parser_dict: The ``parser._sections`` mapping :param str delimiter: The delimiter for nested dictionaries, defaults to ":", optional :param class dict_type: The dictionary type to use for building the dict, defaults to :class:`collections.OrderedDict`, optional :return: The resulting dictionary :rtype: dict """ result = dict_type() for (key, value) in parser_dict.items(): if isinstance(value, dict): nestings = key.split(delimiter) # build nested dictionaries if they don't exist (up to 2nd to last key) base_dict = result for nested_key in nestings[:-1]: if nested_key not in base_dict: base_dict[nested_key] = dict_type() # depends on [control=['if'], data=['nested_key', 'base_dict']] base_dict = base_dict[nested_key] # depends on [control=['for'], data=['nested_key']] base_dict[nestings[-1]] = cls._build_dict(parser_dict.get(key), delimiter=delimiter, dict_type=dict_type) # depends on [control=['if'], data=[]] elif '\n' in value: result[key] = [cls._decode_var(_) for _ in value.lstrip('\n').split('\n')] # depends on [control=['if'], data=['value']] else: result[key] = cls._decode_var(value) # depends on [control=['for'], data=[]] return result
def delay(self, gain_in=0.8, gain_out=0.5, delays=list((1000, 1800)), decays=list((0.3, 0.25)), parallel=False): """delay takes 4 parameters: input gain (max 1), output gain and then two lists, delays and decays. Each list is a pair of comma seperated values within parenthesis. """ self.command.append('echo' + ('s' if parallel else '')) self.command.append(gain_in) self.command.append(gain_out) self.command.extend(list(sum(zip(delays, decays), ()))) return self
def function[delay, parameter[self, gain_in, gain_out, delays, decays, parallel]]: constant[delay takes 4 parameters: input gain (max 1), output gain and then two lists, delays and decays. Each list is a pair of comma seperated values within parenthesis. ] call[name[self].command.append, parameter[binary_operation[constant[echo] + <ast.IfExp object at 0x7da1b0bd8f40>]]] call[name[self].command.append, parameter[name[gain_in]]] call[name[self].command.append, parameter[name[gain_out]]] call[name[self].command.extend, parameter[call[name[list], parameter[call[name[sum], parameter[call[name[zip], parameter[name[delays], name[decays]]], tuple[[]]]]]]]] return[name[self]]
keyword[def] identifier[delay] ( identifier[self] , identifier[gain_in] = literal[int] , identifier[gain_out] = literal[int] , identifier[delays] = identifier[list] (( literal[int] , literal[int] )), identifier[decays] = identifier[list] (( literal[int] , literal[int] )), identifier[parallel] = keyword[False] ): literal[string] identifier[self] . identifier[command] . identifier[append] ( literal[string] +( literal[string] keyword[if] identifier[parallel] keyword[else] literal[string] )) identifier[self] . identifier[command] . identifier[append] ( identifier[gain_in] ) identifier[self] . identifier[command] . identifier[append] ( identifier[gain_out] ) identifier[self] . identifier[command] . identifier[extend] ( identifier[list] ( identifier[sum] ( identifier[zip] ( identifier[delays] , identifier[decays] ),()))) keyword[return] identifier[self]
def delay(self, gain_in=0.8, gain_out=0.5, delays=list((1000, 1800)), decays=list((0.3, 0.25)), parallel=False): """delay takes 4 parameters: input gain (max 1), output gain and then two lists, delays and decays. Each list is a pair of comma seperated values within parenthesis. """ self.command.append('echo' + ('s' if parallel else '')) self.command.append(gain_in) self.command.append(gain_out) self.command.extend(list(sum(zip(delays, decays), ()))) return self
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 count = int(vals[i]) i += 1 for _ in range(count): obj = TypicalOrExtremePeriod() obj.read(vals[i:i + obj.field_count]) self.add_typical_or_extreme_period(obj) i += obj.field_count
def function[read, parameter[self, vals]]: constant[Read values. Args: vals (list): list of strings representing values ] variable[i] assign[=] constant[0] variable[count] assign[=] call[name[int], parameter[call[name[vals]][name[i]]]] <ast.AugAssign object at 0x7da1b0f90c10> for taget[name[_]] in starred[call[name[range], parameter[name[count]]]] begin[:] variable[obj] assign[=] call[name[TypicalOrExtremePeriod], parameter[]] call[name[obj].read, parameter[call[name[vals]][<ast.Slice object at 0x7da1b0f907f0>]]] call[name[self].add_typical_or_extreme_period, parameter[name[obj]]] <ast.AugAssign object at 0x7da1b0f930d0>
keyword[def] identifier[read] ( identifier[self] , identifier[vals] ): literal[string] identifier[i] = literal[int] identifier[count] = identifier[int] ( identifier[vals] [ identifier[i] ]) identifier[i] += literal[int] keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[count] ): identifier[obj] = identifier[TypicalOrExtremePeriod] () identifier[obj] . identifier[read] ( identifier[vals] [ identifier[i] : identifier[i] + identifier[obj] . identifier[field_count] ]) identifier[self] . identifier[add_typical_or_extreme_period] ( identifier[obj] ) identifier[i] += identifier[obj] . identifier[field_count]
def read(self, vals): """Read values. Args: vals (list): list of strings representing values """ i = 0 count = int(vals[i]) i += 1 for _ in range(count): obj = TypicalOrExtremePeriod() obj.read(vals[i:i + obj.field_count]) self.add_typical_or_extreme_period(obj) i += obj.field_count # depends on [control=['for'], data=[]]
def update(self, new_positive_data=None, new_unlabeled_data=None, positive_prob_prior=0.5, *args, **kwargs): '''Update the classifier with new data and re-trains the classifier. :param new_positive_data: List of new, labeled strings. :param new_unlabeled_data: List of new, unlabeled strings. ''' self.positive_prob_prior = positive_prob_prior if new_positive_data: self.positive_set += new_positive_data self.positive_features += [self.extract_features(d) for d in new_positive_data] if new_unlabeled_data: self.unlabeled_set += new_unlabeled_data self.unlabeled_features += [self.extract_features(d) for d in new_unlabeled_data] self.classifier = self.nltk_class.train(self.positive_features, self.unlabeled_features, self.positive_prob_prior, *args, **kwargs) return True
def function[update, parameter[self, new_positive_data, new_unlabeled_data, positive_prob_prior]]: constant[Update the classifier with new data and re-trains the classifier. :param new_positive_data: List of new, labeled strings. :param new_unlabeled_data: List of new, unlabeled strings. ] name[self].positive_prob_prior assign[=] name[positive_prob_prior] if name[new_positive_data] begin[:] <ast.AugAssign object at 0x7da18f58e7a0> <ast.AugAssign object at 0x7da1b26aed70> if name[new_unlabeled_data] begin[:] <ast.AugAssign object at 0x7da1b26afee0> <ast.AugAssign object at 0x7da1b26aceb0> name[self].classifier assign[=] call[name[self].nltk_class.train, parameter[name[self].positive_features, name[self].unlabeled_features, name[self].positive_prob_prior, <ast.Starred object at 0x7da1b26ada50>]] return[constant[True]]
keyword[def] identifier[update] ( identifier[self] , identifier[new_positive_data] = keyword[None] , identifier[new_unlabeled_data] = keyword[None] , identifier[positive_prob_prior] = literal[int] , * identifier[args] ,** identifier[kwargs] ): literal[string] identifier[self] . identifier[positive_prob_prior] = identifier[positive_prob_prior] keyword[if] identifier[new_positive_data] : identifier[self] . identifier[positive_set] += identifier[new_positive_data] identifier[self] . identifier[positive_features] +=[ identifier[self] . identifier[extract_features] ( identifier[d] ) keyword[for] identifier[d] keyword[in] identifier[new_positive_data] ] keyword[if] identifier[new_unlabeled_data] : identifier[self] . identifier[unlabeled_set] += identifier[new_unlabeled_data] identifier[self] . identifier[unlabeled_features] +=[ identifier[self] . identifier[extract_features] ( identifier[d] ) keyword[for] identifier[d] keyword[in] identifier[new_unlabeled_data] ] identifier[self] . identifier[classifier] = identifier[self] . identifier[nltk_class] . identifier[train] ( identifier[self] . identifier[positive_features] , identifier[self] . identifier[unlabeled_features] , identifier[self] . identifier[positive_prob_prior] , * identifier[args] ,** identifier[kwargs] ) keyword[return] keyword[True]
def update(self, new_positive_data=None, new_unlabeled_data=None, positive_prob_prior=0.5, *args, **kwargs): """Update the classifier with new data and re-trains the classifier. :param new_positive_data: List of new, labeled strings. :param new_unlabeled_data: List of new, unlabeled strings. """ self.positive_prob_prior = positive_prob_prior if new_positive_data: self.positive_set += new_positive_data self.positive_features += [self.extract_features(d) for d in new_positive_data] # depends on [control=['if'], data=[]] if new_unlabeled_data: self.unlabeled_set += new_unlabeled_data self.unlabeled_features += [self.extract_features(d) for d in new_unlabeled_data] # depends on [control=['if'], data=[]] self.classifier = self.nltk_class.train(self.positive_features, self.unlabeled_features, self.positive_prob_prior, *args, **kwargs) return True
def is_already_running(self): """Return True if lock exists and has not timed out.""" redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier) return self.celery_self.backend.client.exists(redis_key)
def function[is_already_running, parameter[self]]: constant[Return True if lock exists and has not timed out.] variable[redis_key] assign[=] call[name[self].CELERY_LOCK.format, parameter[]] return[call[name[self].celery_self.backend.client.exists, parameter[name[redis_key]]]]
keyword[def] identifier[is_already_running] ( identifier[self] ): literal[string] identifier[redis_key] = identifier[self] . identifier[CELERY_LOCK] . identifier[format] ( identifier[task_id] = identifier[self] . identifier[task_identifier] ) keyword[return] identifier[self] . identifier[celery_self] . identifier[backend] . identifier[client] . identifier[exists] ( identifier[redis_key] )
def is_already_running(self): """Return True if lock exists and has not timed out.""" redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier) return self.celery_self.backend.client.exists(redis_key)
def _update_pdf(population, fitnesses, pdfs, quantile): """Find a better pdf, based on fitnesses.""" # First we determine a fitness threshold based on a quantile of fitnesses fitness_threshold = _get_quantile_cutoff(fitnesses, quantile) # Then check all of our possible pdfs with a stochastic program return _best_pdf(pdfs, population, fitnesses, fitness_threshold)
def function[_update_pdf, parameter[population, fitnesses, pdfs, quantile]]: constant[Find a better pdf, based on fitnesses.] variable[fitness_threshold] assign[=] call[name[_get_quantile_cutoff], parameter[name[fitnesses], name[quantile]]] return[call[name[_best_pdf], parameter[name[pdfs], name[population], name[fitnesses], name[fitness_threshold]]]]
keyword[def] identifier[_update_pdf] ( identifier[population] , identifier[fitnesses] , identifier[pdfs] , identifier[quantile] ): literal[string] identifier[fitness_threshold] = identifier[_get_quantile_cutoff] ( identifier[fitnesses] , identifier[quantile] ) keyword[return] identifier[_best_pdf] ( identifier[pdfs] , identifier[population] , identifier[fitnesses] , identifier[fitness_threshold] )
def _update_pdf(population, fitnesses, pdfs, quantile): """Find a better pdf, based on fitnesses.""" # First we determine a fitness threshold based on a quantile of fitnesses fitness_threshold = _get_quantile_cutoff(fitnesses, quantile) # Then check all of our possible pdfs with a stochastic program return _best_pdf(pdfs, population, fitnesses, fitness_threshold)
def upload_scan(self, application_id, file_path): """ Uploads and processes a scan file. :param application_id: Application identifier. :param file_path: Path to the scan file to be uploaded. """ return self._request( 'POST', 'rest/applications/' + str(application_id) + '/upload', files={'file': open(file_path, 'rb')} )
def function[upload_scan, parameter[self, application_id, file_path]]: constant[ Uploads and processes a scan file. :param application_id: Application identifier. :param file_path: Path to the scan file to be uploaded. ] return[call[name[self]._request, parameter[constant[POST], binary_operation[binary_operation[constant[rest/applications/] + call[name[str], parameter[name[application_id]]]] + constant[/upload]]]]]
keyword[def] identifier[upload_scan] ( identifier[self] , identifier[application_id] , identifier[file_path] ): literal[string] keyword[return] identifier[self] . identifier[_request] ( literal[string] , literal[string] + identifier[str] ( identifier[application_id] )+ literal[string] , identifier[files] ={ literal[string] : identifier[open] ( identifier[file_path] , literal[string] )} )
def upload_scan(self, application_id, file_path): """ Uploads and processes a scan file. :param application_id: Application identifier. :param file_path: Path to the scan file to be uploaded. """ return self._request('POST', 'rest/applications/' + str(application_id) + '/upload', files={'file': open(file_path, 'rb')})
def save_default_falco_rules_files(self, fsobj, save_dir): '''**Description** Given a dict returned from get_default_falco_rules_files, save those files to a set of files below save_dir. The first level below save_dir is a directory with the tag name. The second level is a directory per file. The third level is a directory per variant. Finally the files are at the lowest level, in a file called "content". For example, using the example dict in get_default_falco_rules_files(), the directory layout would look like: save_dir/ v1.5.9/ falco_rules.yaml/ 29/ content: a file containing "- required_engine_version: 29\n\n- list: foo\n" 1/ content: a file containing "- required_engine_version: 1\n\n- list: foo\n" k8s_audit_rules.yaml/ 0/ content: a file containing "# some comment" **Arguments** - fsobj: a python dict matching the structure returned by get_default_falco_rules_files() - save_dir: a directory path under which to save the files. If the path already exists, it will be removed first. **Success Return Value** - None **Example** `examples/get_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_default_falco_rules_files.py>`_ ''' if os.path.exists(save_dir): try: if os.path.isdir(save_dir): shutil.rmtree(save_dir) else: os.unlink(save_dir) except Exception as e: return [False, "Could not remove existing save dir {}: {}".format(save_dir, str(e))] prefix = os.path.join(save_dir, fsobj["tag"]) try: os.makedirs(prefix) except Exception as e: return [False, "Could not create tag directory {}: {}".format(prefix, str(e))] if "files" in fsobj: for fobj in fsobj["files"]: fprefix = os.path.join(prefix, fobj["name"]) try: os.makedirs(fprefix) except Exception as e: return [False, "Could not create file directory {}: {}".format(fprefix, str(e))] for variant in fobj["variants"]: vprefix = os.path.join(fprefix, str(variant["requiredEngineVersion"])) try: os.makedirs(vprefix) except Exception as e: return [False, "Could not create variant directory {}: {}".format(vprefix, str(e))] cpath = os.path.join(vprefix, "content") try: with open(cpath, "w") as cfile: cfile.write(variant["content"]) except Exception as e: return [False, "Could not write content to {}: {}".format(cfile, str(e))] return [True, None]
def function[save_default_falco_rules_files, parameter[self, fsobj, save_dir]]: constant[**Description** Given a dict returned from get_default_falco_rules_files, save those files to a set of files below save_dir. The first level below save_dir is a directory with the tag name. The second level is a directory per file. The third level is a directory per variant. Finally the files are at the lowest level, in a file called "content". For example, using the example dict in get_default_falco_rules_files(), the directory layout would look like: save_dir/ v1.5.9/ falco_rules.yaml/ 29/ content: a file containing "- required_engine_version: 29 - list: foo " 1/ content: a file containing "- required_engine_version: 1 - list: foo " k8s_audit_rules.yaml/ 0/ content: a file containing "# some comment" **Arguments** - fsobj: a python dict matching the structure returned by get_default_falco_rules_files() - save_dir: a directory path under which to save the files. If the path already exists, it will be removed first. **Success Return Value** - None **Example** `examples/get_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_default_falco_rules_files.py>`_ ] if call[name[os].path.exists, parameter[name[save_dir]]] begin[:] <ast.Try object at 0x7da18ede5840> variable[prefix] assign[=] call[name[os].path.join, parameter[name[save_dir], call[name[fsobj]][constant[tag]]]] <ast.Try object at 0x7da18ede6950> if compare[constant[files] in name[fsobj]] begin[:] for taget[name[fobj]] in starred[call[name[fsobj]][constant[files]]] begin[:] variable[fprefix] assign[=] call[name[os].path.join, parameter[name[prefix], call[name[fobj]][constant[name]]]] <ast.Try object at 0x7da18ede7cd0> for taget[name[variant]] in starred[call[name[fobj]][constant[variants]]] begin[:] variable[vprefix] assign[=] call[name[os].path.join, parameter[name[fprefix], call[name[str], parameter[call[name[variant]][constant[requiredEngineVersion]]]]]] <ast.Try object at 0x7da18ede6560> variable[cpath] assign[=] call[name[os].path.join, parameter[name[vprefix], constant[content]]] <ast.Try object at 0x7da1b2344eb0> return[list[[<ast.Constant object at 0x7da1b26aca00>, <ast.Constant object at 0x7da1b26adff0>]]]
keyword[def] identifier[save_default_falco_rules_files] ( identifier[self] , identifier[fsobj] , identifier[save_dir] ): literal[string] keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[save_dir] ): keyword[try] : keyword[if] identifier[os] . identifier[path] . identifier[isdir] ( identifier[save_dir] ): identifier[shutil] . identifier[rmtree] ( identifier[save_dir] ) keyword[else] : identifier[os] . identifier[unlink] ( identifier[save_dir] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : keyword[return] [ keyword[False] , literal[string] . identifier[format] ( identifier[save_dir] , identifier[str] ( identifier[e] ))] identifier[prefix] = identifier[os] . identifier[path] . identifier[join] ( identifier[save_dir] , identifier[fsobj] [ literal[string] ]) keyword[try] : identifier[os] . identifier[makedirs] ( identifier[prefix] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : keyword[return] [ keyword[False] , literal[string] . identifier[format] ( identifier[prefix] , identifier[str] ( identifier[e] ))] keyword[if] literal[string] keyword[in] identifier[fsobj] : keyword[for] identifier[fobj] keyword[in] identifier[fsobj] [ literal[string] ]: identifier[fprefix] = identifier[os] . identifier[path] . identifier[join] ( identifier[prefix] , identifier[fobj] [ literal[string] ]) keyword[try] : identifier[os] . identifier[makedirs] ( identifier[fprefix] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : keyword[return] [ keyword[False] , literal[string] . identifier[format] ( identifier[fprefix] , identifier[str] ( identifier[e] ))] keyword[for] identifier[variant] keyword[in] identifier[fobj] [ literal[string] ]: identifier[vprefix] = identifier[os] . identifier[path] . identifier[join] ( identifier[fprefix] , identifier[str] ( identifier[variant] [ literal[string] ])) keyword[try] : identifier[os] . identifier[makedirs] ( identifier[vprefix] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : keyword[return] [ keyword[False] , literal[string] . identifier[format] ( identifier[vprefix] , identifier[str] ( identifier[e] ))] identifier[cpath] = identifier[os] . identifier[path] . identifier[join] ( identifier[vprefix] , literal[string] ) keyword[try] : keyword[with] identifier[open] ( identifier[cpath] , literal[string] ) keyword[as] identifier[cfile] : identifier[cfile] . identifier[write] ( identifier[variant] [ literal[string] ]) keyword[except] identifier[Exception] keyword[as] identifier[e] : keyword[return] [ keyword[False] , literal[string] . identifier[format] ( identifier[cfile] , identifier[str] ( identifier[e] ))] keyword[return] [ keyword[True] , keyword[None] ]
def save_default_falco_rules_files(self, fsobj, save_dir): """**Description** Given a dict returned from get_default_falco_rules_files, save those files to a set of files below save_dir. The first level below save_dir is a directory with the tag name. The second level is a directory per file. The third level is a directory per variant. Finally the files are at the lowest level, in a file called "content". For example, using the example dict in get_default_falco_rules_files(), the directory layout would look like: save_dir/ v1.5.9/ falco_rules.yaml/ 29/ content: a file containing "- required_engine_version: 29 - list: foo " 1/ content: a file containing "- required_engine_version: 1 - list: foo " k8s_audit_rules.yaml/ 0/ content: a file containing "# some comment" **Arguments** - fsobj: a python dict matching the structure returned by get_default_falco_rules_files() - save_dir: a directory path under which to save the files. If the path already exists, it will be removed first. **Success Return Value** - None **Example** `examples/get_default_falco_rules_files.py <https://github.com/draios/python-sdc-client/blob/master/examples/get_default_falco_rules_files.py>`_ """ if os.path.exists(save_dir): try: if os.path.isdir(save_dir): shutil.rmtree(save_dir) # depends on [control=['if'], data=[]] else: os.unlink(save_dir) # depends on [control=['try'], data=[]] except Exception as e: return [False, 'Could not remove existing save dir {}: {}'.format(save_dir, str(e))] # depends on [control=['except'], data=['e']] # depends on [control=['if'], data=[]] prefix = os.path.join(save_dir, fsobj['tag']) try: os.makedirs(prefix) # depends on [control=['try'], data=[]] except Exception as e: return [False, 'Could not create tag directory {}: {}'.format(prefix, str(e))] # depends on [control=['except'], data=['e']] if 'files' in fsobj: for fobj in fsobj['files']: fprefix = os.path.join(prefix, fobj['name']) try: os.makedirs(fprefix) # depends on [control=['try'], data=[]] except Exception as e: return [False, 'Could not create file directory {}: {}'.format(fprefix, str(e))] # depends on [control=['except'], data=['e']] for variant in fobj['variants']: vprefix = os.path.join(fprefix, str(variant['requiredEngineVersion'])) try: os.makedirs(vprefix) # depends on [control=['try'], data=[]] except Exception as e: return [False, 'Could not create variant directory {}: {}'.format(vprefix, str(e))] # depends on [control=['except'], data=['e']] cpath = os.path.join(vprefix, 'content') try: with open(cpath, 'w') as cfile: cfile.write(variant['content']) # depends on [control=['with'], data=['cfile']] # depends on [control=['try'], data=[]] except Exception as e: return [False, 'Could not write content to {}: {}'.format(cfile, str(e))] # depends on [control=['except'], data=['e']] # depends on [control=['for'], data=['variant']] # depends on [control=['for'], data=['fobj']] # depends on [control=['if'], data=['fsobj']] return [True, None]
def compose_title(projects, data): """ Compose the projects JSON file only with the projects name :param projects: projects.json :param data: eclipse JSON with the origin format :return: projects.json with titles """ for project in data: projects[project] = { 'meta': { 'title': data[project]['title'] } } return projects
def function[compose_title, parameter[projects, data]]: constant[ Compose the projects JSON file only with the projects name :param projects: projects.json :param data: eclipse JSON with the origin format :return: projects.json with titles ] for taget[name[project]] in starred[name[data]] begin[:] call[name[projects]][name[project]] assign[=] dictionary[[<ast.Constant object at 0x7da1b01277c0>], [<ast.Dict object at 0x7da1b01253c0>]] return[name[projects]]
keyword[def] identifier[compose_title] ( identifier[projects] , identifier[data] ): literal[string] keyword[for] identifier[project] keyword[in] identifier[data] : identifier[projects] [ identifier[project] ]={ literal[string] :{ literal[string] : identifier[data] [ identifier[project] ][ literal[string] ] } } keyword[return] identifier[projects]
def compose_title(projects, data): """ Compose the projects JSON file only with the projects name :param projects: projects.json :param data: eclipse JSON with the origin format :return: projects.json with titles """ for project in data: projects[project] = {'meta': {'title': data[project]['title']}} # depends on [control=['for'], data=['project']] return projects
def reset(self): """Resets the cache of compiled templates.""" with self.lock: if self.cache: if self.use_tmp: shutil.rmtree(self.tmp_dir, ignore_errors=True) else: self.templates = {}
def function[reset, parameter[self]]: constant[Resets the cache of compiled templates.] with name[self].lock begin[:] if name[self].cache begin[:] if name[self].use_tmp begin[:] call[name[shutil].rmtree, parameter[name[self].tmp_dir]]
keyword[def] identifier[reset] ( identifier[self] ): literal[string] keyword[with] identifier[self] . identifier[lock] : keyword[if] identifier[self] . identifier[cache] : keyword[if] identifier[self] . identifier[use_tmp] : identifier[shutil] . identifier[rmtree] ( identifier[self] . identifier[tmp_dir] , identifier[ignore_errors] = keyword[True] ) keyword[else] : identifier[self] . identifier[templates] ={}
def reset(self): """Resets the cache of compiled templates.""" with self.lock: if self.cache: if self.use_tmp: shutil.rmtree(self.tmp_dir, ignore_errors=True) # depends on [control=['if'], data=[]] else: self.templates = {} # depends on [control=['if'], data=[]] # depends on [control=['with'], data=[]]
def resolve_resource_refs(self, input_dict, supported_resource_refs): """ Resolve resource references within a GetAtt dict. Example: { "Fn::GetAtt": ["LogicalId.Property", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]} Theoretically, only the first element of the array can contain reference to SAM resources. The second element is name of an attribute (like Arn) of the resource. However tools like AWS CLI apply the assumption that first element of the array is a LogicalId and cannot contain a 'dot'. So they break at the first dot to convert YAML tag to JSON map like this: `!GetAtt LogicalId.Property.Arn` => {"Fn::GetAtt": [ "LogicalId", "Property.Arn" ] } Therefore to resolve the reference, we join the array into a string, break it back up to check if it contains a known reference, and resolve it if we can. :param input_dict: Dictionary to be resolved :param samtransaltor.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of an `SupportedResourceReferences` object that contain value of the property. :return: Resolved dictionary """ if not self.can_handle(input_dict): return input_dict key = self.intrinsic_name value = input_dict[key] # Value must be an array with *at least* two elements. If not, this is invalid GetAtt syntax. We just pass along # the input to CFN for it to do the "official" validation. if not isinstance(value, list) or len(value) < 2: return input_dict if (not all(isinstance(entry, string_types) for entry in value)): raise InvalidDocumentException( [InvalidTemplateException('Invalid GetAtt value {}. GetAtt expects an array with 2 strings.' .format(value))]) # Value of GetAtt is an array. It can contain any number of elements, with first being the LogicalId of # resource and rest being the attributes. In a SAM template, a reference to a resource can be used in the # first parameter. However tools like AWS CLI might break them down as well. So let's just concatenate # all elements, and break them into separate parts in a more standard way. # # Example: # { Fn::GetAtt: ["LogicalId.Property", "Arn"] } is equivalent to { Fn::GetAtt: ["LogicalId", "Property.Arn"] } # Former is the correct notation. However tools like AWS CLI can construct the later style. # Let's normalize the value into "LogicalId.Property.Arn" to handle both scenarios value_str = self._resource_ref_separator.join(value) splits = value_str.split(self._resource_ref_separator) logical_id = splits[0] property = splits[1] remaining = splits[2:] # if any resolved_value = supported_resource_refs.get(logical_id, property) return self._get_resolved_dictionary(input_dict, key, resolved_value, remaining)
def function[resolve_resource_refs, parameter[self, input_dict, supported_resource_refs]]: constant[ Resolve resource references within a GetAtt dict. Example: { "Fn::GetAtt": ["LogicalId.Property", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]} Theoretically, only the first element of the array can contain reference to SAM resources. The second element is name of an attribute (like Arn) of the resource. However tools like AWS CLI apply the assumption that first element of the array is a LogicalId and cannot contain a 'dot'. So they break at the first dot to convert YAML tag to JSON map like this: `!GetAtt LogicalId.Property.Arn` => {"Fn::GetAtt": [ "LogicalId", "Property.Arn" ] } Therefore to resolve the reference, we join the array into a string, break it back up to check if it contains a known reference, and resolve it if we can. :param input_dict: Dictionary to be resolved :param samtransaltor.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of an `SupportedResourceReferences` object that contain value of the property. :return: Resolved dictionary ] if <ast.UnaryOp object at 0x7da2041dbb80> begin[:] return[name[input_dict]] variable[key] assign[=] name[self].intrinsic_name variable[value] assign[=] call[name[input_dict]][name[key]] if <ast.BoolOp object at 0x7da2044c0a90> begin[:] return[name[input_dict]] if <ast.UnaryOp object at 0x7da2044c39d0> begin[:] <ast.Raise object at 0x7da2044c3040> variable[value_str] assign[=] call[name[self]._resource_ref_separator.join, parameter[name[value]]] variable[splits] assign[=] call[name[value_str].split, parameter[name[self]._resource_ref_separator]] variable[logical_id] assign[=] call[name[splits]][constant[0]] variable[property] assign[=] call[name[splits]][constant[1]] variable[remaining] assign[=] call[name[splits]][<ast.Slice object at 0x7da2054a7e50>] variable[resolved_value] assign[=] call[name[supported_resource_refs].get, parameter[name[logical_id], name[property]]] return[call[name[self]._get_resolved_dictionary, parameter[name[input_dict], name[key], name[resolved_value], name[remaining]]]]
keyword[def] identifier[resolve_resource_refs] ( identifier[self] , identifier[input_dict] , identifier[supported_resource_refs] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[can_handle] ( identifier[input_dict] ): keyword[return] identifier[input_dict] identifier[key] = identifier[self] . identifier[intrinsic_name] identifier[value] = identifier[input_dict] [ identifier[key] ] keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[list] ) keyword[or] identifier[len] ( identifier[value] )< literal[int] : keyword[return] identifier[input_dict] keyword[if] ( keyword[not] identifier[all] ( identifier[isinstance] ( identifier[entry] , identifier[string_types] ) keyword[for] identifier[entry] keyword[in] identifier[value] )): keyword[raise] identifier[InvalidDocumentException] ( [ identifier[InvalidTemplateException] ( literal[string] . identifier[format] ( identifier[value] ))]) identifier[value_str] = identifier[self] . identifier[_resource_ref_separator] . identifier[join] ( identifier[value] ) identifier[splits] = identifier[value_str] . identifier[split] ( identifier[self] . identifier[_resource_ref_separator] ) identifier[logical_id] = identifier[splits] [ literal[int] ] identifier[property] = identifier[splits] [ literal[int] ] identifier[remaining] = identifier[splits] [ literal[int] :] identifier[resolved_value] = identifier[supported_resource_refs] . identifier[get] ( identifier[logical_id] , identifier[property] ) keyword[return] identifier[self] . identifier[_get_resolved_dictionary] ( identifier[input_dict] , identifier[key] , identifier[resolved_value] , identifier[remaining] )
def resolve_resource_refs(self, input_dict, supported_resource_refs): """ Resolve resource references within a GetAtt dict. Example: { "Fn::GetAtt": ["LogicalId.Property", "Arn"] } => {"Fn::GetAtt": ["ResolvedLogicalId", "Arn"]} Theoretically, only the first element of the array can contain reference to SAM resources. The second element is name of an attribute (like Arn) of the resource. However tools like AWS CLI apply the assumption that first element of the array is a LogicalId and cannot contain a 'dot'. So they break at the first dot to convert YAML tag to JSON map like this: `!GetAtt LogicalId.Property.Arn` => {"Fn::GetAtt": [ "LogicalId", "Property.Arn" ] } Therefore to resolve the reference, we join the array into a string, break it back up to check if it contains a known reference, and resolve it if we can. :param input_dict: Dictionary to be resolved :param samtransaltor.intrinsics.resource_refs.SupportedResourceReferences supported_resource_refs: Instance of an `SupportedResourceReferences` object that contain value of the property. :return: Resolved dictionary """ if not self.can_handle(input_dict): return input_dict # depends on [control=['if'], data=[]] key = self.intrinsic_name value = input_dict[key] # Value must be an array with *at least* two elements. If not, this is invalid GetAtt syntax. We just pass along # the input to CFN for it to do the "official" validation. if not isinstance(value, list) or len(value) < 2: return input_dict # depends on [control=['if'], data=[]] if not all((isinstance(entry, string_types) for entry in value)): raise InvalidDocumentException([InvalidTemplateException('Invalid GetAtt value {}. GetAtt expects an array with 2 strings.'.format(value))]) # depends on [control=['if'], data=[]] # Value of GetAtt is an array. It can contain any number of elements, with first being the LogicalId of # resource and rest being the attributes. In a SAM template, a reference to a resource can be used in the # first parameter. However tools like AWS CLI might break them down as well. So let's just concatenate # all elements, and break them into separate parts in a more standard way. # # Example: # { Fn::GetAtt: ["LogicalId.Property", "Arn"] } is equivalent to { Fn::GetAtt: ["LogicalId", "Property.Arn"] } # Former is the correct notation. However tools like AWS CLI can construct the later style. # Let's normalize the value into "LogicalId.Property.Arn" to handle both scenarios value_str = self._resource_ref_separator.join(value) splits = value_str.split(self._resource_ref_separator) logical_id = splits[0] property = splits[1] remaining = splits[2:] # if any resolved_value = supported_resource_refs.get(logical_id, property) return self._get_resolved_dictionary(input_dict, key, resolved_value, remaining)
def _get_running_app_ids(self, rm_address, auth, ssl_verify): """ Return a dictionary of {app_id: (app_name, tracking_url)} for the running MapReduce applications """ metrics_json = self._rest_request_to_json( rm_address, auth, ssl_verify, self.YARN_APPS_PATH, self.YARN_SERVICE_CHECK, states=self.YARN_APPLICATION_STATES, applicationTypes=self.YARN_APPLICATION_TYPES, ) running_apps = {} if metrics_json.get('apps'): if metrics_json['apps'].get('app') is not None: for app_json in metrics_json['apps']['app']: app_id = app_json.get('id') tracking_url = app_json.get('trackingUrl') app_name = app_json.get('name') if app_id and tracking_url and app_name: running_apps[app_id] = (app_name, tracking_url) return running_apps
def function[_get_running_app_ids, parameter[self, rm_address, auth, ssl_verify]]: constant[ Return a dictionary of {app_id: (app_name, tracking_url)} for the running MapReduce applications ] variable[metrics_json] assign[=] call[name[self]._rest_request_to_json, parameter[name[rm_address], name[auth], name[ssl_verify], name[self].YARN_APPS_PATH, name[self].YARN_SERVICE_CHECK]] variable[running_apps] assign[=] dictionary[[], []] if call[name[metrics_json].get, parameter[constant[apps]]] begin[:] if compare[call[call[name[metrics_json]][constant[apps]].get, parameter[constant[app]]] is_not constant[None]] begin[:] for taget[name[app_json]] in starred[call[call[name[metrics_json]][constant[apps]]][constant[app]]] begin[:] variable[app_id] assign[=] call[name[app_json].get, parameter[constant[id]]] variable[tracking_url] assign[=] call[name[app_json].get, parameter[constant[trackingUrl]]] variable[app_name] assign[=] call[name[app_json].get, parameter[constant[name]]] if <ast.BoolOp object at 0x7da18ede4190> begin[:] call[name[running_apps]][name[app_id]] assign[=] tuple[[<ast.Name object at 0x7da207f00af0>, <ast.Name object at 0x7da207f03130>]] return[name[running_apps]]
keyword[def] identifier[_get_running_app_ids] ( identifier[self] , identifier[rm_address] , identifier[auth] , identifier[ssl_verify] ): literal[string] identifier[metrics_json] = identifier[self] . identifier[_rest_request_to_json] ( identifier[rm_address] , identifier[auth] , identifier[ssl_verify] , identifier[self] . identifier[YARN_APPS_PATH] , identifier[self] . identifier[YARN_SERVICE_CHECK] , identifier[states] = identifier[self] . identifier[YARN_APPLICATION_STATES] , identifier[applicationTypes] = identifier[self] . identifier[YARN_APPLICATION_TYPES] , ) identifier[running_apps] ={} keyword[if] identifier[metrics_json] . identifier[get] ( literal[string] ): keyword[if] identifier[metrics_json] [ literal[string] ]. identifier[get] ( literal[string] ) keyword[is] keyword[not] keyword[None] : keyword[for] identifier[app_json] keyword[in] identifier[metrics_json] [ literal[string] ][ literal[string] ]: identifier[app_id] = identifier[app_json] . identifier[get] ( literal[string] ) identifier[tracking_url] = identifier[app_json] . identifier[get] ( literal[string] ) identifier[app_name] = identifier[app_json] . identifier[get] ( literal[string] ) keyword[if] identifier[app_id] keyword[and] identifier[tracking_url] keyword[and] identifier[app_name] : identifier[running_apps] [ identifier[app_id] ]=( identifier[app_name] , identifier[tracking_url] ) keyword[return] identifier[running_apps]
def _get_running_app_ids(self, rm_address, auth, ssl_verify): """ Return a dictionary of {app_id: (app_name, tracking_url)} for the running MapReduce applications """ metrics_json = self._rest_request_to_json(rm_address, auth, ssl_verify, self.YARN_APPS_PATH, self.YARN_SERVICE_CHECK, states=self.YARN_APPLICATION_STATES, applicationTypes=self.YARN_APPLICATION_TYPES) running_apps = {} if metrics_json.get('apps'): if metrics_json['apps'].get('app') is not None: for app_json in metrics_json['apps']['app']: app_id = app_json.get('id') tracking_url = app_json.get('trackingUrl') app_name = app_json.get('name') if app_id and tracking_url and app_name: running_apps[app_id] = (app_name, tracking_url) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['app_json']] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] return running_apps
def parse_response(self, request): """Internal method. Parse data received from server. If REQUEST is not None true is returned if the request with that serial number was received, otherwise false is returned. If REQUEST is -1, we're parsing the server connection setup response. """ if request == -1: return self.parse_connection_setup() # Parse ordinary server response gotreq = 0 while 1: if self.data_recv: # Check the first byte to find out what kind of response it is rtype = byte2int(self.data_recv) # Are we're waiting for additional data for the current packet? if self.recv_packet_len: if len(self.data_recv) < self.recv_packet_len: return gotreq if rtype == 1: gotreq = self.parse_request_response(request) or gotreq continue elif rtype & 0x7f == ge.GenericEventCode: self.parse_event_response(rtype) continue else: raise AssertionError(rtype) # Every response is at least 32 bytes long, so don't bother # until we have received that much if len(self.data_recv) < 32: return gotreq # Error response if rtype == 0: gotreq = self.parse_error_response(request) or gotreq # Request response or generic event. elif rtype == 1 or rtype & 0x7f == ge.GenericEventCode: # Set reply length, and loop around to see if # we have got the full response rlen = int(struct.unpack('=L', self.data_recv[4:8])[0]) self.recv_packet_len = 32 + rlen * 4 # Else non-generic event else: self.parse_event_response(rtype)
def function[parse_response, parameter[self, request]]: constant[Internal method. Parse data received from server. If REQUEST is not None true is returned if the request with that serial number was received, otherwise false is returned. If REQUEST is -1, we're parsing the server connection setup response. ] if compare[name[request] equal[==] <ast.UnaryOp object at 0x7da1b088ae00>] begin[:] return[call[name[self].parse_connection_setup, parameter[]]] variable[gotreq] assign[=] constant[0] while constant[1] begin[:] if name[self].data_recv begin[:] variable[rtype] assign[=] call[name[byte2int], parameter[name[self].data_recv]] if name[self].recv_packet_len begin[:] if compare[call[name[len], parameter[name[self].data_recv]] less[<] name[self].recv_packet_len] begin[:] return[name[gotreq]] if compare[name[rtype] equal[==] constant[1]] begin[:] variable[gotreq] assign[=] <ast.BoolOp object at 0x7da1b08885e0> continue if compare[call[name[len], parameter[name[self].data_recv]] less[<] constant[32]] begin[:] return[name[gotreq]] if compare[name[rtype] equal[==] constant[0]] begin[:] variable[gotreq] assign[=] <ast.BoolOp object at 0x7da18f09e620>
keyword[def] identifier[parse_response] ( identifier[self] , identifier[request] ): literal[string] keyword[if] identifier[request] ==- literal[int] : keyword[return] identifier[self] . identifier[parse_connection_setup] () identifier[gotreq] = literal[int] keyword[while] literal[int] : keyword[if] identifier[self] . identifier[data_recv] : identifier[rtype] = identifier[byte2int] ( identifier[self] . identifier[data_recv] ) keyword[if] identifier[self] . identifier[recv_packet_len] : keyword[if] identifier[len] ( identifier[self] . identifier[data_recv] )< identifier[self] . identifier[recv_packet_len] : keyword[return] identifier[gotreq] keyword[if] identifier[rtype] == literal[int] : identifier[gotreq] = identifier[self] . identifier[parse_request_response] ( identifier[request] ) keyword[or] identifier[gotreq] keyword[continue] keyword[elif] identifier[rtype] & literal[int] == identifier[ge] . identifier[GenericEventCode] : identifier[self] . identifier[parse_event_response] ( identifier[rtype] ) keyword[continue] keyword[else] : keyword[raise] identifier[AssertionError] ( identifier[rtype] ) keyword[if] identifier[len] ( identifier[self] . identifier[data_recv] )< literal[int] : keyword[return] identifier[gotreq] keyword[if] identifier[rtype] == literal[int] : identifier[gotreq] = identifier[self] . identifier[parse_error_response] ( identifier[request] ) keyword[or] identifier[gotreq] keyword[elif] identifier[rtype] == literal[int] keyword[or] identifier[rtype] & literal[int] == identifier[ge] . identifier[GenericEventCode] : identifier[rlen] = identifier[int] ( identifier[struct] . identifier[unpack] ( literal[string] , identifier[self] . identifier[data_recv] [ literal[int] : literal[int] ])[ literal[int] ]) identifier[self] . identifier[recv_packet_len] = literal[int] + identifier[rlen] * literal[int] keyword[else] : identifier[self] . identifier[parse_event_response] ( identifier[rtype] )
def parse_response(self, request): """Internal method. Parse data received from server. If REQUEST is not None true is returned if the request with that serial number was received, otherwise false is returned. If REQUEST is -1, we're parsing the server connection setup response. """ if request == -1: return self.parse_connection_setup() # depends on [control=['if'], data=[]] # Parse ordinary server response gotreq = 0 while 1: if self.data_recv: # Check the first byte to find out what kind of response it is rtype = byte2int(self.data_recv) # depends on [control=['if'], data=[]] # Are we're waiting for additional data for the current packet? if self.recv_packet_len: if len(self.data_recv) < self.recv_packet_len: return gotreq # depends on [control=['if'], data=[]] if rtype == 1: gotreq = self.parse_request_response(request) or gotreq continue # depends on [control=['if'], data=[]] elif rtype & 127 == ge.GenericEventCode: self.parse_event_response(rtype) continue # depends on [control=['if'], data=[]] else: raise AssertionError(rtype) # depends on [control=['if'], data=[]] # Every response is at least 32 bytes long, so don't bother # until we have received that much if len(self.data_recv) < 32: return gotreq # depends on [control=['if'], data=[]] # Error response if rtype == 0: gotreq = self.parse_error_response(request) or gotreq # depends on [control=['if'], data=[]] # Request response or generic event. elif rtype == 1 or rtype & 127 == ge.GenericEventCode: # Set reply length, and loop around to see if # we have got the full response rlen = int(struct.unpack('=L', self.data_recv[4:8])[0]) self.recv_packet_len = 32 + rlen * 4 # depends on [control=['if'], data=[]] else: # Else non-generic event self.parse_event_response(rtype) # depends on [control=['while'], data=[]]
def _diff_text(left, right, verbose=False): """Return the explanation for the diff between text or bytes Unless --verbose is used this will skip leading and trailing characters which are identical to keep the diff minimal. If the input are bytes they will be safely converted to text. """ from difflib import ndiff explanation = [] if isinstance(left, py.builtin.bytes): left = u(repr(left)[1:-1]).replace(r'\n', '\n') if isinstance(right, py.builtin.bytes): right = u(repr(right)[1:-1]).replace(r'\n', '\n') if not verbose: i = 0 # just in case left or right has zero length for i in range(min(len(left), len(right))): if left[i] != right[i]: break if i > 42: i -= 10 # Provide some context explanation = [u('Skipping %s identical leading ' 'characters in diff, use -v to show') % i] left = left[i:] right = right[i:] if len(left) == len(right): for i in range(len(left)): if left[-i] != right[-i]: break if i > 42: i -= 10 # Provide some context explanation += [u('Skipping %s identical trailing ' 'characters in diff, use -v to show') % i] left = left[:-i] right = right[:-i] keepends = True explanation += [line.strip('\n') for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))] return explanation
def function[_diff_text, parameter[left, right, verbose]]: constant[Return the explanation for the diff between text or bytes Unless --verbose is used this will skip leading and trailing characters which are identical to keep the diff minimal. If the input are bytes they will be safely converted to text. ] from relative_module[difflib] import module[ndiff] variable[explanation] assign[=] list[[]] if call[name[isinstance], parameter[name[left], name[py].builtin.bytes]] begin[:] variable[left] assign[=] call[call[name[u], parameter[call[call[name[repr], parameter[name[left]]]][<ast.Slice object at 0x7da18f7237c0>]]].replace, parameter[constant[\n], constant[ ]]] if call[name[isinstance], parameter[name[right], name[py].builtin.bytes]] begin[:] variable[right] assign[=] call[call[name[u], parameter[call[call[name[repr], parameter[name[right]]]][<ast.Slice object at 0x7da1b14392a0>]]].replace, parameter[constant[\n], constant[ ]]] if <ast.UnaryOp object at 0x7da1b1438700> begin[:] variable[i] assign[=] constant[0] for taget[name[i]] in starred[call[name[range], parameter[call[name[min], parameter[call[name[len], parameter[name[left]]], call[name[len], parameter[name[right]]]]]]]] begin[:] if compare[call[name[left]][name[i]] not_equal[!=] call[name[right]][name[i]]] begin[:] break if compare[name[i] greater[>] constant[42]] begin[:] <ast.AugAssign object at 0x7da1b1439120> variable[explanation] assign[=] list[[<ast.BinOp object at 0x7da1b1438430>]] variable[left] assign[=] call[name[left]][<ast.Slice object at 0x7da1b1438730>] variable[right] assign[=] call[name[right]][<ast.Slice object at 0x7da1b14383d0>] if compare[call[name[len], parameter[name[left]]] equal[==] call[name[len], parameter[name[right]]]] begin[:] for taget[name[i]] in starred[call[name[range], parameter[call[name[len], parameter[name[left]]]]]] begin[:] if compare[call[name[left]][<ast.UnaryOp object at 0x7da1b1438f70>] not_equal[!=] call[name[right]][<ast.UnaryOp object at 0x7da1b1607af0>]] begin[:] break if compare[name[i] greater[>] constant[42]] begin[:] <ast.AugAssign object at 0x7da1b16061a0> <ast.AugAssign object at 0x7da1b1605f90> variable[left] assign[=] call[name[left]][<ast.Slice object at 0x7da1b1606260>] variable[right] assign[=] call[name[right]][<ast.Slice object at 0x7da1b1604be0>] variable[keepends] assign[=] constant[True] <ast.AugAssign object at 0x7da1b1604400> return[name[explanation]]
keyword[def] identifier[_diff_text] ( identifier[left] , identifier[right] , identifier[verbose] = keyword[False] ): literal[string] keyword[from] identifier[difflib] keyword[import] identifier[ndiff] identifier[explanation] =[] keyword[if] identifier[isinstance] ( identifier[left] , identifier[py] . identifier[builtin] . identifier[bytes] ): identifier[left] = identifier[u] ( identifier[repr] ( identifier[left] )[ literal[int] :- literal[int] ]). identifier[replace] ( literal[string] , literal[string] ) keyword[if] identifier[isinstance] ( identifier[right] , identifier[py] . identifier[builtin] . identifier[bytes] ): identifier[right] = identifier[u] ( identifier[repr] ( identifier[right] )[ literal[int] :- literal[int] ]). identifier[replace] ( literal[string] , literal[string] ) keyword[if] keyword[not] identifier[verbose] : identifier[i] = literal[int] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[min] ( identifier[len] ( identifier[left] ), identifier[len] ( identifier[right] ))): keyword[if] identifier[left] [ identifier[i] ]!= identifier[right] [ identifier[i] ]: keyword[break] keyword[if] identifier[i] > literal[int] : identifier[i] -= literal[int] identifier[explanation] =[ identifier[u] ( literal[string] literal[string] )% identifier[i] ] identifier[left] = identifier[left] [ identifier[i] :] identifier[right] = identifier[right] [ identifier[i] :] keyword[if] identifier[len] ( identifier[left] )== identifier[len] ( identifier[right] ): keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[left] )): keyword[if] identifier[left] [- identifier[i] ]!= identifier[right] [- identifier[i] ]: keyword[break] keyword[if] identifier[i] > literal[int] : identifier[i] -= literal[int] identifier[explanation] +=[ identifier[u] ( literal[string] literal[string] )% identifier[i] ] identifier[left] = identifier[left] [:- identifier[i] ] identifier[right] = identifier[right] [:- identifier[i] ] identifier[keepends] = keyword[True] identifier[explanation] +=[ identifier[line] . identifier[strip] ( literal[string] ) keyword[for] identifier[line] keyword[in] identifier[ndiff] ( identifier[left] . identifier[splitlines] ( identifier[keepends] ), identifier[right] . identifier[splitlines] ( identifier[keepends] ))] keyword[return] identifier[explanation]
def _diff_text(left, right, verbose=False): """Return the explanation for the diff between text or bytes Unless --verbose is used this will skip leading and trailing characters which are identical to keep the diff minimal. If the input are bytes they will be safely converted to text. """ from difflib import ndiff explanation = [] if isinstance(left, py.builtin.bytes): left = u(repr(left)[1:-1]).replace('\\n', '\n') # depends on [control=['if'], data=[]] if isinstance(right, py.builtin.bytes): right = u(repr(right)[1:-1]).replace('\\n', '\n') # depends on [control=['if'], data=[]] if not verbose: i = 0 # just in case left or right has zero length for i in range(min(len(left), len(right))): if left[i] != right[i]: break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['i']] if i > 42: i -= 10 # Provide some context explanation = [u('Skipping %s identical leading characters in diff, use -v to show') % i] left = left[i:] right = right[i:] # depends on [control=['if'], data=['i']] if len(left) == len(right): for i in range(len(left)): if left[-i] != right[-i]: break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['i']] if i > 42: i -= 10 # Provide some context explanation += [u('Skipping %s identical trailing characters in diff, use -v to show') % i] left = left[:-i] right = right[:-i] # depends on [control=['if'], data=['i']] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] keepends = True explanation += [line.strip('\n') for line in ndiff(left.splitlines(keepends), right.splitlines(keepends))] return explanation
def connect(self): ''' activates the connection object ''' if not HAVE_ZMQ: raise errors.AnsibleError("zmq is not installed") # this is rough/temporary and will likely be optimized later ... self.context = zmq.Context() socket = self.context.socket(zmq.REQ) addr = "tcp://%s:%s" % (self.host, self.port) socket.connect(addr) self.socket = socket return self
def function[connect, parameter[self]]: constant[ activates the connection object ] if <ast.UnaryOp object at 0x7da2044c3100> begin[:] <ast.Raise object at 0x7da2044c0790> name[self].context assign[=] call[name[zmq].Context, parameter[]] variable[socket] assign[=] call[name[self].context.socket, parameter[name[zmq].REQ]] variable[addr] assign[=] binary_operation[constant[tcp://%s:%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da2044c3040>, <ast.Attribute object at 0x7da2044c0250>]]] call[name[socket].connect, parameter[name[addr]]] name[self].socket assign[=] name[socket] return[name[self]]
keyword[def] identifier[connect] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[HAVE_ZMQ] : keyword[raise] identifier[errors] . identifier[AnsibleError] ( literal[string] ) identifier[self] . identifier[context] = identifier[zmq] . identifier[Context] () identifier[socket] = identifier[self] . identifier[context] . identifier[socket] ( identifier[zmq] . identifier[REQ] ) identifier[addr] = literal[string] %( identifier[self] . identifier[host] , identifier[self] . identifier[port] ) identifier[socket] . identifier[connect] ( identifier[addr] ) identifier[self] . identifier[socket] = identifier[socket] keyword[return] identifier[self]
def connect(self): """ activates the connection object """ if not HAVE_ZMQ: raise errors.AnsibleError('zmq is not installed') # depends on [control=['if'], data=[]] # this is rough/temporary and will likely be optimized later ... self.context = zmq.Context() socket = self.context.socket(zmq.REQ) addr = 'tcp://%s:%s' % (self.host, self.port) socket.connect(addr) self.socket = socket return self
def get_CV_prediction(self): """ Returns: np.ndarray: Predictions on the hold-out folds (unseen data, corresponds to :py:attr:`y`). """ # TODO: get it from the test_prediction ... # test_id, prediction # sort by test_id predict_vec = np.zeros((self._n_rows, self._concise_model._num_tasks)) for fold, train, test in self._kf: acc = self._cv_model[fold].get_accuracy() predict_vec[test, :] = acc["y_test_prediction"] return predict_vec
def function[get_CV_prediction, parameter[self]]: constant[ Returns: np.ndarray: Predictions on the hold-out folds (unseen data, corresponds to :py:attr:`y`). ] variable[predict_vec] assign[=] call[name[np].zeros, parameter[tuple[[<ast.Attribute object at 0x7da204621720>, <ast.Attribute object at 0x7da204620f70>]]]] for taget[tuple[[<ast.Name object at 0x7da204623580>, <ast.Name object at 0x7da204621c30>, <ast.Name object at 0x7da204622980>]]] in starred[name[self]._kf] begin[:] variable[acc] assign[=] call[call[name[self]._cv_model][name[fold]].get_accuracy, parameter[]] call[name[predict_vec]][tuple[[<ast.Name object at 0x7da204620b50>, <ast.Slice object at 0x7da204622fe0>]]] assign[=] call[name[acc]][constant[y_test_prediction]] return[name[predict_vec]]
keyword[def] identifier[get_CV_prediction] ( identifier[self] ): literal[string] identifier[predict_vec] = identifier[np] . identifier[zeros] (( identifier[self] . identifier[_n_rows] , identifier[self] . identifier[_concise_model] . identifier[_num_tasks] )) keyword[for] identifier[fold] , identifier[train] , identifier[test] keyword[in] identifier[self] . identifier[_kf] : identifier[acc] = identifier[self] . identifier[_cv_model] [ identifier[fold] ]. identifier[get_accuracy] () identifier[predict_vec] [ identifier[test] ,:]= identifier[acc] [ literal[string] ] keyword[return] identifier[predict_vec]
def get_CV_prediction(self): """ Returns: np.ndarray: Predictions on the hold-out folds (unseen data, corresponds to :py:attr:`y`). """ # TODO: get it from the test_prediction ... # test_id, prediction # sort by test_id predict_vec = np.zeros((self._n_rows, self._concise_model._num_tasks)) for (fold, train, test) in self._kf: acc = self._cv_model[fold].get_accuracy() predict_vec[test, :] = acc['y_test_prediction'] # depends on [control=['for'], data=[]] return predict_vec
def build_kw_dict(kw_list): """ Build keyword dictionary from raw keyword data. Ignore invalid or invalidated records. Args: kw_list (list): List of dicts from :func:`read_kw_file`. Returns: OrderedDict: dictionary with keyword data. """ kw_dict = OrderedDict() sorted_list = sorted( kw_list, key=lambda x: x.get("zahlavi").encode("utf-8") ) for keyword_data in sorted_list: if "zahlavi" not in keyword_data: continue zahlavi = keyword_data["zahlavi"].encode("utf-8") old_record = kw_dict.get(zahlavi) if not old_record: kw_dict[zahlavi] = keyword_data continue key = "angl_ekvivalent" if not old_record.get(key) and keyword_data.get(key): kw_dict[zahlavi] = keyword_data continue key = "zdroj_angl_ekvivalentu" if not old_record.get(key) and keyword_data.get(key): kw_dict[zahlavi] = keyword_data continue if len(str(keyword_data)) > len(str(old_record)): kw_dict[zahlavi] = keyword_data continue return kw_dict
def function[build_kw_dict, parameter[kw_list]]: constant[ Build keyword dictionary from raw keyword data. Ignore invalid or invalidated records. Args: kw_list (list): List of dicts from :func:`read_kw_file`. Returns: OrderedDict: dictionary with keyword data. ] variable[kw_dict] assign[=] call[name[OrderedDict], parameter[]] variable[sorted_list] assign[=] call[name[sorted], parameter[name[kw_list]]] for taget[name[keyword_data]] in starred[name[sorted_list]] begin[:] if compare[constant[zahlavi] <ast.NotIn object at 0x7da2590d7190> name[keyword_data]] begin[:] continue variable[zahlavi] assign[=] call[call[name[keyword_data]][constant[zahlavi]].encode, parameter[constant[utf-8]]] variable[old_record] assign[=] call[name[kw_dict].get, parameter[name[zahlavi]]] if <ast.UnaryOp object at 0x7da1b0a21cc0> begin[:] call[name[kw_dict]][name[zahlavi]] assign[=] name[keyword_data] continue variable[key] assign[=] constant[angl_ekvivalent] if <ast.BoolOp object at 0x7da1b0a20c10> begin[:] call[name[kw_dict]][name[zahlavi]] assign[=] name[keyword_data] continue variable[key] assign[=] constant[zdroj_angl_ekvivalentu] if <ast.BoolOp object at 0x7da1b0a22c50> begin[:] call[name[kw_dict]][name[zahlavi]] assign[=] name[keyword_data] continue if compare[call[name[len], parameter[call[name[str], parameter[name[keyword_data]]]]] greater[>] call[name[len], parameter[call[name[str], parameter[name[old_record]]]]]] begin[:] call[name[kw_dict]][name[zahlavi]] assign[=] name[keyword_data] continue return[name[kw_dict]]
keyword[def] identifier[build_kw_dict] ( identifier[kw_list] ): literal[string] identifier[kw_dict] = identifier[OrderedDict] () identifier[sorted_list] = identifier[sorted] ( identifier[kw_list] , identifier[key] = keyword[lambda] identifier[x] : identifier[x] . identifier[get] ( literal[string] ). identifier[encode] ( literal[string] ) ) keyword[for] identifier[keyword_data] keyword[in] identifier[sorted_list] : keyword[if] literal[string] keyword[not] keyword[in] identifier[keyword_data] : keyword[continue] identifier[zahlavi] = identifier[keyword_data] [ literal[string] ]. identifier[encode] ( literal[string] ) identifier[old_record] = identifier[kw_dict] . identifier[get] ( identifier[zahlavi] ) keyword[if] keyword[not] identifier[old_record] : identifier[kw_dict] [ identifier[zahlavi] ]= identifier[keyword_data] keyword[continue] identifier[key] = literal[string] keyword[if] keyword[not] identifier[old_record] . identifier[get] ( identifier[key] ) keyword[and] identifier[keyword_data] . identifier[get] ( identifier[key] ): identifier[kw_dict] [ identifier[zahlavi] ]= identifier[keyword_data] keyword[continue] identifier[key] = literal[string] keyword[if] keyword[not] identifier[old_record] . identifier[get] ( identifier[key] ) keyword[and] identifier[keyword_data] . identifier[get] ( identifier[key] ): identifier[kw_dict] [ identifier[zahlavi] ]= identifier[keyword_data] keyword[continue] keyword[if] identifier[len] ( identifier[str] ( identifier[keyword_data] ))> identifier[len] ( identifier[str] ( identifier[old_record] )): identifier[kw_dict] [ identifier[zahlavi] ]= identifier[keyword_data] keyword[continue] keyword[return] identifier[kw_dict]
def build_kw_dict(kw_list): """ Build keyword dictionary from raw keyword data. Ignore invalid or invalidated records. Args: kw_list (list): List of dicts from :func:`read_kw_file`. Returns: OrderedDict: dictionary with keyword data. """ kw_dict = OrderedDict() sorted_list = sorted(kw_list, key=lambda x: x.get('zahlavi').encode('utf-8')) for keyword_data in sorted_list: if 'zahlavi' not in keyword_data: continue # depends on [control=['if'], data=[]] zahlavi = keyword_data['zahlavi'].encode('utf-8') old_record = kw_dict.get(zahlavi) if not old_record: kw_dict[zahlavi] = keyword_data continue # depends on [control=['if'], data=[]] key = 'angl_ekvivalent' if not old_record.get(key) and keyword_data.get(key): kw_dict[zahlavi] = keyword_data continue # depends on [control=['if'], data=[]] key = 'zdroj_angl_ekvivalentu' if not old_record.get(key) and keyword_data.get(key): kw_dict[zahlavi] = keyword_data continue # depends on [control=['if'], data=[]] if len(str(keyword_data)) > len(str(old_record)): kw_dict[zahlavi] = keyword_data continue # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['keyword_data']] return kw_dict
def type(self, *args): """ Usage: type([PSMRL], text, [modifiers]) If a pattern is specified, the pattern is clicked first. Doesn't support text paths. Special keys can be entered with the key name between brackets, as `"{SPACE}"`, or as `Key.SPACE`. """ pattern = None text = None modifiers = None if len(args) == 1 and isinstance(args[0], basestring): # Is a string (or Key) to type text = args[0] elif len(args) == 2: if not isinstance(args[0], basestring) and isinstance(args[1], basestring): pattern = args[0] text = args[1] else: text = args[0] modifiers = args[1] elif len(args) == 3 and not isinstance(args[0], basestring): pattern = args[0] text = args[1] modifiers = args[2] else: raise TypeError("type method expected ([PSMRL], text, [modifiers])") if pattern: self.click(pattern) Debug.history("Typing '{}' with modifiers '{}'".format(text, modifiers)) kb = keyboard if modifiers: kb.keyDown(modifiers) if Settings.TypeDelay > 0: typeSpeed = min(1.0, Settings.TypeDelay) Settings.TypeDelay = 0.0 else: typeSpeed = self._defaultTypeSpeed kb.type(text, typeSpeed) if modifiers: kb.keyUp(modifiers) time.sleep(0.2)
def function[type, parameter[self]]: constant[ Usage: type([PSMRL], text, [modifiers]) If a pattern is specified, the pattern is clicked first. Doesn't support text paths. Special keys can be entered with the key name between brackets, as `"{SPACE}"`, or as `Key.SPACE`. ] variable[pattern] assign[=] constant[None] variable[text] assign[=] constant[None] variable[modifiers] assign[=] constant[None] if <ast.BoolOp object at 0x7da204622ec0> begin[:] variable[text] assign[=] call[name[args]][constant[0]] if name[pattern] begin[:] call[name[self].click, parameter[name[pattern]]] call[name[Debug].history, parameter[call[constant[Typing '{}' with modifiers '{}'].format, parameter[name[text], name[modifiers]]]]] variable[kb] assign[=] name[keyboard] if name[modifiers] begin[:] call[name[kb].keyDown, parameter[name[modifiers]]] if compare[name[Settings].TypeDelay greater[>] constant[0]] begin[:] variable[typeSpeed] assign[=] call[name[min], parameter[constant[1.0], name[Settings].TypeDelay]] name[Settings].TypeDelay assign[=] constant[0.0] call[name[kb].type, parameter[name[text], name[typeSpeed]]] if name[modifiers] begin[:] call[name[kb].keyUp, parameter[name[modifiers]]] call[name[time].sleep, parameter[constant[0.2]]]
keyword[def] identifier[type] ( identifier[self] ,* identifier[args] ): literal[string] identifier[pattern] = keyword[None] identifier[text] = keyword[None] identifier[modifiers] = keyword[None] keyword[if] identifier[len] ( identifier[args] )== literal[int] keyword[and] identifier[isinstance] ( identifier[args] [ literal[int] ], identifier[basestring] ): identifier[text] = identifier[args] [ literal[int] ] keyword[elif] identifier[len] ( identifier[args] )== literal[int] : keyword[if] keyword[not] identifier[isinstance] ( identifier[args] [ literal[int] ], identifier[basestring] ) keyword[and] identifier[isinstance] ( identifier[args] [ literal[int] ], identifier[basestring] ): identifier[pattern] = identifier[args] [ literal[int] ] identifier[text] = identifier[args] [ literal[int] ] keyword[else] : identifier[text] = identifier[args] [ literal[int] ] identifier[modifiers] = identifier[args] [ literal[int] ] keyword[elif] identifier[len] ( identifier[args] )== literal[int] keyword[and] keyword[not] identifier[isinstance] ( identifier[args] [ literal[int] ], identifier[basestring] ): identifier[pattern] = identifier[args] [ literal[int] ] identifier[text] = identifier[args] [ literal[int] ] identifier[modifiers] = identifier[args] [ literal[int] ] keyword[else] : keyword[raise] identifier[TypeError] ( literal[string] ) keyword[if] identifier[pattern] : identifier[self] . identifier[click] ( identifier[pattern] ) identifier[Debug] . identifier[history] ( literal[string] . identifier[format] ( identifier[text] , identifier[modifiers] )) identifier[kb] = identifier[keyboard] keyword[if] identifier[modifiers] : identifier[kb] . identifier[keyDown] ( identifier[modifiers] ) keyword[if] identifier[Settings] . identifier[TypeDelay] > literal[int] : identifier[typeSpeed] = identifier[min] ( literal[int] , identifier[Settings] . identifier[TypeDelay] ) identifier[Settings] . identifier[TypeDelay] = literal[int] keyword[else] : identifier[typeSpeed] = identifier[self] . identifier[_defaultTypeSpeed] identifier[kb] . identifier[type] ( identifier[text] , identifier[typeSpeed] ) keyword[if] identifier[modifiers] : identifier[kb] . identifier[keyUp] ( identifier[modifiers] ) identifier[time] . identifier[sleep] ( literal[int] )
def type(self, *args): """ Usage: type([PSMRL], text, [modifiers]) If a pattern is specified, the pattern is clicked first. Doesn't support text paths. Special keys can be entered with the key name between brackets, as `"{SPACE}"`, or as `Key.SPACE`. """ pattern = None text = None modifiers = None if len(args) == 1 and isinstance(args[0], basestring): # Is a string (or Key) to type text = args[0] # depends on [control=['if'], data=[]] elif len(args) == 2: if not isinstance(args[0], basestring) and isinstance(args[1], basestring): pattern = args[0] text = args[1] # depends on [control=['if'], data=[]] else: text = args[0] modifiers = args[1] # depends on [control=['if'], data=[]] elif len(args) == 3 and (not isinstance(args[0], basestring)): pattern = args[0] text = args[1] modifiers = args[2] # depends on [control=['if'], data=[]] else: raise TypeError('type method expected ([PSMRL], text, [modifiers])') if pattern: self.click(pattern) # depends on [control=['if'], data=[]] Debug.history("Typing '{}' with modifiers '{}'".format(text, modifiers)) kb = keyboard if modifiers: kb.keyDown(modifiers) # depends on [control=['if'], data=[]] if Settings.TypeDelay > 0: typeSpeed = min(1.0, Settings.TypeDelay) Settings.TypeDelay = 0.0 # depends on [control=['if'], data=[]] else: typeSpeed = self._defaultTypeSpeed kb.type(text, typeSpeed) if modifiers: kb.keyUp(modifiers) # depends on [control=['if'], data=[]] time.sleep(0.2)
def validate_minimum(value, minimum, is_exclusive, **kwargs): """ Validator function for validating that a value does not violate it's minimum allowed value. This validation can be inclusive, or exclusive of the minimum depending on the value of `is_exclusive`. """ if is_exclusive: comparison_text = "greater than" compare_fn = operator.gt else: comparison_text = "greater than or equal to" compare_fn = operator.ge if not compare_fn(value, minimum): raise ValidationError( MESSAGES['minimum']['invalid'].format(value, comparison_text, minimum), )
def function[validate_minimum, parameter[value, minimum, is_exclusive]]: constant[ Validator function for validating that a value does not violate it's minimum allowed value. This validation can be inclusive, or exclusive of the minimum depending on the value of `is_exclusive`. ] if name[is_exclusive] begin[:] variable[comparison_text] assign[=] constant[greater than] variable[compare_fn] assign[=] name[operator].gt if <ast.UnaryOp object at 0x7da1b0f0f4f0> begin[:] <ast.Raise object at 0x7da1b0f0e3e0>
keyword[def] identifier[validate_minimum] ( identifier[value] , identifier[minimum] , identifier[is_exclusive] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[is_exclusive] : identifier[comparison_text] = literal[string] identifier[compare_fn] = identifier[operator] . identifier[gt] keyword[else] : identifier[comparison_text] = literal[string] identifier[compare_fn] = identifier[operator] . identifier[ge] keyword[if] keyword[not] identifier[compare_fn] ( identifier[value] , identifier[minimum] ): keyword[raise] identifier[ValidationError] ( identifier[MESSAGES] [ literal[string] ][ literal[string] ]. identifier[format] ( identifier[value] , identifier[comparison_text] , identifier[minimum] ), )
def validate_minimum(value, minimum, is_exclusive, **kwargs): """ Validator function for validating that a value does not violate it's minimum allowed value. This validation can be inclusive, or exclusive of the minimum depending on the value of `is_exclusive`. """ if is_exclusive: comparison_text = 'greater than' compare_fn = operator.gt # depends on [control=['if'], data=[]] else: comparison_text = 'greater than or equal to' compare_fn = operator.ge if not compare_fn(value, minimum): raise ValidationError(MESSAGES['minimum']['invalid'].format(value, comparison_text, minimum)) # depends on [control=['if'], data=[]]
def _create_group_tree(self, levels): """This method creates a group tree""" if levels[0] != 0: raise KPError("Invalid group tree") for i in range(len(self.groups)): if(levels[i] == 0): self.groups[i].parent = self.root_group self.groups[i].index = len(self.root_group.children) self.root_group.children.append(self.groups[i]) continue j = i-1 while j >= 0: if levels[j] < levels[i]: if levels[i]-levels[j] != 1: raise KPError("Invalid group tree") self.groups[i].parent = self.groups[j] self.groups[i].index = len(self.groups[j].children) self.groups[i].parent.children.append(self.groups[i]) break if j == 0: raise KPError("Invalid group tree") j -= 1 for e in range(len(self.entries)): for g in range(len(self.groups)): if self.entries[e].group_id == self.groups[g].id_: self.groups[g].entries.append(self.entries[e]) self.entries[e].group = self.groups[g] # from original KeePassX-code, but what does it do? self.entries[e].index = 0 return True
def function[_create_group_tree, parameter[self, levels]]: constant[This method creates a group tree] if compare[call[name[levels]][constant[0]] not_equal[!=] constant[0]] begin[:] <ast.Raise object at 0x7da1b252bd00> for taget[name[i]] in starred[call[name[range], parameter[call[name[len], parameter[name[self].groups]]]]] begin[:] if compare[call[name[levels]][name[i]] equal[==] constant[0]] begin[:] call[name[self].groups][name[i]].parent assign[=] name[self].root_group call[name[self].groups][name[i]].index assign[=] call[name[len], parameter[name[self].root_group.children]] call[name[self].root_group.children.append, parameter[call[name[self].groups][name[i]]]] continue variable[j] assign[=] binary_operation[name[i] - constant[1]] while compare[name[j] greater_or_equal[>=] constant[0]] begin[:] if compare[call[name[levels]][name[j]] less[<] call[name[levels]][name[i]]] begin[:] if compare[binary_operation[call[name[levels]][name[i]] - call[name[levels]][name[j]]] not_equal[!=] constant[1]] begin[:] <ast.Raise object at 0x7da1b252ae60> call[name[self].groups][name[i]].parent assign[=] call[name[self].groups][name[j]] call[name[self].groups][name[i]].index assign[=] call[name[len], parameter[call[name[self].groups][name[j]].children]] call[call[name[self].groups][name[i]].parent.children.append, parameter[call[name[self].groups][name[i]]]] break if compare[name[j] equal[==] constant[0]] begin[:] <ast.Raise object at 0x7da1b252a590> <ast.AugAssign object at 0x7da1b252a4d0> for taget[name[e]] in starred[call[name[range], parameter[call[name[len], parameter[name[self].entries]]]]] begin[:] for taget[name[g]] in starred[call[name[range], parameter[call[name[len], parameter[name[self].groups]]]]] begin[:] if compare[call[name[self].entries][name[e]].group_id equal[==] call[name[self].groups][name[g]].id_] begin[:] call[call[name[self].groups][name[g]].entries.append, parameter[call[name[self].entries][name[e]]]] call[name[self].entries][name[e]].group assign[=] call[name[self].groups][name[g]] call[name[self].entries][name[e]].index assign[=] constant[0] return[constant[True]]
keyword[def] identifier[_create_group_tree] ( identifier[self] , identifier[levels] ): literal[string] keyword[if] identifier[levels] [ literal[int] ]!= literal[int] : keyword[raise] identifier[KPError] ( literal[string] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[self] . identifier[groups] )): keyword[if] ( identifier[levels] [ identifier[i] ]== literal[int] ): identifier[self] . identifier[groups] [ identifier[i] ]. identifier[parent] = identifier[self] . identifier[root_group] identifier[self] . identifier[groups] [ identifier[i] ]. identifier[index] = identifier[len] ( identifier[self] . identifier[root_group] . identifier[children] ) identifier[self] . identifier[root_group] . identifier[children] . identifier[append] ( identifier[self] . identifier[groups] [ identifier[i] ]) keyword[continue] identifier[j] = identifier[i] - literal[int] keyword[while] identifier[j] >= literal[int] : keyword[if] identifier[levels] [ identifier[j] ]< identifier[levels] [ identifier[i] ]: keyword[if] identifier[levels] [ identifier[i] ]- identifier[levels] [ identifier[j] ]!= literal[int] : keyword[raise] identifier[KPError] ( literal[string] ) identifier[self] . identifier[groups] [ identifier[i] ]. identifier[parent] = identifier[self] . identifier[groups] [ identifier[j] ] identifier[self] . identifier[groups] [ identifier[i] ]. identifier[index] = identifier[len] ( identifier[self] . identifier[groups] [ identifier[j] ]. identifier[children] ) identifier[self] . identifier[groups] [ identifier[i] ]. identifier[parent] . identifier[children] . identifier[append] ( identifier[self] . identifier[groups] [ identifier[i] ]) keyword[break] keyword[if] identifier[j] == literal[int] : keyword[raise] identifier[KPError] ( literal[string] ) identifier[j] -= literal[int] keyword[for] identifier[e] keyword[in] identifier[range] ( identifier[len] ( identifier[self] . identifier[entries] )): keyword[for] identifier[g] keyword[in] identifier[range] ( identifier[len] ( identifier[self] . identifier[groups] )): keyword[if] identifier[self] . identifier[entries] [ identifier[e] ]. identifier[group_id] == identifier[self] . identifier[groups] [ identifier[g] ]. identifier[id_] : identifier[self] . identifier[groups] [ identifier[g] ]. identifier[entries] . identifier[append] ( identifier[self] . identifier[entries] [ identifier[e] ]) identifier[self] . identifier[entries] [ identifier[e] ]. identifier[group] = identifier[self] . identifier[groups] [ identifier[g] ] identifier[self] . identifier[entries] [ identifier[e] ]. identifier[index] = literal[int] keyword[return] keyword[True]
def _create_group_tree(self, levels): """This method creates a group tree""" if levels[0] != 0: raise KPError('Invalid group tree') # depends on [control=['if'], data=[]] for i in range(len(self.groups)): if levels[i] == 0: self.groups[i].parent = self.root_group self.groups[i].index = len(self.root_group.children) self.root_group.children.append(self.groups[i]) continue # depends on [control=['if'], data=[]] j = i - 1 while j >= 0: if levels[j] < levels[i]: if levels[i] - levels[j] != 1: raise KPError('Invalid group tree') # depends on [control=['if'], data=[]] self.groups[i].parent = self.groups[j] self.groups[i].index = len(self.groups[j].children) self.groups[i].parent.children.append(self.groups[i]) break # depends on [control=['if'], data=[]] if j == 0: raise KPError('Invalid group tree') # depends on [control=['if'], data=[]] j -= 1 # depends on [control=['while'], data=['j']] # depends on [control=['for'], data=['i']] for e in range(len(self.entries)): for g in range(len(self.groups)): if self.entries[e].group_id == self.groups[g].id_: self.groups[g].entries.append(self.entries[e]) self.entries[e].group = self.groups[g] # from original KeePassX-code, but what does it do? self.entries[e].index = 0 # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['g']] # depends on [control=['for'], data=['e']] return True
def _create_sample_file(data, out_dir): """from data list all the fastq files in a file""" sample_file = os.path.join(out_dir, "sample_file.txt") with open(sample_file, 'w') as outh: for sample in data: outh.write(sample[0]["clean_fastq"] + "\n") return sample_file
def function[_create_sample_file, parameter[data, out_dir]]: constant[from data list all the fastq files in a file] variable[sample_file] assign[=] call[name[os].path.join, parameter[name[out_dir], constant[sample_file.txt]]] with call[name[open], parameter[name[sample_file], constant[w]]] begin[:] for taget[name[sample]] in starred[name[data]] begin[:] call[name[outh].write, parameter[binary_operation[call[call[name[sample]][constant[0]]][constant[clean_fastq]] + constant[ ]]]] return[name[sample_file]]
keyword[def] identifier[_create_sample_file] ( identifier[data] , identifier[out_dir] ): literal[string] identifier[sample_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[out_dir] , literal[string] ) keyword[with] identifier[open] ( identifier[sample_file] , literal[string] ) keyword[as] identifier[outh] : keyword[for] identifier[sample] keyword[in] identifier[data] : identifier[outh] . identifier[write] ( identifier[sample] [ literal[int] ][ literal[string] ]+ literal[string] ) keyword[return] identifier[sample_file]
def _create_sample_file(data, out_dir): """from data list all the fastq files in a file""" sample_file = os.path.join(out_dir, 'sample_file.txt') with open(sample_file, 'w') as outh: for sample in data: outh.write(sample[0]['clean_fastq'] + '\n') # depends on [control=['for'], data=['sample']] # depends on [control=['with'], data=['outh']] return sample_file
def sample_qubo(self, qubo, **params): """Sample from the specified QUBO. Args: qubo (dict of (int, int):float): Coefficients of a quadratic unconstrained binary optimization (QUBO) model. **params: Parameters for the sampling method, specified per solver. Returns: :obj:`Future` Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, submits a :term:`QUBO` problem (a Boolean NOT gate represented by a penalty model), and samples 5 times. >>> from dwave.cloud import Client >>> with Client.from_config() as client: # doctest: +SKIP ... solver = client.get_solver() ... u, v = next(iter(solver.edges)) ... Q = {(u, u): -1, (u, v): 0, (v, u): 2, (v, v): -1} ... computation = solver.sample_qubo(Q, num_reads=5) ... for i in range(5): ... print(computation.samples[i][u], computation.samples[i][v]) ... ... (0, 1) (1, 0) (1, 0) (0, 1) (1, 0) """ # In a QUBO the linear and quadratic terms in the objective are mixed into # a matrix. For the sake of encoding, we will separate them before calling `_sample` linear = {i1: v for (i1, i2), v in uniform_iterator(qubo) if i1 == i2} quadratic = {(i1, i2): v for (i1, i2), v in uniform_iterator(qubo) if i1 != i2} return self._sample('qubo', linear, quadratic, params)
def function[sample_qubo, parameter[self, qubo]]: constant[Sample from the specified QUBO. Args: qubo (dict of (int, int):float): Coefficients of a quadratic unconstrained binary optimization (QUBO) model. **params: Parameters for the sampling method, specified per solver. Returns: :obj:`Future` Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, submits a :term:`QUBO` problem (a Boolean NOT gate represented by a penalty model), and samples 5 times. >>> from dwave.cloud import Client >>> with Client.from_config() as client: # doctest: +SKIP ... solver = client.get_solver() ... u, v = next(iter(solver.edges)) ... Q = {(u, u): -1, (u, v): 0, (v, u): 2, (v, v): -1} ... computation = solver.sample_qubo(Q, num_reads=5) ... for i in range(5): ... print(computation.samples[i][u], computation.samples[i][v]) ... ... (0, 1) (1, 0) (1, 0) (0, 1) (1, 0) ] variable[linear] assign[=] <ast.DictComp object at 0x7da1b0fc48b0> variable[quadratic] assign[=] <ast.DictComp object at 0x7da1b0fc7d30> return[call[name[self]._sample, parameter[constant[qubo], name[linear], name[quadratic], name[params]]]]
keyword[def] identifier[sample_qubo] ( identifier[self] , identifier[qubo] ,** identifier[params] ): literal[string] identifier[linear] ={ identifier[i1] : identifier[v] keyword[for] ( identifier[i1] , identifier[i2] ), identifier[v] keyword[in] identifier[uniform_iterator] ( identifier[qubo] ) keyword[if] identifier[i1] == identifier[i2] } identifier[quadratic] ={( identifier[i1] , identifier[i2] ): identifier[v] keyword[for] ( identifier[i1] , identifier[i2] ), identifier[v] keyword[in] identifier[uniform_iterator] ( identifier[qubo] ) keyword[if] identifier[i1] != identifier[i2] } keyword[return] identifier[self] . identifier[_sample] ( literal[string] , identifier[linear] , identifier[quadratic] , identifier[params] )
def sample_qubo(self, qubo, **params): """Sample from the specified QUBO. Args: qubo (dict of (int, int):float): Coefficients of a quadratic unconstrained binary optimization (QUBO) model. **params: Parameters for the sampling method, specified per solver. Returns: :obj:`Future` Examples: This example creates a client using the local system's default D-Wave Cloud Client configuration file, which is configured to access a D-Wave 2000Q QPU, submits a :term:`QUBO` problem (a Boolean NOT gate represented by a penalty model), and samples 5 times. >>> from dwave.cloud import Client >>> with Client.from_config() as client: # doctest: +SKIP ... solver = client.get_solver() ... u, v = next(iter(solver.edges)) ... Q = {(u, u): -1, (u, v): 0, (v, u): 2, (v, v): -1} ... computation = solver.sample_qubo(Q, num_reads=5) ... for i in range(5): ... print(computation.samples[i][u], computation.samples[i][v]) ... ... (0, 1) (1, 0) (1, 0) (0, 1) (1, 0) """ # In a QUBO the linear and quadratic terms in the objective are mixed into # a matrix. For the sake of encoding, we will separate them before calling `_sample` linear = {i1: v for ((i1, i2), v) in uniform_iterator(qubo) if i1 == i2} quadratic = {(i1, i2): v for ((i1, i2), v) in uniform_iterator(qubo) if i1 != i2} return self._sample('qubo', linear, quadratic, params)
def _connection(self, value): """ If the value is a pipeline, save it as the connection to use for pipelines if to be shared in threads or goot thread. Do not remove the direct connection. If it is not a pipeline, clear it, and set the direct connection again. """ if isinstance(value, _Pipeline): self._pipelined_connection = value else: self._direct_connection = value self._pipelined_connection = None
def function[_connection, parameter[self, value]]: constant[ If the value is a pipeline, save it as the connection to use for pipelines if to be shared in threads or goot thread. Do not remove the direct connection. If it is not a pipeline, clear it, and set the direct connection again. ] if call[name[isinstance], parameter[name[value], name[_Pipeline]]] begin[:] name[self]._pipelined_connection assign[=] name[value]
keyword[def] identifier[_connection] ( identifier[self] , identifier[value] ): literal[string] keyword[if] identifier[isinstance] ( identifier[value] , identifier[_Pipeline] ): identifier[self] . identifier[_pipelined_connection] = identifier[value] keyword[else] : identifier[self] . identifier[_direct_connection] = identifier[value] identifier[self] . identifier[_pipelined_connection] = keyword[None]
def _connection(self, value): """ If the value is a pipeline, save it as the connection to use for pipelines if to be shared in threads or goot thread. Do not remove the direct connection. If it is not a pipeline, clear it, and set the direct connection again. """ if isinstance(value, _Pipeline): self._pipelined_connection = value # depends on [control=['if'], data=[]] else: self._direct_connection = value self._pipelined_connection = None
def listcomprehension_walk2(self, node): """List comprehensions the way they are done in Python 2 and sometimes in Python 3. They're more other comprehensions, e.g. set comprehensions See if we can combine code. """ p = self.prec self.prec = 27 code = Code(node[1].attr, self.scanner, self.currentclass) ast = self.build_ast(code._tokens, code._customize) self.customize(code._customize) # skip over: sstmt, stmt, return, ret_expr # and other singleton derivations while (len(ast) == 1 or (ast in ('sstmt', 'return') and ast[-1] in ('RETURN_LAST', 'RETURN_VALUE'))): self.prec = 100 ast = ast[0] n = ast[1] # collection = node[-3] collections = [node[-3]] list_ifs = [] if self.version == 3.0 and n != 'list_iter': # FIXME 3.0 is a snowflake here. We need # special code for this. Not sure if this is totally # correct. stores = [ast[3]] assert ast[4] == 'comp_iter' n = ast[4] # Find the list comprehension body. It is the inner-most # node that is not comp_.. . while n == 'comp_iter': if n[0] == 'comp_for': n = n[0] stores.append(n[2]) n = n[3] elif n[0] in ('comp_if', 'comp_if_not'): n = n[0] # FIXME: just a guess if n[0].kind == 'expr': list_ifs.append(n) else: list_ifs.append([1]) n = n[2] pass else: break pass # Skip over n[0] which is something like: _[1] self.preorder(n[1]) else: assert n == 'list_iter' stores = [] # Find the list comprehension body. It is the inner-most # node that is not list_.. . while n == 'list_iter': n = n[0] # recurse one step if n == 'list_for': stores.append(n[2]) n = n[3] if self.version >= 3.6 and n[0] == 'list_for': # Dog-paddle down largely singleton reductions # to find the collection (expr) c = n[0][0] if c == 'expr': c = c[0] # FIXME: grammar is wonky here? Is this really an attribute? if c == 'attribute': c = c[0] collections.append(c) pass elif n in ('list_if', 'list_if_not'): # FIXME: just a guess if n[0].kind == 'expr': list_ifs.append(n) else: list_ifs.append([1]) n = n[2] pass pass assert n == 'lc_body', ast self.preorder(n[0]) # FIXME: add indentation around "for"'s and "in"'s if self.version < 3.6: self.write(' for ') self.preorder(stores[0]) self.write(' in ') self.preorder(collections[0]) if list_ifs: self.preorder(list_ifs[0]) pass else: for i, store in enumerate(stores): self.write(' for ') self.preorder(store) self.write(' in ') self.preorder(collections[i]) if i < len(list_ifs): self.preorder(list_ifs[i]) pass pass self.prec = p
def function[listcomprehension_walk2, parameter[self, node]]: constant[List comprehensions the way they are done in Python 2 and sometimes in Python 3. They're more other comprehensions, e.g. set comprehensions See if we can combine code. ] variable[p] assign[=] name[self].prec name[self].prec assign[=] constant[27] variable[code] assign[=] call[name[Code], parameter[call[name[node]][constant[1]].attr, name[self].scanner, name[self].currentclass]] variable[ast] assign[=] call[name[self].build_ast, parameter[name[code]._tokens, name[code]._customize]] call[name[self].customize, parameter[name[code]._customize]] while <ast.BoolOp object at 0x7da18dc04cd0> begin[:] name[self].prec assign[=] constant[100] variable[ast] assign[=] call[name[ast]][constant[0]] variable[n] assign[=] call[name[ast]][constant[1]] variable[collections] assign[=] list[[<ast.Subscript object at 0x7da18dc07d30>]] variable[list_ifs] assign[=] list[[]] if <ast.BoolOp object at 0x7da18dc07c10> begin[:] variable[stores] assign[=] list[[<ast.Subscript object at 0x7da18dc04400>]] assert[compare[call[name[ast]][constant[4]] equal[==] constant[comp_iter]]] variable[n] assign[=] call[name[ast]][constant[4]] while compare[name[n] equal[==] constant[comp_iter]] begin[:] if compare[call[name[n]][constant[0]] equal[==] constant[comp_for]] begin[:] variable[n] assign[=] call[name[n]][constant[0]] call[name[stores].append, parameter[call[name[n]][constant[2]]]] variable[n] assign[=] call[name[n]][constant[3]] pass call[name[self].preorder, parameter[call[name[n]][constant[1]]]] if compare[name[self].version less[<] constant[3.6]] begin[:] call[name[self].write, parameter[constant[ for ]]] call[name[self].preorder, parameter[call[name[stores]][constant[0]]]] call[name[self].write, parameter[constant[ in ]]] call[name[self].preorder, parameter[call[name[collections]][constant[0]]]] if name[list_ifs] begin[:] call[name[self].preorder, parameter[call[name[list_ifs]][constant[0]]]] pass name[self].prec assign[=] name[p]
keyword[def] identifier[listcomprehension_walk2] ( identifier[self] , identifier[node] ): literal[string] identifier[p] = identifier[self] . identifier[prec] identifier[self] . identifier[prec] = literal[int] identifier[code] = identifier[Code] ( identifier[node] [ literal[int] ]. identifier[attr] , identifier[self] . identifier[scanner] , identifier[self] . identifier[currentclass] ) identifier[ast] = identifier[self] . identifier[build_ast] ( identifier[code] . identifier[_tokens] , identifier[code] . identifier[_customize] ) identifier[self] . identifier[customize] ( identifier[code] . identifier[_customize] ) keyword[while] ( identifier[len] ( identifier[ast] )== literal[int] keyword[or] ( identifier[ast] keyword[in] ( literal[string] , literal[string] ) keyword[and] identifier[ast] [- literal[int] ] keyword[in] ( literal[string] , literal[string] ))): identifier[self] . identifier[prec] = literal[int] identifier[ast] = identifier[ast] [ literal[int] ] identifier[n] = identifier[ast] [ literal[int] ] identifier[collections] =[ identifier[node] [- literal[int] ]] identifier[list_ifs] =[] keyword[if] identifier[self] . identifier[version] == literal[int] keyword[and] identifier[n] != literal[string] : identifier[stores] =[ identifier[ast] [ literal[int] ]] keyword[assert] identifier[ast] [ literal[int] ]== literal[string] identifier[n] = identifier[ast] [ literal[int] ] keyword[while] identifier[n] == literal[string] : keyword[if] identifier[n] [ literal[int] ]== literal[string] : identifier[n] = identifier[n] [ literal[int] ] identifier[stores] . identifier[append] ( identifier[n] [ literal[int] ]) identifier[n] = identifier[n] [ literal[int] ] keyword[elif] identifier[n] [ literal[int] ] keyword[in] ( literal[string] , literal[string] ): identifier[n] = identifier[n] [ literal[int] ] keyword[if] identifier[n] [ literal[int] ]. identifier[kind] == literal[string] : identifier[list_ifs] . identifier[append] ( identifier[n] ) keyword[else] : identifier[list_ifs] . identifier[append] ([ literal[int] ]) identifier[n] = identifier[n] [ literal[int] ] keyword[pass] keyword[else] : keyword[break] keyword[pass] identifier[self] . identifier[preorder] ( identifier[n] [ literal[int] ]) keyword[else] : keyword[assert] identifier[n] == literal[string] identifier[stores] =[] keyword[while] identifier[n] == literal[string] : identifier[n] = identifier[n] [ literal[int] ] keyword[if] identifier[n] == literal[string] : identifier[stores] . identifier[append] ( identifier[n] [ literal[int] ]) identifier[n] = identifier[n] [ literal[int] ] keyword[if] identifier[self] . identifier[version] >= literal[int] keyword[and] identifier[n] [ literal[int] ]== literal[string] : identifier[c] = identifier[n] [ literal[int] ][ literal[int] ] keyword[if] identifier[c] == literal[string] : identifier[c] = identifier[c] [ literal[int] ] keyword[if] identifier[c] == literal[string] : identifier[c] = identifier[c] [ literal[int] ] identifier[collections] . identifier[append] ( identifier[c] ) keyword[pass] keyword[elif] identifier[n] keyword[in] ( literal[string] , literal[string] ): keyword[if] identifier[n] [ literal[int] ]. identifier[kind] == literal[string] : identifier[list_ifs] . identifier[append] ( identifier[n] ) keyword[else] : identifier[list_ifs] . identifier[append] ([ literal[int] ]) identifier[n] = identifier[n] [ literal[int] ] keyword[pass] keyword[pass] keyword[assert] identifier[n] == literal[string] , identifier[ast] identifier[self] . identifier[preorder] ( identifier[n] [ literal[int] ]) keyword[if] identifier[self] . identifier[version] < literal[int] : identifier[self] . identifier[write] ( literal[string] ) identifier[self] . identifier[preorder] ( identifier[stores] [ literal[int] ]) identifier[self] . identifier[write] ( literal[string] ) identifier[self] . identifier[preorder] ( identifier[collections] [ literal[int] ]) keyword[if] identifier[list_ifs] : identifier[self] . identifier[preorder] ( identifier[list_ifs] [ literal[int] ]) keyword[pass] keyword[else] : keyword[for] identifier[i] , identifier[store] keyword[in] identifier[enumerate] ( identifier[stores] ): identifier[self] . identifier[write] ( literal[string] ) identifier[self] . identifier[preorder] ( identifier[store] ) identifier[self] . identifier[write] ( literal[string] ) identifier[self] . identifier[preorder] ( identifier[collections] [ identifier[i] ]) keyword[if] identifier[i] < identifier[len] ( identifier[list_ifs] ): identifier[self] . identifier[preorder] ( identifier[list_ifs] [ identifier[i] ]) keyword[pass] keyword[pass] identifier[self] . identifier[prec] = identifier[p]
def listcomprehension_walk2(self, node): """List comprehensions the way they are done in Python 2 and sometimes in Python 3. They're more other comprehensions, e.g. set comprehensions See if we can combine code. """ p = self.prec self.prec = 27 code = Code(node[1].attr, self.scanner, self.currentclass) ast = self.build_ast(code._tokens, code._customize) self.customize(code._customize) # skip over: sstmt, stmt, return, ret_expr # and other singleton derivations while len(ast) == 1 or (ast in ('sstmt', 'return') and ast[-1] in ('RETURN_LAST', 'RETURN_VALUE')): self.prec = 100 ast = ast[0] # depends on [control=['while'], data=[]] n = ast[1] # collection = node[-3] collections = [node[-3]] list_ifs = [] if self.version == 3.0 and n != 'list_iter': # FIXME 3.0 is a snowflake here. We need # special code for this. Not sure if this is totally # correct. stores = [ast[3]] assert ast[4] == 'comp_iter' n = ast[4] # Find the list comprehension body. It is the inner-most # node that is not comp_.. . while n == 'comp_iter': if n[0] == 'comp_for': n = n[0] stores.append(n[2]) n = n[3] # depends on [control=['if'], data=[]] elif n[0] in ('comp_if', 'comp_if_not'): n = n[0] # FIXME: just a guess if n[0].kind == 'expr': list_ifs.append(n) # depends on [control=['if'], data=[]] else: list_ifs.append([1]) n = n[2] pass # depends on [control=['if'], data=[]] else: break pass # depends on [control=['while'], data=['n']] # Skip over n[0] which is something like: _[1] self.preorder(n[1]) # depends on [control=['if'], data=[]] else: assert n == 'list_iter' stores = [] # Find the list comprehension body. It is the inner-most # node that is not list_.. . while n == 'list_iter': n = n[0] # recurse one step if n == 'list_for': stores.append(n[2]) n = n[3] if self.version >= 3.6 and n[0] == 'list_for': # Dog-paddle down largely singleton reductions # to find the collection (expr) c = n[0][0] if c == 'expr': c = c[0] # depends on [control=['if'], data=['c']] # FIXME: grammar is wonky here? Is this really an attribute? if c == 'attribute': c = c[0] # depends on [control=['if'], data=['c']] collections.append(c) pass # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['n']] elif n in ('list_if', 'list_if_not'): # FIXME: just a guess if n[0].kind == 'expr': list_ifs.append(n) # depends on [control=['if'], data=[]] else: list_ifs.append([1]) n = n[2] pass # depends on [control=['if'], data=['n']] pass # depends on [control=['while'], data=['n']] assert n == 'lc_body', ast self.preorder(n[0]) # FIXME: add indentation around "for"'s and "in"'s if self.version < 3.6: self.write(' for ') self.preorder(stores[0]) self.write(' in ') self.preorder(collections[0]) if list_ifs: self.preorder(list_ifs[0]) pass # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] else: for (i, store) in enumerate(stores): self.write(' for ') self.preorder(store) self.write(' in ') self.preorder(collections[i]) if i < len(list_ifs): self.preorder(list_ifs[i]) pass # depends on [control=['if'], data=['i']] pass # depends on [control=['for'], data=[]] self.prec = p
def untag(collector, image, artifact, **kwargs): """Tag an image!""" if artifact in (None, "", NotSpecified): artifact = collector.configuration["harpoon"].tag if artifact is NotSpecified: raise BadOption("Please specify a tag using the artifact or tag options") image.tag = artifact image_name = image.image_name_with_tag log.info("Removing image\timage={0}".format(image_name)) try: image.harpoon.docker_api.remove_image(image_name) except docker.errors.ImageNotFound: log.warning("No image was found to remove")
def function[untag, parameter[collector, image, artifact]]: constant[Tag an image!] if compare[name[artifact] in tuple[[<ast.Constant object at 0x7da2041d9630>, <ast.Constant object at 0x7da2041d9540>, <ast.Name object at 0x7da2041d9240>]]] begin[:] variable[artifact] assign[=] call[name[collector].configuration][constant[harpoon]].tag if compare[name[artifact] is name[NotSpecified]] begin[:] <ast.Raise object at 0x7da2041da4a0> name[image].tag assign[=] name[artifact] variable[image_name] assign[=] name[image].image_name_with_tag call[name[log].info, parameter[call[constant[Removing image image={0}].format, parameter[name[image_name]]]]] <ast.Try object at 0x7da18c4cc2e0>
keyword[def] identifier[untag] ( identifier[collector] , identifier[image] , identifier[artifact] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[artifact] keyword[in] ( keyword[None] , literal[string] , identifier[NotSpecified] ): identifier[artifact] = identifier[collector] . identifier[configuration] [ literal[string] ]. identifier[tag] keyword[if] identifier[artifact] keyword[is] identifier[NotSpecified] : keyword[raise] identifier[BadOption] ( literal[string] ) identifier[image] . identifier[tag] = identifier[artifact] identifier[image_name] = identifier[image] . identifier[image_name_with_tag] identifier[log] . identifier[info] ( literal[string] . identifier[format] ( identifier[image_name] )) keyword[try] : identifier[image] . identifier[harpoon] . identifier[docker_api] . identifier[remove_image] ( identifier[image_name] ) keyword[except] identifier[docker] . identifier[errors] . identifier[ImageNotFound] : identifier[log] . identifier[warning] ( literal[string] )
def untag(collector, image, artifact, **kwargs): """Tag an image!""" if artifact in (None, '', NotSpecified): artifact = collector.configuration['harpoon'].tag # depends on [control=['if'], data=['artifact']] if artifact is NotSpecified: raise BadOption('Please specify a tag using the artifact or tag options') # depends on [control=['if'], data=[]] image.tag = artifact image_name = image.image_name_with_tag log.info('Removing image\timage={0}'.format(image_name)) try: image.harpoon.docker_api.remove_image(image_name) # depends on [control=['try'], data=[]] except docker.errors.ImageNotFound: log.warning('No image was found to remove') # depends on [control=['except'], data=[]]
def rscan(self, name_start, name_end, limit=10): """ Scan and return a dict mapping key/value in the top ``limit`` keys between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The upper bound(not included) of keys to be returned, empty string ``''`` means +inf :param string name_end: The lower bound(included) of keys to be returned, empty string ``''`` means -inf :param int limit: number of elements will be returned. :return: a dict mapping key/value in descending order :rtype: OrderedDict >>> ssdb.scan('set_x3', 'set_x1', 10) {'set_x2': 'x2', 'set_x1': 'x1'} >>> ssdb.scan('set_xx', 'set_x ', 3) {'set_x4': 'x4', 'set_x3': 'x3', 'set_x2': 'x2'} >>> ssdb.scan('', 'set_x ', 10) {'set_x4': 'x4', 'set_x3': 'x3', 'set_x2': 'x2', 'set_x1': 'x1'} >>> ssdb.scan('', 'set_zzzzz', 10) {} """ limit = get_positive_integer('limit', limit) return self.execute_command('rscan', name_start, name_end, limit)
def function[rscan, parameter[self, name_start, name_end, limit]]: constant[ Scan and return a dict mapping key/value in the top ``limit`` keys between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The upper bound(not included) of keys to be returned, empty string ``''`` means +inf :param string name_end: The lower bound(included) of keys to be returned, empty string ``''`` means -inf :param int limit: number of elements will be returned. :return: a dict mapping key/value in descending order :rtype: OrderedDict >>> ssdb.scan('set_x3', 'set_x1', 10) {'set_x2': 'x2', 'set_x1': 'x1'} >>> ssdb.scan('set_xx', 'set_x ', 3) {'set_x4': 'x4', 'set_x3': 'x3', 'set_x2': 'x2'} >>> ssdb.scan('', 'set_x ', 10) {'set_x4': 'x4', 'set_x3': 'x3', 'set_x2': 'x2', 'set_x1': 'x1'} >>> ssdb.scan('', 'set_zzzzz', 10) {} ] variable[limit] assign[=] call[name[get_positive_integer], parameter[constant[limit], name[limit]]] return[call[name[self].execute_command, parameter[constant[rscan], name[name_start], name[name_end], name[limit]]]]
keyword[def] identifier[rscan] ( identifier[self] , identifier[name_start] , identifier[name_end] , identifier[limit] = literal[int] ): literal[string] identifier[limit] = identifier[get_positive_integer] ( literal[string] , identifier[limit] ) keyword[return] identifier[self] . identifier[execute_command] ( literal[string] , identifier[name_start] , identifier[name_end] , identifier[limit] )
def rscan(self, name_start, name_end, limit=10): """ Scan and return a dict mapping key/value in the top ``limit`` keys between ``name_start`` and ``name_end`` in descending order .. note:: The range is (``name_start``, ``name_end``]. ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The upper bound(not included) of keys to be returned, empty string ``''`` means +inf :param string name_end: The lower bound(included) of keys to be returned, empty string ``''`` means -inf :param int limit: number of elements will be returned. :return: a dict mapping key/value in descending order :rtype: OrderedDict >>> ssdb.scan('set_x3', 'set_x1', 10) {'set_x2': 'x2', 'set_x1': 'x1'} >>> ssdb.scan('set_xx', 'set_x ', 3) {'set_x4': 'x4', 'set_x3': 'x3', 'set_x2': 'x2'} >>> ssdb.scan('', 'set_x ', 10) {'set_x4': 'x4', 'set_x3': 'x3', 'set_x2': 'x2', 'set_x1': 'x1'} >>> ssdb.scan('', 'set_zzzzz', 10) {} """ limit = get_positive_integer('limit', limit) return self.execute_command('rscan', name_start, name_end, limit)
def create(cls, ip_version, datacenter, bandwidth, vlan, vm, ip, background): """ Create a new iface """ if not background and not cls.intty(): background = True datacenter_id_ = int(Datacenter.usable_id(datacenter)) iface_params = { 'ip_version': ip_version, 'datacenter_id': datacenter_id_, 'bandwidth': bandwidth, } if vlan: iface_params['vlan'] = Vlan.usable_id(vlan) if ip: iface_params['ip'] = ip result = cls.call('hosting.iface.create', iface_params) if background and not vm: return result # interactive mode, run a progress bar cls.echo('Creating your iface.') cls.display_progress(result) iface_info = cls._info(result['iface_id']) cls.echo('Your iface has been created with the following IP ' 'addresses:') for _ip in iface_info['ips']: cls.echo('ip%d:\t%s' % (_ip['version'], _ip['ip'])) if not vm: return result vm_id = Iaas.usable_id(vm) result = cls._attach(result['iface_id'], vm_id) if background: return result cls.echo('Attaching your iface.') cls.display_progress(result) return result
def function[create, parameter[cls, ip_version, datacenter, bandwidth, vlan, vm, ip, background]]: constant[ Create a new iface ] if <ast.BoolOp object at 0x7da20c7c9d20> begin[:] variable[background] assign[=] constant[True] variable[datacenter_id_] assign[=] call[name[int], parameter[call[name[Datacenter].usable_id, parameter[name[datacenter]]]]] variable[iface_params] assign[=] dictionary[[<ast.Constant object at 0x7da20c7ca2c0>, <ast.Constant object at 0x7da20c7c87c0>, <ast.Constant object at 0x7da20c7cab90>], [<ast.Name object at 0x7da20c7c8c70>, <ast.Name object at 0x7da20c7c82b0>, <ast.Name object at 0x7da20c7ca440>]] if name[vlan] begin[:] call[name[iface_params]][constant[vlan]] assign[=] call[name[Vlan].usable_id, parameter[name[vlan]]] if name[ip] begin[:] call[name[iface_params]][constant[ip]] assign[=] name[ip] variable[result] assign[=] call[name[cls].call, parameter[constant[hosting.iface.create], name[iface_params]]] if <ast.BoolOp object at 0x7da18ede61a0> begin[:] return[name[result]] call[name[cls].echo, parameter[constant[Creating your iface.]]] call[name[cls].display_progress, parameter[name[result]]] variable[iface_info] assign[=] call[name[cls]._info, parameter[call[name[result]][constant[iface_id]]]] call[name[cls].echo, parameter[constant[Your iface has been created with the following IP addresses:]]] for taget[name[_ip]] in starred[call[name[iface_info]][constant[ips]]] begin[:] call[name[cls].echo, parameter[binary_operation[constant[ip%d: %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Subscript object at 0x7da18ede4400>, <ast.Subscript object at 0x7da18ede40a0>]]]]] if <ast.UnaryOp object at 0x7da18ede5660> begin[:] return[name[result]] variable[vm_id] assign[=] call[name[Iaas].usable_id, parameter[name[vm]]] variable[result] assign[=] call[name[cls]._attach, parameter[call[name[result]][constant[iface_id]], name[vm_id]]] if name[background] begin[:] return[name[result]] call[name[cls].echo, parameter[constant[Attaching your iface.]]] call[name[cls].display_progress, parameter[name[result]]] return[name[result]]
keyword[def] identifier[create] ( identifier[cls] , identifier[ip_version] , identifier[datacenter] , identifier[bandwidth] , identifier[vlan] , identifier[vm] , identifier[ip] , identifier[background] ): literal[string] keyword[if] keyword[not] identifier[background] keyword[and] keyword[not] identifier[cls] . identifier[intty] (): identifier[background] = keyword[True] identifier[datacenter_id_] = identifier[int] ( identifier[Datacenter] . identifier[usable_id] ( identifier[datacenter] )) identifier[iface_params] ={ literal[string] : identifier[ip_version] , literal[string] : identifier[datacenter_id_] , literal[string] : identifier[bandwidth] , } keyword[if] identifier[vlan] : identifier[iface_params] [ literal[string] ]= identifier[Vlan] . identifier[usable_id] ( identifier[vlan] ) keyword[if] identifier[ip] : identifier[iface_params] [ literal[string] ]= identifier[ip] identifier[result] = identifier[cls] . identifier[call] ( literal[string] , identifier[iface_params] ) keyword[if] identifier[background] keyword[and] keyword[not] identifier[vm] : keyword[return] identifier[result] identifier[cls] . identifier[echo] ( literal[string] ) identifier[cls] . identifier[display_progress] ( identifier[result] ) identifier[iface_info] = identifier[cls] . identifier[_info] ( identifier[result] [ literal[string] ]) identifier[cls] . identifier[echo] ( literal[string] literal[string] ) keyword[for] identifier[_ip] keyword[in] identifier[iface_info] [ literal[string] ]: identifier[cls] . identifier[echo] ( literal[string] %( identifier[_ip] [ literal[string] ], identifier[_ip] [ literal[string] ])) keyword[if] keyword[not] identifier[vm] : keyword[return] identifier[result] identifier[vm_id] = identifier[Iaas] . identifier[usable_id] ( identifier[vm] ) identifier[result] = identifier[cls] . identifier[_attach] ( identifier[result] [ literal[string] ], identifier[vm_id] ) keyword[if] identifier[background] : keyword[return] identifier[result] identifier[cls] . identifier[echo] ( literal[string] ) identifier[cls] . identifier[display_progress] ( identifier[result] ) keyword[return] identifier[result]
def create(cls, ip_version, datacenter, bandwidth, vlan, vm, ip, background): """ Create a new iface """ if not background and (not cls.intty()): background = True # depends on [control=['if'], data=[]] datacenter_id_ = int(Datacenter.usable_id(datacenter)) iface_params = {'ip_version': ip_version, 'datacenter_id': datacenter_id_, 'bandwidth': bandwidth} if vlan: iface_params['vlan'] = Vlan.usable_id(vlan) if ip: iface_params['ip'] = ip # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] result = cls.call('hosting.iface.create', iface_params) if background and (not vm): return result # depends on [control=['if'], data=[]] # interactive mode, run a progress bar cls.echo('Creating your iface.') cls.display_progress(result) iface_info = cls._info(result['iface_id']) cls.echo('Your iface has been created with the following IP addresses:') for _ip in iface_info['ips']: cls.echo('ip%d:\t%s' % (_ip['version'], _ip['ip'])) # depends on [control=['for'], data=['_ip']] if not vm: return result # depends on [control=['if'], data=[]] vm_id = Iaas.usable_id(vm) result = cls._attach(result['iface_id'], vm_id) if background: return result # depends on [control=['if'], data=[]] cls.echo('Attaching your iface.') cls.display_progress(result) return result
def fix_re_escapes(self, txt: str) -> str: """ The ShEx RE engine allows escaping any character. We have to remove that escape for everything except those that CAN be legitimately escaped :param txt: text to be escaped """ def _subf(matchobj): # o = self.fix_text_escapes(matchobj.group(0)) o = matchobj.group(0).translate(self.re_trans_table) if o[1] in '\b\f\n\t\r': return o[0] + 'bfntr'['\b\f\n\t\r'.index(o[1])] else: return o if o[1] in '\\.?*+^$()[]{|}' else o[1] return re.sub(r'\\.', _subf, txt, flags=re.MULTILINE + re.DOTALL + re.UNICODE)
def function[fix_re_escapes, parameter[self, txt]]: constant[ The ShEx RE engine allows escaping any character. We have to remove that escape for everything except those that CAN be legitimately escaped :param txt: text to be escaped ] def function[_subf, parameter[matchobj]]: variable[o] assign[=] call[call[name[matchobj].group, parameter[constant[0]]].translate, parameter[name[self].re_trans_table]] if compare[call[name[o]][constant[1]] in constant[ ]] begin[:] return[binary_operation[call[name[o]][constant[0]] + call[constant[bfntr]][call[constant[ ].index, parameter[call[name[o]][constant[1]]]]]]] return[call[name[re].sub, parameter[constant[\\.], name[_subf], name[txt]]]]
keyword[def] identifier[fix_re_escapes] ( identifier[self] , identifier[txt] : identifier[str] )-> identifier[str] : literal[string] keyword[def] identifier[_subf] ( identifier[matchobj] ): identifier[o] = identifier[matchobj] . identifier[group] ( literal[int] ). identifier[translate] ( identifier[self] . identifier[re_trans_table] ) keyword[if] identifier[o] [ literal[int] ] keyword[in] literal[string] : keyword[return] identifier[o] [ literal[int] ]+ literal[string] [ literal[string] . identifier[index] ( identifier[o] [ literal[int] ])] keyword[else] : keyword[return] identifier[o] keyword[if] identifier[o] [ literal[int] ] keyword[in] literal[string] keyword[else] identifier[o] [ literal[int] ] keyword[return] identifier[re] . identifier[sub] ( literal[string] , identifier[_subf] , identifier[txt] , identifier[flags] = identifier[re] . identifier[MULTILINE] + identifier[re] . identifier[DOTALL] + identifier[re] . identifier[UNICODE] )
def fix_re_escapes(self, txt: str) -> str: """ The ShEx RE engine allows escaping any character. We have to remove that escape for everything except those that CAN be legitimately escaped :param txt: text to be escaped """ def _subf(matchobj): # o = self.fix_text_escapes(matchobj.group(0)) o = matchobj.group(0).translate(self.re_trans_table) if o[1] in '\x08\x0c\n\t\r': return o[0] + 'bfntr'['\x08\x0c\n\t\r'.index(o[1])] # depends on [control=['if'], data=[]] else: return o if o[1] in '\\.?*+^$()[]{|}' else o[1] return re.sub('\\\\.', _subf, txt, flags=re.MULTILINE + re.DOTALL + re.UNICODE)
def _get_message(self, get_frame, auto_decode): """Get and return a message using a Basic.Get frame. :param Basic.Get get_frame: :param bool auto_decode: Auto-decode strings when possible. :rtype: Message """ message_uuid = self._channel.rpc.register_request( get_frame.valid_responses + ['ContentHeader', 'ContentBody'] ) try: self._channel.write_frame(get_frame) get_ok_frame = self._channel.rpc.get_request(message_uuid, raw=True, multiple=True) if isinstance(get_ok_frame, specification.Basic.GetEmpty): return None content_header = self._channel.rpc.get_request(message_uuid, raw=True, multiple=True) body = self._get_content_body(message_uuid, content_header.body_size) finally: self._channel.rpc.remove(message_uuid) return Message(channel=self._channel, body=body, method=dict(get_ok_frame), properties=dict(content_header.properties), auto_decode=auto_decode)
def function[_get_message, parameter[self, get_frame, auto_decode]]: constant[Get and return a message using a Basic.Get frame. :param Basic.Get get_frame: :param bool auto_decode: Auto-decode strings when possible. :rtype: Message ] variable[message_uuid] assign[=] call[name[self]._channel.rpc.register_request, parameter[binary_operation[name[get_frame].valid_responses + list[[<ast.Constant object at 0x7da20c6a9a20>, <ast.Constant object at 0x7da20c6aa5f0>]]]]] <ast.Try object at 0x7da20c6ab3d0> return[call[name[Message], parameter[]]]
keyword[def] identifier[_get_message] ( identifier[self] , identifier[get_frame] , identifier[auto_decode] ): literal[string] identifier[message_uuid] = identifier[self] . identifier[_channel] . identifier[rpc] . identifier[register_request] ( identifier[get_frame] . identifier[valid_responses] +[ literal[string] , literal[string] ] ) keyword[try] : identifier[self] . identifier[_channel] . identifier[write_frame] ( identifier[get_frame] ) identifier[get_ok_frame] = identifier[self] . identifier[_channel] . identifier[rpc] . identifier[get_request] ( identifier[message_uuid] , identifier[raw] = keyword[True] , identifier[multiple] = keyword[True] ) keyword[if] identifier[isinstance] ( identifier[get_ok_frame] , identifier[specification] . identifier[Basic] . identifier[GetEmpty] ): keyword[return] keyword[None] identifier[content_header] = identifier[self] . identifier[_channel] . identifier[rpc] . identifier[get_request] ( identifier[message_uuid] , identifier[raw] = keyword[True] , identifier[multiple] = keyword[True] ) identifier[body] = identifier[self] . identifier[_get_content_body] ( identifier[message_uuid] , identifier[content_header] . identifier[body_size] ) keyword[finally] : identifier[self] . identifier[_channel] . identifier[rpc] . identifier[remove] ( identifier[message_uuid] ) keyword[return] identifier[Message] ( identifier[channel] = identifier[self] . identifier[_channel] , identifier[body] = identifier[body] , identifier[method] = identifier[dict] ( identifier[get_ok_frame] ), identifier[properties] = identifier[dict] ( identifier[content_header] . identifier[properties] ), identifier[auto_decode] = identifier[auto_decode] )
def _get_message(self, get_frame, auto_decode): """Get and return a message using a Basic.Get frame. :param Basic.Get get_frame: :param bool auto_decode: Auto-decode strings when possible. :rtype: Message """ message_uuid = self._channel.rpc.register_request(get_frame.valid_responses + ['ContentHeader', 'ContentBody']) try: self._channel.write_frame(get_frame) get_ok_frame = self._channel.rpc.get_request(message_uuid, raw=True, multiple=True) if isinstance(get_ok_frame, specification.Basic.GetEmpty): return None # depends on [control=['if'], data=[]] content_header = self._channel.rpc.get_request(message_uuid, raw=True, multiple=True) body = self._get_content_body(message_uuid, content_header.body_size) # depends on [control=['try'], data=[]] finally: self._channel.rpc.remove(message_uuid) return Message(channel=self._channel, body=body, method=dict(get_ok_frame), properties=dict(content_header.properties), auto_decode=auto_decode)
async def article( self, title, description=None, *, url=None, thumb=None, content=None, id=None, text=None, parse_mode=(), link_preview=True, geo=None, period=60, contact=None, game=False, buttons=None ): """ Creates new inline result of article type. Args: title (`str`): The title to be shown for this result. description (`str`, optional): Further explanation of what this result means. url (`str`, optional): The URL to be shown for this result. thumb (:tl:`InputWebDocument`, optional): The thumbnail to be shown for this result. For now it has to be a :tl:`InputWebDocument` if present. content (:tl:`InputWebDocument`, optional): The content to be shown for this result. For now it has to be a :tl:`InputWebDocument` if present. """ # TODO Does 'article' work always? # article, photo, gif, mpeg4_gif, video, audio, # voice, document, location, venue, contact, game result = types.InputBotInlineResult( id=id or '', type='article', send_message=await self._message( text=text, parse_mode=parse_mode, link_preview=link_preview, geo=geo, period=period, contact=contact, game=game, buttons=buttons ), title=title, description=description, url=url, thumb=thumb, content=content ) if id is None: result.id = hashlib.sha256(bytes(result)).hexdigest() return result
<ast.AsyncFunctionDef object at 0x7da18f09c070>
keyword[async] keyword[def] identifier[article] ( identifier[self] , identifier[title] , identifier[description] = keyword[None] , *, identifier[url] = keyword[None] , identifier[thumb] = keyword[None] , identifier[content] = keyword[None] , identifier[id] = keyword[None] , identifier[text] = keyword[None] , identifier[parse_mode] =(), identifier[link_preview] = keyword[True] , identifier[geo] = keyword[None] , identifier[period] = literal[int] , identifier[contact] = keyword[None] , identifier[game] = keyword[False] , identifier[buttons] = keyword[None] ): literal[string] identifier[result] = identifier[types] . identifier[InputBotInlineResult] ( identifier[id] = identifier[id] keyword[or] literal[string] , identifier[type] = literal[string] , identifier[send_message] = keyword[await] identifier[self] . identifier[_message] ( identifier[text] = identifier[text] , identifier[parse_mode] = identifier[parse_mode] , identifier[link_preview] = identifier[link_preview] , identifier[geo] = identifier[geo] , identifier[period] = identifier[period] , identifier[contact] = identifier[contact] , identifier[game] = identifier[game] , identifier[buttons] = identifier[buttons] ), identifier[title] = identifier[title] , identifier[description] = identifier[description] , identifier[url] = identifier[url] , identifier[thumb] = identifier[thumb] , identifier[content] = identifier[content] ) keyword[if] identifier[id] keyword[is] keyword[None] : identifier[result] . identifier[id] = identifier[hashlib] . identifier[sha256] ( identifier[bytes] ( identifier[result] )). identifier[hexdigest] () keyword[return] identifier[result]
async def article(self, title, description=None, *, url=None, thumb=None, content=None, id=None, text=None, parse_mode=(), link_preview=True, geo=None, period=60, contact=None, game=False, buttons=None): """ Creates new inline result of article type. Args: title (`str`): The title to be shown for this result. description (`str`, optional): Further explanation of what this result means. url (`str`, optional): The URL to be shown for this result. thumb (:tl:`InputWebDocument`, optional): The thumbnail to be shown for this result. For now it has to be a :tl:`InputWebDocument` if present. content (:tl:`InputWebDocument`, optional): The content to be shown for this result. For now it has to be a :tl:`InputWebDocument` if present. """ # TODO Does 'article' work always? # article, photo, gif, mpeg4_gif, video, audio, # voice, document, location, venue, contact, game result = types.InputBotInlineResult(id=id or '', type='article', send_message=await self._message(text=text, parse_mode=parse_mode, link_preview=link_preview, geo=geo, period=period, contact=contact, game=game, buttons=buttons), title=title, description=description, url=url, thumb=thumb, content=content) if id is None: result.id = hashlib.sha256(bytes(result)).hexdigest() # depends on [control=['if'], data=[]] return result
def set_directory(path): """ | Creates a directory with given path. | The directory creation is delegated to Python :func:`os.makedirs` definition so that directories hierarchy is recursively created. :param path: Directory path. :type path: unicode :return: Definition success. :rtype: bool """ try: if not foundations.common.path_exists(path): LOGGER.debug("> Creating directory: '{0}'.".format(path)) os.makedirs(path) return True else: LOGGER.debug("> '{0}' directory already exist, skipping creation!".format(path)) return True except Exception as error: raise foundations.exceptions.DirectoryCreationError( "!> {0} | Cannot create '{1}' directory: '{2}'".format(__name__, path, error))
def function[set_directory, parameter[path]]: constant[ | Creates a directory with given path. | The directory creation is delegated to Python :func:`os.makedirs` definition so that directories hierarchy is recursively created. :param path: Directory path. :type path: unicode :return: Definition success. :rtype: bool ] <ast.Try object at 0x7da204347dc0>
keyword[def] identifier[set_directory] ( identifier[path] ): literal[string] keyword[try] : keyword[if] keyword[not] identifier[foundations] . identifier[common] . identifier[path_exists] ( identifier[path] ): identifier[LOGGER] . identifier[debug] ( literal[string] . identifier[format] ( identifier[path] )) identifier[os] . identifier[makedirs] ( identifier[path] ) keyword[return] keyword[True] keyword[else] : identifier[LOGGER] . identifier[debug] ( literal[string] . identifier[format] ( identifier[path] )) keyword[return] keyword[True] keyword[except] identifier[Exception] keyword[as] identifier[error] : keyword[raise] identifier[foundations] . identifier[exceptions] . identifier[DirectoryCreationError] ( literal[string] . identifier[format] ( identifier[__name__] , identifier[path] , identifier[error] ))
def set_directory(path): """ | Creates a directory with given path. | The directory creation is delegated to Python :func:`os.makedirs` definition so that directories hierarchy is recursively created. :param path: Directory path. :type path: unicode :return: Definition success. :rtype: bool """ try: if not foundations.common.path_exists(path): LOGGER.debug("> Creating directory: '{0}'.".format(path)) os.makedirs(path) return True # depends on [control=['if'], data=[]] else: LOGGER.debug("> '{0}' directory already exist, skipping creation!".format(path)) return True # depends on [control=['try'], data=[]] except Exception as error: raise foundations.exceptions.DirectoryCreationError("!> {0} | Cannot create '{1}' directory: '{2}'".format(__name__, path, error)) # depends on [control=['except'], data=['error']]
def create_hopscotch_tour(self, name=None): """ Creates an Hopscotch tour for a website. @Params name - If creating multiple tours at the same time, use this to select the tour you wish to add steps to. """ if not name: name = "default" new_tour = ( """ // Hopscotch Tour var tour = { id: "hopscotch_tour", steps: [ """) self._tour_steps[name] = [] self._tour_steps[name].append(new_tour)
def function[create_hopscotch_tour, parameter[self, name]]: constant[ Creates an Hopscotch tour for a website. @Params name - If creating multiple tours at the same time, use this to select the tour you wish to add steps to. ] if <ast.UnaryOp object at 0x7da1b1beec80> begin[:] variable[name] assign[=] constant[default] variable[new_tour] assign[=] constant[ // Hopscotch Tour var tour = { id: "hopscotch_tour", steps: [ ] call[name[self]._tour_steps][name[name]] assign[=] list[[]] call[call[name[self]._tour_steps][name[name]].append, parameter[name[new_tour]]]
keyword[def] identifier[create_hopscotch_tour] ( identifier[self] , identifier[name] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[name] : identifier[name] = literal[string] identifier[new_tour] =( literal[string] ) identifier[self] . identifier[_tour_steps] [ identifier[name] ]=[] identifier[self] . identifier[_tour_steps] [ identifier[name] ]. identifier[append] ( identifier[new_tour] )
def create_hopscotch_tour(self, name=None): """ Creates an Hopscotch tour for a website. @Params name - If creating multiple tours at the same time, use this to select the tour you wish to add steps to. """ if not name: name = 'default' # depends on [control=['if'], data=[]] new_tour = '\n // Hopscotch Tour\n var tour = {\n id: "hopscotch_tour",\n steps: [\n ' self._tour_steps[name] = [] self._tour_steps[name].append(new_tour)
def get(self, sid): """ Constructs a SigningKeyContext :param sid: The sid :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext """ return SigningKeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid, )
def function[get, parameter[self, sid]]: constant[ Constructs a SigningKeyContext :param sid: The sid :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext ] return[call[name[SigningKeyContext], parameter[name[self]._version]]]
keyword[def] identifier[get] ( identifier[self] , identifier[sid] ): literal[string] keyword[return] identifier[SigningKeyContext] ( identifier[self] . identifier[_version] , identifier[account_sid] = identifier[self] . identifier[_solution] [ literal[string] ], identifier[sid] = identifier[sid] ,)
def get(self, sid): """ Constructs a SigningKeyContext :param sid: The sid :returns: twilio.rest.api.v2010.account.signing_key.SigningKeyContext :rtype: twilio.rest.api.v2010.account.signing_key.SigningKeyContext """ return SigningKeyContext(self._version, account_sid=self._solution['account_sid'], sid=sid)
def addString(self, s): """ Creates a reference to C{s}. If the reference already exists, that reference is returned. @type s: C{str} @param s: The string to be referenced. @rtype: C{int} @return: The reference index. @raise TypeError: The parameter C{s} is not of C{basestring} type. """ if not isinstance(s, basestring): raise TypeError if len(s) == 0: return -1 return self.strings.append(s)
def function[addString, parameter[self, s]]: constant[ Creates a reference to C{s}. If the reference already exists, that reference is returned. @type s: C{str} @param s: The string to be referenced. @rtype: C{int} @return: The reference index. @raise TypeError: The parameter C{s} is not of C{basestring} type. ] if <ast.UnaryOp object at 0x7da1b26acd00> begin[:] <ast.Raise object at 0x7da1b26afb50> if compare[call[name[len], parameter[name[s]]] equal[==] constant[0]] begin[:] return[<ast.UnaryOp object at 0x7da1b26aece0>] return[call[name[self].strings.append, parameter[name[s]]]]
keyword[def] identifier[addString] ( identifier[self] , identifier[s] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[s] , identifier[basestring] ): keyword[raise] identifier[TypeError] keyword[if] identifier[len] ( identifier[s] )== literal[int] : keyword[return] - literal[int] keyword[return] identifier[self] . identifier[strings] . identifier[append] ( identifier[s] )
def addString(self, s): """ Creates a reference to C{s}. If the reference already exists, that reference is returned. @type s: C{str} @param s: The string to be referenced. @rtype: C{int} @return: The reference index. @raise TypeError: The parameter C{s} is not of C{basestring} type. """ if not isinstance(s, basestring): raise TypeError # depends on [control=['if'], data=[]] if len(s) == 0: return -1 # depends on [control=['if'], data=[]] return self.strings.append(s)
def compute_metrics(self): """ Computes metrics for each point Returns: :obj:`Segment`: self """ for prev, point in pairwise(self.points): point.compute_metrics(prev) return self
def function[compute_metrics, parameter[self]]: constant[ Computes metrics for each point Returns: :obj:`Segment`: self ] for taget[tuple[[<ast.Name object at 0x7da1b26add50>, <ast.Name object at 0x7da1b26ae1d0>]]] in starred[call[name[pairwise], parameter[name[self].points]]] begin[:] call[name[point].compute_metrics, parameter[name[prev]]] return[name[self]]
keyword[def] identifier[compute_metrics] ( identifier[self] ): literal[string] keyword[for] identifier[prev] , identifier[point] keyword[in] identifier[pairwise] ( identifier[self] . identifier[points] ): identifier[point] . identifier[compute_metrics] ( identifier[prev] ) keyword[return] identifier[self]
def compute_metrics(self): """ Computes metrics for each point Returns: :obj:`Segment`: self """ for (prev, point) in pairwise(self.points): point.compute_metrics(prev) # depends on [control=['for'], data=[]] return self
def get_setup(cls): """Get package setup.""" try: with open("setup.py") as f: return SetupVisitor(ast.parse(f.read())) except IOError as e: LOG.warning("Couldn't open setup file: %s", e) return SetupVisitor(ast.parse(""))
def function[get_setup, parameter[cls]]: constant[Get package setup.] <ast.Try object at 0x7da20e9575b0>
keyword[def] identifier[get_setup] ( identifier[cls] ): literal[string] keyword[try] : keyword[with] identifier[open] ( literal[string] ) keyword[as] identifier[f] : keyword[return] identifier[SetupVisitor] ( identifier[ast] . identifier[parse] ( identifier[f] . identifier[read] ())) keyword[except] identifier[IOError] keyword[as] identifier[e] : identifier[LOG] . identifier[warning] ( literal[string] , identifier[e] ) keyword[return] identifier[SetupVisitor] ( identifier[ast] . identifier[parse] ( literal[string] ))
def get_setup(cls): """Get package setup.""" try: with open('setup.py') as f: return SetupVisitor(ast.parse(f.read())) # depends on [control=['with'], data=['f']] # depends on [control=['try'], data=[]] except IOError as e: LOG.warning("Couldn't open setup file: %s", e) return SetupVisitor(ast.parse('')) # depends on [control=['except'], data=['e']]
def parse_args(argv=None): """Parse command line options.""" parser = ArgumentParser() parser.add_argument('--replay-file', dest="replay_file", type=str, required=True) options = parser.parse_args(argv) return options
def function[parse_args, parameter[argv]]: constant[Parse command line options.] variable[parser] assign[=] call[name[ArgumentParser], parameter[]] call[name[parser].add_argument, parameter[constant[--replay-file]]] variable[options] assign[=] call[name[parser].parse_args, parameter[name[argv]]] return[name[options]]
keyword[def] identifier[parse_args] ( identifier[argv] = keyword[None] ): literal[string] identifier[parser] = identifier[ArgumentParser] () identifier[parser] . identifier[add_argument] ( literal[string] , identifier[dest] = literal[string] , identifier[type] = identifier[str] , identifier[required] = keyword[True] ) identifier[options] = identifier[parser] . identifier[parse_args] ( identifier[argv] ) keyword[return] identifier[options]
def parse_args(argv=None): """Parse command line options.""" parser = ArgumentParser() parser.add_argument('--replay-file', dest='replay_file', type=str, required=True) options = parser.parse_args(argv) return options
def switch_to_next_app(self): """ switches to the next app """ log.debug("switching to next app...") cmd, url = DEVICE_URLS["switch_to_next_app"] self.result = self._exec(cmd, url)
def function[switch_to_next_app, parameter[self]]: constant[ switches to the next app ] call[name[log].debug, parameter[constant[switching to next app...]]] <ast.Tuple object at 0x7da2054a4c10> assign[=] call[name[DEVICE_URLS]][constant[switch_to_next_app]] name[self].result assign[=] call[name[self]._exec, parameter[name[cmd], name[url]]]
keyword[def] identifier[switch_to_next_app] ( identifier[self] ): literal[string] identifier[log] . identifier[debug] ( literal[string] ) identifier[cmd] , identifier[url] = identifier[DEVICE_URLS] [ literal[string] ] identifier[self] . identifier[result] = identifier[self] . identifier[_exec] ( identifier[cmd] , identifier[url] )
def switch_to_next_app(self): """ switches to the next app """ log.debug('switching to next app...') (cmd, url) = DEVICE_URLS['switch_to_next_app'] self.result = self._exec(cmd, url)
def update_managed_repos(force=False): """For any active, managed repos, update the Dusty-managed copy to bring it up to date with the latest master.""" log_to_client('Pulling latest updates for all active managed repos:') update_specs_repo_and_known_hosts() repos_to_update = get_all_repos(active_only=True, include_specs_repo=False) with parallel_task_queue() as queue: log_to_client('Updating managed repos') for repo in repos_to_update: if not repo.is_overridden: repo.update_local_repo_async(queue, force=force)
def function[update_managed_repos, parameter[force]]: constant[For any active, managed repos, update the Dusty-managed copy to bring it up to date with the latest master.] call[name[log_to_client], parameter[constant[Pulling latest updates for all active managed repos:]]] call[name[update_specs_repo_and_known_hosts], parameter[]] variable[repos_to_update] assign[=] call[name[get_all_repos], parameter[]] with call[name[parallel_task_queue], parameter[]] begin[:] call[name[log_to_client], parameter[constant[Updating managed repos]]] for taget[name[repo]] in starred[name[repos_to_update]] begin[:] if <ast.UnaryOp object at 0x7da20c992740> begin[:] call[name[repo].update_local_repo_async, parameter[name[queue]]]
keyword[def] identifier[update_managed_repos] ( identifier[force] = keyword[False] ): literal[string] identifier[log_to_client] ( literal[string] ) identifier[update_specs_repo_and_known_hosts] () identifier[repos_to_update] = identifier[get_all_repos] ( identifier[active_only] = keyword[True] , identifier[include_specs_repo] = keyword[False] ) keyword[with] identifier[parallel_task_queue] () keyword[as] identifier[queue] : identifier[log_to_client] ( literal[string] ) keyword[for] identifier[repo] keyword[in] identifier[repos_to_update] : keyword[if] keyword[not] identifier[repo] . identifier[is_overridden] : identifier[repo] . identifier[update_local_repo_async] ( identifier[queue] , identifier[force] = identifier[force] )
def update_managed_repos(force=False): """For any active, managed repos, update the Dusty-managed copy to bring it up to date with the latest master.""" log_to_client('Pulling latest updates for all active managed repos:') update_specs_repo_and_known_hosts() repos_to_update = get_all_repos(active_only=True, include_specs_repo=False) with parallel_task_queue() as queue: log_to_client('Updating managed repos') for repo in repos_to_update: if not repo.is_overridden: repo.update_local_repo_async(queue, force=force) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['repo']] # depends on [control=['with'], data=['queue']]
def decoherence_noise_with_asymmetric_ro(gates: Sequence[Gate], p00=0.975, p11=0.911): """Similar to :py:func:`_decoherence_noise_model`, but with asymmetric readout. For simplicity, we use the default values for T1, T2, gate times, et al. and only allow the specification of readout fidelities. """ noise_model = _decoherence_noise_model(gates) aprobs = np.array([[p00, 1 - p00], [1 - p11, p11]]) aprobs = {q: aprobs for q in noise_model.assignment_probs.keys()} return NoiseModel(noise_model.gates, aprobs)
def function[decoherence_noise_with_asymmetric_ro, parameter[gates, p00, p11]]: constant[Similar to :py:func:`_decoherence_noise_model`, but with asymmetric readout. For simplicity, we use the default values for T1, T2, gate times, et al. and only allow the specification of readout fidelities. ] variable[noise_model] assign[=] call[name[_decoherence_noise_model], parameter[name[gates]]] variable[aprobs] assign[=] call[name[np].array, parameter[list[[<ast.List object at 0x7da1b1c5a4a0>, <ast.List object at 0x7da1b1c59540>]]]] variable[aprobs] assign[=] <ast.DictComp object at 0x7da1b1c5b010> return[call[name[NoiseModel], parameter[name[noise_model].gates, name[aprobs]]]]
keyword[def] identifier[decoherence_noise_with_asymmetric_ro] ( identifier[gates] : identifier[Sequence] [ identifier[Gate] ], identifier[p00] = literal[int] , identifier[p11] = literal[int] ): literal[string] identifier[noise_model] = identifier[_decoherence_noise_model] ( identifier[gates] ) identifier[aprobs] = identifier[np] . identifier[array] ([[ identifier[p00] , literal[int] - identifier[p00] ], [ literal[int] - identifier[p11] , identifier[p11] ]]) identifier[aprobs] ={ identifier[q] : identifier[aprobs] keyword[for] identifier[q] keyword[in] identifier[noise_model] . identifier[assignment_probs] . identifier[keys] ()} keyword[return] identifier[NoiseModel] ( identifier[noise_model] . identifier[gates] , identifier[aprobs] )
def decoherence_noise_with_asymmetric_ro(gates: Sequence[Gate], p00=0.975, p11=0.911): """Similar to :py:func:`_decoherence_noise_model`, but with asymmetric readout. For simplicity, we use the default values for T1, T2, gate times, et al. and only allow the specification of readout fidelities. """ noise_model = _decoherence_noise_model(gates) aprobs = np.array([[p00, 1 - p00], [1 - p11, p11]]) aprobs = {q: aprobs for q in noise_model.assignment_probs.keys()} return NoiseModel(noise_model.gates, aprobs)
def run(self): """This function needs to be called to start the computation.""" (task_id, tasks) = self.server.get_task() self.task_store.from_dict(tasks) for (index, task) in self.task_store: result = self.compute(index, task) self.results.append(result) self.server.task_done((task_id, self.results))
def function[run, parameter[self]]: constant[This function needs to be called to start the computation.] <ast.Tuple object at 0x7da20c6a88e0> assign[=] call[name[self].server.get_task, parameter[]] call[name[self].task_store.from_dict, parameter[name[tasks]]] for taget[tuple[[<ast.Name object at 0x7da20c6aada0>, <ast.Name object at 0x7da20c6aa4a0>]]] in starred[name[self].task_store] begin[:] variable[result] assign[=] call[name[self].compute, parameter[name[index], name[task]]] call[name[self].results.append, parameter[name[result]]] call[name[self].server.task_done, parameter[tuple[[<ast.Name object at 0x7da20c6abcd0>, <ast.Attribute object at 0x7da20c6a9bd0>]]]]
keyword[def] identifier[run] ( identifier[self] ): literal[string] ( identifier[task_id] , identifier[tasks] )= identifier[self] . identifier[server] . identifier[get_task] () identifier[self] . identifier[task_store] . identifier[from_dict] ( identifier[tasks] ) keyword[for] ( identifier[index] , identifier[task] ) keyword[in] identifier[self] . identifier[task_store] : identifier[result] = identifier[self] . identifier[compute] ( identifier[index] , identifier[task] ) identifier[self] . identifier[results] . identifier[append] ( identifier[result] ) identifier[self] . identifier[server] . identifier[task_done] (( identifier[task_id] , identifier[self] . identifier[results] ))
def run(self): """This function needs to be called to start the computation.""" (task_id, tasks) = self.server.get_task() self.task_store.from_dict(tasks) for (index, task) in self.task_store: result = self.compute(index, task) self.results.append(result) # depends on [control=['for'], data=[]] self.server.task_done((task_id, self.results))
def decrypt_var(source, passphrase=None): """Attempts to decrypt a variable""" cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(), passphrase_file(passphrase)] return stderr_with_input(flatten(cmd), source)
def function[decrypt_var, parameter[source, passphrase]]: constant[Attempts to decrypt a variable] variable[cmd] assign[=] list[[<ast.Call object at 0x7da1b185a4d0>, <ast.Constant object at 0x7da1b1859930>, <ast.Call object at 0x7da1b185b8b0>, <ast.Call object at 0x7da1b185b010>, <ast.Call object at 0x7da1b1858fd0>]] return[call[name[stderr_with_input], parameter[call[name[flatten], parameter[name[cmd]]], name[source]]]]
keyword[def] identifier[decrypt_var] ( identifier[source] , identifier[passphrase] = keyword[None] ): literal[string] identifier[cmd] =[ identifier[gnupg_bin] (), literal[string] , identifier[gnupg_home] (), identifier[gnupg_verbose] (), identifier[passphrase_file] ( identifier[passphrase] )] keyword[return] identifier[stderr_with_input] ( identifier[flatten] ( identifier[cmd] ), identifier[source] )
def decrypt_var(source, passphrase=None): """Attempts to decrypt a variable""" cmd = [gnupg_bin(), '--decrypt', gnupg_home(), gnupg_verbose(), passphrase_file(passphrase)] return stderr_with_input(flatten(cmd), source)
def _get_end_cursor(self): """ Convenience method that returns a cursor for the last character. """ cursor = self._control.textCursor() cursor.movePosition(QtGui.QTextCursor.End) return cursor
def function[_get_end_cursor, parameter[self]]: constant[ Convenience method that returns a cursor for the last character. ] variable[cursor] assign[=] call[name[self]._control.textCursor, parameter[]] call[name[cursor].movePosition, parameter[name[QtGui].QTextCursor.End]] return[name[cursor]]
keyword[def] identifier[_get_end_cursor] ( identifier[self] ): literal[string] identifier[cursor] = identifier[self] . identifier[_control] . identifier[textCursor] () identifier[cursor] . identifier[movePosition] ( identifier[QtGui] . identifier[QTextCursor] . identifier[End] ) keyword[return] identifier[cursor]
def _get_end_cursor(self): """ Convenience method that returns a cursor for the last character. """ cursor = self._control.textCursor() cursor.movePosition(QtGui.QTextCursor.End) return cursor
def txid_to_block_data(txid, bitcoind_proxy, proxy=None): """ Given a txid, get its block's data. Use SPV to verify the information we receive from the (untrusted) bitcoind host. @bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session) Return the (block hash, block data, txdata) on success Return (None, None, None) on error """ proxy = get_default_proxy() if proxy is None else proxy timeout = 1.0 while True: try: untrusted_tx_data = bitcoind_proxy.getrawtransaction(txid, 1) untrusted_block_hash = untrusted_tx_data['blockhash'] untrusted_block_data = bitcoind_proxy.getblock(untrusted_block_hash) break except (OSError, IOError) as ie: log.exception(ie) log.error('Network error; retrying...') timeout = timeout * 2 + random.randint(0, timeout) continue except Exception as e: log.exception(e) return None, None, None bitcoind_opts = get_bitcoin_opts() spv_headers_path = bitcoind_opts['bitcoind_spv_path'] # first, can we trust this block? is it in the SPV headers? untrusted_block_header_hex = virtualchain.block_header_to_hex( untrusted_block_data, untrusted_block_data['previousblockhash'] ) block_id = SPVClient.block_header_index( spv_headers_path, ('{}00'.format(untrusted_block_header_hex)).decode('hex') ) if block_id < 0: # bad header log.error('Block header "{}" is not in the SPV headers ({})'.format( untrusted_block_header_hex, spv_headers_path )) return None, None, None # block header is trusted. Is the transaction data consistent with it? verified_block_header = virtualchain.block_verify(untrusted_block_data) if not verified_block_header: msg = ( 'Block transaction IDs are not consistent ' 'with the Merkle root of the trusted header' ) log.error(msg) return None, None, None # verify block hash verified_block_hash = virtualchain.block_header_verify( untrusted_block_data, untrusted_block_data['previousblockhash'], untrusted_block_hash ) if not verified_block_hash: log.error('Block hash is not consistent with block header') return None, None, None # we trust the block hash, block data, and txids block_hash = untrusted_block_hash block_data = untrusted_block_data tx_data = untrusted_tx_data return block_hash, block_data, tx_data
def function[txid_to_block_data, parameter[txid, bitcoind_proxy, proxy]]: constant[ Given a txid, get its block's data. Use SPV to verify the information we receive from the (untrusted) bitcoind host. @bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session) Return the (block hash, block data, txdata) on success Return (None, None, None) on error ] variable[proxy] assign[=] <ast.IfExp object at 0x7da18c4cd8a0> variable[timeout] assign[=] constant[1.0] while constant[True] begin[:] <ast.Try object at 0x7da18c4cece0> variable[bitcoind_opts] assign[=] call[name[get_bitcoin_opts], parameter[]] variable[spv_headers_path] assign[=] call[name[bitcoind_opts]][constant[bitcoind_spv_path]] variable[untrusted_block_header_hex] assign[=] call[name[virtualchain].block_header_to_hex, parameter[name[untrusted_block_data], call[name[untrusted_block_data]][constant[previousblockhash]]]] variable[block_id] assign[=] call[name[SPVClient].block_header_index, parameter[name[spv_headers_path], call[call[constant[{}00].format, parameter[name[untrusted_block_header_hex]]].decode, parameter[constant[hex]]]]] if compare[name[block_id] less[<] constant[0]] begin[:] call[name[log].error, parameter[call[constant[Block header "{}" is not in the SPV headers ({})].format, parameter[name[untrusted_block_header_hex], name[spv_headers_path]]]]] return[tuple[[<ast.Constant object at 0x7da1b1722da0>, <ast.Constant object at 0x7da18c4cf400>, <ast.Constant object at 0x7da18c4cd0c0>]]] variable[verified_block_header] assign[=] call[name[virtualchain].block_verify, parameter[name[untrusted_block_data]]] if <ast.UnaryOp object at 0x7da18c4cff40> begin[:] variable[msg] assign[=] constant[Block transaction IDs are not consistent with the Merkle root of the trusted header] call[name[log].error, parameter[name[msg]]] return[tuple[[<ast.Constant object at 0x7da18c4ce020>, <ast.Constant object at 0x7da18c4cd180>, <ast.Constant object at 0x7da18c4ccee0>]]] variable[verified_block_hash] assign[=] call[name[virtualchain].block_header_verify, parameter[name[untrusted_block_data], call[name[untrusted_block_data]][constant[previousblockhash]], name[untrusted_block_hash]]] if <ast.UnaryOp object at 0x7da18c4ce3b0> begin[:] call[name[log].error, parameter[constant[Block hash is not consistent with block header]]] return[tuple[[<ast.Constant object at 0x7da18c4cf460>, <ast.Constant object at 0x7da18c4cd9c0>, <ast.Constant object at 0x7da18c4cc0a0>]]] variable[block_hash] assign[=] name[untrusted_block_hash] variable[block_data] assign[=] name[untrusted_block_data] variable[tx_data] assign[=] name[untrusted_tx_data] return[tuple[[<ast.Name object at 0x7da18c4cc130>, <ast.Name object at 0x7da18c4cdc00>, <ast.Name object at 0x7da18c4cc520>]]]
keyword[def] identifier[txid_to_block_data] ( identifier[txid] , identifier[bitcoind_proxy] , identifier[proxy] = keyword[None] ): literal[string] identifier[proxy] = identifier[get_default_proxy] () keyword[if] identifier[proxy] keyword[is] keyword[None] keyword[else] identifier[proxy] identifier[timeout] = literal[int] keyword[while] keyword[True] : keyword[try] : identifier[untrusted_tx_data] = identifier[bitcoind_proxy] . identifier[getrawtransaction] ( identifier[txid] , literal[int] ) identifier[untrusted_block_hash] = identifier[untrusted_tx_data] [ literal[string] ] identifier[untrusted_block_data] = identifier[bitcoind_proxy] . identifier[getblock] ( identifier[untrusted_block_hash] ) keyword[break] keyword[except] ( identifier[OSError] , identifier[IOError] ) keyword[as] identifier[ie] : identifier[log] . identifier[exception] ( identifier[ie] ) identifier[log] . identifier[error] ( literal[string] ) identifier[timeout] = identifier[timeout] * literal[int] + identifier[random] . identifier[randint] ( literal[int] , identifier[timeout] ) keyword[continue] keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[log] . identifier[exception] ( identifier[e] ) keyword[return] keyword[None] , keyword[None] , keyword[None] identifier[bitcoind_opts] = identifier[get_bitcoin_opts] () identifier[spv_headers_path] = identifier[bitcoind_opts] [ literal[string] ] identifier[untrusted_block_header_hex] = identifier[virtualchain] . identifier[block_header_to_hex] ( identifier[untrusted_block_data] , identifier[untrusted_block_data] [ literal[string] ] ) identifier[block_id] = identifier[SPVClient] . identifier[block_header_index] ( identifier[spv_headers_path] , ( literal[string] . identifier[format] ( identifier[untrusted_block_header_hex] )). identifier[decode] ( literal[string] ) ) keyword[if] identifier[block_id] < literal[int] : identifier[log] . identifier[error] ( literal[string] . identifier[format] ( identifier[untrusted_block_header_hex] , identifier[spv_headers_path] )) keyword[return] keyword[None] , keyword[None] , keyword[None] identifier[verified_block_header] = identifier[virtualchain] . identifier[block_verify] ( identifier[untrusted_block_data] ) keyword[if] keyword[not] identifier[verified_block_header] : identifier[msg] =( literal[string] literal[string] ) identifier[log] . identifier[error] ( identifier[msg] ) keyword[return] keyword[None] , keyword[None] , keyword[None] identifier[verified_block_hash] = identifier[virtualchain] . identifier[block_header_verify] ( identifier[untrusted_block_data] , identifier[untrusted_block_data] [ literal[string] ], identifier[untrusted_block_hash] ) keyword[if] keyword[not] identifier[verified_block_hash] : identifier[log] . identifier[error] ( literal[string] ) keyword[return] keyword[None] , keyword[None] , keyword[None] identifier[block_hash] = identifier[untrusted_block_hash] identifier[block_data] = identifier[untrusted_block_data] identifier[tx_data] = identifier[untrusted_tx_data] keyword[return] identifier[block_hash] , identifier[block_data] , identifier[tx_data]
def txid_to_block_data(txid, bitcoind_proxy, proxy=None): """ Given a txid, get its block's data. Use SPV to verify the information we receive from the (untrusted) bitcoind host. @bitcoind_proxy must be a BitcoindConnection (from virtualchain.lib.session) Return the (block hash, block data, txdata) on success Return (None, None, None) on error """ proxy = get_default_proxy() if proxy is None else proxy timeout = 1.0 while True: try: untrusted_tx_data = bitcoind_proxy.getrawtransaction(txid, 1) untrusted_block_hash = untrusted_tx_data['blockhash'] untrusted_block_data = bitcoind_proxy.getblock(untrusted_block_hash) break # depends on [control=['try'], data=[]] except (OSError, IOError) as ie: log.exception(ie) log.error('Network error; retrying...') timeout = timeout * 2 + random.randint(0, timeout) continue # depends on [control=['except'], data=['ie']] except Exception as e: log.exception(e) return (None, None, None) # depends on [control=['except'], data=['e']] # depends on [control=['while'], data=[]] bitcoind_opts = get_bitcoin_opts() spv_headers_path = bitcoind_opts['bitcoind_spv_path'] # first, can we trust this block? is it in the SPV headers? untrusted_block_header_hex = virtualchain.block_header_to_hex(untrusted_block_data, untrusted_block_data['previousblockhash']) block_id = SPVClient.block_header_index(spv_headers_path, '{}00'.format(untrusted_block_header_hex).decode('hex')) if block_id < 0: # bad header log.error('Block header "{}" is not in the SPV headers ({})'.format(untrusted_block_header_hex, spv_headers_path)) return (None, None, None) # depends on [control=['if'], data=[]] # block header is trusted. Is the transaction data consistent with it? verified_block_header = virtualchain.block_verify(untrusted_block_data) if not verified_block_header: msg = 'Block transaction IDs are not consistent with the Merkle root of the trusted header' log.error(msg) return (None, None, None) # depends on [control=['if'], data=[]] # verify block hash verified_block_hash = virtualchain.block_header_verify(untrusted_block_data, untrusted_block_data['previousblockhash'], untrusted_block_hash) if not verified_block_hash: log.error('Block hash is not consistent with block header') return (None, None, None) # depends on [control=['if'], data=[]] # we trust the block hash, block data, and txids block_hash = untrusted_block_hash block_data = untrusted_block_data tx_data = untrusted_tx_data return (block_hash, block_data, tx_data)
def parse(self, line=None): """parses the line provided, if None then uses sys.argv""" args = self.parser.parse_args(args=line) return args.func(args)
def function[parse, parameter[self, line]]: constant[parses the line provided, if None then uses sys.argv] variable[args] assign[=] call[name[self].parser.parse_args, parameter[]] return[call[name[args].func, parameter[name[args]]]]
keyword[def] identifier[parse] ( identifier[self] , identifier[line] = keyword[None] ): literal[string] identifier[args] = identifier[self] . identifier[parser] . identifier[parse_args] ( identifier[args] = identifier[line] ) keyword[return] identifier[args] . identifier[func] ( identifier[args] )
def parse(self, line=None): """parses the line provided, if None then uses sys.argv""" args = self.parser.parse_args(args=line) return args.func(args)