text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def write_dicts_to_json(self, data): """Saves .json file with data :param data: Data """ with open(self.path, "w") as out: json.dump( data, # data out, # file handler indent=4, sort_keys=True # pretty print )
[ "def", "write_dicts_to_json", "(", "self", ",", "data", ")", ":", "with", "open", "(", "self", ".", "path", ",", "\"w\"", ")", "as", "out", ":", "json", ".", "dump", "(", "data", ",", "# data", "out", ",", "# file handler", "indent", "=", "4", ",", ...
27.818182
12.363636
def create_course(self, courseid, init_content): """ :param courseid: the course id of the course :param init_content: initial descriptor content :raise InvalidNameException or CourseAlreadyExistsException Create a new course folder and set initial descriptor content, folder can ...
[ "def", "create_course", "(", "self", ",", "courseid", ",", "init_content", ")", ":", "if", "not", "id_checker", "(", "courseid", ")", ":", "raise", "InvalidNameException", "(", "\"Course with invalid name: \"", "+", "courseid", ")", "course_fs", "=", "self", "."...
47.210526
26.894737
def _make_probs(self, *sequences): """ https://github.com/gw-c/arith/blob/master/arith.py """ sequences = self._get_counters(*sequences) counts = self._sum_counters(*sequences) if self.terminator is not None: counts[self.terminator] = 1 total_letters =...
[ "def", "_make_probs", "(", "self", ",", "*", "sequences", ")", ":", "sequences", "=", "self", ".", "_get_counters", "(", "*", "sequences", ")", "counts", "=", "self", ".", "_sum_counters", "(", "*", "sequences", ")", "if", "self", ".", "terminator", "is"...
37.285714
12.142857
def _escape(self, msg): """ Escapes double quotes by adding another double quote as per the Scratch protocol. Expects a string without its delimiting quotes. Returns a new escaped string. """ escaped = '' for c in msg: escaped += c if c ...
[ "def", "_escape", "(", "self", ",", "msg", ")", ":", "escaped", "=", "''", "for", "c", "in", "msg", ":", "escaped", "+=", "c", "if", "c", "==", "'\"'", ":", "escaped", "+=", "'\"'", "return", "escaped" ]
30.833333
17.333333
def calc_next_ma_coef(self, ma_order, ma_model): """Determine the MA coefficients of the ARMA model based on its predetermined AR coefficients and the MA ordinates of the given |MA| model. The MA coefficients are determined one at a time, beginning with the first one. Each ARMA...
[ "def", "calc_next_ma_coef", "(", "self", ",", "ma_order", ",", "ma_model", ")", ":", "idx", "=", "ma_order", "-", "1", "coef", "=", "ma_model", ".", "coefs", "[", "idx", "]", "for", "jdx", ",", "ar_coef", "in", "enumerate", "(", "self", ".", "ar_coefs"...
45.058824
18.235294
def getBriefModuleInfoFromFile(fileName): """Builds the brief module info from file""" modInfo = BriefModuleInfo() _cdmpyparser.getBriefModuleInfoFromFile(modInfo, fileName) modInfo.flush() return modInfo
[ "def", "getBriefModuleInfoFromFile", "(", "fileName", ")", ":", "modInfo", "=", "BriefModuleInfo", "(", ")", "_cdmpyparser", ".", "getBriefModuleInfoFromFile", "(", "modInfo", ",", "fileName", ")", "modInfo", ".", "flush", "(", ")", "return", "modInfo" ]
36.5
12.5
def _construct_regex(cls, fmt): """Given a format string, construct the regex with class attributes.""" return re.compile(fmt.format(**vars(cls)), flags=re.U)
[ "def", "_construct_regex", "(", "cls", ",", "fmt", ")", ":", "return", "re", ".", "compile", "(", "fmt", ".", "format", "(", "*", "*", "vars", "(", "cls", ")", ")", ",", "flags", "=", "re", ".", "U", ")" ]
57.333333
10.333333
def count(self, filter=None, order_by=None, group_by=[], page=None, page_size=None, query_parameters=None, async=False, callback=None): """ Get the total count of objects that can be fetched according to filter This method can be asynchronous and trigger the callback method when result ...
[ "def", "count", "(", "self", ",", "filter", "=", "None", ",", "order_by", "=", "None", ",", "group_by", "=", "[", "]", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "query_parameters", "=", "None", ",", "async", "=", "False", ",", "...
52.827586
35.827586
def privileges_grant(name, object_name, object_type, privileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2016.3.0 ...
[ "def", "privileges_grant", "(", "name", ",", "object_name", ",", "object_type", ",", "privileges", "=", "None", ",", "grant_option", "=", "None", ",", "prepend", "=", "'public'", ",", "maintenance_db", "=", "None", ",", "user", "=", "None", ",", "host", "=...
29.043796
23.890511
def build_a(self): """Calculates the total absorption from water, phytoplankton and CDOM a = awater + acdom + aphi """ lg.info('Building total absorption') self.a = self.a_water + self.a_cdom + self.a_phi
[ "def", "build_a", "(", "self", ")", ":", "lg", ".", "info", "(", "'Building total absorption'", ")", "self", ".", "a", "=", "self", ".", "a_water", "+", "self", ".", "a_cdom", "+", "self", ".", "a_phi" ]
34.142857
12.714286
def addConstraint(self, constraint, variables=None): """ Add a constraint to the problem Example: >>> problem = Problem() >>> problem.addVariables(["a", "b"], [1, 2, 3]) >>> problem.addConstraint(lambda a, b: b == a+1, ["a", "b"]) >>> solutions = problem.getSolu...
[ "def", "addConstraint", "(", "self", ",", "constraint", ",", "variables", "=", "None", ")", ":", "if", "not", "isinstance", "(", "constraint", ",", "Constraint", ")", ":", "if", "callable", "(", "constraint", ")", ":", "constraint", "=", "FunctionConstraint"...
42.62963
20.555556
def _function_add_transition_edge(self, dst_addr, src_node, src_func_addr, to_outside=False, dst_func_addr=None, stmt_idx=None, ins_addr=None): """ Add a transition edge to the function transiton map. :param int dst_addr: Address that the control flow trans...
[ "def", "_function_add_transition_edge", "(", "self", ",", "dst_addr", ",", "src_node", ",", "src_func_addr", ",", "to_outside", "=", "False", ",", "dst_func_addr", "=", "None", ",", "stmt_idx", "=", "None", ",", "ins_addr", "=", "None", ")", ":", "try", ":",...
52.648649
30.054054
def _determine_stream_spread(self,simple=_USESIMPLE): """Determine the spread around the stream track, just sets matrices that describe the covariances""" allErrCovs= numpy.empty((self._nTrackChunks,6,6)) if self._multi is None: for ii in range(self._nTrackChunks): al...
[ "def", "_determine_stream_spread", "(", "self", ",", "simple", "=", "_USESIMPLE", ")", ":", "allErrCovs", "=", "numpy", ".", "empty", "(", "(", "self", ".", "_nTrackChunks", ",", "6", ",", "6", ")", ")", "if", "self", ".", "_multi", "is", "None", ":", ...
61.15
24.825
def _short_string_handler_factory(): """Generates the short string (double quoted) handler.""" def before(c, ctx, is_field_name, is_clob): assert not (is_clob and is_field_name) is_string = not is_clob and not is_field_name if is_string: ctx.set_ion_type(IonType.STRING) ...
[ "def", "_short_string_handler_factory", "(", ")", ":", "def", "before", "(", "c", ",", "ctx", ",", "is_field_name", ",", "is_clob", ")", ":", "assert", "not", "(", "is_clob", "and", "is_field_name", ")", "is_string", "=", "not", "is_clob", "and", "not", "i...
39.884615
19.307692
def check_digest_auth(user, passwd): """Check user authentication using HTTP Digest auth""" if request.headers.get('Authorization'): credentials = parse_authorization_header(request.headers.get('Authorization')) if not credentials: return request_uri = request.script_root + ...
[ "def", "check_digest_auth", "(", "user", ",", "passwd", ")", ":", "if", "request", ".", "headers", ".", "get", "(", "'Authorization'", ")", ":", "credentials", "=", "parse_authorization_header", "(", "request", ".", "headers", ".", "get", "(", "'Authorization'...
46.25
21.125
def add_attachment(self, filename, open_file): ''' Adds an attachment to this card. ''' fields = { 'api_key': self.client.api_key, 'token': self.client.user_auth_token } content_type, body = self.encode_multipart_formdata( fields=field...
[ "def", "add_attachment", "(", "self", ",", "filename", ",", "open_file", ")", ":", "fields", "=", "{", "'api_key'", ":", "self", ".", "client", ".", "api_key", ",", "'token'", ":", "self", ".", "client", ".", "user_auth_token", "}", "content_type", ",", ...
27.619048
18.095238
def verify_signature(message, signature, certs): """Verify an RSA cryptographic signature. Checks that the provided ``signature`` was generated from ``bytes`` using the private key associated with the ``cert``. Args: message (Union[str, bytes]): The plaintext message. signature (Union[...
[ "def", "verify_signature", "(", "message", ",", "signature", ",", "certs", ")", ":", "if", "isinstance", "(", "certs", ",", "(", "six", ".", "text_type", ",", "six", ".", "binary_type", ")", ")", ":", "certs", "=", "[", "certs", "]", "for", "cert", "...
34.956522
21.826087
def formula_dual(input_formula: str) -> str: """ Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by switching :math:`∧` and :math:`∨`, and by switching :math:`true` and :ma...
[ "def", "formula_dual", "(", "input_formula", ":", "str", ")", "->", "str", ":", "conversion_dictionary", "=", "{", "'and'", ":", "'or'", ",", "'or'", ":", "'and'", ",", "'True'", ":", "'False'", ",", "'False'", ":", "'True'", "}", "return", "re", ".", ...
33.380952
19.52381
def parse_range_header(value, make_inclusive=True): """Parses a range header into a :class:`~werkzeug.datastructures.Range` object. If the header is missing or malformed `None` is returned. `ranges` is a list of ``(start, stop)`` tuples where the ranges are non-inclusive. .. versionadded:: 0.7 ...
[ "def", "parse_range_header", "(", "value", ",", "make_inclusive", "=", "True", ")", ":", "if", "not", "value", "or", "'='", "not", "in", "value", ":", "return", "None", "ranges", "=", "[", "]", "last_end", "=", "0", "units", ",", "rng", "=", "value", ...
28.487805
15.609756
def deactivate_version(self, service_id, version_number): """Deactivate the current version.""" content = self._fetch("/service/%s/version/%d/deactivate" % (service_id, version_number), method="PUT") return FastlyVersion(self, content)
[ "def", "deactivate_version", "(", "self", ",", "service_id", ",", "version_number", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s/version/%d/deactivate\"", "%", "(", "service_id", ",", "version_number", ")", ",", "method", "=", "\"PUT\"", ...
59.5
21.25
def angular_separation(self, lonp1, latp1, lonp2, latp2): """ Compute the angles between lon / lat points p1 and p2 given in radians. On the unit sphere, this also corresponds to the great circle distance. p1 and p2 can be numpy arrays of the same length. This method simply call...
[ "def", "angular_separation", "(", "self", ",", "lonp1", ",", "latp1", ",", "lonp2", ",", "latp2", ")", ":", "# Call the module-level function", "return", "angular_separation", "(", "lonp1", ",", "latp1", ",", "lonp2", ",", "latp2", ")" ]
51.769231
22.384615
def _process_query_results(self, response_pb): """Process the response from a datastore query. :type response_pb: :class:`.datastore_pb2.RunQueryResponse` :param response_pb: The protobuf response from a ``runQuery`` request. :rtype: iterable :returns: The next page of entity r...
[ "def", "_process_query_results", "(", "self", ",", "response_pb", ")", ":", "self", ".", "_skipped_results", "=", "response_pb", ".", "batch", ".", "skipped_results", "if", "response_pb", ".", "batch", ".", "more_results", "==", "_NO_MORE_RESULTS", ":", "self", ...
38.821429
21.607143
def export(request, count, name='', content_type=None): """ Export banners. :Parameters: - `count`: number of objects to pass into the template - `name`: name of the template ( page/export/banner.html is default ) - `models`: list of Model classes to include """ t_list = [] ...
[ "def", "export", "(", "request", ",", "count", ",", "name", "=", "''", ",", "content_type", "=", "None", ")", ":", "t_list", "=", "[", "]", "if", "name", ":", "t_list", ".", "append", "(", "'page/export/%s.html'", "%", "name", ")", "t_list", ".", "ap...
30.28
19.4
def split_identifiers(identifiers=[], proportions={}): """ Split the given identifiers by the given proportions. Args: identifiers (list): List of identifiers (str). proportions (dict): A dictionary containing the proportions with the identifier from the input as key. Returns: ...
[ "def", "split_identifiers", "(", "identifiers", "=", "[", "]", ",", "proportions", "=", "{", "}", ")", ":", "abs_proportions", "=", "absolute_proportions", "(", "proportions", ",", "len", "(", "identifiers", ")", ")", "parts", "=", "{", "}", "start_index", ...
28.9375
25.6875
def sample_statements(stmts, seed=None): """Return statements sampled according to belief. Statements are sampled independently according to their belief scores. For instance, a Staement with a belief score of 0.7 will end up in the returned Statement list with probability 0.7. Parameters ...
[ "def", "sample_statements", "(", "stmts", ",", "seed", "=", "None", ")", ":", "if", "seed", ":", "numpy", ".", "random", ".", "seed", "(", "seed", ")", "new_stmts", "=", "[", "]", "r", "=", "numpy", ".", "random", ".", "rand", "(", "len", "(", "s...
31.586207
17.310345
def assemble_one(asmcode, pc=0, fork=DEFAULT_FORK): """ Assemble one EVM instruction from its textual representation. :param asmcode: assembly code for one instruction :type asmcode: str :param pc: program counter of the instruction(optional) :type pc: int :param fork: fork ...
[ "def", "assemble_one", "(", "asmcode", ",", "pc", "=", "0", ",", "fork", "=", "DEFAULT_FORK", ")", ":", "try", ":", "instruction_table", "=", "instruction_tables", "[", "fork", "]", "asmcode", "=", "asmcode", ".", "strip", "(", ")", ".", "split", "(", ...
29.566667
17.433333
def element_contains(self, element_id, value): """ Assert provided content is contained within an element found by ``id``. """ elements = ElementSelector( world.browser, str('id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value)), filter_displayed=T...
[ "def", "element_contains", "(", "self", ",", "element_id", ",", "value", ")", ":", "elements", "=", "ElementSelector", "(", "world", ".", "browser", ",", "str", "(", "'id(\"{id}\")[contains(., \"{value}\")]'", ".", "format", "(", "id", "=", "element_id", ",", ...
30.692308
16.076923
def _configure_manager(self): """ Creates a manager to handle the instances, and another to handle flavors. """ self._manager = CloudDNSManager(self, resource_class=CloudDNSDomain, response_key="domains", plural_response_key="domains", uri_base="do...
[ "def", "_configure_manager", "(", "self", ")", ":", "self", ".", "_manager", "=", "CloudDNSManager", "(", "self", ",", "resource_class", "=", "CloudDNSDomain", ",", "response_key", "=", "\"domains\"", ",", "plural_response_key", "=", "\"domains\"", ",", "uri_base"...
40
14.75
def append(self, page, content, **options): """Appends *content* text to *page*. Valid *options* are: * *sum*: (str) change summary * *minor*: (bool) whether this is a minor change """ return self._dokuwiki.send('dokuwiki.appendPage', page, content, options)
[ "def", "append", "(", "self", ",", "page", ",", "content", ",", "*", "*", "options", ")", ":", "return", "self", ".", "_dokuwiki", ".", "send", "(", "'dokuwiki.appendPage'", ",", "page", ",", "content", ",", "options", ")" ]
34.222222
17.444444
def load_handgeometry(): """Hand Geometry Dataset. The data of this dataset is a 3d numpy array vector with shape (224, 224, 3) containing 112 224x224 RGB photos of hands, and the target is a 1d numpy float array containing the width of the wrist in centimeters. """ dataset_path = _load('handge...
[ "def", "load_handgeometry", "(", ")", ":", "dataset_path", "=", "_load", "(", "'handgeometry'", ")", "df", "=", "_load_csv", "(", "dataset_path", ",", "'data'", ")", "X", "=", "_load_images", "(", "os", ".", "path", ".", "join", "(", "dataset_path", ",", ...
36.714286
21.571429
def update_intent(self, workspace_id, intent, new_intent=None, new_description=None, new_examples=None, **kwargs): """ Update intent. Update an existing intent wit...
[ "def", "update_intent", "(", "self", ",", "workspace_id", ",", "intent", ",", "new_intent", "=", "None", ",", "new_description", "=", "None", ",", "new_examples", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "workspace_id", "is", "None", ":", "r...
38.292308
20.261538
def update_repository_config_acl(namespace, config, snapshot_id, acl_updates): """Set configuration permissions. The configuration should exist in the methods repository. Args: namespace (str): Configuration namespace config (str): Configuration name snapshot_id (int): snapshot_id ...
[ "def", "update_repository_config_acl", "(", "namespace", ",", "config", ",", "snapshot_id", ",", "acl_updates", ")", ":", "uri", "=", "\"configurations/{0}/{1}/{2}/permissions\"", ".", "format", "(", "namespace", ",", "config", ",", "snapshot_id", ")", "return", "__...
36.166667
22.5
def virtualenv_setup( ctx, python, inputs=None, outputs=None, touch=None, check_import=False, pip_setup_file=None, pip_setup_touch=None, cache_key=None, always=False, ): """ Create task that sets up `virtualenv` package. :param ctx: BuildContext object. :param p...
[ "def", "virtualenv_setup", "(", "ctx", ",", "python", ",", "inputs", "=", "None", ",", "outputs", "=", "None", ",", "touch", "=", "None", ",", "check_import", "=", "False", ",", "pip_setup_file", "=", "None", ",", "pip_setup_touch", "=", "None", ",", "ca...
22.344595
22.074324
def do_exit(self, line): """exit Exit from the CLI.""" n_remaining_operations = len(self._command_processor.get_operation_queue()) if n_remaining_operations: d1_cli.impl.util.print_warn( """There are {} unperformed operations in the write operation queue. These will b...
[ "def", "do_exit", "(", "self", ",", "line", ")", ":", "n_remaining_operations", "=", "len", "(", "self", ".", "_command_processor", ".", "get_operation_queue", "(", ")", ")", "if", "n_remaining_operations", ":", "d1_cli", ".", "impl", ".", "util", ".", "prin...
40.307692
14.230769
def get_src_or_dst_prompt(mode): """ String together the proper prompt based on the mode :param str mode: "read" or "write" :return str prompt: The prompt needed """ _words = {"read": "from", "write": "to"} # print(os.getcwd()) prompt = "Where would you like to {} your file(s) {}?\n" \ ...
[ "def", "get_src_or_dst_prompt", "(", "mode", ")", ":", "_words", "=", "{", "\"read\"", ":", "\"from\"", ",", "\"write\"", ":", "\"to\"", "}", "# print(os.getcwd())", "prompt", "=", "\"Where would you like to {} your file(s) {}?\\n\"", "\"1. Desktop ({})\\n\"", "\"2. Downl...
39.176471
10.705882
def register_extensions(self): """ Function registers extensions given extensions list Args ---- extensions (list) : the extensions dict on app.config.<env> Raises ------ Exception: Raises exception when extension can't be loaded properly...
[ "def", "register_extensions", "(", "self", ")", ":", "try", ":", "for", "extension", ",", "config", "in", "self", ".", "config", "[", "'extensions'", "]", ".", "items", "(", ")", ":", "extension_bstr", "=", "''", "# gather package name if exists", "extension_p...
38.208333
26.291667
def assign_templates(host, templates, **kwargs): ''' Ensures that templates are assigned to the host. .. versionadded:: 2017.7.0 :param host: technical name of the host :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connectio...
[ "def", "assign_templates", "(", "host", ",", "templates", ",", "*", "*", "kwargs", ")", ":", "connection_args", "=", "{", "}", "if", "'_connection_user'", "in", "kwargs", ":", "connection_args", "[", "'_connection_user'", "]", "=", "kwargs", "[", "'_connection...
37.747664
24.794393
def create_typed_target (self, type, project, name, sources, requirements, default_build, usage_requirements): """ Creates a TypedTarget with the specified properties. The 'name', 'sources', 'requirements', 'default_build' and 'usage_requirements' are assumed to be in the form specified ...
[ "def", "create_typed_target", "(", "self", ",", "type", ",", "project", ",", "name", ",", "sources", ",", "requirements", ",", "default_build", ",", "usage_requirements", ")", ":", "assert", "isinstance", "(", "type", ",", "basestring", ")", "assert", "isinsta...
62.1875
22.5
def player_stats(game_id): """Return dictionary of individual stats of a game with matching id. The additional pitching/batting is mostly the same stats, except it contains some useful stats such as groundouts/flyouts per pitcher (go/ao). MLB decided to have two box score files, thus we return...
[ "def", "player_stats", "(", "game_id", ")", ":", "# get data from data module", "box_score", "=", "mlbgame", ".", "data", ".", "get_box_score", "(", "game_id", ")", "box_score_tree", "=", "etree", ".", "parse", "(", "box_score", ")", ".", "getroot", "(", ")", ...
42.911111
16.844444
def _organize_tools_on(data, is_cwl): """Ensure tools_on inputs match items specified elsewhere. """ # want tools_on: [gvcf] if joint calling specified in CWL if is_cwl: if tz.get_in(["algorithm", "jointcaller"], data): val = tz.get_in(["algorithm", "tools_on"], data) if ...
[ "def", "_organize_tools_on", "(", "data", ",", "is_cwl", ")", ":", "# want tools_on: [gvcf] if joint calling specified in CWL", "if", "is_cwl", ":", "if", "tz", ".", "get_in", "(", "[", "\"algorithm\"", ",", "\"jointcaller\"", "]", ",", "data", ")", ":", "val", ...
36.733333
12.533333
def snapshots_get(container, name, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Get information about snapshot for a container container : The name of the container to get. name : The name of the snapshot. remote_addr : An URL to a remote...
[ "def", "snapshots_get", "(", "container", ",", "name", ",", "remote_addr", "=", "None", ",", "cert", "=", "None", ",", "key", "=", "None", ",", "verify_cert", "=", "True", ")", ":", "container", "=", "container_get", "(", "container", ",", "remote_addr", ...
22.909091
23.454545
def _set_buttons(self, chat, bot): """ Helper methods to set the buttons given the input sender and chat. """ if isinstance(self.reply_markup, ( types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)): self._buttons = [[ MessageButton(self._client...
[ "def", "_set_buttons", "(", "self", ",", "chat", ",", "bot", ")", ":", "if", "isinstance", "(", "self", ".", "reply_markup", ",", "(", "types", ".", "ReplyInlineMarkup", ",", "types", ".", "ReplyKeyboardMarkup", ")", ")", ":", "self", ".", "_buttons", "=...
45.909091
14.090909
def _dict_to_tuple(d): '''Convert a dictionary to a time tuple. Depends on key values in the regexp pattern! ''' # TODO: Adding a ms field to struct_time tuples is problematic # since they don't have this field. Should use datetime # which has a microseconds field, else no ms.. When mapp...
[ "def", "_dict_to_tuple", "(", "d", ")", ":", "# TODO: Adding a ms field to struct_time tuples is problematic ", "# since they don't have this field. Should use datetime", "# which has a microseconds field, else no ms.. When mapping struct_time ", "# to gDateTime the last 3 fields are irrelevant,...
38.175439
18.526316
def expect_false(condition, msg, extras=None): """Expects an expression evaluates to False. If the expectation is not met, the test is marked as fail after its execution finishes. Args: expr: The expression that is evaluated. msg: A string explaining the details in case of failure. ...
[ "def", "expect_false", "(", "condition", ",", "msg", ",", "extras", "=", "None", ")", ":", "try", ":", "asserts", ".", "assert_false", "(", "condition", ",", "msg", ",", "extras", ")", "except", "signals", ".", "TestSignal", "as", "e", ":", "logging", ...
35.411765
20.058824
def break_array(a, threshold=numpy.pi, other=None): """Create a array which masks jumps >= threshold. Extra points are inserted between two subsequent values whose absolute difference differs by more than threshold (default is pi). Other can be a secondary array which is also masked according to ...
[ "def", "break_array", "(", "a", ",", "threshold", "=", "numpy", ".", "pi", ",", "other", "=", "None", ")", ":", "assert", "len", "(", "a", ".", "shape", ")", "==", "1", ",", "\"Only 1D arrays supported\"", "if", "other", "is", "not", "None", "and", "...
31.102041
20.979592
def list_flags(self, only_name=False): """ Determine the flag files associated with this pipeline. :param bool only_name: Whether to return only flag file name(s) (True), or full flag file paths (False); default False (paths) :return list[str]: flag files associated with thi...
[ "def", "list_flags", "(", "self", ",", "only_name", "=", "False", ")", ":", "paths", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "outfolder", ",", "flag_name", "(", "\"*\"", ")", ")", ")", "if", "only_name", ":"...
40
20.461538
def _plot(self, axes_list): ''' Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are listed. Precondition: must have an existing image in figure_list[0] to plot over Args: figure_list: ''' axes = ...
[ "def", "_plot", "(", "self", ",", "axes_list", ")", ":", "axes", "=", "axes_list", "[", "0", "]", "if", "self", ".", "plot_settings", ":", "axes", ".", "imshow", "(", "self", ".", "data", "[", "'image_data'", "]", ",", "cmap", "=", "self", ".", "pl...
39.333333
31.666667
def _wns_authenticate(scope="notify.windows.com", application_id=None): """ Requests an Access token for WNS communication. :return: dict: {'access_token': <str>, 'expires_in': <int>, 'token_type': 'bearer'} """ client_id = get_manager().get_wns_package_security_id(application_id) client_secret = get_manager().g...
[ "def", "_wns_authenticate", "(", "scope", "=", "\"notify.windows.com\"", ",", "application_id", "=", "None", ")", ":", "client_id", "=", "get_manager", "(", ")", ".", "get_wns_package_security_id", "(", "application_id", ")", "client_secret", "=", "get_manager", "("...
30.673077
24.403846
def _pfp__set_value(self, new_val): """Set the new value if type checking is passes, potentially (TODO? reevaluate this) casting the value to something else :new_val: The new value :returns: TODO """ if self._pfp__frozen: raise errors.UnmodifiableConst() ...
[ "def", "_pfp__set_value", "(", "self", ",", "new_val", ")", ":", "if", "self", ".", "_pfp__frozen", ":", "raise", "errors", ".", "UnmodifiableConst", "(", ")", "self", ".", "_pfp__value", "=", "self", ".", "_pfp__get_root_value", "(", "new_val", ")", "self",...
33.5
15.083333
def mnemonic(self, value): """Set instruction mnemonic. """ if value not in REIL_MNEMONICS: raise Exception("Invalid instruction mnemonic : %s" % str(value)) self._mnemonic = value
[ "def", "mnemonic", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "REIL_MNEMONICS", ":", "raise", "Exception", "(", "\"Invalid instruction mnemonic : %s\"", "%", "str", "(", "value", ")", ")", "self", ".", "_mnemonic", "=", "value" ]
31.285714
14.571429
def gen_colors(img): """Generate a colorscheme using Colorz.""" # pylint: disable=not-callable raw_colors = colorz.colorz(img, n=6, bold_add=0) return [util.rgb_to_hex([*color[0]]) for color in raw_colors]
[ "def", "gen_colors", "(", "img", ")", ":", "# pylint: disable=not-callable", "raw_colors", "=", "colorz", ".", "colorz", "(", "img", ",", "n", "=", "6", ",", "bold_add", "=", "0", ")", "return", "[", "util", ".", "rgb_to_hex", "(", "[", "*", "color", "...
43.4
12.6
def update_fluent_cached_urls(item, dry_run=False): """ Regenerate the cached URLs for an item's translations. This is a fiddly business: we use "hidden" methods instead of the public ones to avoid unnecessary and unwanted slug changes to ensure uniqueness, the logic for which doesn't work with our ...
[ "def", "update_fluent_cached_urls", "(", "item", ",", "dry_run", "=", "False", ")", ":", "change_report", "=", "[", "]", "if", "hasattr", "(", "item", ",", "'translations'", ")", ":", "for", "translation", "in", "item", ".", "translations", ".", "all", "("...
44.258065
17.677419
def _rm_is_alignment_line(parts, s1_name, s2_name): """ return true if the tokenized line is a repeatmasker alignment line. :param parts: the line, already split into tokens around whitespace :param s1_name: the name of the first sequence, as extracted from the header of the element this li...
[ "def", "_rm_is_alignment_line", "(", "parts", ",", "s1_name", ",", "s2_name", ")", ":", "if", "len", "(", "parts", ")", "<", "2", ":", "return", "False", "if", "_rm_name_match", "(", "parts", "[", "0", "]", ",", "s1_name", ")", ":", "return", "True", ...
37.611111
19.388889
def open_instance_resource(self, resource, mode='rb'): """Opens a resource from the application's instance folder (:attr:`instance_path`). Otherwise works like :meth:`open_resource`. Instance resources can also be opened for writing. :param resource: the name of the resource. ...
[ "def", "open_instance_resource", "(", "self", ",", "resource", ",", "mode", "=", "'rb'", ")", ":", "return", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "instance_path", ",", "resource", ")", ",", "mode", ")" ]
50.454545
22.363636
def input_flush(): """Flush the input buffer on posix and windows.""" try: import sys, termios # noqa termios.tcflush(sys.stdin, termios.TCIFLUSH) except ImportError: import msvcrt while msvcrt.kbhit(): msvcrt.getch()
[ "def", "input_flush", "(", ")", ":", "try", ":", "import", "sys", ",", "termios", "# noqa", "termios", ".", "tcflush", "(", "sys", ".", "stdin", ",", "termios", ".", "TCIFLUSH", ")", "except", "ImportError", ":", "import", "msvcrt", "while", "msvcrt", "....
29.555556
14.666667
def get_custom_value(self, field_name): """ Get a value for a specified custom field field_name - Name of the custom field you want. """ custom_field = self.get_custom_field(field_name) return CustomFieldValue.objects.get_or_create( field=custom_field, object_id=self....
[ "def", "get_custom_value", "(", "self", ",", "field_name", ")", ":", "custom_field", "=", "self", ".", "get_custom_field", "(", "field_name", ")", "return", "CustomFieldValue", ".", "objects", ".", "get_or_create", "(", "field", "=", "custom_field", ",", "object...
46.571429
9.285714
def _GetExpandedPaths(args): """Yields all possible expansions from given path patterns.""" opts = globbing.PathOpts( follow_links=args.follow_links, pathtype=args.pathtype) for path in args.paths: for expanded_path in globbing.ExpandPath(str(path), opts): yield expanded_path
[ "def", "_GetExpandedPaths", "(", "args", ")", ":", "opts", "=", "globbing", ".", "PathOpts", "(", "follow_links", "=", "args", ".", "follow_links", ",", "pathtype", "=", "args", ".", "pathtype", ")", "for", "path", "in", "args", ".", "paths", ":", "for",...
36.5
17.25
def find_best_match(path, prefixes): """Find the Ingredient that shares the longest prefix with path.""" path_parts = path.split('.') for p in prefixes: if len(p) <= len(path_parts) and p == path_parts[:len(p)]: return '.'.join(p), '.'.join(path_parts[len(p):]) return '', path
[ "def", "find_best_match", "(", "path", ",", "prefixes", ")", ":", "path_parts", "=", "path", ".", "split", "(", "'.'", ")", "for", "p", "in", "prefixes", ":", "if", "len", "(", "p", ")", "<=", "len", "(", "path_parts", ")", "and", "p", "==", "path_...
43.857143
14
def list(self, **params): """ Retrieve all tags Returns all tags available to the user, according to the parameters provided :calls: ``get /tags`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access, which rep...
[ "def", "list", "(", "self", ",", "*", "*", "params", ")", ":", "_", ",", "_", ",", "tags", "=", "self", ".", "http_client", ".", "get", "(", "\"/tags\"", ",", "params", "=", "params", ")", "return", "tags" ]
32.357143
25.357143
def ainput(prompt='', *, streams=None, use_stderr=False, loop=None): """Asynchronous equivalent to *input*.""" # Get standard streams if streams is None: streams = yield from get_standard_streams( use_stderr=use_stderr, loop=loop) reader, writer = streams # Write prompt write...
[ "def", "ainput", "(", "prompt", "=", "''", ",", "*", ",", "streams", "=", "None", ",", "use_stderr", "=", "False", ",", "loop", "=", "None", ")", ":", "# Get standard streams", "if", "streams", "is", "None", ":", "streams", "=", "yield", "from", "get_s...
31.388889
13.666667
def _create_pane(self, window=None, command=None, start_directory=None): """ Create a new :class:`pymux.arrangement.Pane` instance. (Don't put it in a window yet.) :param window: If a window is given, take the CWD of the current process of that window as the start path for t...
[ "def", "_create_pane", "(", "self", ",", "window", "=", "None", ",", "command", "=", "None", ",", "start_directory", "=", "None", ")", ":", "assert", "window", "is", "None", "or", "isinstance", "(", "window", ",", "Window", ")", "assert", "command", "is"...
35.658228
19.987342
def parse_metric(metric, metric_mapping=METRIC_TREE): """Takes a metric formatted by Envoy and splits it into a unique metric name. Returns the unique metric name, a list of tags, and the name of the submission method. Example: 'listener.0.0.0.0_80.downstream_cx_total' -> ('listener.dow...
[ "def", "parse_metric", "(", "metric", ",", "metric_mapping", "=", "METRIC_TREE", ")", ":", "metric_parts", "=", "[", "]", "tag_names", "=", "[", "]", "tag_values", "=", "[", "]", "tag_builder", "=", "[", "]", "unknown_tags", "=", "[", "]", "num_tags", "=...
32.393939
21.560606
def cluster_sample3(): "Start with wrong number of clusters." start_centers = [[0.2, 0.1], [4.0, 1.0]] template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE3, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION) template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE3, criter...
[ "def", "cluster_sample3", "(", ")", ":", "start_centers", "=", "[", "[", "0.2", ",", "0.1", "]", ",", "[", "4.0", ",", "1.0", "]", "]", "template_clustering", "(", "start_centers", ",", "SIMPLE_SAMPLES", ".", "SAMPLE_SIMPLE3", ",", "criterion", "=", "split...
74.8
41.6
def authenticate(self, request, remote_user=None): #pylint:disable=arguments-differ # Django <=1.8 and >=1.9 have different signatures. """ The ``username`` passed here is considered trusted. This method simply returns the ``User`` object with the given username. In ord...
[ "def", "authenticate", "(", "self", ",", "request", ",", "remote_user", "=", "None", ")", ":", "#pylint:disable=arguments-differ", "# Django <=1.8 and >=1.9 have different signatures.", "if", "not", "remote_user", ":", "remote_user", "=", "request", "if", "not", "remote...
45.238095
16.761905
def _get_passwordkey(self): """This method just hashes self.password.""" sha = SHA256.new() sha.update(self.password.encode('utf-8')) return sha.digest()
[ "def", "_get_passwordkey", "(", "self", ")", ":", "sha", "=", "SHA256", ".", "new", "(", ")", "sha", ".", "update", "(", "self", ".", "password", ".", "encode", "(", "'utf-8'", ")", ")", "return", "sha", ".", "digest", "(", ")" ]
30.166667
14.833333
def sem(inlist): """ Returns the estimated standard error of the mean (sx-bar) of the values in the passed list. sem = stdev / sqrt(n) Usage: lsem(inlist) """ sd = stdev(inlist) n = len(inlist) return sd / math.sqrt(n)
[ "def", "sem", "(", "inlist", ")", ":", "sd", "=", "stdev", "(", "inlist", ")", "n", "=", "len", "(", "inlist", ")", "return", "sd", "/", "math", ".", "sqrt", "(", "n", ")" ]
22.9
16.7
def rename(self, name, wait=True): """ Change the name of this droplet Parameters ---------- name: str New name for the droplet wait: bool, default True Whether to block until the pending action is completed Raises ------ ...
[ "def", "rename", "(", "self", ",", "name", ",", "wait", "=", "True", ")", ":", "return", "self", ".", "_action", "(", "'rename'", ",", "name", "=", "name", ",", "wait", "=", "wait", ")" ]
26.9375
17.8125
def make(self): """ Evaluate the command, and write it to a file. """ eval = self.command.eval() with open(self.filename, 'w') as f: f.write(eval)
[ "def", "make", "(", "self", ")", ":", "eval", "=", "self", ".", "command", ".", "eval", "(", ")", "with", "open", "(", "self", ".", "filename", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "eval", ")" ]
35.6
9.8
def OverwriteAndClose(self, compressed_data, size): """Directly overwrite the current contents. Replaces the data currently in the stream with compressed_data, and closes the object. Makes it possible to avoid recompressing the data. Args: compressed_data: The data to write, must be zlib comp...
[ "def", "OverwriteAndClose", "(", "self", ",", "compressed_data", ",", "size", ")", ":", "self", ".", "Set", "(", "self", ".", "Schema", ".", "CONTENT", "(", "compressed_data", ")", ")", "self", ".", "Set", "(", "self", ".", "Schema", ".", "SIZE", "(", ...
38.769231
16.461538
def request(method, uri, *args, **kwargs): """ Handles all the common functionality required for API calls. Returns the resulting response object. Formats the request into a dict representing the headers and body that will be used to make the API call. """ req_method = req_methods[method.up...
[ "def", "request", "(", "method", ",", "uri", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "req_method", "=", "req_methods", "[", "method", ".", "upper", "(", ")", "]", "raise_exception", "=", "kwargs", ".", "pop", "(", "\"raise_exception\"", ",...
34.837838
14.459459
def main(): """ Main entry point of the app """ ROOT_LOGGER.setLevel(logging.DEBUG) file_handler = logging.StreamHandler(LOG_PATH.open("wt")) formatter = logging.Formatter(LOG_FORMAT) file_handler.setFormatter(formatter) file_handler.setLevel(logging.DEBUG) ROOT_LOGGER.addHandler(file_handl...
[ "def", "main", "(", ")", ":", "ROOT_LOGGER", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "file_handler", "=", "logging", ".", "StreamHandler", "(", "LOG_PATH", ".", "open", "(", "\"wt\"", ")", ")", "formatter", "=", "logging", ".", "Formatter", "...
49.730769
21.5
def _process_data(self, obj): """Processes command results.""" assert len(self._waiters) > 0, (type(obj), obj) waiter, encoding, cb = self._waiters.popleft() if isinstance(obj, RedisError): if isinstance(obj, ReplyError): if obj.args[0].startswith('READONLY'):...
[ "def", "_process_data", "(", "self", ",", "obj", ")", ":", "assert", "len", "(", "self", ".", "_waiters", ")", ">", "0", ",", "(", "type", "(", "obj", ")", ",", "obj", ")", "waiter", ",", "encoding", ",", "cb", "=", "self", ".", "_waiters", ".", ...
39.481481
9.333333
def complete_set_acls(self, cmd_param_text, full_cmd, *rest): """ FIXME: complete inside a quoted param is broken """ possible_acl = [ "digest:", "username_password:", "world:anyone:c", "world:anyone:cd", "world:anyone:cdr", "world:...
[ "def", "complete_set_acls", "(", "self", ",", "cmd_param_text", ",", "full_cmd", ",", "*", "rest", ")", ":", "possible_acl", "=", "[", "\"digest:\"", ",", "\"username_password:\"", ",", "\"world:anyone:c\"", ",", "\"world:anyone:cd\"", ",", "\"world:anyone:cdr\"", "...
42.214286
17.285714
def _setup_genome_annotations(g, args, ann_groups): """Configure genome annotations to install based on datatarget. """ available_anns = g.get("annotations", []) + g.pop("annotations_available", []) anns = [] for orig_target in args.datatarget: if orig_target in ann_groups: targe...
[ "def", "_setup_genome_annotations", "(", "g", ",", "args", ",", "ann_groups", ")", ":", "available_anns", "=", "g", ".", "get", "(", "\"annotations\"", ",", "[", "]", ")", "+", "g", ".", "pop", "(", "\"annotations_available\"", ",", "[", "]", ")", "anns"...
36.705882
12.588235
def plot_gos(fout_png, goids, obo_dag, *args, **kws): """Given GO ids and the obo_dag, create a plot of paths from GO ids.""" engine = kws['engine'] if 'engine' in kws else 'pydot' godagsmall = OboToGoDagSmall(goids=goids, obodag=obo_dag).godag godagplot = GODagSmallPlot(godagsmall, *args, **kws) go...
[ "def", "plot_gos", "(", "fout_png", ",", "goids", ",", "obo_dag", ",", "*", "args", ",", "*", "*", "kws", ")", ":", "engine", "=", "kws", "[", "'engine'", "]", "if", "'engine'", "in", "kws", "else", "'pydot'", "godagsmall", "=", "OboToGoDagSmall", "(",...
57.333333
13.166667
def get_under_bridge(self): """Return element closest to the adsorbate in the subsurface layer""" C0 = self.B[-1:] * (3, 3, 1) ads_pos = C0.positions[4] C = self.get_subsurface_layer() * (3, 3, 1) dis = self.B.cell[0][0] * 2 ret = None for ele in C: ...
[ "def", "get_under_bridge", "(", "self", ")", ":", "C0", "=", "self", ".", "B", "[", "-", "1", ":", "]", "*", "(", "3", ",", "3", ",", "1", ")", "ads_pos", "=", "C0", ".", "positions", "[", "4", "]", "C", "=", "self", ".", "get_subsurface_layer"...
27.411765
18.411765
def remove_dangling_shapes(db_conn): """ Remove dangling entries from the shapes directory. Parameters ---------- db_conn: sqlite3.Connection connection to the GTFS object """ db_conn.execute(DELETE_SHAPES_NOT_REFERENCED_IN_TRIPS_SQL) SELECT_MIN_MAX_SHAPE_BREAKS_BY_TRIP_I_SQL = ...
[ "def", "remove_dangling_shapes", "(", "db_conn", ")", ":", "db_conn", ".", "execute", "(", "DELETE_SHAPES_NOT_REFERENCED_IN_TRIPS_SQL", ")", "SELECT_MIN_MAX_SHAPE_BREAKS_BY_TRIP_I_SQL", "=", "\"SELECT trips.trip_I, shape_id, min(shape_break) as min_shape_break, max(shape_break) as max_sh...
48.375
25.708333
def mean_length(infile, limit=None): '''Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N''' total = 0 count = 0 seq_reader = sequences.file_reader(infile) for seq in seq_reader: total += len(seq) ...
[ "def", "mean_length", "(", "infile", ",", "limit", "=", "None", ")", ":", "total", "=", "0", "count", "=", "0", "seq_reader", "=", "sequences", ".", "file_reader", "(", "infile", ")", "for", "seq", "in", "seq_reader", ":", "total", "+=", "len", "(", ...
33.307692
25.307692
def entity_from_snapshot(snapshot): """ Reconstructs domain entity from given snapshot. """ assert isinstance(snapshot, AbstractSnapshop), type(snapshot) if snapshot.state is not None: entity_class = resolve_topic(snapshot.topic) return reconstruct_object(entity_class, snapshot.state...
[ "def", "entity_from_snapshot", "(", "snapshot", ")", ":", "assert", "isinstance", "(", "snapshot", ",", "AbstractSnapshop", ")", ",", "type", "(", "snapshot", ")", "if", "snapshot", ".", "state", "is", "not", "None", ":", "entity_class", "=", "resolve_topic", ...
39.25
10.25
def _set_nssa_area_no_summary(self, v, load=False): """ Setter method for nssa_area_no_summary, mapped from YANG variable /rbridge_id/ipv6/router/ospf/area/nssa/nssa_area_no_summary (empty) If this variable is read-only (config: false) in the source YANG file, then _set_nssa_area_no_summary is considere...
[ "def", "_set_nssa_area_no_summary", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", "...
78.833333
41.875
def getFeatures(self, referenceName=None, start=None, end=None, startIndex=None, maxResults=None, featureTypes=None, parentId=None, name=None, geneSymbol=None): """ method passed to runSearchRequest to fulfill the request :param str ref...
[ "def", "getFeatures", "(", "self", ",", "referenceName", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "startIndex", "=", "None", ",", "maxResults", "=", "None", ",", "featureTypes", "=", "None", ",", "parentId", "=", "None", ",...
48.518519
12.222222
def get_namespace(fn: Callable, namespace: Optional[str]) -> str: """ Returns a representation of a function's name (perhaps within a namespace), like .. code-block:: none mymodule:MyClass.myclassfunc # with no namespace mymodule:MyClass.myclassfunc|somenamespace # with a namespace ...
[ "def", "get_namespace", "(", "fn", ":", "Callable", ",", "namespace", ":", "Optional", "[", "str", "]", ")", "->", "str", ":", "# noqa", "# See hidden attributes with dir(fn)", "# noinspection PyUnresolvedReferences", "return", "\"{module}:{name}{extra}\"", ".", "format...
40.166667
24.833333
def log(self, metric): """Format and output metric. Args: metric (dict): Complete metric. """ message = self.LOGFMT.format(**metric) if metric['context']: message += ' context: {context}'.format(context=metric['context']) self._logger.log(self.lev...
[ "def", "log", "(", "self", ",", "metric", ")", ":", "message", "=", "self", ".", "LOGFMT", ".", "format", "(", "*", "*", "metric", ")", "if", "metric", "[", "'context'", "]", ":", "message", "+=", "' context: {context}'", ".", "format", "(", "context",...
32.3
14.8
def generate_versionwarning_data_json(app, config=None, **kwargs): """ Generate the ``versionwarning-data.json`` file. This file is included in the output and read by the AJAX request when accessing to the documentation and used to compare the live versions with the curent one. Besides, this f...
[ "def", "generate_versionwarning_data_json", "(", "app", ",", "config", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# In Sphinx >= 1.8 we use ``config-initied`` signal which comes with the", "# ``config`` object and in Sphinx < 1.8 we use ``builder-initied`` signal", "# that does...
35.111111
23.904762
def rtt_write(self, buffer_index, data): """Writes data to the RTT buffer. This method will write at most len(data) bytes to the specified RTT buffer. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to write to da...
[ "def", "rtt_write", "(", "self", ",", "buffer_index", ",", "data", ")", ":", "buf_size", "=", "len", "(", "data", ")", "buf", "=", "(", "ctypes", ".", "c_ubyte", "*", "buf_size", ")", "(", "*", "bytearray", "(", "data", ")", ")", "bytes_written", "="...
33.72
24.92
def BuildTemplate(self, context=None, output=None, fleetspeak_service_config=None): """Find template builder and call it.""" context = context or [] context.append("Arch:%s" % self.GetArch()) # Platform context has common platform settings, Tar...
[ "def", "BuildTemplate", "(", "self", ",", "context", "=", "None", ",", "output", "=", "None", ",", "fleetspeak_service_config", "=", "None", ")", ":", "context", "=", "context", "or", "[", "]", "context", ".", "append", "(", "\"Arch:%s\"", "%", "self", "...
36.958333
16.125
def printcsv(csvdiffs): """print the csv""" for row in csvdiffs: print(','.join([str(cell) for cell in row]))
[ "def", "printcsv", "(", "csvdiffs", ")", ":", "for", "row", "in", "csvdiffs", ":", "print", "(", "','", ".", "join", "(", "[", "str", "(", "cell", ")", "for", "cell", "in", "row", "]", ")", ")" ]
30.5
11.25
def _parse_geo_file(self, file_path, run_input_dir): """Scan SH12A GEO file for references to external files (like voxelised geometry) and return them""" external_files = [] paths_to_replace = [] with open(file_path, 'r') as geo_f: for line in geo_f.readlines(): ...
[ "def", "_parse_geo_file", "(", "self", ",", "file_path", ",", "run_input_dir", ")", ":", "external_files", "=", "[", "]", "paths_to_replace", "=", "[", "]", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "geo_f", ":", "for", "line", "in", "geo_...
60.75
21.833333
def create_key(self, title, key): """Create a deploy key. :param str title: (required), title of key :param str key: (required), key text :returns: :class:`Key <github3.users.Key>` if successful, else None """ json = None if title and key: data = {'ti...
[ "def", "create_key", "(", "self", ",", "title", ",", "key", ")", ":", "json", "=", "None", "if", "title", "and", "key", ":", "data", "=", "{", "'title'", ":", "title", ",", "'key'", ":", "key", "}", "url", "=", "self", ".", "_build_url", "(", "'k...
38.923077
14.615385
def _verify_client_authentication(self, request_body, http_headers=None): # type (str, Optional[Mapping[str, str]] -> Mapping[str, str] """ Verifies the client authentication. :param request_body: urlencoded token request :param http_headers: :return: The parsed request b...
[ "def", "_verify_client_authentication", "(", "self", ",", "request_body", ",", "http_headers", "=", "None", ")", ":", "# type (str, Optional[Mapping[str, str]] -> Mapping[str, str]", "if", "http_headers", "is", "None", ":", "http_headers", "=", "{", "}", "token_request", ...
46.230769
17.307692
def get_mnist_sym(output_op=None, num_hidden=400): """Get symbol of mnist""" net = mx.symbol.Variable('data') net = mx.symbol.FullyConnected(data=net, name='mnist_fc1', num_hidden=num_hidden) net = mx.symbol.Activation(data=net, name='mnist_relu1', act_type="relu") net = mx.symbol.FullyConnected(dat...
[ "def", "get_mnist_sym", "(", "output_op", "=", "None", ",", "num_hidden", "=", "400", ")", ":", "net", "=", "mx", ".", "symbol", ".", "Variable", "(", "'data'", ")", "net", "=", "mx", ".", "symbol", ".", "FullyConnected", "(", "data", "=", "net", ","...
52
24.538462
def plotPointing(self, maptype=None, colour='b', mod3='r', showOuts=True, **kwargs): """Plot the FOV """ if maptype is None: maptype=self.defaultMap radec = self.currentRaDec for ch in radec[:,2][::4]: idx = np.where(radec[:,2].astype(np.int) == ch)[0] ...
[ "def", "plotPointing", "(", "self", ",", "maptype", "=", "None", ",", "colour", "=", "'b'", ",", "mod3", "=", "'r'", ",", "showOuts", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "maptype", "is", "None", ":", "maptype", "=", "self", ".", ...
35.3
21.7
def _check_accept_keywords(approved, flag): '''check compatibility of accept_keywords''' if flag in approved: return False elif (flag.startswith('~') and flag[1:] in approved) \ or ('~'+flag in approved): return False else: return True
[ "def", "_check_accept_keywords", "(", "approved", ",", "flag", ")", ":", "if", "flag", "in", "approved", ":", "return", "False", "elif", "(", "flag", ".", "startswith", "(", "'~'", ")", "and", "flag", "[", "1", ":", "]", "in", "approved", ")", "or", ...
31
15.444444
def lit_count(self): """ The number of LEDs on the bar graph actually lit up. Note that just like :attr:`value`, this can be negative if the LEDs are lit from last to first. """ lit_value = self.value * len(self) if not isinstance(self[0], PWMLED): lit...
[ "def", "lit_count", "(", "self", ")", ":", "lit_value", "=", "self", ".", "value", "*", "len", "(", "self", ")", "if", "not", "isinstance", "(", "self", "[", "0", "]", ",", "PWMLED", ")", ":", "lit_value", "=", "int", "(", "lit_value", ")", "return...
35.9
13.9
def bounding_box(alpha, threshold=0.1): """ Returns a bounding box of the support. Parameters ---------- alpha : ndarray, ndim=2 Any one-channel image where the background has zero or low intensity. threshold : float The threshold that divides background from foreground. Re...
[ "def", "bounding_box", "(", "alpha", ",", "threshold", "=", "0.1", ")", ":", "assert", "alpha", ".", "ndim", "==", "2", "# Take the bounding box of the support, with a certain threshold.", "supp_axs", "=", "[", "alpha", ".", "max", "(", "axis", "=", "1", "-", ...
31.884615
21.884615
def nodes_map(self): """ Build a mapping from node type to a list of nodes. A typed mapping helps avoid polymorphism at non-persistent layers. """ dct = dict() for node in self.nodes.values(): cls = next(base for base in getmro(node.__class__) if "__tablenam...
[ "def", "nodes_map", "(", "self", ")", ":", "dct", "=", "dict", "(", ")", "for", "node", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "cls", "=", "next", "(", "base", "for", "base", "in", "getmro", "(", "node", ".", "__class__", ")", ...
36
22.307692
def setup_variables(self): """ Set up variables. """ if self.input_tensor: if type(self.input_tensor) == int: x = dim_to_var(self.input_tensor, name="x") else: x = self.input_tensor else: x = T.matrix('x') ...
[ "def", "setup_variables", "(", "self", ")", ":", "if", "self", ".", "input_tensor", ":", "if", "type", "(", "self", ".", "input_tensor", ")", "==", "int", ":", "x", "=", "dim_to_var", "(", "self", ".", "input_tensor", ",", "name", "=", "\"x\"", ")", ...
28.142857
11.285714
def supplementary_files(self): """The supplementary files of this notebook""" if self._supplementary_files is not None: return self._supplementary_files return getattr(self.nb.metadata, 'supplementary_files', None)
[ "def", "supplementary_files", "(", "self", ")", ":", "if", "self", ".", "_supplementary_files", "is", "not", "None", ":", "return", "self", ".", "_supplementary_files", "return", "getattr", "(", "self", ".", "nb", ".", "metadata", ",", "'supplementary_files'", ...
49.2
10.4
def process_job(self, job_request): """ Validate, execute, and run the job request, wrapping it with any applicable job middleware. :param job_request: The job request :type job_request: dict :return: A `JobResponse` object :rtype: JobResponse :raise: JobError ...
[ "def", "process_job", "(", "self", ",", "job_request", ")", ":", "try", ":", "# Validate JobRequest message", "validation_errors", "=", "[", "Error", "(", "code", "=", "error", ".", "code", ",", "message", "=", "error", ".", "message", ",", "field", "=", "...
38.589286
21.232143
def authors(self, *usernames): """ Return the entries written by the given usernames When multiple tags are provided, they operate as "OR" query. """ if len(usernames) == 1: return self.filter(**{"author__{}".format(User.USERNAME_FIELD): usernames[0]}) else: ...
[ "def", "authors", "(", "self", ",", "*", "usernames", ")", ":", "if", "len", "(", "usernames", ")", "==", "1", ":", "return", "self", ".", "filter", "(", "*", "*", "{", "\"author__{}\"", ".", "format", "(", "User", ".", "USERNAME_FIELD", ")", ":", ...
44.666667
21.333333