text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _extract_direct(self, *, stream): """Attempt to extract the image directly to a usable image file If there is no way to extract the image without decompressing or transcoding then raise an exception. The type and format of image generated will vary. Args: stream...
[ "def", "_extract_direct", "(", "self", ",", "*", ",", "stream", ")", ":", "def", "normal_dct_rgb", "(", ")", ":", "# Normal DCTDecode RGB images have the default value of", "# /ColorTransform 1 and are actually in YUV. Such a file can be", "# saved as a standard JPEG. RGB JPEGs wit...
43.439024
0.002197
def _build_connections(self, process_list, ignore_dependencies, auto_dependency): """Parses the process connections dictionaries into a process list This method is called upon instantiation of the NextflowGenerator class. Essentially, it sets the main input/output cha...
[ "def", "_build_connections", "(", "self", ",", "process_list", ",", "ignore_dependencies", ",", "auto_dependency", ")", ":", "logger", ".", "debug", "(", "\"=============================\"", ")", "logger", ".", "debug", "(", "\"Building pipeline connections\"", ")", "...
46.539007
0.000597
def get_build_status(req_id, nodename): ''' get the build status from CLC to make sure we dont return to early ''' counter = 0 req_id = six.text_type(req_id) while counter < 10: queue = clc.v1.Blueprint.GetStatus(request_id=(req_id)) if queue["PercentComplete"] == 100: ...
[ "def", "get_build_status", "(", "req_id", ",", "nodename", ")", ":", "counter", "=", "0", "req_id", "=", "six", ".", "text_type", "(", "req_id", ")", "while", "counter", "<", "10", ":", "queue", "=", "clc", ".", "v1", ".", "Blueprint", ".", "GetStatus"...
40.35
0.001211
def copy(self): """Return a copy of the polynomial.""" return Poly(self.A.copy(), self.dim, self.shape, self.dtype)
[ "def", "copy", "(", "self", ")", ":", "return", "Poly", "(", "self", ".", "A", ".", "copy", "(", ")", ",", "self", ".", "dim", ",", "self", ".", "shape", ",", "self", ".", "dtype", ")" ]
35
0.020979
def get_command(arguments, output=None): """Parse C{arguments} and configure a L{Command} instance. An access key, secret key, endpoint and action are required. Additional parameters included with the request are passed as parameters to the method call. For example, the following command will create ...
[ "def", "get_command", "(", "arguments", ",", "output", "=", "None", ")", ":", "options", "=", "parse_options", "(", "arguments", ")", "key", "=", "options", ".", "pop", "(", "\"key\"", ")", "secret", "=", "options", ".", "pop", "(", "\"secret\"", ")", ...
46.434783
0.000917
def enumerate_keyword_args(tokens): """ Iterates over *tokens* and returns a dictionary with function names as the keys and lists of keyword arguments as the values. """ keyword_args = {} inside_function = False for index, tok in enumerate(tokens): token_type = tok[0] token_s...
[ "def", "enumerate_keyword_args", "(", "tokens", ")", ":", "keyword_args", "=", "{", "}", "inside_function", "=", "False", "for", "index", ",", "tok", "in", "enumerate", "(", "tokens", ")", ":", "token_type", "=", "tok", "[", "0", "]", "token_string", "=", ...
39
0.002384
def same_disks(self, count=2): """ filter self to the required number of disks with same size and type Select the disks with the same type and same size. If not enough disks available, set self to empty. :param count: number of disks to retrieve :return: disk list """ ...
[ "def", "same_disks", "(", "self", ",", "count", "=", "2", ")", ":", "ret", "=", "self", "if", "len", "(", "self", ")", ">", "0", ":", "type_counter", "=", "Counter", "(", "self", ".", "drive_type", ")", "drive_type", ",", "counts", "=", "type_counter...
32.615385
0.002291
def change_crypto_domain_config(self, crypto_domain_index, access_mode): """ Change the access mode for a crypto domain that is currently included in the crypto configuration of this partition. The access mode will be changed for the specified crypto domain on all crypto adapter...
[ "def", "change_crypto_domain_config", "(", "self", ",", "crypto_domain_index", ",", "access_mode", ")", ":", "body", "=", "{", "'domain-index'", ":", "crypto_domain_index", ",", "'access-mode'", ":", "access_mode", "}", "self", ".", "manager", ".", "session", ".",...
38.394737
0.001337
def modify_access(src, dst='any', port=None, proto=None, action='allow', index=None): """ Grant access to an address or subnet :param src: address (e.g. 192.168.1.234) or subnet (e.g. 192.168.1.0/24). :param dst: destiny of the connection, if the machine has multiple I...
[ "def", "modify_access", "(", "src", ",", "dst", "=", "'any'", ",", "port", "=", "None", ",", "proto", "=", "None", ",", "action", "=", "'allow'", ",", "index", "=", "None", ")", ":", "if", "not", "is_enabled", "(", ")", ":", "hookenv", ".", "log", ...
32.24
0.000602
def to_json_file(self, json_file_path): """ Save this instance to a json file.""" with open(json_file_path, "w", encoding='utf-8') as writer: writer.write(self.to_json_string())
[ "def", "to_json_file", "(", "self", ",", "json_file_path", ")", ":", "with", "open", "(", "json_file_path", ",", "\"w\"", ",", "encoding", "=", "'utf-8'", ")", "as", "writer", ":", "writer", ".", "write", "(", "self", ".", "to_json_string", "(", ")", ")"...
50.5
0.009756
def get_json(request, token): """Return matching results as JSON""" result = [] searchtext = request.GET['q'] if len(searchtext) >= 3: pickled = _simple_autocomplete_queryset_cache.get(token, None) if pickled is not None: app_label, model_name, query = pickle.loads(pickled) ...
[ "def", "get_json", "(", "request", ",", "token", ")", ":", "result", "=", "[", "]", "searchtext", "=", "request", ".", "GET", "[", "'q'", "]", "if", "len", "(", "searchtext", ")", ">=", "3", ":", "pickled", "=", "_simple_autocomplete_queryset_cache", "."...
40.061224
0.001989
async def answerInlineQuery(self, inline_query_id, results, cache_time=None, is_personal=None, next_offset=None, switch_pm_text=None, switch_pm_parameter=None):...
[ "async", "def", "answerInlineQuery", "(", "self", ",", "inline_query_id", ",", "results", ",", "cache_time", "=", "None", ",", "is_personal", "=", "None", ",", "next_offset", "=", "None", ",", "switch_pm_text", "=", "None", ",", "switch_pm_parameter", "=", "No...
54.222222
0.014113
def offset2line(offset, linestarts): """linestarts is expected to be a *list) of (offset, line number) where both offset and line number are in increasing order. Return the closes line number at or below the offset. If offset is less than the first line number given in linestarts, return line number...
[ "def", "offset2line", "(", "offset", ",", "linestarts", ")", ":", "if", "len", "(", "linestarts", ")", "==", "0", "or", "offset", "<", "linestarts", "[", "0", "]", "[", "0", "]", ":", "return", "0", "low", "=", "0", "high", "=", "len", "(", "line...
34.92
0.001115
def status(name, sig=None, runas=None): ''' Return the status for a service. :param str name: Used to find the service from launchctl. Can be any part of the service name or a regex expression. :param str sig: Find the service with status.pid instead. Note that ``name`` must still be...
[ "def", "status", "(", "name", ",", "sig", "=", "None", ",", "runas", "=", "None", ")", ":", "# Find service with ps", "if", "sig", ":", "return", "__salt__", "[", "'status.pid'", "]", "(", "sig", ")", "try", ":", "_get_service", "(", "name", ")", "exce...
29.350877
0.001735
def get_solver_name(mip=False, qp=False): """Select a solver for a given optimization problem. Parameters ---------- mip : bool Does the solver require mixed integer linear programming capabilities? qp : bool Does the solver require quadratic programming capabilities? Returns ...
[ "def", "get_solver_name", "(", "mip", "=", "False", ",", "qp", "=", "False", ")", ":", "if", "len", "(", "solvers", ")", "==", "0", ":", "raise", "SolverNotFound", "(", "\"no solvers installed\"", ")", "# Those lists need to be updated as optlang implements more sol...
31.813953
0.000709
def _handle_config(self, data): """ Handles received configuration data. :param data: Configuration string to parse :type data: string """ _, config_string = data.split('>') for setting in config_string.split('&'): key, val = setting.split('=') ...
[ "def", "_handle_config", "(", "self", ",", "data", ")", ":", "_", ",", "config_string", "=", "data", ".", "split", "(", "'>'", ")", "for", "setting", "in", "config_string", ".", "split", "(", "'&'", ")", ":", "key", ",", "val", "=", "setting", ".", ...
35.322581
0.001778
def FirstSlotSlicer(primary_query, secondary_query, limit=30): # noqa """ Inject the first object from a queryset into the first position of a reading list. :param primary_queryset: djes.LazySearch object. Default queryset for reading list. :param secondary_queryset: djes.LazySearch object. first resu...
[ "def", "FirstSlotSlicer", "(", "primary_query", ",", "secondary_query", ",", "limit", "=", "30", ")", ":", "# noqa", "reading_list", "=", "SearchSlicer", "(", "limit", "=", "limit", ")", "reading_list", ".", "register_queryset", "(", "primary_query", ")", "readi...
48.833333
0.008375
def _SerializeRequest(self, request): """Convert a http_wrapper.Request object into a string. Args: request: A http_wrapper.Request to serialize. Returns: The request as a string in application/http format. """ # Construct status line parsed = urllib...
[ "def", "_SerializeRequest", "(", "self", ",", "request", ")", ":", "# Construct status line", "parsed", "=", "urllib_parse", ".", "urlsplit", "(", "request", ".", "url", ")", "request_line", "=", "urllib_parse", ".", "urlunsplit", "(", "(", "''", ",", "''", ...
33.822222
0.001277
def validation_report(path, notifications, filename): """ Generate a validation report from a notification object. Parameters ---------- path : string Path to model file. notifications : dict A simple dictionary structure containing a list of errors and warnings. """ en...
[ "def", "validation_report", "(", "path", ",", "notifications", ",", "filename", ")", ":", "env", "=", "Environment", "(", "loader", "=", "PackageLoader", "(", "'memote.suite'", ",", "'templates'", ")", ",", "autoescape", "=", "select_autoescape", "(", "[", "'h...
32.55
0.001493
def get_bbox(self): """Returns bounding box (xmin, xmax, ymin, ymax)""" width = self.width height = self.height cos_angle = cos(self.angle) sin_angle = sin(self.angle) x_diff = 0.5 * width y_diff = 0.5 * height # self rotates around (0, 0). c_x...
[ "def", "get_bbox", "(", "self", ")", ":", "width", "=", "self", ".", "width", "height", "=", "self", ".", "height", "cos_angle", "=", "cos", "(", "self", ".", "angle", ")", "sin_angle", "=", "sin", "(", "self", ".", "angle", ")", "x_diff", "=", "0....
28.636364
0.001535
def get_key(key_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if a key exists. Returns fingerprint and name if it does and False if it doesn't CLI Example: .. code-block:: bash salt myminion boto_ec2.get_key mykey ''' conn = _get_conn(region=region, key=k...
[ "def", "get_key", "(", "key_name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid", ...
29.380952
0.00157
def delete_user(deleted_user_id,**kwargs): """ Delete a user """ #check_perm(kwargs.get('user_id'), 'edit_user') try: user_i = db.DBSession.query(User).filter(User.id==deleted_user_id).one() db.DBSession.delete(user_i) except NoResultFound: raise ResourceNotFoundError...
[ "def", "delete_user", "(", "deleted_user_id", ",", "*", "*", "kwargs", ")", ":", "#check_perm(kwargs.get('user_id'), 'edit_user')", "try", ":", "user_i", "=", "db", ".", "DBSession", ".", "query", "(", "User", ")", ".", "filter", "(", "User", ".", "id", "=="...
29.230769
0.020408
def description_from_content(self): """ Returns the first block or sentence of the first content-like field. """ description = "" # Use the first RichTextField, or TextField if none found. for field_type in (RichTextField, models.TextField): if not des...
[ "def", "description_from_content", "(", "self", ")", ":", "description", "=", "\"\"", "# Use the first RichTextField, or TextField if none found.", "for", "field_type", "in", "(", "RichTextField", ",", "models", ".", "TextField", ")", ":", "if", "not", "description", ...
42.111111
0.001289
def do_work_units(self, args): '''list work units that have not yet completed''' work_spec_name = self._get_work_spec_name(args) if args.status: status = args.status.upper() statusi = getattr(self.task_master, status, None) if statusi is None: ...
[ "def", "do_work_units", "(", "self", ",", "args", ")", ":", "work_spec_name", "=", "self", ".", "_get_work_spec_name", "(", "args", ")", "if", "args", ".", "status", ":", "status", "=", "args", ".", "status", ".", "upper", "(", ")", "statusi", "=", "ge...
42
0.001663
def satellitePopulationOrig(config, n, range_distance_modulus=[16.5, 24.], range_stellar_mass=[1.e2, 1.e5], range_r_physical=[5.e-3, 1.], mode='mask', plot=False): """ Crea...
[ "def", "satellitePopulationOrig", "(", "config", ",", "n", ",", "range_distance_modulus", "=", "[", "16.5", ",", "24.", "]", ",", "range_stellar_mass", "=", "[", "1.e2", ",", "1.e5", "]", ",", "range_r_physical", "=", "[", "5.e-3", ",", "1.", "]", ",", "...
51.985915
0.008508
def is_up(self): ''' Return True if the interface is up, False otherwise. ''' # Get existing device flags ifreq = struct.pack('16sh', self.name, 0) flags = struct.unpack('16sh', fcntl.ioctl(sockfd, SIOCGIFFLAGS, ifreq))[1] # Set new flags if flags & IFF_UP: ...
[ "def", "is_up", "(", "self", ")", ":", "# Get existing device flags", "ifreq", "=", "struct", ".", "pack", "(", "'16sh'", ",", "self", ".", "name", ",", "0", ")", "flags", "=", "struct", ".", "unpack", "(", "'16sh'", ",", "fcntl", ".", "ioctl", "(", ...
29.916667
0.008108
def translate_featuring(state_name=None, im_name=None, use_full_path=False, **kwargs): """ Translates one optimized state into another image where the particles have moved by a small amount (~1 particle radius). Returns a completely-optimized state. The user can interactively selects the in...
[ "def", "translate_featuring", "(", "state_name", "=", "None", ",", "im_name", "=", "None", ",", "use_full_path", "=", "False", ",", "*", "*", "kwargs", ")", ":", "state_name", ",", "im_name", "=", "_pick_state_im_name", "(", "state_name", ",", "im_name", ","...
42.373626
0.000507
def build_TKIP_payload(data, iv, mac, tk): """Build a TKIP header for IV @iv and mac @mac, and encrypt @data based on temporal key @tk """ TSC5, TSC4, TSC3, TSC2, TSC1, TSC0 = ( (iv >> 40) & 0xFF, (iv >> 32) & 0xFF, (iv >> 24) & 0xFF, (iv >> 16) & 0xFF, (iv >> 8) ...
[ "def", "build_TKIP_payload", "(", "data", ",", "iv", ",", "mac", ",", "tk", ")", ":", "TSC5", ",", "TSC4", ",", "TSC3", ",", "TSC2", ",", "TSC1", ",", "TSC0", "=", "(", "(", "iv", ">>", "40", ")", "&", "0xFF", ",", "(", "iv", ">>", "32", ")",...
33.5
0.001319
def is_all_field_none(self): """ :rtype: bool """ if self._BunqMeFundraiserResult is not None: return False if self._BunqMeTab is not None: return False if self._BunqMeTabResultInquiry is not None: return False if self._Bunq...
[ "def", "is_all_field_none", "(", "self", ")", ":", "if", "self", ".", "_BunqMeFundraiserResult", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_BunqMeTab", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_BunqMeTabResultIn...
22.5
0.001183
def search_album(self, album_name, quiet=False, limit=9): """Search album by album name. :params album_name: album name. :params quiet: automatically select the best one. :params limit: album count returned by weapi. :return: a Album object. """ result = self.se...
[ "def", "search_album", "(", "self", ",", "album_name", ",", "quiet", "=", "False", ",", "limit", "=", "9", ")", ":", "result", "=", "self", ".", "search", "(", "album_name", ",", "search_type", "=", "10", ",", "limit", "=", "limit", ")", "if", "resul...
38.545455
0.002301
def setCurrentLocale(self, locale): """ Sets the current locale for this box to the inputed locale. :param locale | <babel.Locale> || <str> :return <bool> """ locale = str(locale) for i in xrange(self.count()): if s...
[ "def", "setCurrentLocale", "(", "self", ",", "locale", ")", ":", "locale", "=", "str", "(", "locale", ")", "for", "i", "in", "xrange", "(", "self", ".", "count", "(", ")", ")", ":", "if", "self", ".", "itemData", "(", "i", ")", "==", "locale", ":...
30.357143
0.009132
def min(self, axis=None, skipna=True, *args, **kwargs): """ Return the minimum value of the Index or minimum along an axis. See Also -------- numpy.ndarray.min Series.min : Return the minimum value in a Series. """ nv.validate_min(args, kwargs) ...
[ "def", "min", "(", "self", ",", "axis", "=", "None", ",", "skipna", "=", "True", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "nv", ".", "validate_min", "(", "args", ",", "kwargs", ")", "nv", ".", "validate_minmax_axis", "(", "axis", ")", ...
27.878788
0.002101
def get(self, uuid): """ Get one document store into LinShare.""" #return self.core.get("documents/" + uuid) documents = (v for v in self.list() if v.get('uuid') == uuid) for i in documents: self.log.debug(i) return i return None
[ "def", "get", "(", "self", ",", "uuid", ")", ":", "#return self.core.get(\"documents/\" + uuid)", "documents", "=", "(", "v", "for", "v", "in", "self", ".", "list", "(", ")", "if", "v", ".", "get", "(", "'uuid'", ")", "==", "uuid", ")", "for", "i", "...
35.75
0.010239
def dump_document(cls, instance, fields_own=None, fields_to_many=None): """ Get document for model_instance. redefine dump rule for field x: def dump_document_x :param django.db.models.Model instance: model instance :param list<Field> or None fields: model_instance field to dump ...
[ "def", "dump_document", "(", "cls", ",", "instance", ",", "fields_own", "=", "None", ",", "fields_to_many", "=", "None", ")", ":", "if", "fields_own", "is", "not", "None", ":", "fields_own", "=", "{", "f", ".", "name", "for", "f", "in", "fields_own", "...
42.108434
0.001118
def _update(self, filename, dir1, dir2): """ Private function for updating a file based on last time stamp of modification """ # NOTE: dir1 is source & dir2 is target if self._updatefiles: file1 = os.path.join(dir1, filename) file2 = os.path.join(dir2, filename)...
[ "def", "_update", "(", "self", ",", "filename", ",", "dir1", ",", "dir2", ")", ":", "# NOTE: dir1 is source & dir2 is target", "if", "self", ".", "_updatefiles", ":", "file1", "=", "os", ".", "path", ".", "join", "(", "dir1", ",", "filename", ")", "file2",...
40.256098
0.000591
def xml_file(self, cu, analysis): """Add to the XML report for a single file.""" # Create the 'lines' and 'package' XML elements, which # are populated later. Note that a package == a directory. package_name = rpartition(cu.name, ".")[0] className = cu.name package = s...
[ "def", "xml_file", "(", "self", ",", "cu", ",", "analysis", ")", ":", "# Create the 'lines' and 'package' XML elements, which", "# are populated later. Note that a package == a directory.", "package_name", "=", "rpartition", "(", "cu", ".", "name", ",", "\".\"", ")", "["...
39.819672
0.002411
def _load_from_results_dir(self, compile_classpath, vts_results_dir, coursier_cache_path, invalidation_check, pants_jar_path_base): """ Given vts_results_dir, load the results which can be from multiple runs of coursier into compile_classpath. :return: True if success; False if...
[ "def", "_load_from_results_dir", "(", "self", ",", "compile_classpath", ",", "vts_results_dir", ",", "coursier_cache_path", ",", "invalidation_check", ",", "pants_jar_path_base", ")", ":", "result_file_path", "=", "os", ".", "path", ".", "join", "(", "vts_results_dir"...
41.296296
0.008764
def get_password(request, mapping) -> None: """ Resolve the given credential request in the provided mapping definition. The result is printed automatically. Args: request: The credential request specified as a dict of key-value pairs. mapping: The mapping confi...
[ "def", "get_password", "(", "request", ",", "mapping", ")", "->", "None", ":", "LOGGER", ".", "debug", "(", "'Received request \"%s\"'", ",", "request", ")", "if", "'host'", "not", "in", "request", ":", "LOGGER", ".", "error", "(", "'host= entry missing in req...
38.2
0.000425
def _is_known_unsigned_by_dtype(dt): """Helper returning True if dtype is known to be unsigned.""" return { tf.bool: True, tf.uint8: True, tf.uint16: True, }.get(dt.base_dtype, False)
[ "def", "_is_known_unsigned_by_dtype", "(", "dt", ")", ":", "return", "{", "tf", ".", "bool", ":", "True", ",", "tf", ".", "uint8", ":", "True", ",", "tf", ".", "uint16", ":", "True", ",", "}", ".", "get", "(", "dt", ".", "base_dtype", ",", "False",...
28.714286
0.014493
def in_channels(m:nn.Module) -> List[int]: "Return the shape of the first weight layer in `m`." for l in flatten_model(m): if hasattr(l, 'weight'): return l.weight.shape[1] raise Exception('No weight layer')
[ "def", "in_channels", "(", "m", ":", "nn", ".", "Module", ")", "->", "List", "[", "int", "]", ":", "for", "l", "in", "flatten_model", "(", "m", ")", ":", "if", "hasattr", "(", "l", ",", "'weight'", ")", ":", "return", "l", ".", "weight", ".", "...
44.6
0.017621
def _wait_and_kill(pid_to_wait, pids_to_kill): """ Helper function. Wait for a process to finish if it exists, and then try to kill a list of processes. Used by local_train Args: pid_to_wait: the process to wait for. pids_to_kill: a list of processes to kill after the process of pid_to_...
[ "def", "_wait_and_kill", "(", "pid_to_wait", ",", "pids_to_kill", ")", ":", "# cloud workers don't have psutil", "import", "psutil", "if", "psutil", ".", "pid_exists", "(", "pid_to_wait", ")", ":", "psutil", ".", "Process", "(", "pid", "=", "pid_to_wait", ")", "...
27.181818
0.016155
def write_plugin_items(xml_tree, records, app_id, api_ver=3, app_ver=None): """Generate the plugin blocklists. <pluginItem blockID="p422"> <match name="filename" exp="JavaAppletPlugin\\.plugin"/> <versionRange minVersion="Java 7 Update 16" maxVersion="Java 7 Update 24" ...
[ "def", "write_plugin_items", "(", "xml_tree", ",", "records", ",", "app_id", ",", "api_ver", "=", "3", ",", "app_ver", "=", "None", ")", ":", "if", "not", "records", ":", "return", "pluginItems", "=", "etree", ".", "SubElement", "(", "xml_tree", ",", "'p...
43.870968
0.002158
def charge(self): '''Charge of the species as an integer. Computed as a property as most species do not have a charge and so storing it would be a waste of memory. ''' try: return self._charge except AttributeError: self._charge = charge_from_form...
[ "def", "charge", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_charge", "except", "AttributeError", ":", "self", ".", "_charge", "=", "charge_from_formula", "(", "self", ".", "formula", ")", "return", "self", ".", "_charge" ]
36
0.00813
def add_property_orders(query_proto, *orders): """Add ordering constraint for the given datastore.Query proto message. Args: query_proto: datastore.Query proto message. orders: list of propertype name string, default to ascending order and set descending if prefixed by '-'. Usage: >>> add_proper...
[ "def", "add_property_orders", "(", "query_proto", ",", "*", "orders", ")", ":", "for", "order", "in", "orders", ":", "proto", "=", "query_proto", ".", "order", ".", "add", "(", ")", "if", "order", "[", "0", "]", "==", "'-'", ":", "order", "=", "order...
34.5
0.008463
def get_limits(self, coord='data'): """Get the bounding box of the viewer extents. Returns ------- limits : tuple Bounding box in coordinates of type `coord` in the form of ``(ll_pt, ur_pt)``. """ limits = self.t_['limits'] if limits ...
[ "def", "get_limits", "(", "self", ",", "coord", "=", "'data'", ")", ":", "limits", "=", "self", ".", "t_", "[", "'limits'", "]", "if", "limits", "is", "None", ":", "# No user defined limits. If there is an image loaded", "# use its dimensions as the limits", "image...
33.135135
0.001585
def copy_modules(filespath=None, modules_path=None, verbose=None): ''' Copy over the tree module files into your path ''' # find or define a modules path if not modules_path: modulepath = os.getenv("MODULEPATH") if not modulepath: modules_path = input('Enter the root path for yo...
[ "def", "copy_modules", "(", "filespath", "=", "None", ",", "modules_path", "=", "None", ",", "verbose", "=", "None", ")", ":", "# find or define a modules path", "if", "not", "modules_path", ":", "modulepath", "=", "os", ".", "getenv", "(", "\"MODULEPATH\"", "...
39.589744
0.001896
def start_discovery(add_callback=None, remove_callback=None): """ Start discovering chromecasts on the network. This method will start discovering chromecasts on a separate thread. When a chromecast is discovered, the callback will be called with the discovered chromecast's zeroconf name. This is t...
[ "def", "start_discovery", "(", "add_callback", "=", "None", ",", "remove_callback", "=", "None", ")", ":", "listener", "=", "CastListener", "(", "add_callback", ",", "remove_callback", ")", "service_browser", "=", "False", "try", ":", "service_browser", "=", "ze...
41.642857
0.000838
def get_storage_pools(self, id_or_uri): """ Gets a list of Storage pools. Returns a list of storage pools belonging to the storage system referred by the Path property {ID} parameter or URI. Args: id_or_uri: Can be either the storage system ID (serial number) or the storage ...
[ "def", "get_storage_pools", "(", "self", ",", "id_or_uri", ")", ":", "uri", "=", "self", ".", "_client", ".", "build_uri", "(", "id_or_uri", ")", "+", "\"/storage-pools\"", "return", "self", ".", "_client", ".", "get", "(", "uri", ")" ]
40.25
0.008097
def at(host, command, seq, params): """ Parameters: command -- the command seq -- the sequence number params -- a list of elements which can be either int, float or string """ params_str = [] for p in params: if type(p) == int: params_str.append('{:d}'.format(p)) ...
[ "def", "at", "(", "host", ",", "command", ",", "seq", ",", "params", ")", ":", "params_str", "=", "[", "]", "for", "p", "in", "params", ":", "if", "type", "(", "p", ")", "==", "int", ":", "params_str", ".", "append", "(", "'{:d}'", ".", "format",...
36.944444
0.001466
def pred_from_list(self, species_list): """ There are an exceptionally large number of substitutions to look at (260^n), where n is the number of species in the list. We need a more efficient than brute force way of going through these possibilities. The brute force method would ...
[ "def", "pred_from_list", "(", "self", ",", "species_list", ")", ":", "species_list", "=", "get_el_sp", "(", "species_list", ")", "# calculate the highest probabilities to help us stop the recursion", "max_probabilities", "=", "[", "]", "for", "s2", "in", "species_list", ...
41.5
0.000872
def parse_connection_string_psycopg2(connection_string): """ parses psycopg2 consumable connection string :param connection_string: :return: return dictionary with connection string parts """ conn_prepared = {} conn_parsed = urlparse(connection_string) if not conn_parsed.hostname: ...
[ "def", "parse_connection_string_psycopg2", "(", "connection_string", ")", ":", "conn_prepared", "=", "{", "}", "conn_parsed", "=", "urlparse", "(", "connection_string", ")", "if", "not", "conn_parsed", ".", "hostname", ":", "_re_dbstr", "=", "re", ".", "compile", ...
43.305556
0.001255
def _execute_multi_level_task(self): """ Execute a multi-level task """ self.log(u"Executing multi level task...") self.log(u"Saving rconf...") # save original rconf orig_rconf = self.rconf.clone() # clone rconfs and set granularity # TODO the following code assu...
[ "def", "_execute_multi_level_task", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Executing multi level task...\"", ")", "self", ".", "log", "(", "u\"Saving rconf...\"", ")", "# save original rconf", "orig_rconf", "=", "self", ".", "rconf", ".", "clone", "("...
45.813333
0.001709
def slack_package(prgnam): """Return maximum binary Slackware package from output directory """ binaries, cache, binary = [], "0", "" for pkg in find_package(prgnam, _meta_.output): if pkg.startswith(prgnam) and pkg[:-4].endswith("_SBo"): binaries.append(pkg) for bins in binaries...
[ "def", "slack_package", "(", "prgnam", ")", ":", "binaries", ",", "cache", ",", "binary", "=", "[", "]", ",", "\"0\"", ",", "\"\"", "for", "pkg", "in", "find_package", "(", "prgnam", ",", "_meta_", ".", "output", ")", ":", "if", "pkg", ".", "startswi...
36
0.001805
def get_pwm(self, led_num): """Generic getter for all LED PWM value""" self.__check_range('led_number', led_num) register_low = self.calc_led_register(led_num) return self.__get_led_value(register_low)
[ "def", "get_pwm", "(", "self", ",", "led_num", ")", ":", "self", ".", "__check_range", "(", "'led_number'", ",", "led_num", ")", "register_low", "=", "self", ".", "calc_led_register", "(", "led_num", ")", "return", "self", ".", "__get_led_value", "(", "regis...
45.8
0.008584
def get_swagger_operation(self, context=default_context): """ get the swagger_schema operation representation. """ consumes = produces = context.contenttype_serializers.keys() parameters = get_swagger_parameters(self.parameters, context) responses = { "400": R...
[ "def", "get_swagger_operation", "(", "self", ",", "context", "=", "default_context", ")", ":", "consumes", "=", "produces", "=", "context", ".", "contenttype_serializers", ".", "keys", "(", ")", "parameters", "=", "get_swagger_parameters", "(", "self", ".", "par...
35.5
0.001371
def _EccZmaxRperiRap(self,*args,**kwargs): """ NAME: EccZmaxRperiRap (_EccZmaxRperiRap) PURPOSE: evaluate the eccentricity, maximum height above the plane, peri- and apocenter in the adiabatic approximation INPUT: Either: a) R,vR,vT,z,vz[,ph...
[ "def", "_EccZmaxRperiRap", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "(", "(", "self", ".", "_c", "and", "not", "(", "'c'", "in", "kwargs", "and", "not", "kwargs", "[", "'c'", "]", ")", ")", "or", "(", "ext_loaded", ...
48.090909
0.023154
def open(self, output_only = False, shared = True): """Open HID device and obtain 'Collection Information'. It effectively prepares the HidDevice object for reading and writing """ if self.is_opened(): raise HIDError("Device already opened") sharing_flags = 0 ...
[ "def", "open", "(", "self", ",", "output_only", "=", "False", ",", "shared", "=", "True", ")", ":", "if", "self", ".", "is_opened", "(", ")", ":", "raise", "HIDError", "(", "\"Device already opened\"", ")", "sharing_flags", "=", "0", "if", "shared", ":",...
43.026549
0.009449
def extract(cls, timestamp_str): """ Tries to extract a `datetime` object from the given string. First the datetime format is tried, if it fails, the date format is used for extraction. Raises `DateTimeFormatterException` if the extraction fails. """ if not times...
[ "def", "extract", "(", "cls", ",", "timestamp_str", ")", ":", "if", "not", "timestamp_str", ":", "raise", "DateTimeFormatterException", "(", "'timestamp_str must a valid string {}'", ".", "format", "(", "timestamp_str", ")", ")", "if", "isinstance", "(", "timestamp_...
32.37931
0.002068
def sympy_empirical_equal(expr1, expr2): """ Compare long , complex, expressions by replacing all symbols by a set of arbitrary expressions :param expr1: first expression :param expr2: second expression :return: True if expressions are empirically equal, false otherwise """ atoms_1 = expr...
[ "def", "sympy_empirical_equal", "(", "expr1", ",", "expr2", ")", ":", "atoms_1", "=", "expr1", ".", "atoms", "(", ")", "atoms_1", "=", "[", "a", "for", "a", "in", "atoms_1", "if", "isinstance", "(", "a", ",", "sympy", ".", "Symbol", ")", "]", "atoms_...
32.451613
0.008687
def heterozygosity_expected(af, ploidy, fill=np.nan): """Calculate the expected rate of heterozygosity for each variant under Hardy-Weinberg equilibrium. Parameters ---------- af : array_like, float, shape (n_variants, n_alleles) Allele frequencies array. ploidy : int Sample pl...
[ "def", "heterozygosity_expected", "(", "af", ",", "ploidy", ",", "fill", "=", "np", ".", "nan", ")", ":", "# check inputs", "af", "=", "asarray_ndim", "(", "af", ",", "2", ")", "# calculate expected heterozygosity", "out", "=", "1", "-", "np", ".", "sum", ...
27.847826
0.000754
def main(): '''main routine''' # Load Azure app defaults try: with open('azurermconfig.json') as config_file: config_data = json.load(config_file) except FileNotFoundError: sys.exit('Error: Expecting azurermconfig.json in current folder') tenant_id = config_data['tenantI...
[ "def", "main", "(", ")", ":", "# Load Azure app defaults", "try", ":", "with", "open", "(", "'azurermconfig.json'", ")", "as", "config_file", ":", "config_data", "=", "json", ".", "load", "(", "config_file", ")", "except", "FileNotFoundError", ":", "sys", ".",...
42.853659
0.002226
def _add_json_binary_field(b, serialized, field): '''' Set the given field to the given val (bytes) in the serialized dictionary. If the value isn't valid utf-8, we base64 encode it and use field+"64" as the field name. ''' try: val = b.decode('utf-8') serialized[field] = val ...
[ "def", "_add_json_binary_field", "(", "b", ",", "serialized", ",", "field", ")", ":", "try", ":", "val", "=", "b", ".", "decode", "(", "'utf-8'", ")", "serialized", "[", "field", "]", "=", "val", "except", "UnicodeDecodeError", ":", "val", "=", "base64",...
35.416667
0.002294
def process_ndex_network(network_id, username=None, password=None, require_grounding=True): """Process an NDEx network into Statements. Parameters ---------- network_id : str NDEx network ID. username : str NDEx username. password : str NDEx pass...
[ "def", "process_ndex_network", "(", "network_id", ",", "username", "=", "None", ",", "password", "=", "None", ",", "require_grounding", "=", "True", ")", ":", "nd", "=", "ndex2", ".", "client", ".", "Ndex2", "(", "username", "=", "username", ",", "password...
34.787879
0.000847
def get_device_by_ain(self, ain): """Returns a device specified by the AIN.""" devices = self.get_devices() for device in devices: if device.ain == ain: return device
[ "def", "get_device_by_ain", "(", "self", ",", "ain", ")", ":", "devices", "=", "self", ".", "get_devices", "(", ")", "for", "device", "in", "devices", ":", "if", "device", ".", "ain", "==", "ain", ":", "return", "device" ]
35.5
0.009174
def rmtree_log_error (func, path, exc): """Error function for shutil.rmtree(). Raises a PatoolError.""" msg = "Error in %s(%s): %s" % (func.__name__, path, str(exc[1])) util.log_error(msg)
[ "def", "rmtree_log_error", "(", "func", ",", "path", ",", "exc", ")", ":", "msg", "=", "\"Error in %s(%s): %s\"", "%", "(", "func", ".", "__name__", ",", "path", ",", "str", "(", "exc", "[", "1", "]", ")", ")", "util", ".", "log_error", "(", "msg", ...
49.25
0.01
def scope2lat(telescope): """ Convert a telescope name into a latitude returns None when the telescope is unknown. Parameters ---------- telescope : str Acronym (name) of telescope, eg MWA. Returns ------- lat : float The latitude of the telescope. Notes --...
[ "def", "scope2lat", "(", "telescope", ")", ":", "scopes", "=", "{", "'MWA'", ":", "-", "26.703319", ",", "\"ATCA\"", ":", "-", "30.3128", ",", "\"VLA\"", ":", "34.0790", ",", "\"LOFAR\"", ":", "52.9088", ",", "\"KAT7\"", ":", "-", "30.721", ",", "\"MEE...
27.7
0.000697
def chrome_tracing_object_transfer_dump(self, filename=None): """Return a list of transfer events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing ...
[ "def", "chrome_tracing_object_transfer_dump", "(", "self", ",", "filename", "=", "None", ")", ":", "client_id_to_address", "=", "{", "}", "for", "client_info", "in", "ray", ".", "global_state", ".", "client_table", "(", ")", ":", "client_id_to_address", "[", "cl...
44.577778
0.000488
def wald_wolfowitz(sequence): """ implements the wald-wolfowitz runs test: http://en.wikipedia.org/wiki/Wald-Wolfowitz_runs_test http://support.sas.com/kb/33/092.html :param sequence: any iterable with at most 2 values. e.g. '1001001' [1, 0, 1, 0, 1] ...
[ "def", "wald_wolfowitz", "(", "sequence", ")", ":", "R", "=", "n_runs", "=", "sum", "(", "1", "for", "s", "in", "groupby", "(", "sequence", ",", "lambda", "a", ":", "a", ")", ")", "n", "=", "float", "(", "sum", "(", "1", "for", "s", "in", "sequ...
33.265306
0.002384
def run_main_error_group(): """Run the phase group example where an error occurs in a main phase. The main phase in this example is terminal. The PhaseGroup was entered because the setup phases ran without error, so the teardown phases are run. The other main phase is skipped. """ test = htf.Test(htf.Phas...
[ "def", "run_main_error_group", "(", ")", ":", "test", "=", "htf", ".", "Test", "(", "htf", ".", "PhaseGroup", "(", "setup", "=", "[", "setup_phase", "]", ",", "main", "=", "[", "error_main_phase", ",", "main_phase", "]", ",", "teardown", "=", "[", "tea...
33.846154
0.00885
def jdbc_datasource_absent(name, both=True, server=None): ''' Ensures the JDBC Datasource doesn't exists name Name of the datasource both Delete both the pool and the resource, defaults to ``true`` ''' ret = {'name': name, 'result': None, 'comment': None, 'changes': {}} pool...
[ "def", "jdbc_datasource_absent", "(", "name", ",", "both", "=", "True", ",", "server", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "None", ",", "'comment'", ":", "None", ",", "'changes'", ":", "{", "}", "}", ...
35
0.002225
def update(self): """Update load stats.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib # Get the load using the os standard lib load = self._getloadavg() if ...
[ "def", "update", "(", "self", ")", ":", "# Init new stats", "stats", "=", "self", ".", "get_init_value", "(", ")", "if", "self", ".", "input_method", "==", "'local'", ":", "# Update stats using the standard system lib", "# Get the load using the os standard lib", "load"...
30.27027
0.00173
def splitext( filename ): """ Return the filename and extension according to the first dot in the filename. This helps date stamping .tar.bz2 or .ext.gz files properly. """ index = filename.find('.') if index == 0: index = 1+filename[1:].find('.') if index == -1: return filen...
[ "def", "splitext", "(", "filename", ")", ":", "index", "=", "filename", ".", "find", "(", "'.'", ")", "if", "index", "==", "0", ":", "index", "=", "1", "+", "filename", "[", "1", ":", "]", ".", "find", "(", "'.'", ")", "if", "index", "==", "-",...
36.454545
0.009732
def sift4(s1, s2, max_offset=5): """ This is an implementation of general Sift4. """ t1, t2 = list(s1), list(s2) l1, l2 = len(t1), len(t2) if not s1: return l2 if not s2: return l1 # Cursors for each string c1, c2 = 0, 0 # Largest common subsequence lcss =...
[ "def", "sift4", "(", "s1", ",", "s2", ",", "max_offset", "=", "5", ")", ":", "t1", ",", "t2", "=", "list", "(", "s1", ")", ",", "list", "(", "s2", ")", "l1", ",", "l2", "=", "len", "(", "t1", ")", ",", "len", "(", "t2", ")", "if", "not", ...
24.47619
0.000468
def make_case2(context): """This is a helper method for testing. When run with the current context, it will create a case 2 entries in the database. See top of file for what case 2 is. """ query = context.session.query(models.IPAddress) period_start, period_end = billing.calc_periods() ip_l...
[ "def", "make_case2", "(", "context", ")", ":", "query", "=", "context", ".", "session", ".", "query", "(", "models", ".", "IPAddress", ")", "period_start", ",", "period_end", "=", "billing", ".", "calc_periods", "(", ")", "ip_list", "=", "billing", ".", ...
38.375
0.00159
def interactions(problem, Y, print_to_console=False): """Computes the second order effects Computes the second order effects (interactions) between all combinations of pairs of input factors Arguments --------- problem: dict The problem definition Y: numpy.array The NumPy a...
[ "def", "interactions", "(", "problem", ",", "Y", ",", "print_to_console", "=", "False", ")", ":", "names", "=", "problem", "[", "'names'", "]", "num_vars", "=", "problem", "[", "'num_vars'", "]", "X", "=", "generate_contrast", "(", "problem", ")", "ie_name...
25.547619
0.000898
def force_delete(self): """ Force a hard delete on a soft deleted model. """ self.__force_deleting__ = True self.delete() self.__force_deleting__ = False
[ "def", "force_delete", "(", "self", ")", ":", "self", ".", "__force_deleting__", "=", "True", "self", ".", "delete", "(", ")", "self", ".", "__force_deleting__", "=", "False" ]
21.666667
0.009852
def find_frame_urls(self, site, frametype, gpsstart, gpsend, match=None, urltype=None, on_gaps="warn"): """Find the framefiles for the given type in the [start, end) interval frame @param site: single-character name of site to match @param frametype: ...
[ "def", "find_frame_urls", "(", "self", ",", "site", ",", "frametype", ",", "gpsstart", ",", "gpsend", ",", "match", "=", "None", ",", "urltype", "=", "None", ",", "on_gaps", "=", "\"warn\"", ")", ":", "if", "on_gaps", "not", "in", "(", "\"warn\"", ",",...
36.898551
0.002295
def add_tools(self): """Adds tools from self.toolbardata to self""" for data in self.toolbardata: # tool type is in data[0] if data[0] == "T": # Simple tool _, msg_type, label, tool_tip = data icon = icons[label] ...
[ "def", "add_tools", "(", "self", ")", ":", "for", "data", "in", "self", ".", "toolbardata", ":", "# tool type is in data[0]", "if", "data", "[", "0", "]", "==", "\"T\"", ":", "# Simple tool", "_", ",", "msg_type", ",", "label", ",", "tool_tip", "=", "dat...
26.313725
0.001437
def hmget(key, *fields, **options): ''' Returns the values of all the given hash fields. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' redis.hmget foo_hash bar_field1 bar_field2 ''' host = options.get('host', None) port = options.get('port', None) ...
[ "def", "hmget", "(", "key", ",", "*", "fields", ",", "*", "*", "options", ")", ":", "host", "=", "options", ".", "get", "(", "'host'", ",", "None", ")", "port", "=", "options", ".", "get", "(", "'port'", ",", "None", ")", "database", "=", "option...
26.333333
0.002037
def n_sum(n, nums, target, **kv): """ n: int nums: list[object] target: object sum_closure: function, optional Given two elements of nums, return sum of both. compare_closure: function, optional Given one object of nums and target, return -1, 1, or 0. same_closure: function, ...
[ "def", "n_sum", "(", "n", ",", "nums", ",", "target", ",", "*", "*", "kv", ")", ":", "def", "sum_closure_default", "(", "a", ",", "b", ")", ":", "return", "a", "+", "b", "def", "compare_closure_default", "(", "num", ",", "target", ")", ":", "\"\"\"...
30.485981
0.000594
def replaceSelected(self): """ Replace the currently selected string with the new one. The method return **False** if another match to the right of the cursor exists, and **True** if not (ie. when the end of the document was reached). """ SCI = self.qteWidget ...
[ "def", "replaceSelected", "(", "self", ")", ":", "SCI", "=", "self", ".", "qteWidget", "# Restore the original styling.", "self", ".", "qteWidget", ".", "SCISetStylingEx", "(", "0", ",", "0", ",", "self", ".", "styleOrig", ")", "# Select the region spanned by the ...
36.74359
0.00136
def get_source(self, spec, row): """ Sources can be specified as plain strings or as a reference to a column. """ value = self.get_value({'column': spec.get('source_url_column')}, row) if value is not None: return value return spec.get('source_url')
[ "def", "get_source", "(", "self", ",", "spec", ",", "row", ")", ":", "value", "=", "self", ".", "get_value", "(", "{", "'column'", ":", "spec", ".", "get", "(", "'source_url_column'", ")", "}", ",", "row", ")", "if", "value", "is", "not", "None", "...
48
0.010239
def refresh_jwt_token(self, token, override_access_lifespan=None): """ Creates a new token for a user if and only if the old token's access permission is expired but its refresh permission is not yet expired. The new token's refresh expiration moment is the same as the old token'...
[ "def", "refresh_jwt_token", "(", "self", ",", "token", ",", "override_access_lifespan", "=", "None", ")", ":", "moment", "=", "pendulum", ".", "now", "(", "'UTC'", ")", "# Note: we disable exp verification because we do custom checks here", "with", "InvalidTokenHeader", ...
41.107143
0.000849
def get_cluster_vsan_info(cluster_ref): ''' Returns the extended cluster vsan configuration object (vim.VsanConfigInfoEx). cluster_ref Reference to the cluster ''' cluster_name = salt.utils.vmware.get_managed_object_name(cluster_ref) log.trace('Retrieving cluster vsan info of clust...
[ "def", "get_cluster_vsan_info", "(", "cluster_ref", ")", ":", "cluster_name", "=", "salt", ".", "utils", ".", "vmware", ".", "get_managed_object_name", "(", "cluster_ref", ")", "log", ".", "trace", "(", "'Retrieving cluster vsan info of cluster \\'%s\\''", ",", "clust...
36.846154
0.001017
def _get_formated_symbol(self, symbol): """ Returns the symbol formated to be searched by regular expression. :param symbol: The symbol. :type symbol: str :return: The symbol formated. :rtype: str """ # pylint: disable=no-self-use old_symbols = [...
[ "def", "_get_formated_symbol", "(", "self", ",", "symbol", ")", ":", "# pylint: disable=no-self-use", "old_symbols", "=", "[", "'\\\\'", ",", "'.'", ",", "'+'", ",", "'*'", ",", "'?'", ",", "'^'", ",", "'$'", ",", "'['", ",", "']'", ",", "'{'", ",", "'...
21.431034
0.001538
def write_error(self, status_code, **kwargs): """Override of RequestHandler.write_error Calls ``error()`` or ``fail()`` from JSendMixin depending on which exception was raised with provided reason and status code. :type status_code: int :param status_code: HTTP status code ...
[ "def", "write_error", "(", "self", ",", "status_code", ",", "*", "*", "kwargs", ")", ":", "def", "get_exc_message", "(", "exception", ")", ":", "return", "exception", ".", "log_message", "if", "hasattr", "(", "exception", ",", "\"log_message\"", ")", "else",...
42.805556
0.001269
def views(self): """ Views packages """ for upg, size in sorted(zip(self.upgrade_all, self.comp_sum)): pkg_repo = split_package(upg[:-4]) color = self.meta.color["RED"] pkg_inst = GetFromInstalled(pkg_repo[0]).name() if pkg_repo[0] == pkg_i...
[ "def", "views", "(", "self", ")", ":", "for", "upg", ",", "size", "in", "sorted", "(", "zip", "(", "self", ".", "upgrade_all", ",", "self", ".", "comp_sum", ")", ")", ":", "pkg_repo", "=", "split_package", "(", "upg", "[", ":", "-", "4", "]", ")"...
46.166667
0.002358
def data(self): """Convert to a :py:class:`NodeData` for subsequent serial.""" return NodeData( self.foo, get_arguments(self.bound_args), self.hints)
[ "def", "data", "(", "self", ")", ":", "return", "NodeData", "(", "self", ".", "foo", ",", "get_arguments", "(", "self", ".", "bound_args", ")", ",", "self", ".", "hints", ")" ]
43.5
0.011299
def segments_colinear(ab, cd): ''' segments_colinear_2D((a, b), (c, d)) yields True if either a or b is on the line segment (c,d) or if c or d is on the line segment (a,b) and the lines are colinear; otherwise yields False. All of a, b, c, and d must be (x,y) coordinates or 2xN (x,y) coordinate matrices...
[ "def", "segments_colinear", "(", "ab", ",", "cd", ")", ":", "(", "a", ",", "b", ")", "=", "ab", "(", "c", ",", "d", ")", "=", "cd", "ss", "=", "[", "point_on_segment", "(", "ab", ",", "c", ")", ",", "point_on_segment", "(", "ab", ",", "d", ")...
44.5
0.011009
def residual_unit(data, num_filter, stride, dim_match, name, bottle_neck=True, num_group=32, bn_mom=0.9, workspace=256, memonger=False): """Return ResNet Unit symbol for building ResNet Parameters ---------- data : str Input data num_filter : int Number of output channels bnf : i...
[ "def", "residual_unit", "(", "data", ",", "num_filter", ",", "stride", ",", "dim_match", ",", "name", ",", "bottle_neck", "=", "True", ",", "num_group", "=", "32", ",", "bn_mom", "=", "0.9", ",", "workspace", "=", "256", ",", "memonger", "=", "False", ...
52.361111
0.014059
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: WorkspaceStatisticsContext for this WorkspaceStatisticsInstance :rtype: twilio.rest.taskrouter.v1...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "WorkspaceStatisticsContext", "(", "self", ".", "_version", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspace_sid'", ...
43.142857
0.009724
def handle_event(event, context): """ Do the actual event handling - try to enqueue the request. :param event: Lambda event that triggered the handler :type event: dict :param context: Lambda function context - see http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html :re...
[ "def", "handle_event", "(", "event", ",", "context", ")", ":", "queues", "=", "queues_for_endpoint", "(", "event", ")", "# store some state", "msg_ids", "=", "[", "]", "failed", "=", "0", "# get the message to enqueue", "msg", "=", "msg_body_for_event", "(", "ev...
30.891892
0.000848
def cmd_fernet_genkey(writecfg): """Generate a new Fernet Key, optionally write it to ~/.habu.json Example: \b $ habu.fernet.genkey xgvWCIvjwe9Uq7NBvwO796iI4dsGD623QOT9GWqnuhg= """ key = Fernet.generate_key() print(key.decode()) if writecfg: habucfg = loadcfg(environment=...
[ "def", "cmd_fernet_genkey", "(", "writecfg", ")", ":", "key", "=", "Fernet", ".", "generate_key", "(", ")", "print", "(", "key", ".", "decode", "(", ")", ")", "if", "writecfg", ":", "habucfg", "=", "loadcfg", "(", "environment", "=", "False", ")", "hab...
26.888889
0.001996
def create_brand(cls, brand, **kwargs): """Create Brand Create a new Brand This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_brand(brand, async=True) >>> result = thread.get() ...
[ "def", "create_brand", "(", "cls", ",", "brand", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_create_brand_with_http_info", "("...
37.47619
0.002478
def getParamValues(self, paramName=None, paramId=None, useOnlyValids=True): """ Return the rows of sampleDF that are associated to the parameter specified in paramName. """ if not paramName is None: if not paramId is None: if getParameterTypeN...
[ "def", "getParamValues", "(", "self", ",", "paramName", "=", "None", ",", "paramId", "=", "None", ",", "useOnlyValids", "=", "True", ")", ":", "if", "not", "paramName", "is", "None", ":", "if", "not", "paramId", "is", "None", ":", "if", "getParameterType...
44.083333
0.012026
def _rename_nvram_file(self): """ Before starting the VM, rename the nvram and vlan.dat files with the correct IOU application identifier. """ destination = self._nvram_file() for file_path in glob.glob(os.path.join(glob.escape(self.working_dir), "nvram_*")): shutil....
[ "def", "_rename_nvram_file", "(", "self", ")", ":", "destination", "=", "self", ".", "_nvram_file", "(", ")", "for", "file_path", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "glob", ".", "escape", "(", "self", ".", "working_dir...
52.818182
0.010152
def main(json_file): """ cachemaker.py creates a precache datastore of all available apis of CloudStack and dumps the precache dictionary in an importable python module. This way we cheat on the runtime overhead of completing commands and help docs. This reduces the overall search and cache_miss...
[ "def", "main", "(", "json_file", ")", ":", "f", "=", "open", "(", "\"precache.py\"", ",", "\"w\"", ")", "f", ".", "write", "(", "\"\"\"# -*- coding: utf-8 -*-\n# Auto-generated code by cachemaker.py\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contribu...
45.862069
0.000736
def _parse_extra_args(self, api, extra_args_raw): """ Parses extra arguments into a map keyed on particular data types. """ extra_args = {} def invalid(msg, extra_arg_raw): print('Invalid --extra-arg:%s: %s' % (msg, extra_arg_raw), file=sys.stderr) ...
[ "def", "_parse_extra_args", "(", "self", ",", "api", ",", "extra_args_raw", ")", ":", "extra_args", "=", "{", "}", "def", "invalid", "(", "msg", ",", "extra_arg_raw", ")", ":", "print", "(", "'Invalid --extra-arg:%s: %s'", "%", "(", "msg", ",", "extra_arg_ra...
47.032787
0.001707
def timeSeries(self, tag = None, outputFile = None, giveYears = True, greatestFirst = True, limitTo = False, pandasMode = True): """Creates an pandas dict of the ordered list of all the values of _tag_, with and ranked by the year the occurred in, multiple year occurrences will create multiple entries. A list c...
[ "def", "timeSeries", "(", "self", ",", "tag", "=", "None", ",", "outputFile", "=", "None", ",", "giveYears", "=", "True", ",", "greatestFirst", "=", "True", ",", "limitTo", "=", "False", ",", "pandasMode", "=", "True", ")", ":", "seriesDict", "=", "{",...
40.409639
0.011641
def lmx_h4k_f16k(): """HParams for training languagemodel_lm1b32k_packed. 1470M Params.""" hparams = lmx_base() hparams.hidden_size = 4096 hparams.filter_size = 16384 hparams.batch_size = 1024 hparams.weight_dtype = "bfloat16" return hparams
[ "def", "lmx_h4k_f16k", "(", ")", ":", "hparams", "=", "lmx_base", "(", ")", "hparams", ".", "hidden_size", "=", "4096", "hparams", ".", "filter_size", "=", "16384", "hparams", ".", "batch_size", "=", "1024", "hparams", ".", "weight_dtype", "=", "\"bfloat16\"...
31.125
0.03125