text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _add_sort(self, field, ascending=True): """Sort the search results by a certain field. If this method is called multiple times, the later sort fields are given lower priority, and will only be considered when the eariler fields have the same value. Arguments: field (str...
[ "def", "_add_sort", "(", "self", ",", "field", ",", "ascending", "=", "True", ")", ":", "# Fields must be strings for Elasticsearch", "field", "=", "str", "(", "field", ")", "# No-op on blank sort field", "if", "field", ":", "self", ".", "__query", "[", "\"sort\...
36.045455
21.181818
def validate_obj(keys, obj): """Super simple "object" validation.""" msg = '' for k in keys: if isinstance(k, str): if k not in obj or (not isinstance(obj[k], list) and not obj[k]): if msg: msg = "%s," % msg msg = "%s%s" % (msg, k) ...
[ "def", "validate_obj", "(", "keys", ",", "obj", ")", ":", "msg", "=", "''", "for", "k", "in", "keys", ":", "if", "isinstance", "(", "k", ",", "str", ")", ":", "if", "k", "not", "in", "obj", "or", "(", "not", "isinstance", "(", "obj", "[", "k", ...
24.769231
18.961538
def stacked_graph(labels, data, normal_data, len_categories, args, colors): """Prepare the horizontal stacked graph. Each row is printed through the print_row function.""" val_min = find_min(data) for i in range(len(labels)): if args['no_labels']: # Hide the labels. l...
[ "def", "stacked_graph", "(", "labels", ",", "data", ",", "normal_data", ",", "len_categories", ",", "args", ",", "colors", ")", ":", "val_min", "=", "find_min", "(", "data", ")", "for", "i", "in", "range", "(", "len", "(", "labels", ")", ")", ":", "i...
33.826087
19.173913
def reboot(*args): """Reboot python in the Lore virtualenv """ args = list(sys.argv) + list(args) if args[0] == 'python' or not args[0]: args[0] = BIN_PYTHON elif os.path.basename(sys.argv[0]) in ['lore', 'lore.exe']: args[0] = BIN_LORE try: os.execv(args[0], args) ex...
[ "def", "reboot", "(", "*", "args", ")", ":", "args", "=", "list", "(", "sys", ".", "argv", ")", "+", "list", "(", "args", ")", "if", "args", "[", "0", "]", "==", "'python'", "or", "not", "args", "[", "0", "]", ":", "args", "[", "0", "]", "=...
40.5
21.214286
def rename(src, dst): ''' Rename a file or directory CLI Example: .. code-block:: bash salt '*' file.rename /path/to/src /path/to/dst ''' src = os.path.expanduser(src) dst = os.path.expanduser(dst) if not os.path.isabs(src): raise SaltInvocationError('File path must b...
[ "def", "rename", "(", "src", ",", "dst", ")", ":", "src", "=", "os", ".", "path", ".", "expanduser", "(", "src", ")", "dst", "=", "os", ".", "path", ".", "expanduser", "(", "dst", ")", "if", "not", "os", ".", "path", ".", "isabs", "(", "src", ...
21.625
23.708333
def debugfile(filename, args=None, wdir=None, post_mortem=False): """ Debug filename args: command line arguments (string) wdir: working directory post_mortem: boolean, included for compatiblity with runfile """ debugger = pdb.Pdb() filename = debugger.canonic(filename) debugger._wai...
[ "def", "debugfile", "(", "filename", ",", "args", "=", "None", ",", "wdir", "=", "None", ",", "post_mortem", "=", "False", ")", ":", "debugger", "=", "pdb", ".", "Pdb", "(", ")", "filename", "=", "debugger", ".", "canonic", "(", "filename", ")", "deb...
36.333333
11.4
def check_length_of_shape_or_intercept_names(name_list, num_alts, constrained_param, list_title): """ Ensures that the length of the parameter names matches the number of pa...
[ "def", "check_length_of_shape_or_intercept_names", "(", "name_list", ",", "num_alts", ",", "constrained_param", ",", "list_title", ")", ":", "if", "len", "(", "name_list", ")", "!=", "(", "num_alts", "-", "constrained_param", ")", ":", "msg_1", "=", "\"{} is of th...
41.027778
22.527778
def get(self): """ Constructs a TaskActionsContext :returns: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext :rtype: twilio.rest.autopilot.v1.assistant.task.task_actions.TaskActionsContext """ return TaskActionsContext( self._version, ...
[ "def", "get", "(", "self", ")", ":", "return", "TaskActionsContext", "(", "self", ".", "_version", ",", "assistant_sid", "=", "self", ".", "_solution", "[", "'assistant_sid'", "]", ",", "task_sid", "=", "self", ".", "_solution", "[", "'task_sid'", "]", ","...
35.5
20
def post(self): """Start a new profiler.""" if is_profiler_running(): self.set_status(201) self.finish() return start_profiling() self.set_status(201) self.finish()
[ "def", "post", "(", "self", ")", ":", "if", "is_profiler_running", "(", ")", ":", "self", ".", "set_status", "(", "201", ")", "self", ".", "finish", "(", ")", "return", "start_profiling", "(", ")", "self", ".", "set_status", "(", "201", ")", "self", ...
23.2
16.3
def xhtml_escape(value: Union[str, bytes]) -> str: """Escapes a string so it is valid within HTML or XML. Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``. When used in attribute values the escaped strings must be enclosed in quotes. .. versionchanged:: 3.2 Added the single quo...
[ "def", "xhtml_escape", "(", "value", ":", "Union", "[", "str", ",", "bytes", "]", ")", "->", "str", ":", "return", "_XHTML_ESCAPE_RE", ".", "sub", "(", "lambda", "match", ":", "_XHTML_ESCAPE_DICT", "[", "match", ".", "group", "(", "0", ")", "]", ",", ...
33.571429
23.5
def get_password_hash(username): """ Fetch a user's password hash. """ try: h = spwd.getspnam(username) except KeyError: return None # mitogen.core.Secret() is a Unicode subclass with a repr() that hides the # secret data. This keeps secret stuff out of logs. Like blobs, sec...
[ "def", "get_password_hash", "(", "username", ")", ":", "try", ":", "h", "=", "spwd", ".", "getspnam", "(", "username", ")", "except", "KeyError", ":", "return", "None", "# mitogen.core.Secret() is a Unicode subclass with a repr() that hides the", "# secret data. This keep...
28.923077
17.846154
async def add_listener(self, channel, callback): """Add a listener for Postgres notifications. :param str channel: Channel to listen on. :param callable callback: A callable receiving the following arguments: **connection**: a Connection the callback is registered with;...
[ "async", "def", "add_listener", "(", "self", ",", "channel", ",", "callback", ")", ":", "self", ".", "_check_open", "(", ")", "if", "channel", "not", "in", "self", ".", "_listeners", ":", "await", "self", ".", "fetch", "(", "'LISTEN {}'", ".", "format", ...
43.823529
17
def check(self, state, *args, **kwargs): """ Check if this engine can be used for execution on the current state. A callback `check_failure` is called upon failed checks. Note that the execution can still fail even if check() returns True. You should only override this method in a subcl...
[ "def", "check", "(", "self", ",", "state", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_check", "(", "state", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
58.533333
38.4
def set_pixel(self, x, y, *args): """ Updates the single [R,G,B] pixel specified by x and y on the LED matrix Top left = 0,0 Bottom right = 7,7 e.g. ap.set_pixel(x, y, r, g, b) or pixel = (r, g, b) ap.set_pixel(x, y, pixel) """ pixel_error = 'Pix...
[ "def", "set_pixel", "(", "self", ",", "x", ",", "y", ",", "*", "args", ")", ":", "pixel_error", "=", "'Pixel arguments must be given as (r, g, b) or r, g, b'", "if", "len", "(", "args", ")", "==", "1", ":", "pixel", "=", "args", "[", "0", "]", "if", "len...
31.675676
18.594595
def run(self): """开始线程.""" while not self.stop_flag: timestamp = time.time() cpu_percent = self.process.cpu_percent() / self.cpu_num # mem_percent = mem = self.process.memory_percent() mem_info = dict(self.process.memory_info()._asdict()) mem_g...
[ "def", "run", "(", "self", ")", ":", "while", "not", "self", ".", "stop_flag", ":", "timestamp", "=", "time", ".", "time", "(", ")", "cpu_percent", "=", "self", ".", "process", ".", "cpu_percent", "(", ")", "/", "self", ".", "cpu_num", "# mem_percent =...
46.583333
20.333333
def edit_project_preferences(self): """Edit Spyder active project preferences""" from spyder.plugins.projects.confpage import ProjectPreferences if self.project_active: active_project = self.project_list[0] dlg = ProjectPreferences(self, active_project) # ...
[ "def", "edit_project_preferences", "(", "self", ")", ":", "from", "spyder", ".", "plugins", ".", "projects", ".", "confpage", "import", "ProjectPreferences", "if", "self", ".", "project_active", ":", "active_project", "=", "self", ".", "project_list", "[", "0", ...
50.076923
17.076923
def set_sensitivity(self, sensitivity=DEFAULT_SENSITIVITY): """Set the sensitivity value. Valid values are 31 (lowest) to 254 (highest), default is 69. """ if sensitivity < 31: self._mtreg = 31 elif sensitivity > 254: self._mtreg = 254 else: ...
[ "def", "set_sensitivity", "(", "self", ",", "sensitivity", "=", "DEFAULT_SENSITIVITY", ")", ":", "if", "sensitivity", "<", "31", ":", "self", ".", "_mtreg", "=", "31", "elif", "sensitivity", ">", "254", ":", "self", ".", "_mtreg", "=", "254", "else", ":"...
32.8
14.133333
def add_property(self, pred, obj): """ adds a property and its value to the class instance args: pred: the predicate/property to add obj: the value/object to add obj_method: *** No longer used. """ pred = Uri(pred) try: self[pred]....
[ "def", "add_property", "(", "self", ",", "pred", ",", "obj", ")", ":", "pred", "=", "Uri", "(", "pred", ")", "try", ":", "self", "[", "pred", "]", ".", "append", "(", "obj", ")", "# except AttributeError:", "# new_list = [self[pred]]", "# new_list.ap...
35.575
12.875
def get_next_file_path(self, service, operation): """ Returns a tuple with the next file to read and the serializer format used """ base_name = '{0}.{1}'.format(service, operation) if self.prefix: base_name = '{0}.{1}'.format(self.prefix, base_name) LO...
[ "def", "get_next_file_path", "(", "self", ",", "service", ",", "operation", ")", ":", "base_name", "=", "'{0}.{1}'", ".", "format", "(", "service", ",", "operation", ")", "if", "self", ".", "prefix", ":", "base_name", "=", "'{0}.{1}'", ".", "format", "(", ...
37.962963
16.555556
def register_bec_task(self, *args, **kwargs): """Register a BEC task.""" kwargs["task_class"] = BecTask return self.register_task(*args, **kwargs)
[ "def", "register_bec_task", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"task_class\"", "]", "=", "BecTask", "return", "self", ".", "register_task", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
41.75
4.25
def GetByteSize(self): """Retrieves the byte size of the data type definition. Returns: int: data type size in bytes or None if size cannot be determined. """ if not self.element_data_type_definition: return None if self.elements_data_size: return self.elements_data_size if ...
[ "def", "GetByteSize", "(", "self", ")", ":", "if", "not", "self", ".", "element_data_type_definition", ":", "return", "None", "if", "self", ".", "elements_data_size", ":", "return", "self", ".", "elements_data_size", "if", "not", "self", ".", "number_of_elements...
26.2
21.3
def get_send_request_correct_body(self, path, action): """Get an example body which is correct to send to the given path with the given action. Args: path: path of the request action: action of the request (get, post, put, delete) Returns: A dict representin...
[ "def", "get_send_request_correct_body", "(", "self", ",", "path", ",", "action", ")", ":", "path_name", ",", "path_spec", "=", "self", ".", "get_path_spec", "(", "path", ")", "if", "path_spec", "is", "not", "None", "and", "action", "in", "path_spec", ".", ...
58.894737
28.447368
def read(*paths, **validators): """ Load the configuration, make each section available in a separate dict. The configuration location can specified via an environment variable: - OQ_CONFIG_FILE In the absence of this environment variable the following paths will be used: - sys.prefi...
[ "def", "read", "(", "*", "paths", ",", "*", "*", "validators", ")", ":", "paths", "=", "config", ".", "paths", "+", "list", "(", "paths", ")", "parser", "=", "configparser", ".", "ConfigParser", "(", ")", "found", "=", "parser", ".", "read", "(", "...
39.310345
21.724138
def pixel_to_utm(row, column, transform): """ Convert pixel coordinate to UTM coordinate given a transform :param row: row pixel coordinate :type row: int or float :param column: column pixel coordinate :type column: int or float :param transform: georeferencing transform of the image, e.g. `(x...
[ "def", "pixel_to_utm", "(", "row", ",", "column", ",", "transform", ")", ":", "east", "=", "transform", "[", "0", "]", "+", "column", "*", "transform", "[", "1", "]", "north", "=", "transform", "[", "3", "]", "+", "row", "*", "transform", "[", "5",...
38.666667
13.266667
def sendSync(self, query, *parameters, **options): '''Performs a synchronous query against a q service and returns parsed data. In typical use case, `query` is the name of the function to call and `parameters` are its parameters. When `parameters` list is empty, the q...
[ "def", "sendSync", "(", "self", ",", "query", ",", "*", "parameters", ",", "*", "*", "options", ")", ":", "self", ".", "query", "(", "MessageType", ".", "SYNC", ",", "query", ",", "*", "parameters", ",", "*", "*", "options", ")", "response", "=", "...
43.532258
25.403226
def key(self, *path_args, **kwargs): """Proxy to :class:`google.cloud.datastore.key.Key`. Passes our ``project``. """ if "project" in kwargs: raise TypeError("Cannot pass project") kwargs["project"] = self.project if "namespace" not in kwargs: kwa...
[ "def", "key", "(", "self", ",", "*", "path_args", ",", "*", "*", "kwargs", ")", ":", "if", "\"project\"", "in", "kwargs", ":", "raise", "TypeError", "(", "\"Cannot pass project\"", ")", "kwargs", "[", "\"project\"", "]", "=", "self", ".", "project", "if"...
34.909091
7.545455
def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ if vars is None: vars = {} define_rx = re.compile("#de...
[ "def", "parse_config_h", "(", "fp", ",", "vars", "=", "None", ")", ":", "if", "vars", "is", "None", ":", "vars", "=", "{", "}", "define_rx", "=", "re", ".", "compile", "(", "\"#define ([A-Z][A-Za-z0-9_]+) (.*)\\n\"", ")", "undef_rx", "=", "re", ".", "com...
27.689655
18.103448
def backends_to_mutate(self, namespace, stream): """ Return all the backends enabled for writing for `stream`. """ if namespace not in self.namespaces: raise NamespaceMissing('`{}` namespace is not configured' .format(namespace)) return self.prefix_confs[namespace]...
[ "def", "backends_to_mutate", "(", "self", ",", "namespace", ",", "stream", ")", ":", "if", "namespace", "not", "in", "self", ".", "namespaces", ":", "raise", "NamespaceMissing", "(", "'`{}` namespace is not configured'", ".", "format", "(", "namespace", ")", ")"...
46.888889
14.222222
def get_lat_lon_time_from_gpx(gpx_file, local_time=True): ''' Read location and time stamps from a track in a GPX file. Returns a list of tuples (time, lat, lon). GPX stores time in UTC, by default we assume your camera used the local time and convert accordingly. ''' with open(gpx_file, '...
[ "def", "get_lat_lon_time_from_gpx", "(", "gpx_file", ",", "local_time", "=", "True", ")", ":", "with", "open", "(", "gpx_file", ",", "'r'", ")", "as", "f", ":", "gpx", "=", "gpxpy", ".", "parse", "(", "f", ")", "points", "=", "[", "]", "if", "len", ...
34.357143
23.785714
def get_process_path(tshark_path=None, process_name="tshark"): """ Finds the path of the tshark executable. If the user has provided a path or specified a location in config.ini it will be used. Otherwise default locations will be searched. :param tshark_path: Path of the tshark binary :raises ...
[ "def", "get_process_path", "(", "tshark_path", "=", "None", ",", "process_name", "=", "\"tshark\"", ")", ":", "config", "=", "get_config", "(", ")", "possible_paths", "=", "[", "config", ".", "get", "(", "process_name", ",", "\"%s_path\"", "%", "process_name",...
39.571429
19.761905
def drop(self, table): """ Drop a table from a database. Accepts either a string representing a table name or a list of strings representing a table names. """ existing_tables = self.tables if isinstance(table, (list, set, tuple)): for t in table: ...
[ "def", "drop", "(", "self", ",", "table", ")", ":", "existing_tables", "=", "self", ".", "tables", "if", "isinstance", "(", "table", ",", "(", "list", ",", "set", ",", "tuple", ")", ")", ":", "for", "t", "in", "table", ":", "self", ".", "_drop", ...
30.857143
13.428571
def _member_defs(self): """ A single string containing the aggregated member definitions section of the documentation page """ members = self._clsdict['__members__'] member_defs = [ self._member_def(member) for member in members if member.name is n...
[ "def", "_member_defs", "(", "self", ")", ":", "members", "=", "self", ".", "_clsdict", "[", "'__members__'", "]", "member_defs", "=", "[", "self", ".", "_member_def", "(", "member", ")", "for", "member", "in", "members", "if", "member", ".", "name", "is"...
33.181818
12.454545
def approximation(self, latitude, longitude): """ Dummy approximation with nearest points. The nearest the neighbour the more important will be its elevation. """ d = 1. / self.square_side d_meters = d * mod_utils.ONE_DEGREE # Since the less the distance => the m...
[ "def", "approximation", "(", "self", ",", "latitude", ",", "longitude", ")", ":", "d", "=", "1.", "/", "self", ".", "square_side", "d_meters", "=", "d", "*", "mod_utils", ".", "ONE_DEGREE", "# Since the less the distance => the more important should be the", "# dist...
50.734694
30.44898
def fling_forward_horizontally(self, *args, **selectors): """ Perform fling forward (horizontally)action on the object which has *selectors* attributes. Return whether the object can be fling or not. """ return self.device(**selectors).fling.horiz.forward()
[ "def", "fling_forward_horizontally", "(", "self", ",", "*", "args", ",", "*", "*", "selectors", ")", ":", "return", "self", ".", "device", "(", "*", "*", "selectors", ")", ".", "fling", ".", "horiz", ".", "forward", "(", ")" ]
41.714286
21.428571
def get_t_conjunction(self, params): """ Return the time of primary transit center (calculated using `params.t_secondary`). """ phase = self._get_phase(params, "primary") phase2 = self._get_phase(params, "secondary") return params.t_secondary + params.per*(phase-phase2)
[ "def", "get_t_conjunction", "(", "self", ",", "params", ")", ":", "phase", "=", "self", ".", "_get_phase", "(", "params", ",", "\"primary\"", ")", "phase2", "=", "self", ".", "_get_phase", "(", "params", ",", "\"secondary\"", ")", "return", "params", ".", ...
39.428571
10.571429
def _crawl_container_pids(self, container_dict, custom_cgroups=False): """Crawl `/proc` to find container PIDs and add them to `containers_by_id`.""" proc_path = os.path.join(self.docker_util._docker_root, 'proc') pid_dirs = [_dir for _dir in os.listdir(proc_path) if _dir.isdigit()] if ...
[ "def", "_crawl_container_pids", "(", "self", ",", "container_dict", ",", "custom_cgroups", "=", "False", ")", ":", "proc_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "docker_util", ".", "_docker_root", ",", "'proc'", ")", "pid_dirs", "=", ...
47.419355
23.645161
def get_tu(source, lang='c', all_warnings=False, flags=None): """Obtain a translation unit from source and language. By default, the translation unit is created from source file "t.<ext>" where <ext> is the default file extension for the specified language. By default it is C, so "t.c" is the default f...
[ "def", "get_tu", "(", "source", ",", "lang", "=", "'c'", ",", "all_warnings", "=", "False", ",", "flags", "=", "None", ")", ":", "args", "=", "list", "(", "flags", "or", "[", "]", ")", "name", "=", "'t.c'", "if", "lang", "==", "'cpp'", ":", "name...
34.307692
22.5
def schedule_downtime(scope, api_key=None, app_key=None, monitor_id=None, start=None, end=None, message=None, recurrence=None, timezone=None, ...
[ "def", "schedule_downtime", "(", "scope", ",", "api_key", "=", "None", ",", "app_key", "=", "None", ",", "monitor_id", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "message", "=", "None", ",", "recurrence", "=", "None", ",", ...
36.507692
20.476923
def patch_mutating_webhook_configuration(self, name, body, **kwargs): """ partially update the specified MutatingWebhookConfiguration This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_m...
[ "def", "patch_mutating_webhook_configuration", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ...
79.64
50.68
def diff_files(from_file, to_file, index_columns, sep=',', ignored_columns=None): """ Diff two CSV files, returning the patch which transforms one into the other. """ with open(from_file) as from_stream: with open(to_file) as to_stream: from_records = records.load(from_stream, se...
[ "def", "diff_files", "(", "from_file", ",", "to_file", ",", "index_columns", ",", "sep", "=", "','", ",", "ignored_columns", "=", "None", ")", ":", "with", "open", "(", "from_file", ")", "as", "from_stream", ":", "with", "open", "(", "to_file", ")", "as"...
46.454545
17.909091
def set_homepage(self, shop_id, template_id, url=None): """ 设置商家主页 详情请参考 http://mp.weixin.qq.com/wiki/6/2732f3cf83947e0e4971aa8797ee9d6a.html :param shop_id: 门店 ID :param template_id: 模板ID,0-默认模板,1-自定义url :param url: 自定义链接,当template_id为1时必填 :return: 返回的 ...
[ "def", "set_homepage", "(", "self", ",", "shop_id", ",", "template_id", ",", "url", "=", "None", ")", ":", "data", "=", "{", "'shop_id'", ":", "shop_id", ",", "'template_id'", ":", "template_id", ",", "}", "if", "url", ":", "data", "[", "'struct'", "]"...
28
16.842105
def contribute_to_class(self, cls, name): """ Because django doesn't give us a nice way to provide a through table without losing functionality. We have to provide our own through table creation that uses the FKToVersion field to be used for the from field. """ s...
[ "def", "contribute_to_class", "(", "self", ",", "cls", ",", "name", ")", ":", "self", ".", "update_rel_to", "(", "cls", ")", "# Called to get a name", "self", ".", "set_attributes_from_name", "(", "name", ")", "self", ".", "model", "=", "cls", "# Set the throu...
34.380952
19.714286
def mp_a_trous_kernel(C0, wavelet_filter, scale, slice_ind, slice_width, r_or_c="row"): """ This is the convolution step of the a trous algorithm. INPUTS: C0 (no default): The current array which is to be decomposed. wavelet_filter (no default): The filter-bank which is ap...
[ "def", "mp_a_trous_kernel", "(", "C0", ",", "wavelet_filter", ",", "scale", ",", "slice_ind", ",", "slice_width", ",", "r_or_c", "=", "\"row\"", ")", ":", "lower_bound", "=", "slice_ind", "*", "slice_width", "upper_bound", "=", "(", "slice_ind", "+", "1", ")...
53.245283
42.037736
def parseSdr(s): """ Parses a string containing only 0's and 1's and return a Python list object. :param s: (string) string to parse :returns: (list) SDR out """ assert isinstance(s, basestring) sdr = [int(c) for c in s if c in ("0", "1")] if len(sdr) != len(s): raise ValueError("The provided strin...
[ "def", "parseSdr", "(", "s", ")", ":", "assert", "isinstance", "(", "s", ",", "basestring", ")", "sdr", "=", "[", "int", "(", "c", ")", "for", "c", "in", "s", "if", "c", "in", "(", "\"0\"", ",", "\"1\"", ")", "]", "if", "len", "(", "sdr", ")"...
29
18.571429
def find_similar(self, doc, min_score=0.0, max_results=100): """ Find `max_results` most similar articles in the index, each having similarity score of at least `min_score`. The resulting list may be shorter than `max_results`, in case there are not enough matching documents. `d...
[ "def", "find_similar", "(", "self", ",", "doc", ",", "min_score", "=", "0.0", ",", "max_results", "=", "100", ")", ":", "logger", ".", "debug", "(", "\"received query call with %r\"", "%", "doc", ")", "if", "self", ".", "is_locked", "(", ")", ":", "msg",...
49.2
22.133333
def login(self, email=None, password=None): """Login to establish a valid session.""" auth_url = self.url('auth') email = email or self._config.get('email') password = password or self._config.get('password') if password and not email: raise Exception('Email must be p...
[ "def", "login", "(", "self", ",", "email", "=", "None", ",", "password", "=", "None", ")", ":", "auth_url", "=", "self", ".", "url", "(", "'auth'", ")", "email", "=", "email", "or", "self", ".", "_config", ".", "get", "(", "'email'", ")", "password...
42.37037
12.185185
def cmd(send, *_): """Enumerate threads. Syntax: {command} """ thread_names = [] for x in sorted(threading.enumerate(), key=lambda k: k.name): res = re.match(r'Thread-(\d+$)', x.name) if res: tid = int(res.group(1)) # Handle the main server thread (permanent...
[ "def", "cmd", "(", "send", ",", "*", "_", ")", ":", "thread_names", "=", "[", "]", "for", "x", "in", "sorted", "(", "threading", ".", "enumerate", "(", ")", ",", "key", "=", "lambda", "k", ":", "k", ".", "name", ")", ":", "res", "=", "re", "....
40.5
22.5
def from_times(cls, times, delta_t=DEFAULT_OBSERVATION_TIME): """ Create a TimeMOC from a `astropy.time.Time` Parameters ---------- times : `astropy.time.Time` astropy observation times delta_t : `astropy.time.TimeDelta`, optional the duration of ...
[ "def", "from_times", "(", "cls", ",", "times", ",", "delta_t", "=", "DEFAULT_OBSERVATION_TIME", ")", ":", "times_arr", "=", "np", ".", "asarray", "(", "times", ".", "jd", "*", "TimeMOC", ".", "DAY_MICRO_SEC", ",", "dtype", "=", "int", ")", "intervals_arr",...
43.565217
25.391304
def get_ancestor_tag_names(mention): """Return the HTML tag of the Mention's ancestors. For example, ['html', 'body', 'p']. If a candidate is passed in, only the ancestors of its first Mention are returned. :param mention: The Mention to evaluate :rtype: list of strings """ span = _to_span...
[ "def", "get_ancestor_tag_names", "(", "mention", ")", ":", "span", "=", "_to_span", "(", "mention", ")", "tag_names", "=", "[", "]", "i", "=", "_get_node", "(", "span", ".", "sentence", ")", "while", "i", "is", "not", "None", ":", "tag_names", ".", "in...
29.875
15.0625
def merge(cls, *others): """ Merge the `others` schema into this instance. The values will all be read from the provider of the original object. """ for other in others: for k, v in other: setattr(cls, k, BoundValue(cls, k, v.value))
[ "def", "merge", "(", "cls", ",", "*", "others", ")", ":", "for", "other", "in", "others", ":", "for", "k", ",", "v", "in", "other", ":", "setattr", "(", "cls", ",", "k", ",", "BoundValue", "(", "cls", ",", "k", ",", "v", ".", "value", ")", ")...
32.666667
16.444444
def psislw(log_weights, reff=1.0): """ Pareto smoothed importance sampling (PSIS). Parameters ---------- log_weights : array Array of size (n_samples, n_observations) reff : float relative MCMC efficiency, `ess / n` Returns ------- lw_out : array Smoothed lo...
[ "def", "psislw", "(", "log_weights", ",", "reff", "=", "1.0", ")", ":", "rows", ",", "cols", "=", "log_weights", ".", "shape", "log_weights_out", "=", "np", ".", "copy", "(", "log_weights", ",", "order", "=", "\"F\"", ")", "kss", "=", "np", ".", "emp...
33.217391
19.130435
def new(self, time_flags): # type: (int) -> None ''' Create a new Rock Ridge Time Stamp record. Parameters: time_flags - The flags to use for this time stamp record. Returns: Nothing. ''' if self._initialized: raise pycdlibexception....
[ "def", "new", "(", "self", ",", "time_flags", ")", ":", "# type: (int) -> None", "if", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'TF record already initialized!'", ")", "self", ".", "time_flags", "=", "time_fla...
31.035714
22.035714
def geosearch( self, latitude=None, longitude=None, radius=1000, title=None, auto_suggest=True, results=10, ): """ Search for pages that relate to the provided geocoords or near the page Args: latitude (Decimal ...
[ "def", "geosearch", "(", "self", ",", "latitude", "=", "None", ",", "longitude", "=", "None", ",", "radius", "=", "1000", ",", "title", "=", "None", ",", "auto_suggest", "=", "True", ",", "results", "=", "10", ",", ")", ":", "def", "test_lat_long", "...
37.266667
20.383333
def set_baudrate(self, baudrate): '''set baudrate''' try: self.port.setBaudrate(baudrate) except Exception: # for pySerial 3.0, which doesn't have setBaudrate() self.port.baudrate = baudrate
[ "def", "set_baudrate", "(", "self", ",", "baudrate", ")", ":", "try", ":", "self", ".", "port", ".", "setBaudrate", "(", "baudrate", ")", "except", "Exception", ":", "# for pySerial 3.0, which doesn't have setBaudrate()", "self", ".", "port", ".", "baudrate", "=...
34.857143
13.142857
def get_property(self, prop): """Access nested value using dot separated keys Args: prop (:obj:`str`): Property in the form of dot separated keys Returns: Property value if exists, else `None` """ prop = prop.split('.') root = self for p ...
[ "def", "get_property", "(", "self", ",", "prop", ")", ":", "prop", "=", "prop", ".", "split", "(", "'.'", ")", "root", "=", "self", "for", "p", "in", "prop", ":", "if", "p", "in", "root", ":", "root", "=", "root", "[", "p", "]", "else", ":", ...
25.588235
18.529412
def setup_logging(filename, log_dir=None, force_setup=False): ''' Try to load logging configuration from a file. Set level to INFO if failed. ''' if not force_setup and ChirpCLI.SETUP_COMPLETED: logging.debug("Master logging has been setup. This call will be ignored.") return if log_dir ...
[ "def", "setup_logging", "(", "filename", ",", "log_dir", "=", "None", ",", "force_setup", "=", "False", ")", ":", "if", "not", "force_setup", "and", "ChirpCLI", ".", "SETUP_COMPLETED", ":", "logging", ".", "debug", "(", "\"Master logging has been setup. This call ...
44.47619
17.809524
def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). """ result = dict( version=0, name=name, ...
[ "def", "create_cookie", "(", "name", ",", "value", ",", "*", "*", "kwargs", ")", ":", "result", "=", "dict", "(", "version", "=", "0", ",", "name", "=", "name", ",", "value", "=", "value", ",", "port", "=", "None", ",", "domain", "=", "''", ",", ...
32.733333
17.633333
def empty(cls: Type[BoardT], *, chess960: bool = False) -> BoardT: """Creates a new empty board. Also see :func:`~chess.Board.clear()`.""" return cls(None, chess960=chess960)
[ "def", "empty", "(", "cls", ":", "Type", "[", "BoardT", "]", ",", "*", ",", "chess960", ":", "bool", "=", "False", ")", "->", "BoardT", ":", "return", "cls", "(", "None", ",", "chess960", "=", "chess960", ")" ]
62.666667
9.666667
def chol(A): """ Calculate the lower triangular matrix of the Cholesky decomposition of a symmetric, positive-definite matrix. """ A = np.array(A) assert A.shape[0] == A.shape[1], "Input matrix must be square" L = [[0.0] * len(A) for _ in range(len(A))] for i in range(len(A)): ...
[ "def", "chol", "(", "A", ")", ":", "A", "=", "np", ".", "array", "(", "A", ")", "assert", "A", ".", "shape", "[", "0", "]", "==", "A", ".", "shape", "[", "1", "]", ",", "\"Input matrix must be square\"", "L", "=", "[", "[", "0.0", "]", "*", "...
32.117647
20.117647
def decode_wireformat_uuid(rawguid): """Decode a wire format UUID It handles the rather particular scheme where half is little endian and half is big endian. It returns a string like dmidecode would output. """ if isinstance(rawguid, list): rawguid = bytearray(rawguid) lebytes = struct...
[ "def", "decode_wireformat_uuid", "(", "rawguid", ")", ":", "if", "isinstance", "(", "rawguid", ",", "list", ")", ":", "rawguid", "=", "bytearray", "(", "rawguid", ")", "lebytes", "=", "struct", ".", "unpack_from", "(", "'<IHH'", ",", "buffer", "(", "rawgui...
46.666667
19.25
def get_creation_date( self, bucket: str, key: str, ) -> datetime.datetime: """ Retrieves the creation date for a given key in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which the creation...
[ "def", "get_creation_date", "(", "self", ",", "bucket", ":", "str", ",", "key", ":", "str", ",", ")", "->", "datetime", ".", "datetime", ":", "blob_obj", "=", "self", ".", "_get_blob_obj", "(", "bucket", ",", "key", ")", "return", "blob_obj", ".", "tim...
36
15.692308
def NetFxSDKIncludes(self): """ Microsoft .Net Framework SDK Includes """ if self.vc_ver < 14.0 or not self.si.NetFxSdkDir: return [] return [os.path.join(self.si.NetFxSdkDir, r'include\um')]
[ "def", "NetFxSDKIncludes", "(", "self", ")", ":", "if", "self", ".", "vc_ver", "<", "14.0", "or", "not", "self", ".", "si", ".", "NetFxSdkDir", ":", "return", "[", "]", "return", "[", "os", ".", "path", ".", "join", "(", "self", ".", "si", ".", "...
29.625
14.875
def _set_path(self, path): "Set self.path, self.dirname and self.basename." import os.path self.path = os.path.abspath(path) self.dirname = os.path.dirname(path) self.basename = os.path.basename(path)
[ "def", "_set_path", "(", "self", ",", "path", ")", ":", "import", "os", ".", "path", "self", ".", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "self", ".", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", ...
35.833333
8.833333
def merge(self, obj): """This function merge another object's values with this instance :param obj: An object to be merged with into this layer :type obj: object """ for attribute in dir(obj): if '__' in attribute: continue setattr(self, a...
[ "def", "merge", "(", "self", ",", "obj", ")", ":", "for", "attribute", "in", "dir", "(", "obj", ")", ":", "if", "'__'", "in", "attribute", ":", "continue", "setattr", "(", "self", ",", "attribute", ",", "getattr", "(", "obj", ",", "attribute", ")", ...
34.5
14.7
def parse_output(self, line): """Convert output to key value pairs""" try: key, value = line.split(":") self.update_value(key.strip(), value.strip()) except ValueError: pass
[ "def", "parse_output", "(", "self", ",", "line", ")", ":", "try", ":", "key", ",", "value", "=", "line", ".", "split", "(", "\":\"", ")", "self", ".", "update_value", "(", "key", ".", "strip", "(", ")", ",", "value", ".", "strip", "(", ")", ")", ...
28.375
16.75
def scaleToBoxParam(quad, shape): ''' so, you have a [quad] ((x0,y0),,,) inside a box [shape](width,height) this function gives you center [x,y], and scale factor [x,y] you would need to apply to [quad] in order to scale it to the same shape as the box !quad corners needs to be sorted...
[ "def", "scaleToBoxParam", "(", "quad", ",", "shape", ")", ":", "#get edge middle points", "x0", "=", "0.5", "*", "(", "quad", "[", "0", "]", "[", "0", "]", "+", "quad", "[", "1", "]", "[", "0", "]", ")", "x1", "=", "0.5", "*", "(", "quad", "[",...
27
22.44
def min(self, binby=[], limits=None, shape=default_shape, selection=False, delay=False, progress=None): '''Shortcut for ds.min(expression, ...), see `Dataset.min`''' kwargs = dict(locals()) del kwargs['self'] kwargs['expression'] = self.expression return self.ds.min(**kwargs)
[ "def", "min", "(", "self", ",", "binby", "=", "[", "]", ",", "limits", "=", "None", ",", "shape", "=", "default_shape", ",", "selection", "=", "False", ",", "delay", "=", "False", ",", "progress", "=", "None", ")", ":", "kwargs", "=", "dict", "(", ...
51.833333
20.833333
def from_dict(self, d): """ Initialise an API message from a transmission-safe dictionary. """ for key in d: if key == 'data': for dkey in d['data']: if dkey in self._encode_fields: setattr(self, str(dkey), base64.b6...
[ "def", "from_dict", "(", "self", ",", "d", ")", ":", "for", "key", "in", "d", ":", "if", "key", "==", "'data'", ":", "for", "dkey", "in", "d", "[", "'data'", "]", ":", "if", "dkey", "in", "self", ".", "_encode_fields", ":", "setattr", "(", "self"...
37.769231
15.615385
def get_function_url(self, function): """ Registers the given callable in the system (if it isn't already) and returns the URL that can be used to invoke the given function from remote. """ assert self._opened, "RPC System is not opened" logging.debug("get_function_url(%s...
[ "def", "get_function_url", "(", "self", ",", "function", ")", ":", "assert", "self", ".", "_opened", ",", "\"RPC System is not opened\"", "logging", ".", "debug", "(", "\"get_function_url(%s)\"", "%", "repr", "(", "function", ")", ")", "if", "function", "in", ...
47.230769
16.769231
def serialize(self): """serialize.""" if self.request is None: request = None else: request = json.loads(self.request) if self.response is None: response = None else: response = json.loads(self.response) return { ...
[ "def", "serialize", "(", "self", ")", ":", "if", "self", ".", "request", "is", "None", ":", "request", "=", "None", "else", ":", "request", "=", "json", ".", "loads", "(", "self", ".", "request", ")", "if", "self", ".", "response", "is", "None", ":...
22.421053
18.210526
def get_stats(self, pattern, with_descriptions): """Get the VM statistics in a XMLish format. in pattern of type str The selection pattern. A bit similar to filename globbing. in with_descriptions of type bool Whether to include the descriptions. return stats o...
[ "def", "get_stats", "(", "self", ",", "pattern", ",", "with_descriptions", ")", ":", "if", "not", "isinstance", "(", "pattern", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"pattern can only be an instance of type basestring\"", ")", "if", "not", "isi...
38.2
19.05
def paginator(self): """ The paginator instance associated with the view, or `None`. """ if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator = None else: self._paginator = self.pagination_class() ...
[ "def", "paginator", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_paginator'", ")", ":", "if", "self", ".", "pagination_class", "is", "None", ":", "self", ".", "_paginator", "=", "None", "else", ":", "self", ".", "_paginator", "="...
33.9
10.7
def parse_date(ims): """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """ try: ts = email.utils.parsedate_tz(ims) return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone except (TypeError, ValueError, IndexError): return None
[ "def", "parse_date", "(", "ims", ")", ":", "try", ":", "ts", "=", "email", ".", "utils", ".", "parsedate_tz", "(", "ims", ")", "return", "time", ".", "mktime", "(", "ts", "[", ":", "8", "]", "+", "(", "0", ",", ")", ")", "-", "(", "ts", "[", ...
40.857143
16.285714
def edges(self): """ Return the edge characters of this node. """ edge_str = ctypes.create_string_buffer(MAX_CHARS) cgaddag.gdg_edges(self.gdg, self.node, edge_str) return [char for char in edge_str.value.decode("ascii")]
[ "def", "edges", "(", "self", ")", ":", "edge_str", "=", "ctypes", ".", "create_string_buffer", "(", "MAX_CHARS", ")", "cgaddag", ".", "gdg_edges", "(", "self", ".", "gdg", ",", "self", ".", "node", ",", "edge_str", ")", "return", "[", "char", "for", "c...
29.222222
18.777778
def on_leave(self): ''' Quit chat room ''' # Only if user has time to call self.initialize # (sometimes it's not the case) if self.roomId != '-1': # Debug logging.debug('chat: leave room (roomId: %s)' % self.roomId) # Say to other users the current us...
[ "def", "on_leave", "(", "self", ")", ":", "# Only if user has time to call self.initialize", "# (sometimes it's not the case)", "if", "self", ".", "roomId", "!=", "'-1'", ":", "# Debug", "logging", ".", "debug", "(", "'chat: leave room (roomId: %s)'", "%", "self", ".", ...
31.444444
18.777778
def complete_visualize(self, text, line, begidx, endidx): """completion for file command""" opts = self.VISUALIZE_OPTS if not text: completions = opts else: completions = [f for f in opts if f.startswith(text...
[ "def", "complete_visualize", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "opts", "=", "self", ".", "VISUALIZE_OPTS", "if", "not", "text", ":", "completions", "=", "opts", "else", ":", "completions", "=", "[", "f", "fo...
28.076923
15.846154
def _getUE4BuildInterrogator(self): """ Uses UE4BuildInterrogator to interrogate UnrealBuildTool about third-party library details """ ubtLambda = lambda target, platform, config, args: self._runUnrealBuildTool(target, platform, config, args, True) interrogator = UE4BuildInterrogator(self.getEngineRoot(), sel...
[ "def", "_getUE4BuildInterrogator", "(", "self", ")", ":", "ubtLambda", "=", "lambda", "target", ",", "platform", ",", "config", ",", "args", ":", "self", ".", "_runUnrealBuildTool", "(", "target", ",", "platform", ",", "config", ",", "args", ",", "True", "...
58
34.857143
def page(self, date_created_before=values.unset, date_created=values.unset, date_created_after=values.unset, date_updated_before=values.unset, date_updated=values.unset, date_updated_after=values.unset, friendly_name=values.unset, status=values.unset, page_token=value...
[ "def", "page", "(", "self", ",", "date_created_before", "=", "values", ".", "unset", ",", "date_created", "=", "values", ".", "unset", ",", "date_created_after", "=", "values", ".", "unset", ",", "date_updated_before", "=", "values", ".", "unset", ",", "date...
51.152174
26.413043
def next_token(self): """Lexical analyser of the raw input.""" while self.char is not None: if self.char.isspace(): # The current character is a whitespace self.whitespace() continue elif self.char == '#': # The cu...
[ "def", "next_token", "(", "self", ")", ":", "while", "self", ".", "char", "is", "not", "None", ":", "if", "self", ".", "char", ".", "isspace", "(", ")", ":", "# The current character is a whitespace", "self", ".", "whitespace", "(", ")", "continue", "elif"...
32.080645
14.822581
def _prepare_container(self, client, action, volume_container, volume_alias): """ Runs a temporary container for preparing an attached volume for a container configuration. :param client: Docker client. :type client: docker.Client :param action: Action configuration. :ty...
[ "def", "_prepare_container", "(", "self", ",", "client", ",", "action", ",", "volume_container", ",", "volume_alias", ")", ":", "apc_kwargs", "=", "self", ".", "get_attached_preparation_create_kwargs", "(", "action", ",", "volume_container", ",", "volume_alias", ")"...
50.066667
22.933333
def basic_parse(response, buf_size=ijson.backend.BUFSIZE): """ Iterator yielding unprefixed events. Parameters: - response: a stream response from requests """ lexer = iter(IncrementalJsonParser.lexer(response, buf_size)) for value in ijson.backend.parse_value(l...
[ "def", "basic_parse", "(", "response", ",", "buf_size", "=", "ijson", ".", "backend", ".", "BUFSIZE", ")", ":", "lexer", "=", "iter", "(", "IncrementalJsonParser", ".", "lexer", "(", "response", ",", "buf_size", ")", ")", "for", "value", "in", "ijson", "...
28.941176
18.823529
def domain_search(self, query, exclude_query=[], max_length=25, min_length=2, has_hyphen=True, has_number=True, active_only=False, deleted_only=False, anchor_left=False, anchor_right=False, page=1, **kwargs): """Each term in the query string must be at least three characters long. ...
[ "def", "domain_search", "(", "self", ",", "query", ",", "exclude_query", "=", "[", "]", ",", "max_length", "=", "25", ",", "min_length", "=", "2", ",", "has_hyphen", "=", "True", ",", "has_number", "=", "True", ",", "active_only", "=", "False", ",", "d...
87.8
46.7
def list_rooms(api_key=None): ''' List all Slack rooms. :param api_key: The Slack admin api key. :return: The room list. CLI Example: .. code-block:: bash salt '*' slack.list_rooms salt '*' slack.list_rooms api_key=peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' if not api_key:...
[ "def", "list_rooms", "(", "api_key", "=", "None", ")", ":", "if", "not", "api_key", ":", "api_key", "=", "_get_api_key", "(", ")", "return", "salt", ".", "utils", ".", "slack", ".", "query", "(", "function", "=", "'rooms'", ",", "api_key", "=", "api_ke...
24.3
22.4
def _update_data_out(self, data, dtype): """Append the data of the given dtype_out to the data_out attr.""" try: self.data_out.update({dtype: data}) except AttributeError: self.data_out = {dtype: data}
[ "def", "_update_data_out", "(", "self", ",", "data", ",", "dtype", ")", ":", "try", ":", "self", ".", "data_out", ".", "update", "(", "{", "dtype", ":", "data", "}", ")", "except", "AttributeError", ":", "self", ".", "data_out", "=", "{", "dtype", ":...
40.666667
7.666667
def main(argv=None): """Run Tika from command line according to USAGE.""" global Verbose global EncodeUtf8 global csvOutput if argv is None: argv = sys.argv if (len(argv) < 3 and not (('-h' in argv) or ('--help' in argv))): log.exception('Bad args') raise TikaException('...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "global", "Verbose", "global", "EncodeUtf8", "global", "csvOutput", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "if", "(", "len", "(", "argv", ")", "<", "3", "and", "not", "("...
37.404762
22.690476
def make_publisher(self): """ not implemented :return: """ LOGGER.debug("zeromq.Driver.make_publisher") if not self.configuration_OK or self.connection_args is None: raise exceptions.ArianeConfError('zeromq connection arguments') publisher = Publisher....
[ "def", "make_publisher", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"zeromq.Driver.make_publisher\"", ")", "if", "not", "self", ".", "configuration_OK", "or", "self", ".", "connection_args", "is", "None", ":", "raise", "exceptions", ".", "ArianeConfEr...
38.272727
16.636364
def set_motion_detect(self, enable): """Set motion detection.""" if enable: return api.request_motion_detection_enable(self.sync.blink, self.network_id, self.camera_id) retur...
[ "def", "set_motion_detect", "(", "self", ",", "enable", ")", ":", "if", "enable", ":", "return", "api", ".", "request_motion_detection_enable", "(", "self", ".", "sync", ".", "blink", ",", "self", ".", "network_id", ",", "self", ".", "camera_id", ")", "ret...
56
22.333333
def extract_program_summary(data): ''' Extract the summary data from a program's detail page ''' from bs4 import BeautifulSoup soup = BeautifulSoup(data, 'html.parser') try: return soup.find( 'div', {'class': 'episode-synopsis'} ).find_all('div')[-1].text.strip() ...
[ "def", "extract_program_summary", "(", "data", ")", ":", "from", "bs4", "import", "BeautifulSoup", "soup", "=", "BeautifulSoup", "(", "data", ",", "'html.parser'", ")", "try", ":", "return", "soup", ".", "find", "(", "'div'", ",", "{", "'class'", ":", "'ep...
33.571429
16.142857
def _split_string_to_tokens(text): """Splits text to a list of string tokens.""" if not text: return [] ret = [] token_start = 0 # Classify each character in the input string is_alnum = [c in _ALPHANUMERIC_CHAR_SET for c in text] for pos in xrange(1, len(text)): if is_alnum[pos] != is_alnum[pos - ...
[ "def", "_split_string_to_tokens", "(", "text", ")", ":", "if", "not", "text", ":", "return", "[", "]", "ret", "=", "[", "]", "token_start", "=", "0", "# Classify each character in the input string", "is_alnum", "=", "[", "c", "in", "_ALPHANUMERIC_CHAR_SET", "for...
30.058824
13.647059
def normalize_hex(hex_value): """ Normalize a hexadecimal color value to 6 digits, lowercase. """ match = HEX_COLOR_RE.match(hex_value) if match is None: raise ValueError( u"'{}' is not a valid hexadecimal color value.".format(hex_value) ) hex_digits = match.group(1)...
[ "def", "normalize_hex", "(", "hex_value", ")", ":", "match", "=", "HEX_COLOR_RE", ".", "match", "(", "hex_value", ")", "if", "match", "is", "None", ":", "raise", "ValueError", "(", "u\"'{}' is not a valid hexadecimal color value.\"", ".", "format", "(", "hex_value...
31.285714
15.571429
def packet2dict(packet, *, count=NotImplemented): """Convert Scapy packet into dict.""" if scapy_all is None: raise ModuleNotFound("No module named 'scapy'", name='scapy') def wrapper(packet): dict_ = packet.fields payload = packet.payload if not isinstance(payload, scapy_al...
[ "def", "packet2dict", "(", "packet", ",", "*", ",", "count", "=", "NotImplemented", ")", ":", "if", "scapy_all", "is", "None", ":", "raise", "ModuleNotFound", "(", "\"No module named 'scapy'\"", ",", "name", "=", "'scapy'", ")", "def", "wrapper", "(", "packe...
30.5
18.4375
def connect(): """ create socket and connect to adb server """ global adb_socket if adb_socket is not None: raise RuntimeError('connection already existed') host, port = config.HOST, config.PORT connection = socket.socket() try: connection.connect((host, port)) except Conne...
[ "def", "connect", "(", ")", ":", "global", "adb_socket", "if", "adb_socket", "is", "not", "None", ":", "raise", "RuntimeError", "(", "'connection already existed'", ")", "host", ",", "port", "=", "config", ".", "HOST", ",", "config", ".", "PORT", "connection...
28.315789
20.052632
def rename_directory(self, relativePath, newName, raiseError=True, ntrials=3): """ Rename a directory in the repository. It insures renaming the directory in the system. :Parameters: #. relativePath (string): The relative to the repository path of the directory to be ...
[ "def", "rename_directory", "(", "self", ",", "relativePath", ",", "newName", ",", "raiseError", "=", "True", ",", "ntrials", "=", "3", ")", ":", "assert", "isinstance", "(", "raiseError", ",", "bool", ")", ",", "\"raiseError must be boolean\"", "assert", "isin...
53.813725
27.088235
def get_modified_files(): """Returns a list of all modified files.""" c = subprocess.Popen( ["git", "diff-index", "--cached", "--name-only", "HEAD"], stdout=subprocess.PIPE ) return c.communicate()[0].splitlines()
[ "def", "get_modified_files", "(", ")", ":", "c", "=", "subprocess", ".", "Popen", "(", "[", "\"git\"", ",", "\"diff-index\"", ",", "\"--cached\"", ",", "\"--name-only\"", ",", "\"HEAD\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "return", "...
38.666667
19.166667
def md_to_notebook(text): """Convert a Markdown text to a Jupyter notebook, using Pandoc""" tmp_file = tempfile.NamedTemporaryFile(delete=False) tmp_file.write(text.encode('utf-8')) tmp_file.close() pandoc(u'--from markdown --to ipynb -s --atx-headers --wrap=preserve --preserve-tabs', tmp_file.name...
[ "def", "md_to_notebook", "(", "text", ")", ":", "tmp_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "tmp_file", ".", "write", "(", "text", ".", "encode", "(", "'utf-8'", ")", ")", "tmp_file", ".", "close", "(", ")", ...
38.692308
25.384615
def get_clan(self): """(a)sync function to return clan.""" try: return self.client.get_clan(self.clan.tag) except AttributeError: try: return self.client.get_clan(self.tag) except AttributeError: raise ValueError('This player do...
[ "def", "get_clan", "(", "self", ")", ":", "try", ":", "return", "self", ".", "client", ".", "get_clan", "(", "self", ".", "clan", ".", "tag", ")", "except", "AttributeError", ":", "try", ":", "return", "self", ".", "client", ".", "get_clan", "(", "se...
37
16.111111
def list_compliance_results(self, limit=50, direction=None, cursor=None, filter=""): '''**Description** Get the list of all compliance tasks runs. **Arguments** - limit: Maximum number of alerts in the response. - direction: the direction (PREV or NEXT) that determin...
[ "def", "list_compliance_results", "(", "self", ",", "limit", "=", "50", ",", "direction", "=", "None", ",", "cursor", "=", "None", ",", "filter", "=", "\"\"", ")", ":", "url", "=", "\"{url}/api/complianceResults?cursor{cursor}&filter={filter}&limit={limit}{direction}\...
57.571429
36.142857
def sampleLocation(self): """ Simple method to sample uniformly from a cylinder. """ areaRatio = self.radius / (self.radius + self.height) if random.random() < areaRatio: return self._sampleLocationOnDisc() else: return self._sampleLocationOnSide()
[ "def", "sampleLocation", "(", "self", ")", ":", "areaRatio", "=", "self", ".", "radius", "/", "(", "self", ".", "radius", "+", "self", ".", "height", ")", "if", "random", ".", "random", "(", ")", "<", "areaRatio", ":", "return", "self", ".", "_sample...
30.666667
9.333333
def create(self, list_id, subscriber_hash, data): """ Add a new note for a specific subscriber. The documentation lists only the note request body parameter so it is being documented and error-checked as if it were required based on the description of the method. :param...
[ "def", "create", "(", "self", ",", "list_id", ",", "subscriber_hash", ",", "data", ")", ":", "subscriber_hash", "=", "check_subscriber_hash", "(", "subscriber_hash", ")", "self", ".", "list_id", "=", "list_id", "self", ".", "subscriber_hash", "=", "subscriber_ha...
39.666667
17.8
def _create_model(self, X, Y): """ Creates the model given some input data X and Y. """ from sklearn.ensemble import RandomForestRegressor self.X = X self.Y = Y self.model = RandomForestRegressor(bootstrap = self.bootstrap, ...
[ "def", "_create_model", "(", "self", ",", "X", ",", "Y", ")", ":", "from", "sklearn", ".", "ensemble", "import", "RandomForestRegressor", "self", ".", "X", "=", "X", "self", ".", "Y", "=", "Y", "self", ".", "model", "=", "RandomForestRegressor", "(", "...
56
26.5