text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def send_group_image(self, sender, receiver, media_id): """ 发送群聊图片消息 :param sender: 发送人 :param receiver: 会话 ID :param media_id: 图片媒体文件id,可以调用上传素材文件接口获取 :return: 返回的 JSON 数据包 """ return self.send_image(sender, 'group', receiver, media_id)
[ "def", "send_group_image", "(", "self", ",", "sender", ",", "receiver", ",", "media_id", ")", ":", "return", "self", ".", "send_image", "(", "sender", ",", "'group'", ",", "receiver", ",", "media_id", ")" ]
29.3
14.9
def dicom_to_nifti(dicom_input, output_file): """ This function will convert an anatomical dicom series to a nifti Examples: See unit test :param output_file: filepath to the output nifti :param dicom_input: directory with the dicom files for a single scan, or list of read in dicoms """ if...
[ "def", "dicom_to_nifti", "(", "dicom_input", ",", "output_file", ")", ":", "if", "len", "(", "dicom_input", ")", "<=", "0", ":", "raise", "ConversionError", "(", "'NO_DICOM_FILES_FOUND'", ")", "# remove duplicate slices based on position and data", "dicom_input", "=", ...
41.227273
22.924242
def prop_budget(self, budget): """ Set limit on the number of propagations. """ if self.glucose: pysolvers.glucose3_pbudget(self.glucose, budget)
[ "def", "prop_budget", "(", "self", ",", "budget", ")", ":", "if", "self", ".", "glucose", ":", "pysolvers", ".", "glucose3_pbudget", "(", "self", ".", "glucose", ",", "budget", ")" ]
26.857143
14
def updatetext(self): """Recompute textual value based on the text content of the children. Only supported on elements that are a ``TEXTCONTAINER``""" if self.TEXTCONTAINER: s = "" for child in self: if isinstance(child, AbstractElement): child...
[ "def", "updatetext", "(", "self", ")", ":", "if", "self", ".", "TEXTCONTAINER", ":", "s", "=", "\"\"", "for", "child", "in", "self", ":", "if", "isinstance", "(", "child", ",", "AbstractElement", ")", ":", "child", ".", "updatetext", "(", ")", "s", "...
41.636364
9.636364
def rename(self, dn: str, new_rdn: str, new_base_dn: Optional[str] = None) -> None: """ rename a dn in the ldap database; see ldap module. doesn't return a result if transactions enabled. """ raise NotImplementedError()
[ "def", "rename", "(", "self", ",", "dn", ":", "str", ",", "new_rdn", ":", "str", ",", "new_base_dn", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "None", ":", "raise", "NotImplementedError", "(", ")" ]
42.333333
14
def configureLastWill(self, topic, payload, QoS): """ **Description** Used to configure the last will topic, payload and QoS of the client. Should be called before connect. This is a public facing API inherited by application level public clients. **Syntax** .. code:: ...
[ "def", "configureLastWill", "(", "self", ",", "topic", ",", "payload", ",", "QoS", ")", ":", "# AWSIoTMQTTClient.configureLastWill(srcTopic, srcPayload, srcQos)", "self", ".", "_AWSIoTMQTTClient", ".", "configureLastWill", "(", "topic", ",", "payload", ",", "QoS", ")"...
29.310345
30.068966
def getRolesForUser(self, username, filter=None, maxCount=None): """ This operation returns a list of role names that have been assigned to a particular user account. Inputs: username - name of the user for whom the returned roles filter - filter to b...
[ "def", "getRolesForUser", "(", "self", ",", "username", ",", "filter", "=", "None", ",", "maxCount", "=", "None", ")", ":", "uURL", "=", "self", ".", "_url", "+", "\"/roles/getRolesForUser\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"username\...
41.086957
17.347826
def resetPassword(self, userId): ''' Changes a user's password to a system-generated value. ''' self._setHeaders('resetPassword') return self._sforce.service.resetPassword(userId)
[ "def", "resetPassword", "(", "self", ",", "userId", ")", ":", "self", ".", "_setHeaders", "(", "'resetPassword'", ")", "return", "self", ".", "_sforce", ".", "service", ".", "resetPassword", "(", "userId", ")" ]
32.333333
18
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = CoordinatorLayout(self.get_context(), None, d.style)
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "widget", "=", "CoordinatorLayout", "(", "self", ".", "get_context", "(", ")", ",", "None", ",", "d", ".", "style", ")" ]
29.666667
17
def _quantize_params(qsym, params, th_dict): """Given a quantized symbol and a dict of params that have not been quantized, generate quantized params. Currently only supports quantizing the arg_params with names of `weight` or `bias`, not aux_params. If `qsym` contains symbols that are excluded from bei...
[ "def", "_quantize_params", "(", "qsym", ",", "params", ",", "th_dict", ")", ":", "inputs_name", "=", "qsym", ".", "list_arguments", "(", ")", "quantized_params", "=", "{", "}", "for", "name", "in", "inputs_name", ":", "if", "name", ".", "endswith", "(", ...
46.538462
17.128205
def sample_to(self, count, skip_header_rows, strategy, target): """Sample rows from GCS or local file and save results to target file. Args: count: number of rows to sample. If strategy is "BIGQUERY", it is used as approximate number. skip_header_rows: whether to skip first row when reading from so...
[ "def", "sample_to", "(", "self", ",", "count", ",", "skip_header_rows", ",", "strategy", ",", "target", ")", ":", "# TODO(qimingj) Add unit test", "# Read data from source into DataFrame.", "if", "sys", ".", "version_info", ".", "major", ">", "2", ":", "xrange", "...
46.490909
21.018182
def get_input_info_dict(self, signature=None): """Describes the inputs required by a signature. Args: signature: A string with the signature to get inputs information for. If None, the default signature is used if defined. Returns: The result of ModuleSpec.get_input_info_dict() for the...
[ "def", "get_input_info_dict", "(", "self", ",", "signature", "=", "None", ")", ":", "return", "self", ".", "_spec", ".", "get_input_info_dict", "(", "signature", "=", "signature", ",", "tags", "=", "self", ".", "_tags", ")" ]
36.8
25.933333
def trim_docstring(docstring): """Removes indentation from triple-quoted strings. This is the function specified in PEP 257 to handle docstrings: https://www.python.org/dev/peps/pep-0257/. Args: docstring: str, a python docstring. Returns: str, docstring with indentation removed. """ if not doc...
[ "def", "trim_docstring", "(", "docstring", ")", ":", "if", "not", "docstring", ":", "return", "''", "# If you've got a line longer than this you have other problems...", "max_indent", "=", "1", "<<", "29", "# Convert tabs to spaces (following the normal Python rules)", "# and s...
28.55
17.875
def add_definition_tags(self, tags, project, definition_id): """AddDefinitionTags. [Preview API] Adds multiple tags to a definition. :param [str] tags: The tags to add. :param str project: Project ID or project name :param int definition_id: The ID of the definition. :rty...
[ "def", "add_definition_tags", "(", "self", ",", "tags", ",", "project", ",", "definition_id", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", ".", ...
51.35
17.95
def make_butterworth_b_a(lowcut, highcut, SampleFreq, order=5, btype='band'): """ Generates the b and a coefficients for a butterworth IIR filter. Parameters ---------- lowcut : float frequency of lower bandpass limit highcut : float frequency of higher bandpass limit Sample...
[ "def", "make_butterworth_b_a", "(", "lowcut", ",", "highcut", ",", "SampleFreq", ",", "order", "=", "5", ",", "btype", "=", "'band'", ")", ":", "nyq", "=", "0.5", "*", "SampleFreq", "low", "=", "lowcut", "/", "nyq", "high", "=", "highcut", "/", "nyq", ...
32.111111
19.611111
def make_cdisk_kernel(psf, sigma, npix, cdelt, xpix, ypix, psf_scale_fn=None, normalize=False): """Make a kernel for a PSF-convolved 2D disk. Parameters ---------- psf : `~fermipy.irfs.PSFModel` sigma : float 68% containment radius in degrees. """ sigma /= 0.8...
[ "def", "make_cdisk_kernel", "(", "psf", ",", "sigma", ",", "npix", ",", "cdelt", ",", "xpix", ",", "ypix", ",", "psf_scale_fn", "=", "None", ",", "normalize", "=", "False", ")", ":", "sigma", "/=", "0.8246211251235321", "dtheta", "=", "psf", ".", "dtheta...
25.096774
22.903226
def execute(self): """ Execute the search and return an instance of ``Response`` wrapping all the data. """ if hasattr(self, "_executed"): return self._executed es = connections.get_connection(self._using) if getattr(self, "_full", False) is False: ...
[ "def", "execute", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"_executed\"", ")", ":", "return", "self", ".", "_executed", "es", "=", "connections", ".", "get_connection", "(", "self", ".", "_using", ")", "if", "getattr", "(", "self", "...
42.608696
23.565217
def serialize_html_fragment(el, skip_outer=False): """ Serialize a single lxml element as HTML. The serialized form includes the elements tail. If skip_outer is true, then don't serialize the outermost tag """ assert not isinstance(el, basestring), ( "You should pass in an element, not a...
[ "def", "serialize_html_fragment", "(", "el", ",", "skip_outer", "=", "False", ")", ":", "assert", "not", "isinstance", "(", "el", ",", "basestring", ")", ",", "(", "\"You should pass in an element, not a string like %r\"", "%", "el", ")", "html", "=", "etree", "...
37
13.705882
def find_first_tag(tags, entity_type, after_index=-1): """Searches tags for entity type after given index Args: tags(list): a list of tags with entity types to be compaired too entity_type entity_type(str): This is he entity type to be looking for in tags after_index(int): the start tok...
[ "def", "find_first_tag", "(", "tags", ",", "entity_type", ",", "after_index", "=", "-", "1", ")", ":", "for", "tag", "in", "tags", ":", "for", "entity", "in", "tag", ".", "get", "(", "'entities'", ")", ":", "for", "v", ",", "t", "in", "entity", "."...
40.904762
22.857143
def createLrrBafPlot(raw_dir, problematic_samples, format, dpi, out_prefix): """Creates the LRR and BAF plot. :param raw_dir: the directory containing the intensities. :param problematic_samples: the file containing the problematic samples. :param format: the format of the plot. :param dpi: the DPI...
[ "def", "createLrrBafPlot", "(", "raw_dir", ",", "problematic_samples", ",", "format", ",", "dpi", ",", "out_prefix", ")", ":", "# First, we create an output directory", "dir_name", "=", "out_prefix", "+", "\".LRR_BAF\"", "if", "not", "os", ".", "path", ".", "isdir...
36.588235
19.558824
def __var_find_to_py_ast( var_name: str, ns_name: str, py_var_ctx: ast.AST ) -> GeneratedPyAST: """Generate Var.find calls for the named symbol.""" return GeneratedPyAST( node=ast.Attribute( value=ast.Call( func=_FIND_VAR_FN_NAME, args=[ ...
[ "def", "__var_find_to_py_ast", "(", "var_name", ":", "str", ",", "ns_name", ":", "str", ",", "py_var_ctx", ":", "ast", ".", "AST", ")", "->", "GeneratedPyAST", ":", "return", "GeneratedPyAST", "(", "node", "=", "ast", ".", "Attribute", "(", "value", "=", ...
30.714286
16.47619
def parse(md, model, encoding='utf-8', config=None): """ Translate the Versa Markdown syntax into Versa model relationships md -- markdown source text model -- Versa model to take the output relationship encoding -- character encoding (defaults to UTF-8) Returns: The overall base URI (`@base`)...
[ "def", "parse", "(", "md", ",", "model", ",", "encoding", "=", "'utf-8'", ",", "config", "=", "None", ")", ":", "#Set up configuration to interpret the conventions for the Markdown", "config", "=", "config", "or", "{", "}", "#This mapping takes syntactical elements such...
48.273438
23.492188
def lhood(self, trsig, recalc=False, cachefile=None): """Returns likelihood of transit signal Returns sum of ``trsig`` MCMC samples evaluated at ``self.kde``. :param trsig: :class:`vespa.TransitSignal` object. :param recalc: (optional) Whether to recalc...
[ "def", "lhood", "(", "self", ",", "trsig", ",", "recalc", "=", "False", ",", "cachefile", "=", "None", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'kde'", ")", ":", "self", ".", "_make_kde", "(", ")", "if", "cachefile", "is", "None", ":", ...
27
17.65
def cond_remove_all(ol,**kwargs): ''' from elist.elist import * ol = [1,'X',3,'b',5,'c',6,'A',7,'b',8,'B',9] id(ol) def afterCH(ele,ch): cond = (ord(str(ele)) > ord(ch)) return(cond) new = cond_remove_all(ol,cond_func=afterCH,cond_func_args=['B']) ...
[ "def", "cond_remove_all", "(", "ol", ",", "*", "*", "kwargs", ")", ":", "cond_func", "=", "kwargs", "[", "'cond_func'", "]", "if", "(", "'cond_func_args'", "in", "kwargs", ")", ":", "cond_func_args", "=", "kwargs", "[", "'cond_func_args'", "]", "else", ":"...
26.209302
21.651163
def _handle_response(self, response): """Returns the given response or raises an APIError for non-2xx responses. :param requests.Response response: HTTP response :returns: requested data :rtype: requests.Response :raises APIError: for non-2xx responses """ if not str(response.status_code)....
[ "def", "_handle_response", "(", "self", ",", "response", ")", ":", "if", "not", "str", "(", "response", ".", "status_code", ")", ".", "startswith", "(", "'2'", ")", ":", "raise", "get_api_error", "(", "response", ")", "return", "response" ]
31.75
13.333333
def distances(self): """The matrix with the all-pairs shortest path lenghts""" from molmod.ext import graphs_floyd_warshall distances = np.zeros((self.num_vertices,)*2, dtype=int) #distances[:] = -1 # set all -1, which is just a very big integer #distances.ravel()[::len(distances...
[ "def", "distances", "(", "self", ")", ":", "from", "molmod", ".", "ext", "import", "graphs_floyd_warshall", "distances", "=", "np", ".", "zeros", "(", "(", "self", ".", "num_vertices", ",", ")", "*", "2", ",", "dtype", "=", "int", ")", "#distances[:] = -...
47.454545
15
def rst2node(doc_name, data): """Converts a reStructuredText into its node """ if not data: return parser = docutils.parsers.rst.Parser() document = docutils.utils.new_document('<%s>' % doc_name) document.settings = docutils.frontend.OptionParser().get_default_values() document.setti...
[ "def", "rst2node", "(", "doc_name", ",", "data", ")", ":", "if", "not", "data", ":", "return", "parser", "=", "docutils", ".", "parsers", ".", "rst", ".", "Parser", "(", ")", "document", "=", "docutils", ".", "utils", ".", "new_document", "(", "'<%s>'"...
34.1
11.45
def run(self): """ Perform phantomas run """ self._logger.info("running for <{url}>".format(url=self._url)) args = format_args(self._options) self._logger.debug("command: `{cmd}` / args: {args}". format(cmd=self._cmd, args=args)) # run the process ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"running for <{url}>\"", ".", "format", "(", "url", "=", "self", ".", "_url", ")", ")", "args", "=", "format_args", "(", "self", ".", "_options", ")", "self", ".", "_log...
32.45283
20.132075
def search( self, search_space, valid_data, init_args=[], train_args=[], init_kwargs={}, train_kwargs={}, module_args={}, module_kwargs={}, max_search=None, shuffle=True, verbose=True, **score_kwargs, ): ...
[ "def", "search", "(", "self", ",", "search_space", ",", "valid_data", ",", "init_args", "=", "[", "]", ",", "train_args", "=", "[", "]", ",", "init_kwargs", "=", "{", "}", ",", "train_kwargs", "=", "{", "}", ",", "module_args", "=", "{", "}", ",", ...
38.810811
22.810811
def _flatten_subsection(subsection, _type, offset, parent): '''Flatten a subsection from its nested version Args: subsection: Nested subsection as produced by _parse_section, except one level in _type: type of section, ie: AXON, etc parent: first element has this as it's parent ...
[ "def", "_flatten_subsection", "(", "subsection", ",", "_type", ",", "offset", ",", "parent", ")", ":", "for", "row", "in", "subsection", ":", "# TODO: Figure out what these correspond to in neurolucida", "if", "row", "in", "(", "'Low'", ",", "'Generated'", ",", "'...
40.238095
19.666667
def occurrences_after(self, after=None): """ It is often useful to know what the next occurrence is given a list of events. This function produces a generator that yields the the most recent occurrence after the date ``after`` from any of the events in ``self.events`` ""...
[ "def", "occurrences_after", "(", "self", ",", "after", "=", "None", ")", ":", "from", "schedule", ".", "models", "import", "Occurrence", "if", "after", "is", "None", ":", "after", "=", "timezone", ".", "now", "(", ")", "occ_replacer", "=", "OccurrenceRepla...
38.4
20.6
def add_error(self, txt): """Add a message in the configuration errors list so we can print them all in one place Set the object configuration as not correct :param txt: error message :type txt: str :return: None """ self.configuration_errors.append(tx...
[ "def", "add_error", "(", "self", ",", "txt", ")", ":", "self", ".", "configuration_errors", ".", "append", "(", "txt", ")", "self", ".", "conf_is_correct", "=", "False" ]
29
14.583333
def df(unit = 'GB'): '''A wrapper for the df shell command.''' details = {} headers = ['Filesystem', 'Type', 'Size', 'Used', 'Available', 'Capacity', 'MountedOn'] n = len(headers) unit = df_conversions[unit] p = subprocess.Popen(args = ['df', '-TP'], stdout = subprocess.PIPE) # -P prevents line...
[ "def", "df", "(", "unit", "=", "'GB'", ")", ":", "details", "=", "{", "}", "headers", "=", "[", "'Filesystem'", ",", "'Type'", ",", "'Size'", ",", "'Used'", ",", "'Available'", ",", "'Capacity'", ",", "'MountedOn'", "]", "n", "=", "len", "(", "header...
36.386364
21.659091
def get_tamil_words( letters ): """ reverse a Tamil word according to letters, not unicode-points """ if not isinstance(letters,list): raise Exception("metehod needs to be used with list generated from 'tamil.utf8.get_letters(...)'") return [word for word in get_words_iterable( letters, tamil_only =...
[ "def", "get_tamil_words", "(", "letters", ")", ":", "if", "not", "isinstance", "(", "letters", ",", "list", ")", ":", "raise", "Exception", "(", "\"metehod needs to be used with list generated from 'tamil.utf8.get_letters(...)'\"", ")", "return", "[", "word", "for", "...
64.8
23.4
def add_options(self): """ Add configuration options. """ super(ScriptBaseWithConfig, self).add_options() self.add_value_option("--config-dir", "DIR", help="configuration directory [{}]".format(os.environ.get('PYRO_CONFIG_DIR', self.CONFIG_DIR_DEFAULT))) self.add_val...
[ "def", "add_options", "(", "self", ")", ":", "super", "(", "ScriptBaseWithConfig", ",", "self", ")", ".", "add_options", "(", ")", "self", ".", "add_value_option", "(", "\"--config-dir\"", ",", "\"DIR\"", ",", "help", "=", "\"configuration directory [{}]\"", "."...
47.384615
18.692308
def normalLines(actor, ratio=1, c=(0.6, 0.6, 0.6), alpha=0.8): """ Build an ``vtkActor`` made of the normals at vertices shown as lines. """ maskPts = vtk.vtkMaskPoints() maskPts.SetOnRatio(ratio) maskPts.RandomModeOff() actor = actor.computeNormals() src = actor.polydata() maskPts.S...
[ "def", "normalLines", "(", "actor", ",", "ratio", "=", "1", ",", "c", "=", "(", "0.6", ",", "0.6", ",", "0.6", ")", ",", "alpha", "=", "0.8", ")", ":", "maskPts", "=", "vtk", ".", "vtkMaskPoints", "(", ")", "maskPts", ".", "SetOnRatio", "(", "rat...
34.827586
13.103448
def serve_file(self, load): ''' Serve up a chunk of a file ''' ret = {'data': '', 'dest': ''} if 'env' in load: # "env" is not supported; Use "saltenv". load.pop('env') if 'path' not in load or 'loc' not in load or 'saltenv' not in...
[ "def", "serve_file", "(", "self", ",", "load", ")", ":", "ret", "=", "{", "'data'", ":", "''", ",", "'dest'", ":", "''", "}", "if", "'env'", "in", "load", ":", "# \"env\" is not supported; Use \"saltenv\".", "load", ".", "pop", "(", "'env'", ")", "if", ...
31.26087
19.782609
def instr(str, substr): """ Locate the position of the first occurrence of substr column in the given string. Returns null if either of the arguments are null. .. note:: The position is not zero based, but 1 based index. Returns 0 if substr could not be found in str. >>> df = spark.createD...
[ "def", "instr", "(", "str", ",", "substr", ")", ":", "sc", "=", "SparkContext", ".", "_active_spark_context", "return", "Column", "(", "sc", ".", "_jvm", ".", "functions", ".", "instr", "(", "_to_java_column", "(", "str", ")", ",", "substr", ")", ")" ]
38.071429
21.214286
def as_cql_query(self, formatted=False): """ Returns a CQL query that can be used to recreate this function. If `formatted` is set to :const:`True`, extra whitespace will be added to make the query more readable. """ sep = '\n ' if formatted else ' ' keyspace =...
[ "def", "as_cql_query", "(", "self", ",", "formatted", "=", "False", ")", ":", "sep", "=", "'\\n '", "if", "formatted", "else", "' '", "keyspace", "=", "protect_name", "(", "self", ".", "keyspace", ")", "name", "=", "protect_name", "(", "self", ".", "n...
44.714286
15.095238
def from_uri(cls, uri: URI, w3: Web3) -> "Package": """ Returns a Package object instantiated by a manifest located at a content-addressed URI. A valid ``Web3`` instance is also required. URI schemes supported: - IPFS `ipfs://Qm...` - HTTP `https://api.g...
[ "def", "from_uri", "(", "cls", ",", "uri", ":", "URI", ",", "w3", ":", "Web3", ")", "->", "\"Package\"", ":", "contents", "=", "to_text", "(", "resolve_uri_contents", "(", "uri", ")", ")", "validate_raw_manifest_format", "(", "contents", ")", "manifest", "...
44.647059
21.235294
def get_user_permissions(uid, **kwargs): """ Get the roles for a user. @param user_id """ try: _get_user(uid) user_perms = db.DBSession.query(Perm).filter(Perm.id==RolePerm.perm_id, RolePerm.role_id==Role.id, ...
[ "def", "get_user_permissions", "(", "uid", ",", "*", "*", "kwargs", ")", ":", "try", ":", "_get_user", "(", "uid", ")", "user_perms", "=", "db", ".", "DBSession", ".", "query", "(", "Perm", ")", ".", "filter", "(", "Perm", ".", "id", "==", "RolePerm"...
37.8
23.4
def delete(self, role, commit=True): """ Delete a role """ events.role_deleted_event.send(role) return super().delete(role, commit)
[ "def", "delete", "(", "self", ",", "role", ",", "commit", "=", "True", ")", ":", "events", ".", "role_deleted_event", ".", "send", "(", "role", ")", "return", "super", "(", ")", ".", "delete", "(", "role", ",", "commit", ")" ]
38
2.75
def render_impl(self, template, context, **options): """ Inherited class must implement this! :param template: Template file path :param context: A dict or dict-like object to instantiate given template file :param options: Same options as :meth:`renders_impl` ...
[ "def", "render_impl", "(", "self", ",", "template", ",", "context", ",", "*", "*", "options", ")", ":", "ropts", "=", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "options", ".", "items", "(", ")", "if", "k", "!=", "\"safe\...
45.3
21.7
def sinc(self, high_pass_frequency=None, low_pass_frequency=None, left_t=None, left_n=None, right_t=None, right_n=None, attenuation=None, beta=None, phase=None, M=None, I=None, ...
[ "def", "sinc", "(", "self", ",", "high_pass_frequency", "=", "None", ",", "low_pass_frequency", "=", "None", ",", "left_t", "=", "None", ",", "left_n", "=", "None", ",", "right_t", "=", "None", ",", "right_n", "=", "None", ",", "attenuation", "=", "None"...
36.4
17.6875
def has(self, name, ignore_empty=False): """Return ``True`` if any parameter in the template is named *name*. With *ignore_empty*, ``False`` will be returned even if the template contains a parameter with the name *name*, if the parameter's value is empty. Note that a template may have ...
[ "def", "has", "(", "self", ",", "name", ",", "ignore_empty", "=", "False", ")", ":", "name", "=", "str", "(", "name", ")", ".", "strip", "(", ")", "for", "param", "in", "self", ".", "params", ":", "if", "param", ".", "name", ".", "strip", "(", ...
44.6
17.466667
def rdl_decomposition(T, k=None, norm='auto', ncv=None, reversible=False, mu=None): r"""Compute the decomposition into left and right eigenvectors. Parameters ---------- T : sparse matrix Transition matrix k : int (optional) Number of eigenvector/eigenvalue pairs norm: {'standar...
[ "def", "rdl_decomposition", "(", "T", ",", "k", "=", "None", ",", "norm", "=", "'auto'", ",", "ncv", "=", "None", ",", "reversible", "=", "False", ",", "mu", "=", "None", ")", ":", "if", "k", "is", "None", ":", "raise", "ValueError", "(", "\"Number...
38.98
21.42
def get_single_by_flags(self, flags): """Get the register info matching the flag. Raises ValueError if more than one are found.""" regs = list(self.get_by_flags(flags)) if len(regs) != 1: raise ValueError("Flags do not return unique resigter. {!r}", regs) return regs[0]
[ "def", "get_single_by_flags", "(", "self", ",", "flags", ")", ":", "regs", "=", "list", "(", "self", ".", "get_by_flags", "(", "flags", ")", ")", "if", "len", "(", "regs", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"Flags do not return unique resig...
44.142857
17
def validate(self): """ validate: Makes sure input question is valid Args: None Returns: boolean indicating if input question is valid """ try: assert self.question_type == exercises.INPUT_QUESTION, "Assumption Failed: Question should be input answer type" ...
[ "def", "validate", "(", "self", ")", ":", "try", ":", "assert", "self", ".", "question_type", "==", "exercises", ".", "INPUT_QUESTION", ",", "\"Assumption Failed: Question should be input answer type\"", "assert", "len", "(", "self", ".", "answers", ")", ">", "0",...
55.210526
27.789474
def __get_html(self, body=None): """ Returns the html content with given body tag content. :param body: Body tag content. :type body: unicode :return: Html. :rtype: unicode """ output = [] output.append("<html>") output.append("<head>") ...
[ "def", "__get_html", "(", "self", ",", "body", "=", "None", ")", ":", "output", "=", "[", "]", "output", ".", "append", "(", "\"<html>\"", ")", "output", ".", "append", "(", "\"<head>\"", ")", "for", "javascript", "in", "(", "self", ".", "__jquery_java...
32.71875
12.03125
def getElementsByAttr(self, attr, value): ''' getElementsByAttr - Get elements within this collection posessing a given attribute/value pair @param attr - Attribute name (lowercase) @param value - Matching value @return - TagCollection of all elements matching n...
[ "def", "getElementsByAttr", "(", "self", ",", "attr", ",", "value", ")", ":", "ret", "=", "TagCollection", "(", ")", "if", "len", "(", "self", ")", "==", "0", ":", "return", "ret", "attr", "=", "attr", ".", "lower", "(", ")", "_cmpFunc", "=", "lamb...
31.736842
23.736842
def results_from_cli(opts, load_samples=True, **kwargs): """Loads an inference result file along with any labels associated with it from the command line options. Parameters ---------- opts : ArgumentParser options The options from the command line. load_samples : bool, optional ...
[ "def", "results_from_cli", "(", "opts", ",", "load_samples", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# lists for files and samples from all input files", "fp_all", "=", "[", "]", "samples_all", "=", "[", "]", "input_files", "=", "opts", ".", "input_file...
32.108108
20.716216
def pause(path, service_names=None): ''' Pause running containers in the docker-compose file, service_names is a python list, if omitted pause all containers path Path where the docker-compose file is stored on the server service_names If specified will pause only the specified serv...
[ "def", "pause", "(", "path", ",", "service_names", "=", "None", ")", ":", "project", "=", "__load_project", "(", "path", ")", "debug_ret", "=", "{", "}", "result", "=", "{", "}", "if", "isinstance", "(", "project", ",", "dict", ")", ":", "return", "p...
35.542857
25.714286
def close( self, exc_info: Union[ None, bool, BaseException, Tuple[ "Optional[Type[BaseException]]", Optional[BaseException], Optional[TracebackType], ], ] = False, ) -> None: ...
[ "def", "close", "(", "self", ",", "exc_info", ":", "Union", "[", "None", ",", "bool", ",", "BaseException", ",", "Tuple", "[", "\"Optional[Type[BaseException]]\"", ",", "Optional", "[", "BaseException", "]", ",", "Optional", "[", "TracebackType", "]", ",", "...
33.842105
13.842105
def method_call(receiver, message, args, pseudo_type=None): '''A shortcut for a method call, expands a str receiver to a identifier''' if not isinstance(receiver, Node): receiver = local(receiver) return Node('method_call', receiver=receiver, message=message, args=args, pseudo_type=pseudo_type)
[ "def", "method_call", "(", "receiver", ",", "message", ",", "args", ",", "pseudo_type", "=", "None", ")", ":", "if", "not", "isinstance", "(", "receiver", ",", "Node", ")", ":", "receiver", "=", "local", "(", "receiver", ")", "return", "Node", "(", "'m...
51.833333
27.833333
def _compute_mean(self, C, mag, ztor, rrup): """ Compute mean value as in ``subroutine getGeom`` in ``hazgridXnga2.f`` """ gc0 = 0.2418 ci = 0.3846 gch = 0.00607 g4 = 1.7818 ge = 0.554 gm = 1.414 mean = ( gc0 + ci + ztor * gch ...
[ "def", "_compute_mean", "(", "self", ",", "C", ",", "mag", ",", "ztor", ",", "rrup", ")", ":", "gc0", "=", "0.2418", "ci", "=", "0.3846", "gch", "=", "0.00607", "g4", "=", "1.7818", "ge", "=", "0.554", "gm", "=", "1.414", "mean", "=", "(", "gc0",...
25.444444
19.888889
def CMOVNP(cpu, dest, src): """ Conditional move - Not parity/parity odd. Tests the status flags in the EFLAGS register and moves the source operand (second operand) to the destination operand (first operand) if the given test condition is true. :param cpu: current CPU....
[ "def", "CMOVNP", "(", "cpu", ",", "dest", ",", "src", ")", ":", "dest", ".", "write", "(", "Operators", ".", "ITEBV", "(", "dest", ".", "size", ",", "cpu", ".", "PF", "==", "False", ",", "src", ".", "read", "(", ")", ",", "dest", ".", "read", ...
37.461538
19.615385
def is_prime(n): """ Miller-Rabin primality test. Keep in mind that this is not a deterministic algorithm: if it return True, it means that n is probably a prime. Args: n (int): the integer to check Returns: True if n is probably a prime number, False if it is not Raises: ...
[ "def", "is_prime", "(", "n", ")", ":", "if", "not", "isinstance", "(", "n", ",", "int", ")", ":", "raise", "TypeError", "(", "\"Expecting an integer\"", ")", "if", "n", "<", "2", ":", "return", "False", "if", "n", "in", "__known_primes", ":", "return",...
24.512195
22.536585
def future(self, request_iterator, timeout=None, metadata=None, credentials=None): """Asynchronously invokes the underlying RPC on the client. Args: request_iterator: An ASYNC iterator that yields request values for the RPC. timeout: A...
[ "def", "future", "(", "self", ",", "request_iterator", ",", "timeout", "=", "None", ",", "metadata", "=", "None", ",", "credentials", "=", "None", ")", ":", "return", "_utils", ".", "wrap_future_call", "(", "self", ".", "_inner", ".", "future", "(", "_ut...
42
19.733333
def unproject(self, image_points): """Find (up to scale) 3D coordinate of an image point This is the inverse of the `project` function. The resulting 3D points are only valid up to an unknown scale. Parameters ---------------------- image_points : (2, N) ndarray ...
[ "def", "unproject", "(", "self", ",", "image_points", ")", ":", "undist_image_points", "=", "cv2", ".", "undistortPoints", "(", "image_points", ".", "T", ".", "reshape", "(", "1", ",", "-", "1", ",", "2", ")", ",", "self", ".", "camera_matrix", ",", "s...
38.631579
23.684211
def begin(self): """ Begin recording coverage information. """ log.debug("Coverage begin") self.skipModules = sys.modules.keys()[:] if self.coverErase: log.debug("Clearing previously collected coverage statistics") self.coverInstance.combine() ...
[ "def", "begin", "(", "self", ")", ":", "log", ".", "debug", "(", "\"Coverage begin\"", ")", "self", ".", "skipModules", "=", "sys", ".", "modules", ".", "keys", "(", ")", "[", ":", "]", "if", "self", ".", "coverErase", ":", "log", ".", "debug", "("...
37.769231
11
def get_build_logs_zip(self, project, build_id, **kwargs): """GetBuildLogsZip. Gets the logs for a build. :param str project: Project ID or project name :param int build_id: The ID of the build. :rtype: object """ route_values = {} if project is not None: ...
[ "def", "get_build_logs_zip", "(", "self", ",", "project", ",", "build_id", ",", "*", "*", "kwargs", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize",...
45.136364
16.5
def profile(): """View for editing a profile.""" # Create forms verification_form = VerificationForm(formdata=None, prefix="verification") profile_form = profile_form_factory() # Process forms form = request.form.get('submit', None) if form == 'profile': handle_profile_form(profile_...
[ "def", "profile", "(", ")", ":", "# Create forms", "verification_form", "=", "VerificationForm", "(", "formdata", "=", "None", ",", "prefix", "=", "\"verification\"", ")", "profile_form", "=", "profile_form_factory", "(", ")", "# Process forms", "form", "=", "requ...
33.235294
15.882353
def set_option(self, key, value): """Sets general options used by plugins and streams originating from this session object. :param key: key of the option :param value: value to set the option to **Available options**: ======================== =========================...
[ "def", "set_option", "(", "self", ",", "key", ",", "value", ")", ":", "# Backwards compatibility", "if", "key", "==", "\"rtmpdump\"", ":", "key", "=", "\"rtmp-rtmpdump\"", "elif", "key", "==", "\"rtmpdump-proxy\"", ":", "key", "=", "\"rtmp-proxy\"", "elif", "k...
44.368687
24.661616
def find(cls, device=None): """ Factory method that returns the requested :py:class:`USBDevice` device, or the first device. :param device: Tuple describing the USB device to open, as returned by find_all(). :type device: tuple :returns: :py:class...
[ "def", "find", "(", "cls", ",", "device", "=", "None", ")", ":", "if", "not", "have_pyftdi", ":", "raise", "ImportError", "(", "'The USBDevice class has been disabled due to missing requirement: pyftdi or pyusb.'", ")", "cls", ".", "find_all", "(", ")", "if", "len",...
34.038462
25.576923
def find_proc_date(header): """Search the HISTORY fields of a header looking for the FLIPS processing date. """ import string, re for h in header.ascardlist(): if h.key=="HISTORY": g=h.value if ( string.find(g,'FLIPS 1.0 -:') ): result=re.search('imred...
[ "def", "find_proc_date", "(", "header", ")", ":", "import", "string", ",", "re", "for", "h", "in", "header", ".", "ascardlist", "(", ")", ":", "if", "h", ".", "key", "==", "\"HISTORY\"", ":", "g", "=", "h", ".", "value", "if", "(", "string", ".", ...
35.25
12.4375
def evaluate(args): """ %prog evaluate prediction.bed reality.bed fastafile Make a truth table like: True False --- Reality True TP FP False FN TN |----Prediction Sn = TP / (all true in reality) = TP / (TP + FN) Sp = TP / (all true in prediction) = TP / ...
[ "def", "evaluate", "(", "args", ")", ":", "from", "jcvi", ".", "formats", ".", "sizes", "import", "Sizes", "p", "=", "OptionParser", "(", "evaluate", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--query\"", ",", "help", "=", "\"Chromosome location ...
28.644068
17.830508
def _valid_folder(self, base, name): """Return whether a folder can be searched.""" valid = True fullpath = os.path.join(base, name) if ( not self.recursive or ( self.folder_exclude_check is not None and not self.compare_directory(...
[ "def", "_valid_folder", "(", "self", ",", "base", ",", "name", ")", ":", "valid", "=", "True", "fullpath", "=", "os", ".", "path", ".", "join", "(", "base", ",", "name", ")", "if", "(", "not", "self", ".", "recursive", "or", "(", "self", ".", "fo...
36.6875
22.4375
def k_weights_int(self): """ Returns ------- ndarray Geometric k-point weights (number of arms of k-star in BZ). dtype='intc' shape=(irreducible_kpoints,) """ nk = np.prod(self.k_mesh) _weights = self.k_weights * nk wei...
[ "def", "k_weights_int", "(", "self", ")", ":", "nk", "=", "np", ".", "prod", "(", "self", ".", "k_mesh", ")", "_weights", "=", "self", ".", "k_weights", "*", "nk", "weights", "=", "np", ".", "rint", "(", "_weights", ")", ".", "astype", "(", "'intc'...
30.266667
14.933333
def _handle_request_exception(request): """Raise the proper exception based on the response""" try: data = request.json() except: data = {} code = request.status_code if code == requests.codes.bad: raise BadRequestException(response=data) ...
[ "def", "_handle_request_exception", "(", "request", ")", ":", "try", ":", "data", "=", "request", ".", "json", "(", ")", "except", ":", "data", "=", "{", "}", "code", "=", "request", ".", "status_code", "if", "code", "==", "requests", ".", "codes", "."...
29.842105
16.263158
def path_fraction_point(points, fraction): '''Computes the point which corresponds to the fraction of the path length along the piecewise linear curve which is constructed from the set of points. Args: points: an iterable of indexable objects with indices 0, 1, 2 correspoding to 3D cart...
[ "def", "path_fraction_point", "(", "points", ",", "fraction", ")", ":", "seg_id", ",", "offset", "=", "path_fraction_id_offset", "(", "points", ",", "fraction", ",", "relative_offset", "=", "True", ")", "return", "linear_interpolate", "(", "points", "[", "seg_id...
41.266667
24.2
def write_netrc(host, entity, key): """Add our host and key to .netrc""" if len(key) != 40: click.secho( 'API-key must be exactly 40 characters long: {} ({} chars)'.format(key, len(key))) return None try: normalized_host = host.split("/")[-1].split(":")[0] print("...
[ "def", "write_netrc", "(", "host", ",", "entity", ",", "key", ")", ":", "if", "len", "(", "key", ")", "!=", "40", ":", "click", ".", "secho", "(", "'API-key must be exactly 40 characters long: {} ({} chars)'", ".", "format", "(", "key", ",", "len", "(", "k...
37.8
14.25
def dataset_walker(datasets): """Walk through *datasets* and their ancillary data. Yields datasets and their parent. """ for dataset in datasets: yield dataset, None for anc_ds in dataset.attrs.get('ancillary_variables', []): try: anc_ds.attrs ...
[ "def", "dataset_walker", "(", "datasets", ")", ":", "for", "dataset", "in", "datasets", ":", "yield", "dataset", ",", "None", "for", "anc_ds", "in", "dataset", ".", "attrs", ".", "get", "(", "'ancillary_variables'", ",", "[", "]", ")", ":", "try", ":", ...
30
12.846154
def setup(self, glbls): """ Sets up the resource manager as modular functions. :param glbls | <dict> """ if not self.pluginPath() in sys.path: log.debug(self.pluginPath()) sys.path.append(self.pluginPath()) glbls['f...
[ "def", "setup", "(", "self", ",", "glbls", ")", ":", "if", "not", "self", ".", "pluginPath", "(", ")", "in", "sys", ".", "path", ":", "log", ".", "debug", "(", "self", ".", "pluginPath", "(", ")", ")", "sys", ".", "path", ".", "append", "(", "s...
34
9.615385
def bounds(self): """The bounds of the random variable. Set `self.i=0.95` to return the 95% interval if this is used for setting bounds on optimizers/etc. where infinite bounds may not be useful. """ return [scipy.stats.lognorm.interval(self.i, s, loc=0, scale=em) for s,...
[ "def", "bounds", "(", "self", ")", ":", "return", "[", "scipy", ".", "stats", ".", "lognorm", ".", "interval", "(", "self", ".", "i", ",", "s", ",", "loc", "=", "0", ",", "scale", "=", "em", ")", "for", "s", ",", "em", "in", "zip", "(", "self...
49.571429
28.714286
def center_origin(self): """Sets the origin to the center of the image.""" self.set_origin(Vector2(self.image.get_width() / 2.0, self.image.get_height() / 2.0))
[ "def", "center_origin", "(", "self", ")", ":", "self", ".", "set_origin", "(", "Vector2", "(", "self", ".", "image", ".", "get_width", "(", ")", "/", "2.0", ",", "self", ".", "image", ".", "get_height", "(", ")", "/", "2.0", ")", ")" ]
58
23
def _get_input(self, length): """! @brief Extract requested amount of data from the read buffer.""" self._buffer_lock.acquire() try: if length == -1: actualLength = len(self._buffer) else: actualLength = min(length, len(self._buffer)) ...
[ "def", "_get_input", "(", "self", ",", "length", ")", ":", "self", ".", "_buffer_lock", ".", "acquire", "(", ")", "try", ":", "if", "length", "==", "-", "1", ":", "actualLength", "=", "len", "(", "self", ".", "_buffer", ")", "else", ":", "actualLengt...
35.75
13.6875
def _pad(arr, n, dir='right'): """Pad an array with zeros along the first axis. Parameters ---------- n : int Size of the returned array in the first axis. dir : str Direction of the padding. Must be one 'left' or 'right'. """ assert dir in ('left', 'right') if n < 0: ...
[ "def", "_pad", "(", "arr", ",", "n", ",", "dir", "=", "'right'", ")", ":", "assert", "dir", "in", "(", "'left'", ",", "'right'", ")", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "\"'n' must be positive: {0}.\"", ".", "format", "(", "n", ")"...
26.621622
17.621622
def accept(self): """ This is the other part of the shutdown() workaround. Since servers create new sockets, we have to infect them with our magic. :) """ c, a = self.__dict__["conn"].accept() return (SSLWrapper(c), a)
[ "def", "accept", "(", "self", ")", ":", "c", ",", "a", "=", "self", ".", "__dict__", "[", "\"conn\"", "]", ".", "accept", "(", ")", "return", "(", "SSLWrapper", "(", "c", ")", ",", "a", ")" ]
33.375
10.375
def beginlock(self, container): "Start to acquire lock in another routine. Call trylock or lock later to acquire the lock. Call unlock to cancel the lock routine" if self.locked: return True if self.lockroutine: return False self.lockroutine = container.subroutine...
[ "def", "beginlock", "(", "self", ",", "container", ")", ":", "if", "self", ".", "locked", ":", "return", "True", "if", "self", ".", "lockroutine", ":", "return", "False", "self", ".", "lockroutine", "=", "container", ".", "subroutine", "(", "self", ".", ...
47.125
28.375
def get_composition_query_session_for_repository(self, repository_id): """Gets a composition query session for the given repository. arg: repository_id (osid.id.Id): the ``Id`` of the repository return: (osid.repository.CompositionQuerySession) - a ``CompositionQuerySession``...
[ "def", "get_composition_query_session_for_repository", "(", "self", ",", "repository_id", ")", ":", "if", "not", "self", ".", "supports_composition_query", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "##", "# Also include check to see if the catalo...
48.826087
21.434783
def load_app(self, app): """ Tries to load an initial data class for a specified app. If the specified file does not exist, an error will be raised. If the class does exist, but it isn't a subclass of `BaseInitialData` then None will be returned. :param app: The name of the app i...
[ "def", "load_app", "(", "self", ",", "app", ")", ":", "if", "self", ".", "loaded_apps", ".", "get", "(", "app", ")", ":", "return", "self", ".", "loaded_apps", ".", "get", "(", "app", ")", "self", ".", "loaded_apps", "[", "app", "]", "=", "None", ...
45.285714
20.52381
def _unquote(self, value): """Return an unquoted version of a value""" if not value: # should only happen during parsing of lists raise SyntaxError if (value[0] == value[-1]) and (value[0] in ('"', "'")): value = value[1:-1] return value
[ "def", "_unquote", "(", "self", ",", "value", ")", ":", "if", "not", "value", ":", "# should only happen during parsing of lists", "raise", "SyntaxError", "if", "(", "value", "[", "0", "]", "==", "value", "[", "-", "1", "]", ")", "and", "(", "value", "["...
37.25
14.125
def hxbyterle_decode(output_size, data): """Decode HxRLE data stream If C-extension is not compiled it will use a (slower) Python equivalent :param int output_size: the number of items when ``data`` is uncompressed :param str data: a raw stream of data to be unpacked :return numpy.array ou...
[ "def", "hxbyterle_decode", "(", "output_size", ",", "data", ")", ":", "output", "=", "byterle_decoder", "(", "data", ",", "output_size", ")", "assert", "len", "(", "output", ")", "==", "output_size", "return", "output" ]
38.25
17.583333
def get_SCAT(points, low_bound, high_bound, x_max, y_max): """ runs SCAT test and returns boolean """ # iterate through all relevant points and see if any of them fall outside of your SCAT box SCAT = True for point in points: result = in_SCAT_box(point[0], point[1], low_bound, high_bound...
[ "def", "get_SCAT", "(", "points", ",", "low_bound", ",", "high_bound", ",", "x_max", ",", "y_max", ")", ":", "# iterate through all relevant points and see if any of them fall outside of your SCAT box", "SCAT", "=", "True", "for", "point", "in", "points", ":", "result",...
35.916667
18.083333
def tensor_components_to_use(mrr, mtt, mpp, mrt, mrp, mtp): ''' Converts components to Up, South, East definition:: USE = [[mrr, mrt, mrp], [mtt, mtt, mtp], [mrp, mtp, mpp]] ''' return np.array([[mrr, mrt, mrp], [mrt, mtt, mtp], [mrp, mtp, mpp]])
[ "def", "tensor_components_to_use", "(", "mrr", ",", "mtt", ",", "mpp", ",", "mrt", ",", "mrp", ",", "mtp", ")", ":", "return", "np", ".", "array", "(", "[", "[", "mrr", ",", "mrt", ",", "mrp", "]", ",", "[", "mrt", ",", "mtt", ",", "mtp", "]", ...
31.555556
23.111111
def restore_configuration_files(self): """ restore a previously saved postgresql.conf """ try: for f in self._configuration_to_save: config_file = os.path.join(self._config_dir, f) backup_file = os.path.join(self._data_dir, f + '.backup') if no...
[ "def", "restore_configuration_files", "(", "self", ")", ":", "try", ":", "for", "f", "in", "self", ".", "_configuration_to_save", ":", "config_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_config_dir", ",", "f", ")", "backup_file", "=", ...
54.357143
19.785714
def exception_wrapper(f): """Decorator to convert dbus exception to pympris exception.""" @wraps(f) def wrapper(*args, **kwds): try: return f(*args, **kwds) except dbus.exceptions.DBusException as err: _args = err.args raise PyMPRISException(*_args) re...
[ "def", "exception_wrapper", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwds", ")", ":", "try", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwds", ")", "except", "dbus", ".", ...
32.3
13.2
def success(self, buf, newline=True): """ Same as `write`, but adds success coloring if enabled. `buf` Data buffer to write. `newline` Append newline character to buffer before writing. """ if self._colored: buf = self.ESC...
[ "def", "success", "(", "self", ",", "buf", ",", "newline", "=", "True", ")", ":", "if", "self", ".", "_colored", ":", "buf", "=", "self", ".", "ESCAPE_GREEN", "+", "buf", "+", "self", ".", "ESCAPE_CLEAR", "self", ".", "write", "(", "buf", ",", "new...
29
18.307692
def fit(self, X, chunks): """Learn the RCA model. Parameters ---------- data : (n x d) data matrix Each row corresponds to a single instance chunks : (n,) array of ints When ``chunks[i] == -1``, point i doesn't belong to any chunklet. When ``chunks[i] == j``, point i belongs...
[ "def", "fit", "(", "self", ",", "X", ",", "chunks", ")", ":", "X", "=", "self", ".", "_prepare_inputs", "(", "X", ",", "ensure_min_samples", "=", "2", ")", "# PCA projection to remove noise and redundant information.", "if", "self", ".", "pca_comps", "is", "no...
33.136364
19.818182
def doubleclickrowindex(self, window_name, object_name, row_index, col_index=0): """ Double click row matching given text @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: O...
[ "def", "doubleclickrowindex", "(", "self", ",", "window_name", ",", "object_name", ",", "row_index", ",", "col_index", "=", "0", ")", ":", "object_handle", "=", "self", ".", "_get_object_handle", "(", "window_name", ",", "object_name", ")", "if", "not", "objec...
41.483871
16.451613
def tokenize(self, docs): """ The first pass consists of converting documents into "transactions" (sets of their tokens) and the initial frequency/support filtering. Then iterate until we close in on a final set. `docs` can be any iterator or generator so long as it yie...
[ "def", "tokenize", "(", "self", ",", "docs", ")", ":", "if", "self", ".", "min_sup", "<", "1", "/", "len", "(", "docs", ")", ":", "raise", "Exception", "(", "'`min_sup` must be greater than or equal to `1/len(docs)`.'", ")", "# First pass", "candidates", "=", ...
37.880952
22.071429
def factory_chat(js_obj, driver=None): """Factory function for creating appropriate object given selenium JS object""" if js_obj["kind"] not in ["chat", "group", "broadcast"]: raise AssertionError("Expected chat, group or broadcast object, got {0}".format(js_obj["kind"])) if js_obj["isGroup"]: ...
[ "def", "factory_chat", "(", "js_obj", ",", "driver", "=", "None", ")", ":", "if", "js_obj", "[", "\"kind\"", "]", "not", "in", "[", "\"chat\"", ",", "\"group\"", ",", "\"broadcast\"", "]", ":", "raise", "AssertionError", "(", "\"Expected chat, group or broadca...
38.833333
19.416667
def copy_groups_to_folder(dicom_groups, folder_path, groupby_field_name): """Copy the DICOM file groups to folder_path. Each group will be copied into a subfolder with named given by groupby_field. Parameters ---------- dicom_groups: boyle.dicom.sets.DicomFileSet folder_path: str Path to ...
[ "def", "copy_groups_to_folder", "(", "dicom_groups", ",", "folder_path", ",", "groupby_field_name", ")", ":", "if", "dicom_groups", "is", "None", "or", "not", "dicom_groups", ":", "raise", "ValueError", "(", "'Expected a boyle.dicom.sets.DicomFileSet.'", ")", "if", "n...
34.162791
19.209302
def set_objective(self, objective, extraobjexpr=None): """Set or change the objective function of the polynomial optimization problem. :param objective: Describes the objective function. :type objective: :class:`sympy.core.expr.Expr` :param extraobjexpr: Optional parameter of a ...
[ "def", "set_objective", "(", "self", ",", "objective", ",", "extraobjexpr", "=", "None", ")", ":", "if", "objective", "is", "not", "None", "and", "self", ".", "matrix_var_dim", "is", "not", "None", ":", "facvar", "=", "self", ".", "__get_trace_facvar", "("...
49.409091
18.545455
def query_remote_ref(self, remote, ref): """Query remote repo about given ref. :return: ``('tag', sha)`` if ref is a tag in remote ``('branch', sha)`` if ref is branch (aka "head") in remote ``(None, ref)`` if ref does not exist in remote. This happens ...
[ "def", "query_remote_ref", "(", "self", ",", "remote", ",", "ref", ")", ":", "out", "=", "self", ".", "log_call", "(", "[", "'git'", ",", "'ls-remote'", ",", "remote", ",", "ref", "]", ",", "cwd", "=", "self", ".", "cwd", ",", "callwith", "=", "sub...
49.333333
14.333333
def jdn_to_gdate(jdn): """ Convert from the Julian day to the Gregorian day. Algorithm from 'Julian and Gregorian Day Numbers' by Peter Meyer. Return: day, month, year """ # pylint: disable=invalid-name # The algorithm is a verbatim copy from Peter Meyer's article # No explanation in t...
[ "def", "jdn_to_gdate", "(", "jdn", ")", ":", "# pylint: disable=invalid-name", "# The algorithm is a verbatim copy from Peter Meyer's article", "# No explanation in the article is given for the variables", "# Hence the exceptions for pylint and for flake8 (E741)", "l", "=", "jdn", "+", "...
32.92
16.92
def p_suffix(self, length=None, elipsis=False): "Return the rest of the input" if length is not None: result = self.input[self.pos:self.pos + length] if elipsis and len(result) == length: result += "..." return result return self.input[self.pos...
[ "def", "p_suffix", "(", "self", ",", "length", "=", "None", ",", "elipsis", "=", "False", ")", ":", "if", "length", "is", "not", "None", ":", "result", "=", "self", ".", "input", "[", "self", ".", "pos", ":", "self", ".", "pos", "+", "length", "]...
39.375
9.375
def name(self): """ Application name. It's used as a process name. """ try: return self.config_parser.get('application', 'name') except CONFIGPARSER_EXC: return super(IniConfig, self).name
[ "def", "name", "(", "self", ")", ":", "try", ":", "return", "self", ".", "config_parser", ".", "get", "(", "'application'", ",", "'name'", ")", "except", "CONFIGPARSER_EXC", ":", "return", "super", "(", "IniConfig", ",", "self", ")", ".", "name" ]
30.625
13.125
def com_adobe_fonts_check_cff_call_depth(ttFont): """Is the CFF subr/gsubr call depth > 10?""" any_failures = False cff = ttFont['CFF '].cff for top_dict in cff.topDictIndex: if hasattr(top_dict, 'FDArray'): for fd_index, font_dict in enumerate(top_dict.FDArray): if ...
[ "def", "com_adobe_fonts_check_cff_call_depth", "(", "ttFont", ")", ":", "any_failures", "=", "False", "cff", "=", "ttFont", "[", "'CFF '", "]", ".", "cff", "for", "top_dict", "in", "cff", ".", "topDictIndex", ":", "if", "hasattr", "(", "top_dict", ",", "'FDA...
38.84
14.92
def validateEmail(value, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None, excMsg=None): """Raises ValidationException if value is not an email address. Returns the value argument. * value (str): The value being validated as an email address. * blank (bool): If True, a blank strin...
[ "def", "validateEmail", "(", "value", ",", "blank", "=", "False", ",", "strip", "=", "None", ",", "allowlistRegexes", "=", "None", ",", "blocklistRegexes", "=", "None", ",", "excMsg", "=", "None", ")", ":", "# Reuse the logic in validateRegex()", "try", ":", ...
58.555556
36.407407