text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def watch(key, recurse=False, profile=None, timeout=0, index=None, **kwargs): ''' .. versionadded:: 2016.3.0 Makes a best effort to watch for a key or tree change in etcd. Returns a dict containing the new key value ( or None if the key was deleted ), the modifiedIndex of the key, whether the key c...
[ "def", "watch", "(", "key", ",", "recurse", "=", "False", ",", "profile", "=", "None", ",", "timeout", "=", "0", ",", "index", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client", "=", "__utils__", "[", "'etcd_util.get_conn'", "]", "(", "__opts_...
38.956522
0.001089
def parse_hash(address): ''' str -> bytes There's probably a better way to do this. ''' raw = parse(address) # Cash addresses try: if address.find(riemann.network.CASHADDR_PREFIX) == 0: if raw.find(riemann.network.CASHADDR_P2SH) == 0: return raw[len(riem...
[ "def", "parse_hash", "(", "address", ")", ":", "raw", "=", "parse", "(", "address", ")", "# Cash addresses", "try", ":", "if", "address", ".", "find", "(", "riemann", ".", "network", ".", "CASHADDR_PREFIX", ")", "==", "0", ":", "if", "raw", ".", "find"...
32.969697
0.000893
def docker_windows_path_adjust(path): # type: (Text) -> Text r""" Changes only windows paths so that the can be appropriately passed to the docker run command as as docker treats them as unix paths. Example: 'C:\Users\foo to /C/Users/foo (Docker for Windows) or /c/Users/foo (Docker toolbox). ...
[ "def", "docker_windows_path_adjust", "(", "path", ")", ":", "# type: (Text) -> Text", "if", "onWindows", "(", ")", ":", "split", "=", "path", ".", "split", "(", "':'", ")", "if", "len", "(", "split", ")", "==", "2", ":", "if", "platform", ".", "win32_ver...
40.714286
0.002286
def show_distribution_section(config, title, section_name): """ Obtain distribution data and display latest distribution section, i.e. "demos" or "apps" or "themes". """ payload = requests.get(config.apps_url).json() distributions = sorted(payload.keys(), reverse=True) latest_distribution = ...
[ "def", "show_distribution_section", "(", "config", ",", "title", ",", "section_name", ")", ":", "payload", "=", "requests", ".", "get", "(", "config", ".", "apps_url", ")", ".", "json", "(", ")", "distributions", "=", "sorted", "(", "payload", ".", "keys",...
43.071429
0.001623
def _convert_to_unicode(string): """This method should work with both Python 2 and 3 with the caveat that they need to be compiled with wide unicode character support. If there isn't wide unicode character support it'll blow up with a warning. """ codepoints = [] for character in string.sp...
[ "def", "_convert_to_unicode", "(", "string", ")", ":", "codepoints", "=", "[", "]", "for", "character", "in", "string", ".", "split", "(", "'-'", ")", ":", "if", "character", "in", "BLACKLIST_UNICODE", ":", "next", "codepoints", ".", "append", "(", "'\\U{0...
27.777778
0.001934
def map_from_config(cls, config, context_names, section_key="scoring_contexts"): """ Loads a whole set of ScoringContext's from a configuration file while maintaining a cache of model names. This aids in better memory management and allows model aliases to be imp...
[ "def", "map_from_config", "(", "cls", ",", "config", ",", "context_names", ",", "section_key", "=", "\"scoring_contexts\"", ")", ":", "model_key_map", "=", "{", "}", "context_map", "=", "{", "}", "for", "context_name", "in", "context_names", ":", "section", "=...
40.290323
0.002346
def permute_outputs(Y, X): """ Permute the output according to one of the inputs as in [_2] References ---------- .. [2] Elmar Plischke (2010) "An effective algorithm for computing global sensitivity indices (EASI) Reliability Engineering & System Safety", 95:4, 354-360....
[ "def", "permute_outputs", "(", "Y", ",", "X", ")", ":", "permutation_index", "=", "np", ".", "argsort", "(", "X", ")", "permutation_index", "=", "np", ".", "concatenate", "(", "[", "permutation_index", "[", ":", ":", "2", "]", ",", "permutation_index", "...
37.2
0.001748
def get_plugin_apps(self): """Obtains a mapping between routes and handlers. Stores the logdir. Returns: A mapping between routes and handlers (functions that respond to requests). """ return { '/infer': self._infer, '/update_example': self._update_example, '/example...
[ "def", "get_plugin_apps", "(", "self", ")", ":", "return", "{", "'/infer'", ":", "self", ".", "_infer", ",", "'/update_example'", ":", "self", ".", "_update_example", ",", "'/examples_from_path'", ":", "self", ".", "_examples_from_path_handler", ",", "'/sprite'", ...
37.117647
0.001546
def res_to_str(res): """ :param res: :class:`requests.Response` object Parse the given request and generate an informative string from it """ if 'Authorization' in res.request.headers: res.request.headers['Authorization'] = "*****" return """ #################################### url = %...
[ "def", "res_to_str", "(", "res", ")", ":", "if", "'Authorization'", "in", "res", ".", "request", ".", "headers", ":", "res", ".", "request", ".", "headers", "[", "'Authorization'", "]", "=", "\"*****\"", "return", "\"\"\"\n####################################\nurl...
24.966667
0.001285
def get_link_domain(link, dist): """ tool to identify the domain of a given monotonic link function Parameters ---------- link : Link object dist : Distribution object Returns ------- domain : list of length 2, representing the interval of the domain. """ domain = np.array(...
[ "def", "get_link_domain", "(", "link", ",", "dist", ")", ":", "domain", "=", "np", ".", "array", "(", "[", "-", "np", ".", "inf", ",", "-", "1", ",", "0", ",", "1", ",", "np", ".", "inf", "]", ")", "domain", "=", "domain", "[", "~", "np", "...
26.5
0.002278
def publish(request): """Accept a publication request at form value 'epub'""" if 'epub' not in request.POST: raise httpexceptions.HTTPBadRequest("Missing EPUB in POST body.") is_pre_publication = asbool(request.POST.get('pre-publication')) epub_upload = request.POST['epub'].file try: ...
[ "def", "publish", "(", "request", ")", ":", "if", "'epub'", "not", "in", "request", ".", "POST", ":", "raise", "httpexceptions", ".", "HTTPBadRequest", "(", "\"Missing EPUB in POST body.\"", ")", "is_pre_publication", "=", "asbool", "(", "request", ".", "POST", ...
36.225806
0.000867
def parseFASTACommandLineOptions(args): """ Examine parsed command-line options and return a Reads instance. @param args: An argparse namespace, as returned by the argparse C{parse_args} function. @return: A C{Reads} subclass instance, depending on the type of FASTA file given. """ ...
[ "def", "parseFASTACommandLineOptions", "(", "args", ")", ":", "# Set default FASTA type.", "if", "not", "(", "args", ".", "fasta", "or", "args", ".", "fastq", "or", "args", ".", "fasta_ss", ")", ":", "args", ".", "fasta", "=", "True", "readClass", "=", "re...
34.791667
0.001166
def refresh(self, leave_clean=False): """Attempt to pull-with-rebase from upstream. This is implemented as fetch-plus-rebase so that we can distinguish between errors in the fetch stage (likely network errors) and errors in the rebase stage (conflicts). If leave_clean is true, then in the event ...
[ "def", "refresh", "(", "self", ",", "leave_clean", "=", "False", ")", ":", "remote", ",", "merge", "=", "self", ".", "_get_upstream", "(", ")", "self", ".", "_check_call", "(", "[", "'fetch'", ",", "'--tags'", ",", "remote", ",", "merge", "]", ",", "...
53.285714
0.013169
def jsontype(self, name, path=Path.rootPath()): """ Gets the type of the JSON value under ``path`` from key ``name`` """ return self.execute_command('JSON.TYPE', name, str_path(path))
[ "def", "jsontype", "(", "self", ",", "name", ",", "path", "=", "Path", ".", "rootPath", "(", ")", ")", ":", "return", "self", ".", "execute_command", "(", "'JSON.TYPE'", ",", "name", ",", "str_path", "(", "path", ")", ")" ]
42.2
0.009302
def _yield_callbacks(self): """Yield all callbacks set on this instance including a set whether its name was set by the user. Handles these cases: * default and user callbacks * callbacks with and without name * initialized and uninitialized callbacks * p...
[ "def", "_yield_callbacks", "(", "self", ")", ":", "print_logs", "=", "[", "]", "for", "item", "in", "self", ".", "get_default_callbacks", "(", ")", "+", "(", "self", ".", "callbacks", "or", "[", "]", ")", ":", "if", "isinstance", "(", "item", ",", "(...
36.035714
0.001931
def _trace_memory_usage(self, frame, event, arg): #pylint: disable=unused-argument """Checks memory usage when 'line' event occur.""" if event == 'line' and frame.f_code.co_filename in self.target_modules: self._events_list.append( (frame.f_lineno, self._process.memory_info(...
[ "def", "_trace_memory_usage", "(", "self", ",", "frame", ",", "event", ",", "arg", ")", ":", "#pylint: disable=unused-argument", "if", "event", "==", "'line'", "and", "frame", ".", "f_code", ".", "co_filename", "in", "self", ".", "target_modules", ":", "self",...
60.857143
0.009259
def GET(self, mid=None): ''' Show the list of minion keys or detail on a specific key .. versionadded:: 2014.7.0 .. http:get:: /keys/(mid) List all keys or show a specific key :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| ...
[ "def", "GET", "(", "self", ",", "mid", "=", "None", ")", ":", "if", "mid", ":", "lowstate", "=", "[", "{", "'client'", ":", "'wheel'", ",", "'fun'", ":", "'key.finger'", ",", "'match'", ":", "mid", ",", "}", "]", "else", ":", "lowstate", "=", "["...
22.77907
0.000978
def name(self): """Dict with locale codes as keys and localized name as value""" # pylint:disable=E1101 return next((self.names.get(x) for x in self._locales if x in self.names), None)
[ "def", "name", "(", "self", ")", ":", "# pylint:disable=E1101", "return", "next", "(", "(", "self", ".", "names", ".", "get", "(", "x", ")", "for", "x", "in", "self", ".", "_locales", "if", "x", "in", "self", ".", "names", ")", ",", "None", ")" ]
45
0.008734
def _add_cloud_distro_check(cloud_archive_release, openstack_release): """Add the cloud pocket, but also check the cloud_archive_release against the current distro, and use the openstack_release as the full lookup. This just calls _add_cloud_pocket() with the openstack_release as pocket to get the corr...
[ "def", "_add_cloud_distro_check", "(", "cloud_archive_release", ",", "openstack_release", ")", ":", "_verify_is_ubuntu_rel", "(", "cloud_archive_release", ",", "openstack_release", ")", "_add_cloud_pocket", "(", "\"{}-{}\"", ".", "format", "(", "cloud_archive_release", ",",...
52.733333
0.001242
def override(self, config_params): """ Overrides parameters with new values from specified ConfigParams and returns a new ConfigParams object. :param config_params: ConfigMap with parameters to override the current values. :return: a new ConfigParams object. """ map = S...
[ "def", "override", "(", "self", ",", "config_params", ")", ":", "map", "=", "StringValueMap", ".", "from_maps", "(", "self", ",", "config_params", ")", "return", "ConfigParams", "(", "map", ")" ]
38.8
0.010076
def serialize_dictionary(dictionary): """Function to stringify a dictionary recursively. :param dictionary: The dictionary. :type dictionary: dict :return: The string. :rtype: basestring """ string_value = {} for k, v in list(dictionary.items()): if isinstance(v, QUrl): ...
[ "def", "serialize_dictionary", "(", "dictionary", ")", ":", "string_value", "=", "{", "}", "for", "k", ",", "v", "in", "list", "(", "dictionary", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "QUrl", ")", ":", "string_value", "...
31.16
0.001245
def add_rolling_statistics_variables( df = None, variable = None, window = 20, upper_factor = 2, lower_factor = 2 ): """ Add rolling statistics variables derived from a specified variable in a DataFrame. """ df[variable + "_rolling_mean"] = p...
[ "def", "add_rolling_statistics_variables", "(", "df", "=", "None", ",", "variable", "=", "None", ",", "window", "=", "20", ",", "upper_factor", "=", "2", ",", "lower_factor", "=", "2", ")", ":", "df", "[", "variable", "+", "\"_rolling_mean\"", "]", "=", ...
47.4375
0.028424
def main(): """ Parse command line arguments and then run the test suite """ parser = argparse.ArgumentParser(description='A distributed test framework') parser.add_argument('testfile', help='The file that is used to determine the test suite run') parser.add_argument('--test-only', nargs='*', ...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'A distributed test framework'", ")", "parser", ".", "add_argument", "(", "'testfile'", ",", "help", "=", "'The file that is used to determine the test suite run'",...
46.25641
0.018458
def _default_url(self): """ Websocket URL to connect to and listen for reload requests """ host = 'localhost' if self.mode == 'remote' else self.host return 'ws://{}:{}/dev'.format(host, self.port)
[ "def", "_default_url", "(", "self", ")", ":", "host", "=", "'localhost'", "if", "self", ".", "mode", "==", "'remote'", "else", "self", ".", "host", "return", "'ws://{}:{}/dev'", ".", "format", "(", "host", ",", "self", ".", "port", ")" ]
54.5
0.00905
def _get_version(): ''' Get the pkgin version ''' version_string = __salt__['cmd.run']( [_check_pkgin(), '-v'], output_loglevel='trace') if version_string is None: # Dunno why it would, but... return False version_match = VERSION_MATCH.search(version_string) ...
[ "def", "_get_version", "(", ")", ":", "version_string", "=", "__salt__", "[", "'cmd.run'", "]", "(", "[", "_check_pkgin", "(", ")", ",", "'-v'", "]", ",", "output_loglevel", "=", "'trace'", ")", "if", "version_string", "is", "None", ":", "# Dunno why it woul...
24.5625
0.002451
def remainshowcase_get(self, session): '''taobao.shop.remainshowcase.get 获取卖家店铺剩余橱窗数量 获取卖家店铺剩余橱窗数量,已用橱窗数量,总橱窗数量(对于B卖家,后两个参数返回-1)''' request = TOPRequest('taobao.shop.remainshowcase.get') self.create(self.execute(request, session)['shop']) return self
[ "def", "remainshowcase_get", "(", "self", ",", "session", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.shop.remainshowcase.get'", ")", "self", ".", "create", "(", "self", ".", "execute", "(", "request", ",", "session", ")", "[", "'shop'", "]", ")", ...
41.857143
0.010033
def getouterframes(frame, context=1): """Get a list of records for a frame and all higher (calling) frames. Each record contains a frame object, filename, line number, function name, a list of lines of context, and index within the context.""" framelist = [] while frame: framelist.append((f...
[ "def", "getouterframes", "(", "frame", ",", "context", "=", "1", ")", ":", "framelist", "=", "[", "]", "while", "frame", ":", "framelist", ".", "append", "(", "(", "frame", ",", ")", "+", "getframeinfo", "(", "frame", ",", "context", ")", ")", "frame...
39.9
0.002451
def _get_predicton_csv_lines(data, headers, images): """Create CSV lines from list-of-dict data.""" if images: data = copy.deepcopy(data) for img_col in images: for d, im in zip(data, images[img_col]): if im == '': continue im = im.copy() im.thumbnail((299, 299), Im...
[ "def", "_get_predicton_csv_lines", "(", "data", ",", "headers", ",", "images", ")", ":", "if", "images", ":", "data", "=", "copy", ".", "deepcopy", "(", "data", ")", "for", "img_col", "in", "images", ":", "for", "d", ",", "im", "in", "zip", "(", "dat...
27.16
0.01138
def fgrad_y_psi(self, y, return_covar_chain=False): """ gradient of f w.r.t to y and psi :returns: NxIx4 tensor of partial derivatives """ mpsi = self.psi w, s, r, d = self.fgrad_y(y, return_precalc=True) gradients = np.zeros((y.shape[0], y.shape[1], len(mpsi), ...
[ "def", "fgrad_y_psi", "(", "self", ",", "y", ",", "return_covar_chain", "=", "False", ")", ":", "mpsi", "=", "self", ".", "psi", "w", ",", "s", ",", "r", ",", "d", "=", "self", ".", "fgrad_y", "(", "y", ",", "return_precalc", "=", "True", ")", "g...
42.714286
0.008994
def _set_global_vars(metadata): """Identify files used multiple times in metadata and replace with global variables """ fnames = collections.defaultdict(list) for sample in metadata.keys(): for k, v in metadata[sample].items(): if isinstance(v, six.string_types) and os.path.isfile(v)...
[ "def", "_set_global_vars", "(", "metadata", ")", ":", "fnames", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "sample", "in", "metadata", ".", "keys", "(", ")", ":", "for", "k", ",", "v", "in", "metadata", "[", "sample", "]", ".", ...
42.36
0.001847
def _are_aligned_angles(self, b1, b2): "Are two boxes aligned according to their angle?" return abs(b1 - b2) <= self.angle_tol or abs(np.pi - abs(b1 - b2)) <= self.angle_tol
[ "def", "_are_aligned_angles", "(", "self", ",", "b1", ",", "b2", ")", ":", "return", "abs", "(", "b1", "-", "b2", ")", "<=", "self", ".", "angle_tol", "or", "abs", "(", "np", ".", "pi", "-", "abs", "(", "b1", "-", "b2", ")", ")", "<=", "self", ...
62.333333
0.015873
def run(users, hosts, func, **kwargs): """ Convenience function that creates an Exscript.Queue instance, adds the given accounts, and calls Queue.run() with the given hosts and function as an argument. If you also want to pass arguments to the given function, you may use util.decorator.bind() l...
[ "def", "run", "(", "users", ",", "hosts", ",", "func", ",", "*", "*", "kwargs", ")", ":", "attempts", "=", "kwargs", ".", "get", "(", "\"attempts\"", ",", "1", ")", "if", "\"attempts\"", "in", "kwargs", ":", "del", "kwargs", "[", "\"attempts\"", "]",...
32.242424
0.000912
def add_attribute(self, attribute): """ Add the given attribute to this Card. Returns the length of attributes after addition. """ self.attributes.append(attribute) return len(self.attributes)
[ "def", "add_attribute", "(", "self", ",", "attribute", ")", ":", "self", ".", "attributes", ".", "append", "(", "attribute", ")", "return", "len", "(", "self", ".", "attributes", ")" ]
33.428571
0.008333
def dp(**kwargs): """ Debugging print. Prints a list of labels and values, each on their own line. """ for label,value in kwargs.iteritems(): print "{0}\t{1}".format(label, value)
[ "def", "dp", "(", "*", "*", "kwargs", ")", ":", "for", "label", ",", "value", "in", "kwargs", ".", "iteritems", "(", ")", ":", "print", "\"{0}\\t{1}\"", ".", "format", "(", "label", ",", "value", ")" ]
29.285714
0.014218
def tune(runner, kernel_options, device_options, tuning_options): """ Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type...
[ "def", "tune", "(", "runner", ",", "kernel_options", ",", "device_options", ",", "tuning_options", ")", ":", "results", "=", "[", "]", "cache", "=", "{", "}", "method", "=", "tuning_options", ".", "method", "#scale variables in x to make 'eps' relevant for multiple ...
33.26
0.002336
def calc_requiredremoterelease_v1(self): """Guess the required release necessary to not fall below the threshold value at a cross section far downstream with a certain level of certainty. Required control parameter: |RemoteDischargeSafety| Required derived parameters: |RemoteDischargeSmoot...
[ "def", "calc_requiredremoterelease_v1", "(", "self", ")", ":", "con", "=", "self", ".", "parameters", ".", "control", ".", "fastaccess", "der", "=", "self", ".", "parameters", ".", "derived", ".", "fastaccess", "flu", "=", "self", ".", "sequences", ".", "f...
39.574074
0.000228
def patch(): """ Patch botocore client so it generates subsegments when calling AWS services. """ if hasattr(botocore.client, '_xray_enabled'): return setattr(botocore.client, '_xray_enabled', True) wrapt.wrap_function_wrapper( 'botocore.client', 'BaseClient._make_ap...
[ "def", "patch", "(", ")", ":", "if", "hasattr", "(", "botocore", ".", "client", ",", "'_xray_enabled'", ")", ":", "return", "setattr", "(", "botocore", ".", "client", ",", "'_xray_enabled'", ",", "True", ")", "wrapt", ".", "wrap_function_wrapper", "(", "'b...
23.7
0.002028
def find_signature_inputs_from_multivalued_ops(inputs): """Returns error message for module inputs from ops with multiple outputs.""" dense_inputs = [] # List of (str, Tensor), with SparseTensors decomposed. for name, tensor in sorted(inputs.items()): if isinstance(tensor, tf.SparseTensor): dense_input...
[ "def", "find_signature_inputs_from_multivalued_ops", "(", "inputs", ")", ":", "dense_inputs", "=", "[", "]", "# List of (str, Tensor), with SparseTensors decomposed.", "for", "name", ",", "tensor", "in", "sorted", "(", "inputs", ".", "items", "(", ")", ")", ":", "if...
53.315789
0.009699
def purge(): """Removes all files generated by Blended""" print("Purging the Blended files!") # Remove the templates folder templ_dir = os.path.join(cwd, "templates") if os.path.exists(templ_dir): shutil.rmtree(templ_dir) # Remove the content folder cont_dir = os.path.join(cwd, "co...
[ "def", "purge", "(", ")", ":", "print", "(", "\"Purging the Blended files!\"", ")", "# Remove the templates folder", "templ_dir", "=", "os", ".", "path", ".", "join", "(", "cwd", ",", "\"templates\"", ")", "if", "os", ".", "path", ".", "exists", "(", "templ_...
29.484848
0.000995
def _get_adjustment(mag, year, mmin, completeness_year, t_f, mag_inc=0.1): ''' If the magnitude is greater than the minimum in the completeness table and the year is greater than the corresponding completeness year then return the Weichert factor :param float mag: Magnitude of an earthquake...
[ "def", "_get_adjustment", "(", "mag", ",", "year", ",", "mmin", ",", "completeness_year", ",", "t_f", ",", "mag_inc", "=", "0.1", ")", ":", "if", "len", "(", "completeness_year", ")", "==", "1", ":", "if", "(", "mag", ">=", "mmin", ")", "and", "(", ...
27.051282
0.000915
def insertImage(page, rect, filename=None, pixmap=None, stream=None, rotate=0, keep_proportion = True, overlay=True): """Insert an image in a rectangle on the current page. Notes: Exactly one of filename, pixmap or stream must be provided. Args: rect: (rect-l...
[ "def", "insertImage", "(", "page", ",", "rect", ",", "filename", "=", "None", ",", "pixmap", "=", "None", ",", "stream", "=", "None", ",", "rotate", "=", "0", ",", "keep_proportion", "=", "True", ",", "overlay", "=", "True", ")", ":", "def", "calc_ma...
35.275168
0.001295
def last_versions_with_age(self, col_name='age'): ''' Leaves only the latest version for each object. Adds a new column which represents age. The age is computed by subtracting _start of the oldest version from one of these possibilities:: # psuedo-code i...
[ "def", "last_versions_with_age", "(", "self", ",", "col_name", "=", "'age'", ")", ":", "min_start_map", "=", "{", "}", "max_start_map", "=", "{", "}", "max_start_ser_map", "=", "{", "}", "cols", "=", "self", ".", "columns", ".", "tolist", "(", ")", "i_oi...
34.320755
0.001069
def split_variants_by_sample(data): """Split a multi-sample call file into inputs for individual samples. For tumor/normal paired analyses, do not split the final file and attach it to the tumor input. """ # not split, do nothing if "group_orig" not in data: return [[data]] # cancer...
[ "def", "split_variants_by_sample", "(", "data", ")", ":", "# not split, do nothing", "if", "\"group_orig\"", "not", "in", "data", ":", "return", "[", "[", "data", "]", "]", "# cancer tumor/normal", "elif", "(", "vcfutils", ".", "get_paired_phenotype", "(", "data",...
40.676471
0.002119
def moralize(self): """ Removes all the immoralities in the Network and creates a moral graph (UndirectedGraph). A v-structure X->Z<-Y is an immorality if there is no directed edge between X and Y. Examples -------- >>> from pgmpy.models import DynamicBa...
[ "def", "moralize", "(", "self", ")", ":", "moral_graph", "=", "self", ".", "to_undirected", "(", ")", "for", "node", "in", "super", "(", "DynamicBayesianNetwork", ",", "self", ")", ".", "nodes", "(", ")", ":", "moral_graph", ".", "add_edges_from", "(", "...
31.321429
0.002212
def build_interpolatable_ttfs(self, designspace, **kwargs): """Build OpenType binaries with interpolatable TrueType outlines from DesignSpaceDocument object. """ return self._build_interpolatable_masters(designspace, ttf=True, **kwargs)
[ "def", "build_interpolatable_ttfs", "(", "self", ",", "designspace", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_build_interpolatable_masters", "(", "designspace", ",", "ttf", "=", "True", ",", "*", "*", "kwargs", ")" ]
52.8
0.011194
def request(community_id, record_id, accept): """Request a record acceptance to a community.""" c = Community.get(community_id) assert c is not None record = Record.get_record(record_id) if accept: c.add_record(record) record.commit() else: InclusionRequest.create(communi...
[ "def", "request", "(", "community_id", ",", "record_id", ",", "accept", ")", ":", "c", "=", "Community", ".", "get", "(", "community_id", ")", "assert", "c", "is", "not", "None", "record", "=", "Record", ".", "get_record", "(", "record_id", ")", "if", ...
33.923077
0.002208
def oldest_frame(self, raw=False): """ Get the oldest frame in the panel. """ if raw: return self.buffer.values[:, self._start_index, :] return self.buffer.iloc[:, self._start_index, :]
[ "def", "oldest_frame", "(", "self", ",", "raw", "=", "False", ")", ":", "if", "raw", ":", "return", "self", ".", "buffer", ".", "values", "[", ":", ",", "self", ".", "_start_index", ",", ":", "]", "return", "self", ".", "buffer", ".", "iloc", "[", ...
33
0.008439
def get_repo_info(loader, sha, prov_g): """Generate swagger information from the repo being used.""" user_repo = loader.getFullName() repo_title = loader.getRepoTitle() contact_name = loader.getContactName() contact_url = loader.getContactUrl() commit_list = loader.getCommitList() licence_ur...
[ "def", "get_repo_info", "(", "loader", ",", "sha", ",", "prov_g", ")", ":", "user_repo", "=", "loader", ".", "getFullName", "(", ")", "repo_title", "=", "loader", ".", "getRepoTitle", "(", ")", "contact_name", "=", "loader", ".", "getContactName", "(", ")"...
30.789474
0.000829
def mmGetMetricDistinctnessConfusion(self): """ For each iteration that doesn't follow a reset, looks at every other iteration for every other world that doesn't follow a reset, and computes the number of bits that show up in both sets of active cells those that iteration. This metric returns the di...
[ "def", "mmGetMetricDistinctnessConfusion", "(", "self", ")", ":", "self", ".", "_mmComputeSequenceRepresentationData", "(", ")", "numbers", "=", "self", ".", "_mmData", "[", "\"distinctnessConfusion\"", "]", "return", "Metric", "(", "self", ",", "\"distinctness confus...
46.333333
0.001764
def eps(self): """Print the canvas to a postscript file""" import tkFileDialog,tkMessageBox filename=tkFileDialog.asksaveasfilename(message="save postscript to file",filetypes=['eps','ps']) if filename is None: return self.postscript(file=filename)
[ "def", "eps", "(", "self", ")", ":", "import", "tkFileDialog", ",", "tkMessageBox", "filename", "=", "tkFileDialog", ".", "asksaveasfilename", "(", "message", "=", "\"save postscript to file\"", ",", "filetypes", "=", "[", "'eps'", ",", "'ps'", "]", ")", "if",...
29.666667
0.054545
def grid_reload_from_ids(oargrid_jobids): """Reload all running or pending jobs of Grid'5000 from their ids Args: oargrid_jobids (list): list of ``(site, oar_jobid)`` identifying the jobs on each site Returns: The list of python-grid5000 jobs retrieved """ gk = get_api_...
[ "def", "grid_reload_from_ids", "(", "oargrid_jobids", ")", ":", "gk", "=", "get_api_client", "(", ")", "jobs", "=", "[", "]", "for", "site", ",", "job_id", "in", "oargrid_jobids", ":", "jobs", ".", "append", "(", "gk", ".", "sites", "[", "site", "]", "...
28.866667
0.002237
def contains_pts(self, pts): """Containment test on arrays.""" obj1, obj2 = self.objects arg1 = obj2.contains_pts(pts) arg2 = np.logical_not(obj1.contains_pts(pts)) return np.logical_and(arg1, arg2)
[ "def", "contains_pts", "(", "self", ",", "pts", ")", ":", "obj1", ",", "obj2", "=", "self", ".", "objects", "arg1", "=", "obj2", ".", "contains_pts", "(", "pts", ")", "arg2", "=", "np", ".", "logical_not", "(", "obj1", ".", "contains_pts", "(", "pts"...
38.833333
0.008403
def DatabaseEnabled(cls): """Given persistence methods to classes with this annotation. All this really does is add some functions that forward to the mapped database class. """ if not issubclass(cls, Storable): raise ValueError( "%s is not a subclass of gludb.datab.Storage" % r...
[ "def", "DatabaseEnabled", "(", "cls", ")", ":", "if", "not", "issubclass", "(", "cls", ",", "Storable", ")", ":", "raise", "ValueError", "(", "\"%s is not a subclass of gludb.datab.Storage\"", "%", "repr", "(", "cls", ")", ")", "cls", ".", "ensure_table", "=",...
29.947368
0.001704
def publish(self, key, data): ''' Publishes the data to the event stream. ''' publish_data = {key: data} pub = salt.utils.json.dumps(publish_data) + str('\n\n') # future lint: disable=blacklisted-function self.handler.write_message(pub)
[ "def", "publish", "(", "self", ",", "key", ",", "data", ")", ":", "publish_data", "=", "{", "key", ":", "data", "}", "pub", "=", "salt", ".", "utils", ".", "json", ".", "dumps", "(", "publish_data", ")", "+", "str", "(", "'\\n\\n'", ")", "# future ...
39.857143
0.010526
def recoverTransaction(self, serialized_transaction): ''' Get the address of the account that signed this transaction. :param serialized_transaction: the complete signed transaction :type serialized_transaction: hex str, bytes or int :returns: address of signer, hex-encoded & ch...
[ "def", "recoverTransaction", "(", "self", ",", "serialized_transaction", ")", ":", "txn_bytes", "=", "HexBytes", "(", "serialized_transaction", ")", "txn", "=", "Transaction", ".", "from_bytes", "(", "txn_bytes", ")", "msg_hash", "=", "hash_of_signed_transaction", "...
51.368421
0.002012
def prices(self): """ TimeSeries of prices. """ if self.root.stale: self.root.update(self.now, None) return self._prices.loc[:self.now]
[ "def", "prices", "(", "self", ")", ":", "if", "self", ".", "root", ".", "stale", ":", "self", ".", "root", ".", "update", "(", "self", ".", "now", ",", "None", ")", "return", "self", ".", "_prices", ".", "loc", "[", ":", "self", ".", "now", "]"...
25.857143
0.010695
def backgroundMMD(self, catalog, method='cloud-in-cells', weights=None): """ Generate an empirical background model in magnitude-magnitude space. INPUTS: catalog: Catalog object OUTPUTS: background """ # Select objects in annulus ...
[ "def", "backgroundMMD", "(", "self", ",", "catalog", ",", "method", "=", "'cloud-in-cells'", ",", "weights", "=", "None", ")", ":", "# Select objects in annulus", "cut_annulus", "=", "self", ".", "roi", ".", "inAnnulus", "(", "catalog", ".", "lon", ",", "cat...
50.647059
0.008544
def _get_method_repo(self, namespace=None): """ Returns the method repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock...
[ "def", "_get_method_repo", "(", "self", ",", "namespace", "=", "None", ")", ":", "self", ".", "_validate_namespace", "(", "namespace", ")", "if", "namespace", "not", "in", "self", ".", "methods", ":", "self", ".", "methods", "[", "namespace", "]", "=", "...
31.678571
0.002188
def Database_executeSQL(self, databaseId, query): """ Function path: Database.executeSQL Domain: Database Method name: executeSQL Parameters: Required arguments: 'databaseId' (type: DatabaseId) -> No description 'query' (type: string) -> No description Returns: 'columnNames' (type: ...
[ "def", "Database_executeSQL", "(", "self", ",", "databaseId", ",", "query", ")", ":", "assert", "isinstance", "(", "query", ",", "(", "str", ",", ")", ")", ",", "\"Argument 'query' must be of type '['str']'. Received type: '%s'\"", "%", "type", "(", "query", ")", ...
31.090909
0.04539
def request(self, method, url, path=(), extension=None, suffix=None, params=None, headers=None, data=None, debug=None, cache_lifetime=None, silent=None, ignore_cache=False, format='json', delay=0.0, formatter=None, **kwargs): """Requests a URL and returns a *Bunch...
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "path", "=", "(", ")", ",", "extension", "=", "None", ",", "suffix", "=", "None", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "data", "=", "None", ",", "debug", "=",...
43.668919
0.000908
def remove_layer(svg_source, layer_name): ''' Remove layer(s) from SVG document. Arguments --------- svg_source : str or file-like A file path, URI, or file-like object. layer_name : str or list Layer name or list of layer names to remove from SVG document. Returns ----...
[ "def", "remove_layer", "(", "svg_source", ",", "layer_name", ")", ":", "# Parse input file.", "xml_root", "=", "lxml", ".", "etree", ".", "parse", "(", "svg_source", ")", "svg_root", "=", "xml_root", ".", "xpath", "(", "'/svg:svg'", ",", "namespaces", "=", "...
29.447368
0.000865
def swatch(self, x, y, w=35, h=35, roundness=0): """ Rectangle swatch for this color. """ _ctx.fill(self) _ctx.rect(x, y, w, h, roundness)
[ "def", "swatch", "(", "self", ",", "x", ",", "y", ",", "w", "=", "35", ",", "h", "=", "35", ",", "roundness", "=", "0", ")", ":", "_ctx", ".", "fill", "(", "self", ")", "_ctx", ".", "rect", "(", "x", ",", "y", ",", "w", ",", "h", ",", "...
28.833333
0.011236
def submit_export(cls, file, volume, location, properties=None, overwrite=False, copy_only=False, api=None): """ Submit new export job. :param file: File to be exported. :param volume: Volume identifier. :param location: Volume location. :param prop...
[ "def", "submit_export", "(", "cls", ",", "file", ",", "volume", ",", "location", ",", "properties", "=", "None", ",", "overwrite", "=", "False", ",", "copy_only", "=", "False", ",", "api", "=", "None", ")", ":", "data", "=", "{", "}", "params", "=", ...
29.877551
0.001984
def ex_literal(val): """An int, float, long, bool, string, or None literal with the given value. """ if val is None: return ast.Name('None', ast.Load()) elif isinstance(val, int): return ast.Num(val) elif isinstance(val, bool): return ast.Name(bytes(val), ast.Load()) ...
[ "def", "ex_literal", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "ast", ".", "Name", "(", "'None'", ",", "ast", ".", "Load", "(", ")", ")", "elif", "isinstance", "(", "val", ",", "int", ")", ":", "return", "ast", ".", "Num", ...
32.538462
0.002299
def getSubgraphList(self, parent_name): """Returns list of names of subgraphs for Root Graph with name parent_name. @param parent_name: Name of Root Graph. @return: List of subgraph names. """ if not self.isMultigraph: raise AttributeError...
[ "def", "getSubgraphList", "(", "self", ",", "parent_name", ")", ":", "if", "not", "self", ".", "isMultigraph", ":", "raise", "AttributeError", "(", "\"Simple Munin Plugins cannot have subgraphs.\"", ")", "if", "self", ".", "_graphDict", ".", "has_key", "(", "paren...
42.214286
0.009934
def new_data(self, mem, addr, data): """Callback for when new memory data has been fetched""" if mem.id == self.id: if addr == 0: done = False # Check for header if data[0:4] == EEPROM_TOKEN: logger.debug('Got new data: {}'....
[ "def", "new_data", "(", "self", ",", "mem", ",", "addr", ",", "data", ")", ":", "if", "mem", ".", "id", "==", "self", ".", "id", ":", "if", "addr", "==", "0", ":", "done", "=", "False", "# Check for header", "if", "data", "[", "0", ":", "4", "]...
43.619048
0.001068
def store_data(self, data): """ 存储数据到存储队列 :param data: 数据 :return: """ self.ch.basic_publish(exchange='', routing_key=self.store_queue, properties=pika.BasicProperties(delivery_mode=2), body=data)
[ "def", "store_data", "(", "self", ",", "data", ")", ":", "self", ".", "ch", ".", "basic_publish", "(", "exchange", "=", "''", ",", "routing_key", "=", "self", ".", "store_queue", ",", "properties", "=", "pika", ".", "BasicProperties", "(", "delivery_mode",...
31.125
0.011719
async def _request(self, method, *args, **kwargs): """Send a request to the device and awaits a response. This mainly ensures that requests are sent serially, as the Modbus protocol does not allow simultaneous requests (it'll ignore any request sent while it's processing something). The...
[ "async", "def", "_request", "(", "self", ",", "method", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "open", ":", "await", "self", ".", "_connect", "(", ")", "while", "self", ".", "waiting", ":", "await", "asyncio"...
45.628571
0.001226
def energy_minimum(self, x): """ Given an input array `x` it returns its associated encoding `y(x)`, that is, a stable configuration (local energy minimum) of the hidden units while the visible units are clampled to `x`. """ E = self.energy y_min = self.find_energy_minimum(E, x) ...
[ "def", "energy_minimum", "(", "self", ",", "x", ")", ":", "E", "=", "self", ".", "energy", "y_min", "=", "self", ".", "find_energy_minimum", "(", "E", ",", "x", ")", "return", "y_min" ]
36
0.018072
def ryb_to_rgb(hue): """Maps a hue on Itten's RYB color wheel to the standard RGB wheel. Parameters: :hue: The hue on Itten's RYB color wheel [0...360] Returns: An approximation of the corresponding hue on the standard RGB wheel. >>> ryb_to_rgb(15) 8.0 """ d = hue % 15 i = int(hue / 15...
[ "def", "ryb_to_rgb", "(", "hue", ")", ":", "d", "=", "hue", "%", "15", "i", "=", "int", "(", "hue", "/", "15", ")", "x0", "=", "_RgbWheel", "[", "i", "]", "x1", "=", "_RgbWheel", "[", "i", "+", "1", "]", "return", "x0", "+", "(", "x1", "-",...
19.789474
0.017766
def week(self): '''set unit to week''' self.magnification = 345600 self._update(self.baseNumber, self.magnification) return self
[ "def", "week", "(", "self", ")", ":", "self", ".", "magnification", "=", "345600", "self", ".", "_update", "(", "self", ".", "baseNumber", ",", "self", ".", "magnification", ")", "return", "self" ]
31.2
0.0125
def datetime_mod(dt, period, start=None): """ Find the time which is the specified date/time truncated to the time delta relative to the start date/time. By default, the start time is midnight of the same day as the specified date/time. >>> datetime_mod(datetime.datetime(2004, 1, 2, 3), ... datetime.timedel...
[ "def", "datetime_mod", "(", "dt", ",", "period", ",", "start", "=", "None", ")", ":", "if", "start", "is", "None", ":", "# use midnight of the same day", "start", "=", "datetime", ".", "datetime", ".", "combine", "(", "dt", ".", "date", "(", ")", ",", ...
41.390244
0.022453
def scanResource(uri = None, listRegexp = None, verbosity=1, logFolder= "./logs"): """ [Optionally] recursive method to scan the files in a given folder. Args: ----- uri: the URI to be scanned. listRegexp: listRegexp is an array of <RegexpObject>. Returns: ------- dict:...
[ "def", "scanResource", "(", "uri", "=", "None", ",", "listRegexp", "=", "None", ",", "verbosity", "=", "1", ",", "logFolder", "=", "\"./logs\"", ")", ":", "logSet", ".", "setupLogger", "(", "loggerName", "=", "\"osrframework.entify\"", ",", "verbosity", "=",...
28.25
0.0125
def parse_intervals(path, as_context=False): """ Parse path strings into a collection of Intervals. `path` is a string describing a region in a file. It's format is dotted.module.name:[line | start-stop | context] `dotted.module.name` is a python module `line` is a single line number in t...
[ "def", "parse_intervals", "(", "path", ",", "as_context", "=", "False", ")", ":", "def", "_regions_from_range", "(", ")", ":", "if", "as_context", ":", "ctxs", "=", "list", "(", "set", "(", "pf", ".", "lines", "[", "start", "-", "1", ":", "stop", "-"...
31.493151
0.000422
def wind(direction: Number, speed: Number, gust: Number, vardir: typing.List[Number] = None, # type: ignore unit: str = 'kt', cardinals: bool = True, spoken: bool = False) -> str: """ Format wind elements into a readable sentence Returns the translatio...
[ "def", "wind", "(", "direction", ":", "Number", ",", "speed", ":", "Number", ",", "gust", ":", "Number", ",", "vardir", ":", "typing", ".", "List", "[", "Number", "]", "=", "None", ",", "# type: ignore", "unit", ":", "str", "=", "'kt'", ",", "cardina...
31.432432
0.001668
def subscribe_to_human_connection_events( self, subscriber: Callable[[events.HumanConnectionEvent], None], ) -> None: """ Not thread-safe. """ self._human_connection_subscribers.append(subscriber)
[ "def", "subscribe_to_human_connection_events", "(", "self", ",", "subscriber", ":", "Callable", "[", "[", "events", ".", "HumanConnectionEvent", "]", ",", "None", "]", ",", ")", "->", "None", ":", "self", ".", "_human_connection_subscribers", ".", "append", "(",...
26.777778
0.012048
def record_get_field(rec, tag, field_position_global=None, field_position_local=None): """ Return the the matching field. One has to enter either a global field position or a local field position. :return: a list of subfield tuples (subfield code, value). :rtype: list """ ...
[ "def", "record_get_field", "(", "rec", ",", "tag", ",", "field_position_global", "=", "None", ",", "field_position_local", "=", "None", ")", ":", "if", "field_position_global", "is", "None", "and", "field_position_local", "is", "None", ":", "raise", "InvenioBibRec...
39.526316
0.00065
def fix_input_files_for_numbered_seq(sourceDir, suffix, timestamp, containers): """Fixes files used as input when pre-processing MPL-containers in their numbered form.""" # Fix input files for each MPL-container type. for container in containers: files = glob.glob( os.path.join( sourceDir, container...
[ "def", "fix_input_files_for_numbered_seq", "(", "sourceDir", ",", "suffix", ",", "timestamp", ",", "containers", ")", ":", "# Fix input files for each MPL-container type.", "for", "container", "in", "containers", ":", "files", "=", "glob", ".", "glob", "(", "os", "....
63.571429
0.02439
def make_contiguous(im, keep_zeros=True): r""" Take an image with arbitrary greyscale values and adjust them to ensure all values fall in a contiguous range starting at 0. This function will handle negative numbers such that most negative number will become 0, *unless* ``keep_zeros`` is ``True`` in...
[ "def", "make_contiguous", "(", "im", ",", "keep_zeros", "=", "True", ")", ":", "im", "=", "sp", ".", "copy", "(", "im", ")", "if", "keep_zeros", ":", "mask", "=", "(", "im", "==", "0", ")", "im", "[", "mask", "]", "=", "im", ".", "min", "(", ...
30.74
0.000631
def fill_package(app_name, build_dir=None, install_dir=None): """ Creates the theme package (.zip) from templates and optionally assets installed in the ``build_dir``. """ zip_path = os.path.join(install_dir, '%s.zip' % app_name) with zipfile.ZipFile(zip_path, 'w') as zip_file: fill_pack...
[ "def", "fill_package", "(", "app_name", ",", "build_dir", "=", "None", ",", "install_dir", "=", "None", ")", ":", "zip_path", "=", "os", ".", "path", ".", "join", "(", "install_dir", ",", "'%s.zip'", "%", "app_name", ")", "with", "zipfile", ".", "ZipFile...
43.777778
0.002488
def l1_regularizer(decay, name_filter='weights'): """Create an l1 regularizer.""" return regularizer( 'l1_regularizer', lambda x: tf.reduce_sum(tf.abs(x)) * decay, name_filter=name_filter)
[ "def", "l1_regularizer", "(", "decay", ",", "name_filter", "=", "'weights'", ")", ":", "return", "regularizer", "(", "'l1_regularizer'", ",", "lambda", "x", ":", "tf", ".", "reduce_sum", "(", "tf", ".", "abs", "(", "x", ")", ")", "*", "decay", ",", "na...
34.333333
0.018957
def remove_action_callback(self, *event): """Callback method for remove action The method checks whether a shortcut ('Delete') is in the gui config model which shadow the delete functionality of maybe active a entry widget. If a entry widget is active the remove callback return with None. ...
[ "def", "remove_action_callback", "(", "self", ",", "*", "event", ")", ":", "if", "react_to_event", "(", "self", ".", "view", ",", "self", ".", "tree_view", ",", "event", ")", "and", "not", "(", "self", ".", "active_entry_widget", "and", "not", "is_event_of...
53.6
0.009174
def removed(name, features=None, remove_payload=False, restart=False): ''' Remove the windows feature To remove a single feature, use the ``name`` parameter. To remove multiple features, use the ``features`` parameter. Args: name (str): Short name of the feature (the right column in...
[ "def", "removed", "(", "name", ",", "features", "=", "None", ",", "remove_payload", "=", "False", ",", "restart", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ",", "'...
31.410853
0.000718
def _relative_uris(self, uri_list): """ if uris in list are relative, re-relate them to our basedir """ return [u for u in (self._relative(uri) for uri in uri_list) if u]
[ "def", "_relative_uris", "(", "self", ",", "uri_list", ")", ":", "return", "[", "u", "for", "u", "in", "(", "self", ".", "_relative", "(", "uri", ")", "for", "uri", "in", "uri_list", ")", "if", "u", "]" ]
33
0.009852
def send_password_reset(self, base_url=None, view_class=None, **kw): """ Reset a password and send email :param user: AuthUser :param email: str - The auth user login email :param base_url: str - By default it will use the current url, base_url will allow custom url :para...
[ "def", "send_password_reset", "(", "self", ",", "base_url", "=", "None", ",", "view_class", "=", "None", ",", "*", "*", "kw", ")", ":", "view", "=", "view_class", "or", "views", ".", "auth", ".", "Login", "endpoint_reset", "=", "getattr", "(", "view", ...
43.785714
0.001596
def analysis_question_extractor(impact_report, component_metadata): """Extracting analysis question from the impact layer. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :param...
[ "def", "analysis_question_extractor", "(", "impact_report", ",", "component_metadata", ")", ":", "multi_exposure", "=", "impact_report", ".", "multi_exposure_impact_function", "if", "multi_exposure", ":", "return", "multi_exposure_analysis_question_extractor", "(", "impact_repo...
34.882353
0.00082
def xml_open(filename, expected_root=None): """Opens the provided 'filename'. Handles detecting if the file is an archive, detecting the document version, and validating the root tag.""" # Is the file a zip (.twbx or .tdsx) if zipfile.is_zipfile(filename): tree = get_xml_from_archive(filename) ...
[ "def", "xml_open", "(", "filename", ",", "expected_root", "=", "None", ")", ":", "# Is the file a zip (.twbx or .tdsx)", "if", "zipfile", ".", "is_zipfile", "(", "filename", ")", ":", "tree", "=", "get_xml_from_archive", "(", "filename", ")", "else", ":", "tree"...
37.304348
0.002273
def preprocess(train_dataset, output_dir, eval_dataset, checkpoint, pipeline_option): """Preprocess data in Cloud with DataFlow.""" import apache_beam as beam import google.datalab.utils from . import _preprocess if checkpoint is None: checkpoint = _util._DEFAULT_CHECKPOINT_GSURL job_na...
[ "def", "preprocess", "(", "train_dataset", ",", "output_dir", ",", "eval_dataset", ",", "checkpoint", ",", "pipeline_option", ")", ":", "import", "apache_beam", "as", "beam", "import", "google", ".", "datalab", ".", "utils", "from", ".", "import", "_preprocess",...
42.719298
0.010036
def bidiagonalize_unitary_with_special_orthogonals( mat: np.ndarray, *, rtol: float = 1e-5, atol: float = 1e-8, check_preconditions: bool = True ) -> Tuple[np.ndarray, np.array, np.ndarray]: """Finds orthogonal matrices L, R such that L @ matrix @ R is diagonal. Args: ...
[ "def", "bidiagonalize_unitary_with_special_orthogonals", "(", "mat", ":", "np", ".", "ndarray", ",", "*", ",", "rtol", ":", "float", "=", "1e-5", ",", "atol", ":", "float", "=", "1e-8", ",", "check_preconditions", ":", "bool", "=", "True", ")", "->", "Tupl...
33.543478
0.001259
def GetModuleText(heading, name, showprivate=False): """Returns the needed text to automatically document a module in RSF/sphinx""" und = '='*len(heading) if showprivate: opts = ':private-members:' else: opts = '' return r''' %s %s .. automodule:: %s ...
[ "def", "GetModuleText", "(", "heading", ",", "name", ",", "showprivate", "=", "False", ")", ":", "und", "=", "'='", "*", "len", "(", "heading", ")", "if", "showprivate", ":", "opts", "=", "':private-members:'", "else", ":", "opts", "=", "''", "return", ...
21.375
0.008403
def has_successor(self, graph, orig, dest, branch, turn, tick, *, forward=None): """Return whether an edge connects the origin to the destination at the given time. Doesn't require the edge's index, which makes it slower than retrieving a particular edge. """ if forward is None...
[ "def", "has_successor", "(", "self", ",", "graph", ",", "orig", ",", "dest", ",", "branch", ",", "turn", ",", "tick", ",", "*", ",", "forward", "=", "None", ")", ":", "if", "forward", "is", "None", ":", "forward", "=", "self", ".", "db", ".", "_f...
44.4
0.013245
def get_row_failures(df, value_cols, type_cols, verbose=False, outfile=None): """ Input: already validated DataFrame, value & type column names, and output options. Get details on each detected issue, row by row. Output: DataFrame with type & value validation columns, plus an "issues" column wit...
[ "def", "get_row_failures", "(", "df", ",", "value_cols", ",", "type_cols", ",", "verbose", "=", "False", ",", "outfile", "=", "None", ")", ":", "# set temporary numeric index", "df", "[", "\"num\"", "]", "=", "list", "(", "range", "(", "len", "(", "df", ...
42.366667
0.001538
def autobuild_bootstrap_file(file_name, image_list): """Combine multiple firmware images into a single bootstrap hex file. The files listed in image_list must be products of either this tile or any dependency tile and should correspond exactly with the base name listed on the products section of the mo...
[ "def", "autobuild_bootstrap_file", "(", "file_name", ",", "image_list", ")", ":", "family", "=", "utilities", ".", "get_family", "(", "'module_settings.json'", ")", "target", "=", "family", ".", "platform_independent_target", "(", ")", "resolver", "=", "ProductResol...
41.452381
0.001684
def _combine_attr_fast_update(self, attr, typ): '''Avoids having to call _update for each intermediate base. Only works for class attr of type UpdateDict. ''' values = dict(getattr(self, attr, {})) for base in self._class_data.bases: vals = dict(getattr(bas...
[ "def", "_combine_attr_fast_update", "(", "self", ",", "attr", ",", "typ", ")", ":", "values", "=", "dict", "(", "getattr", "(", "self", ",", "attr", ",", "{", "}", ")", ")", "for", "base", "in", "self", ".", "_class_data", ".", "bases", ":", "vals", ...
35.615385
0.008421
def get_text(self): ''' ::returns: a rendered string representation of the given table ''' self.compute_column_width_and_height() return '\n'.join((row.get_text() for row in self.rows))
[ "def", "get_text", "(", "self", ")", ":", "self", ".", "compute_column_width_and_height", "(", ")", "return", "'\\n'", ".", "join", "(", "(", "row", ".", "get_text", "(", ")", "for", "row", "in", "self", ".", "rows", ")", ")" ]
33.571429
0.008299
def get_extension_classes(sort, extra_extension_paths=None): """ Banana banana """ all_classes = {} deps_map = {} for entry_point in pkg_resources.iter_entry_points( group='hotdoc.extensions', name='get_extension_classes'): if entry_point.module_name == 'hotdoc_c_extension.e...
[ "def", "get_extension_classes", "(", "sort", ",", "extra_extension_paths", "=", "None", ")", ":", "all_classes", "=", "{", "}", "deps_map", "=", "{", "}", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "group", "=", "'hotdoc.extensio...
33.470588
0.000569
def add_component(self, kind, **kwargs): """ Add a new component (star or orbit) to the system. If not provided, 'component' (the name of the new star or orbit) will be created for you and can be accessed by the 'component' attribute of the returned ParameterSet. >>> b....
[ "def", "add_component", "(", "self", ",", "kind", ",", "*", "*", "kwargs", ")", ":", "func", "=", "_get_add_func", "(", "component", ",", "kind", ")", "if", "kwargs", ".", "get", "(", "'component'", ",", "False", ")", "is", "None", ":", "# then we want...
38.577465
0.001068
def GetClientConfig(self, context, validate=True, deploy_timestamp=True): """Generates the client config file for inclusion in deployable binaries.""" with utils.TempDirectory() as tmp_dir: # Make sure we write the file in yaml format. filename = os.path.join( tmp_dir, config.CON...
[ "def", "GetClientConfig", "(", "self", ",", "context", ",", "validate", "=", "True", ",", "deploy_timestamp", "=", "True", ")", ":", "with", "utils", ".", "TempDirectory", "(", ")", "as", "tmp_dir", ":", "# Make sure we write the file in yaml format.", "filename",...
39.945455
0.01155
def play(self, stream_url, offset=0, opaque_token=None): """Sends a Play Directive to begin playback and replace current and enqueued streams.""" self._response['shouldEndSession'] = True directive = self._play_directive('REPLACE_ALL') directive['audioItem'] = self._audio_item(stream_ur...
[ "def", "play", "(", "self", ",", "stream_url", ",", "offset", "=", "0", ",", "opaque_token", "=", "None", ")", ":", "self", ".", "_response", "[", "'shouldEndSession'", "]", "=", "True", "directive", "=", "self", ".", "_play_directive", "(", "'REPLACE_ALL'...
55.375
0.008889
def replace_namespaced_persistent_volume_claim(self, name, namespace, body, **kwargs): # noqa: E501 """replace_namespaced_persistent_volume_claim # noqa: E501 replace the specified PersistentVolumeClaim # noqa: E501 This method makes a synchronous HTTP request by default. To make an ...
[ "def", "replace_namespaced_persistent_volume_claim", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asy...
65.36
0.001206