text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def ceil(a, b): """ Divide a / b and return the biggest integer close to the quotient. :param a: a number :param b: a positive number :returns: the biggest integer close to the quotient """ assert b > 0, b return int(math.ceil(float(a) / b))
[ "def", "ceil", "(", "a", ",", "b", ")", ":", "assert", "b", ">", "0", ",", "b", "return", "int", "(", "math", ".", "ceil", "(", "float", "(", "a", ")", "/", "b", ")", ")" ]
22
18.923077
def _extract(archive, compression, cmd, format, verbosity, outdir): """Extract an LZMA or XZ archive with the lzma Python module.""" targetname = util.get_single_outfile(outdir, archive) try: with lzma.LZMAFile(archive, **_get_lzma_options(format)) as lzmafile: with open(targetname, 'wb'...
[ "def", "_extract", "(", "archive", ",", "compression", ",", "cmd", ",", "format", ",", "verbosity", ",", "outdir", ")", ":", "targetname", "=", "util", ".", "get_single_outfile", "(", "outdir", ",", "archive", ")", "try", ":", "with", "lzma", ".", "LZMAF...
47.285714
17.714286
def en004(self, value=None): """ Corresponds to IDD Field `en004` mean coincident dry-bulb temperature to Enthalpy corresponding to 0.4% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `en004` Unit: kJ/kg if...
[ "def", "en004", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "not", "None", ":", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "'value {} need to be of type float '"...
35.636364
20.272727
def addLayer(self,layer,z=-1): """ Adds a new layer to the stack, optionally at the specified z-value. ``layer`` must be an instance of Layer or subclasses. ``z`` can be used to override the index of the layer in the stack. Defaults to ``-1`` for appending. """ ...
[ "def", "addLayer", "(", "self", ",", "layer", ",", "z", "=", "-", "1", ")", ":", "# Adds a new layer to the stack, optionally at the specified z-value", "# The z-value is the index this layer should be inserted in, or -1 for appending", "if", "not", "isinstance", "(", "layer", ...
42.9375
22.6875
def _check_value_recursively(key, val, haystack): """ Check if there is key _key_ with value _val_ in the given dictionary. ..warning: This is geared at JSON dictionaries, so some corner cases are ignored, we assume all iterables are either arrays or dicts """ if isinstance(haystack,...
[ "def", "_check_value_recursively", "(", "key", ",", "val", ",", "haystack", ")", ":", "if", "isinstance", "(", "haystack", ",", "list", ")", ":", "return", "any", "(", "[", "_check_value_recursively", "(", "key", ",", "val", ",", "l", ")", "for", "l", ...
41.529412
20
def check_ly(text): """Check the text.""" err = "garner.phrasal_adjectives.ly" msg = u"""No hyphen is necessary in phrasal adjectives with an adverb ending in -ly, unless the -ly adverb is part of a longer phrase""" regex = "\s[^\s-]+ly-" return existence_check(text, [r...
[ "def", "check_ly", "(", "text", ")", ":", "err", "=", "\"garner.phrasal_adjectives.ly\"", "msg", "=", "u\"\"\"No hyphen is necessary in phrasal adjectives with an adverb\n ending in -ly, unless the -ly adverb is part of a longer\n phrase\"\"\"", "regex", "=", "\...
35.181818
16
def load_json_dct( dct, record_store=None, schema=None, loader=from_json_compatible ): """ Create a Record instance from a json-compatible dictionary The dictionary values should have types that are json compatible, as if just loaded from a json serialized record string. ...
[ "def", "load_json_dct", "(", "dct", ",", "record_store", "=", "None", ",", "schema", "=", "None", ",", "loader", "=", "from_json_compatible", ")", ":", "if", "schema", "is", "None", ":", "if", "record_store", "is", "None", ":", "record_store", "=", "auto_s...
30.26087
19.891304
def _get_fixed_params(im): """ Parameters that the user has no influence on. Mostly chosen bases on the input images. """ p = Parameters() if not isinstance(im, np.ndarray): return p # Dimension of the inputs p.FixedImageDimension = im.ndim p.MovingImageDimension =...
[ "def", "_get_fixed_params", "(", "im", ")", ":", "p", "=", "Parameters", "(", ")", "if", "not", "isinstance", "(", "im", ",", "np", ".", "ndarray", ")", ":", "return", "p", "# Dimension of the inputs", "p", ".", "FixedImageDimension", "=", "im", ".", "nd...
23.875
17.291667
def get_jira_key_from_scenario(scenario): """Extract Jira Test Case key from scenario tags. Two tag formats are allowed: @jira('PROJECT-32') @jira=PROJECT-32 :param scenario: behave scenario :returns: Jira test case key """ jira_regex = re.compile('jira[=\(\']*([A-Z]+\-[0-9]+)[\'\)]*$')...
[ "def", "get_jira_key_from_scenario", "(", "scenario", ")", ":", "jira_regex", "=", "re", ".", "compile", "(", "'jira[=\\(\\']*([A-Z]+\\-[0-9]+)[\\'\\)]*$'", ")", "for", "tag", "in", "scenario", ".", "tags", ":", "match", "=", "jira_regex", ".", "search", "(", "t...
29.533333
12.866667
def update_font(self): """Update font from Preferences""" color_scheme = self.get_color_scheme() font = self.get_plugin_font() for editor in self.editors: editor.set_font(font, color_scheme)
[ "def", "update_font", "(", "self", ")", ":", "color_scheme", "=", "self", ".", "get_color_scheme", "(", ")", "font", "=", "self", ".", "get_plugin_font", "(", ")", "for", "editor", "in", "self", ".", "editors", ":", "editor", ".", "set_font", "(", "font"...
39
6.166667
async def register(self): """Register library device id and get initial device list. """ url = '{}/Sessions'.format(self.construct_url(API_URL)) params = {'api_key': self._api_key} reg = await self.api_request(url, params) if reg is None: self._registered = False ...
[ "async", "def", "register", "(", "self", ")", ":", "url", "=", "'{}/Sessions'", ".", "format", "(", "self", ".", "construct_url", "(", "API_URL", ")", ")", "params", "=", "{", "'api_key'", ":", "self", ".", "_api_key", "}", "reg", "=", "await", "self",...
38.722222
18.833333
def bookWS(symbols=None, on_data=None): '''https://iextrading.com/developer/docs/#book51''' symbols = _strToList(symbols) sendinit = ({'symbols': symbols, 'channels': ['book']},) return _stream(_wsURL('deep'), sendinit, on_data)
[ "def", "bookWS", "(", "symbols", "=", "None", ",", "on_data", "=", "None", ")", ":", "symbols", "=", "_strToList", "(", "symbols", ")", "sendinit", "=", "(", "{", "'symbols'", ":", "symbols", ",", "'channels'", ":", "[", "'book'", "]", "}", ",", ")",...
48
11.2
def addProfile(self, profile): """ Adds the inputed profile as an action to the toolbar. :param profile | <projexui.widgets.xviewwidget.XViewProfile> """ # use the existing version for exist in self.profiles(): if exist.name() == profile....
[ "def", "addProfile", "(", "self", ",", "profile", ")", ":", "# use the existing version\r", "for", "exist", "in", "self", ".", "profiles", "(", ")", ":", "if", "exist", ".", "name", "(", ")", "==", "profile", ".", "name", "(", ")", ":", "if", "exist", ...
34.157895
13.105263
def get_advices(target, ctx=None, local=False): """Get element advices. :param target: target from where get advices. :param ctx: ctx from where get target. :param bool local: If ctx is not None or target is a method, if True (False by default) get only target advices without resolving super ...
[ "def", "get_advices", "(", "target", ",", "ctx", "=", "None", ",", "local", "=", "False", ")", ":", "result", "=", "[", "]", "if", "is_intercepted", "(", "target", ")", ":", "# find ctx if not given", "if", "ctx", "is", "None", ":", "ctx", "=", "find_c...
46.052632
18.736842
def save_instances(self, path, binary=False, mode=SaveMode.LOCAL_SAVE): """Save the instances in the system to the specified file. If binary is True, the instances will be saved in binary format. The Python equivalent of the CLIPS save-instances command. """ if binary: ...
[ "def", "save_instances", "(", "self", ",", "path", ",", "binary", "=", "False", ",", "mode", "=", "SaveMode", ".", "LOCAL_SAVE", ")", ":", "if", "binary", ":", "ret", "=", "lib", ".", "EnvBinarySaveInstances", "(", "self", ".", "_env", ",", "path", "."...
33.75
25.4375
def execute(self): """ Builds, sends and handles the responses to all requests listed in C{self.requests}. """ requests = self.requests[:] for r in requests: self.removeRequest(r) body = remoting.encode(self.getAMFRequest(requests), stric...
[ "def", "execute", "(", "self", ")", ":", "requests", "=", "self", ".", "requests", "[", ":", "]", "for", "r", "in", "requests", ":", "self", ".", "removeRequest", "(", "r", ")", "body", "=", "remoting", ".", "encode", "(", "self", ".", "getAMFRequest...
26.636364
20.363636
def canvasReleaseEvent(self, e): """Handle canvas release events has finished capturing e. :param e: A Qt event object. :type: QEvent """ _ = e # NOQA self.is_emitting_point = False self.rectangle_created.emit()
[ "def", "canvasReleaseEvent", "(", "self", ",", "e", ")", ":", "_", "=", "e", "# NOQA", "self", ".", "is_emitting_point", "=", "False", "self", ".", "rectangle_created", ".", "emit", "(", ")" ]
29
10.555556
def validate(self, request): """ validate method for %ParameterSet Since the introduction of ResponseFieldListParser, the parameter _response_field_list will be ignored, this is a prestans reserved parameter, and cannot be used by apps. :param request: The request object to be ...
[ "def", "validate", "(", "self", ",", "request", ")", ":", "validated_parameter_set", "=", "self", ".", "__class__", "(", ")", "# Inspects the attributes of a parameter set and tries to validate the input", "for", "attribute_name", ",", "type_instance", "in", "self", ".", ...
44.142857
24.492063
def constant_q_lengths(sr, fmin, n_bins=84, bins_per_octave=12, tuning=0.0, window='hann', filter_scale=1): r'''Return length of each filter in a constant-Q basis. Parameters ---------- sr : number > 0 [scalar] Audio sampling rate fmin : float > 0 [scalar] Mi...
[ "def", "constant_q_lengths", "(", "sr", ",", "fmin", ",", "n_bins", "=", "84", ",", "bins_per_octave", "=", "12", ",", "tuning", "=", "0.0", ",", "window", "=", "'hann'", ",", "filter_scale", "=", "1", ")", ":", "if", "fmin", "<=", "0", ":", "raise",...
26.583333
24.555556
def clear(name): ''' Clear the namespace from the register USAGE: .. code-block:: yaml clearns: reg.clear: - name: myregister ''' ret = {'name': name, 'changes': {}, 'comment': '', 'result': True} if name in __reg__: _...
[ "def", "clear", "(", "name", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", ",", "'result'", ":", "True", "}", "if", "name", "in", "__reg__", ":", "__reg__", "[", "name", "]", ".", ...
17.736842
22.368421
def label_video( self, parent, basic_config, feature, video_classification_config=None, object_detection_config=None, object_tracking_config=None, event_config=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gap...
[ "def", "label_video", "(", "self", ",", "parent", ",", "basic_config", ",", "feature", ",", "video_classification_config", "=", "None", ",", "object_detection_config", "=", "None", ",", "object_tracking_config", "=", "None", ",", "event_config", "=", "None", ",", ...
48.527778
28.097222
def add(backend, variable, value, force=False): '''add the variable to the config ''' print('[add]') settings = read_client_secrets() # If the variable begins with the SREGISTRY_<CLIENT> don't add it prefix = 'SREGISTRY_%s_' %backend.upper() if not variable.startswith(prefix): varia...
[ "def", "add", "(", "backend", ",", "variable", ",", "value", ",", "force", "=", "False", ")", ":", "print", "(", "'[add]'", ")", "settings", "=", "read_client_secrets", "(", ")", "# If the variable begins with the SREGISTRY_<CLIENT> don't add it", "prefix", "=", "...
30.928571
18.5
def dumps(cls, value): '''returns mapping typed serialized `value`.''' if not hasattr(value, '__getitem__') or not hasattr(value, 'iteritems'): value = {cls.sentinel: value} return value
[ "def", "dumps", "(", "cls", ",", "value", ")", ":", "if", "not", "hasattr", "(", "value", ",", "'__getitem__'", ")", "or", "not", "hasattr", "(", "value", ",", "'iteritems'", ")", ":", "value", "=", "{", "cls", ".", "sentinel", ":", "value", "}", "...
40
18.8
def Lorentzian(x, a, x0, sigma, y0): """Lorentzian peak Inputs: ------- ``x``: independent variable ``a``: scaling factor (extremal value) ``x0``: center ``sigma``: half width at half maximum ``y0``: additive constant Formula: -------- ``a/(1+((x-x0)...
[ "def", "Lorentzian", "(", "x", ",", "a", ",", "x0", ",", "sigma", ",", "y0", ")", ":", "return", "a", "/", "(", "1", "+", "(", "(", "x", "-", "x0", ")", "/", "sigma", ")", "**", "2", ")", "+", "y0" ]
23.625
15.6875
def inflate_bbox(self): """ Realign the left and right edges of the bounding box such that they are inflated to align modulo 4. This method is optional, and used mainly to accommodate devices with COM/SEG GDDRAM structures that store pixels in 4-bit nibbles. """ ...
[ "def", "inflate_bbox", "(", "self", ")", ":", "left", ",", "top", ",", "right", ",", "bottom", "=", "self", ".", "bounding_box", "self", ".", "bounding_box", "=", "(", "left", "&", "0xFFFC", ",", "top", ",", "right", "if", "right", "%", "4", "==", ...
33.9375
20.0625
def max_item(self): """Get item with max key of tree, raises ValueError if tree is empty.""" if self.is_empty(): raise ValueError("Tree is empty") node = self._root while node.right is not None: node = node.right return node.key, node.value
[ "def", "max_item", "(", "self", ")", ":", "if", "self", ".", "is_empty", "(", ")", ":", "raise", "ValueError", "(", "\"Tree is empty\"", ")", "node", "=", "self", ".", "_root", "while", "node", ".", "right", "is", "not", "None", ":", "node", "=", "no...
37.125
9.125
def convert_all(cls, records): """Convert the list of bibrecs into one MARCXML. >>> from harvestingkit.bibrecord import BibRecordPackage >>> from harvestingkit.inspire_cds_package import Inspire2CDS >>> bibrecs = BibRecordPackage("inspire.xml") >>> bibrecs.parse() >>> xm...
[ "def", "convert_all", "(", "cls", ",", "records", ")", ":", "out", "=", "[", "\"<collection>\"", "]", "for", "rec", "in", "records", ":", "conversion", "=", "cls", "(", "rec", ")", "out", ".", "append", "(", "conversion", ".", "convert", "(", ")", ")...
34.05
15.4
def join(self, *groupnames): """Return an index group that contains atoms from all *groupnames*. The method will silently ignore any groups that are not in the index. **Example** Always make a solvent group from water and ions, even if not all ions are present in all ...
[ "def", "join", "(", "self", ",", "*", "groupnames", ")", ":", "return", "self", ".", "_sum", "(", "[", "self", "[", "k", "]", "for", "k", "in", "groupnames", "if", "k", "in", "self", "]", ")" ]
33
23.785714
def request(key, features, query, timeout=5): """Make an API request :param string key: API key to use :param list features: features to request. It must be a subset of :data:`FEATURES` :param string query: query to send :param integer timeout: timeout of the request :returns: result of the API...
[ "def", "request", "(", "key", ",", "features", ",", "query", ",", "timeout", "=", "5", ")", ":", "data", "=", "{", "}", "data", "[", "'key'", "]", "=", "key", "data", "[", "'features'", "]", "=", "'/'", ".", "join", "(", "[", "f", "for", "f", ...
33.263158
16.684211
def __ensure_gcloud(): """The *NIX installer is not guaranteed to add the google cloud sdk to the user's PATH (the Windows installer does). This ensures that if the default directory for the executables exists, it is added to the PATH for the duration of this package's use.""" if which('gcloud') is ...
[ "def", "__ensure_gcloud", "(", ")", ":", "if", "which", "(", "'gcloud'", ")", "is", "None", ":", "gcloud_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", ",", "'google-cloud-sdk'", ",", "'bin'", ...
49.071429
15.071429
def htmlReadMemory(buffer, size, URL, encoding, options): """parse an XML in-memory document and build a tree. """ ret = libxml2mod.htmlReadMemory(buffer, size, URL, encoding, options) if ret is None:raise treeError('htmlReadMemory() failed') return xmlDoc(_obj=ret)
[ "def", "htmlReadMemory", "(", "buffer", ",", "size", ",", "URL", ",", "encoding", ",", "options", ")", ":", "ret", "=", "libxml2mod", ".", "htmlReadMemory", "(", "buffer", ",", "size", ",", "URL", ",", "encoding", ",", "options", ")", "if", "ret", "is"...
55.6
16.8
def check_interface_is_subset(circuit1, circuit2): """ Checks that the interface of circuit1 is a subset of circuit2 Subset is defined as circuit2 contains all the ports of circuit1. Ports are matched by name comparison, then the types are checked to see if one could be converted to another. ""...
[ "def", "check_interface_is_subset", "(", "circuit1", ",", "circuit2", ")", ":", "circuit1_port_names", "=", "circuit1", ".", "interface", ".", "ports", ".", "keys", "(", ")", "for", "name", "in", "circuit1_port_names", ":", "if", "name", "not", "in", "circuit2...
52.428571
20.904762
def get_label(self): """ get label rdd from ImageFrame """ tensor_rdd = callBigDlFunc(self.bigdl_type, "distributedImageFrameToLabelTensorRdd", self.value) return tensor_rdd.map(lambda tensor: tensor.to_ndarray())
[ "def", "get_label", "(", "self", ")", ":", "tensor_rdd", "=", "callBigDlFunc", "(", "self", ".", "bigdl_type", ",", "\"distributedImageFrameToLabelTensorRdd\"", ",", "self", ".", "value", ")", "return", "tensor_rdd", ".", "map", "(", "lambda", "tensor", ":", "...
41.333333
18.666667
def _load_permissions(campus, calendarid, resp_fragment, permission_list): """ :return: a list of sorted trumba.Permission objects None if error, [] if not exists """ for record in resp_fragment: if not _is_valid_email(record['Email']): # skip the non UW users ...
[ "def", "_load_permissions", "(", "campus", ",", "calendarid", ",", "resp_fragment", ",", "permission_list", ")", ":", "for", "record", "in", "resp_fragment", ":", "if", "not", "_is_valid_email", "(", "record", "[", "'Email'", "]", ")", ":", "# skip the non UW us...
36.25
9.25
def classify_tangent_intersection( intersection, nodes1, tangent1, nodes2, tangent2 ): """Helper for func:`classify_intersection` at tangencies. .. note:: This is a helper used only by :func:`classify_intersection`. Args: intersection (.Intersection): An intersection object. no...
[ "def", "classify_tangent_intersection", "(", "intersection", ",", "nodes1", ",", "tangent1", ",", "nodes2", ",", "tangent2", ")", ":", "# Each array is 2 x 1 (i.e. a column vector), we want the vector", "# dot product.", "dot_prod", "=", "np", ".", "vdot", "(", "tangent1"...
37.380282
22.478873
def mssql_transaction_count(engine_or_conn: Union[Connection, Engine]) -> int: """ For Microsoft SQL Server specifically: fetch the value of the ``TRANCOUNT`` variable (see e.g. https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql?view=sql-server-2017). Returns ``None`` if it ...
[ "def", "mssql_transaction_count", "(", "engine_or_conn", ":", "Union", "[", "Connection", ",", "Engine", "]", ")", "->", "int", ":", "sql", "=", "\"SELECT @@TRANCOUNT\"", "with", "contextlib", ".", "closing", "(", "engine_or_conn", ".", "execute", "(", "sql", ...
46.333333
20.333333
def getcomments(object): """Get lines of comments immediately preceding an object's source code.""" try: lines, lnum = findsource(object) except IOError: return None if ismodule(object): # Look for a comment block at the top of the file. start = 0 if lines and lines[0][:2] == '#...
[ "def", "getcomments", "(", "object", ")", ":", "try", ":", "lines", ",", "lnum", "=", "findsource", "(", "object", ")", "except", "IOError", ":", "return", "None", "if", "ismodule", "(", "object", ")", ":", "# Look for a comment block at the top of the file.", ...
43.333333
17.179487
def walk_rows(self, mapping=identity): """Iterate over rows. :return: an iterator over :class:`rows <RowsInGrid>` :param mapping: funcion to map the result, see :meth:`walk_instructions` for an example usage """ row_in_grid = self._walk.row_in_grid return map(l...
[ "def", "walk_rows", "(", "self", ",", "mapping", "=", "identity", ")", ":", "row_in_grid", "=", "self", ".", "_walk", ".", "row_in_grid", "return", "map", "(", "lambda", "row", ":", "mapping", "(", "row_in_grid", "(", "row", ")", ")", ",", "self", ".",...
40.111111
13.888889
def read_geo(fid, key): """Read geolocation and related datasets.""" dsid = GEO_NAMES[key.name] add_epoch = False if "time" in key.name: days = fid["/L1C/" + dsid["day"]].value msecs = fid["/L1C/" + dsid["msec"]].value data = _form_datetimes(days, msecs) add_epoch = True ...
[ "def", "read_geo", "(", "fid", ",", "key", ")", ":", "dsid", "=", "GEO_NAMES", "[", "key", ".", "name", "]", "add_epoch", "=", "False", "if", "\"time\"", "in", "key", ".", "name", ":", "days", "=", "fid", "[", "\"/L1C/\"", "+", "dsid", "[", "\"day\...
31.2
17.1
def load_config(files=None, root_path=None, local_path=None): """Load the configuration from specified files.""" config = cfg.ConfigOpts() config.register_opts([ cfg.Opt('root_path', default=root_path), cfg.Opt('local_path', default=local_path), ]) # XXX register actual config group...
[ "def", "load_config", "(", "files", "=", "None", ",", "root_path", "=", "None", ",", "local_path", "=", "None", ")", ":", "config", "=", "cfg", ".", "ConfigOpts", "(", ")", "config", ".", "register_opts", "(", "[", "cfg", ".", "Opt", "(", "'root_path'"...
35.923077
15.923077
def instance(): """Return an PyVabamorf instance. It returns the previously initialized instance or creates a new one if nothing exists. Also creates new instance in case the process has been forked. """ if not hasattr(Vabamorf, 'pid') or Vabamorf.pid != os.getpid(): ...
[ "def", "instance", "(", ")", ":", "if", "not", "hasattr", "(", "Vabamorf", ",", "'pid'", ")", "or", "Vabamorf", ".", "pid", "!=", "os", ".", "getpid", "(", ")", ":", "Vabamorf", ".", "pid", "=", "os", ".", "getpid", "(", ")", "Vabamorf", ".", "mo...
37.545455
16.272727
def replace_all(self, old, new): """ Replaces all instances of expression `old` with expression `new`. :param old: A claripy expression. Must contain at least one named variable (to make it possible to use the name index for speedup). :param new: The new variable to ...
[ "def", "replace_all", "(", "self", ",", "old", ",", "new", ")", ":", "if", "options", ".", "REVERSE_MEMORY_NAME_MAP", "not", "in", "self", ".", "state", ".", "options", ":", "raise", "SimMemoryError", "(", "\"replace_all is not doable without a reverse name mapping....
45.306122
25.959184
def get_items(self, collection_uri): """Return all items in this collection. :param collection_uri: The URI that references the collection :type collection_uri: String :rtype: List :returns: a list of the URIs of the items in this collection """ cname = os.pat...
[ "def", "get_items", "(", "self", ",", "collection_uri", ")", ":", "cname", "=", "os", ".", "path", ".", "split", "(", "collection_uri", ")", "[", "1", "]", "return", "self", ".", "search_metadata", "(", "\"collection_name:%s\"", "%", "cname", ")" ]
30.769231
21.384615
def polygon_to_geohashes(polygon, precision, inner=True): """ :param polygon: shapely polygon. :param precision: int. Geohashes' precision that form resulting polygon. :param inner: bool, default 'True'. If false, geohashes that are completely outside from the polygon are ignored. :return: set. Set ...
[ "def", "polygon_to_geohashes", "(", "polygon", ",", "precision", ",", "inner", "=", "True", ")", ":", "inner_geohashes", "=", "set", "(", ")", "outer_geohashes", "=", "set", "(", ")", "envelope", "=", "polygon", ".", "envelope", "centroid", "=", "polygon", ...
41.45
24.3
def bcc(self, bcc): ''' :param bcc: Email addresses for the 'Bcc' API field. :type bcc: :keyword:`list` or `str` ''' if isinstance(bcc, basestring): bcc = bcc.split(',') self._bcc = bcc
[ "def", "bcc", "(", "self", ",", "bcc", ")", ":", "if", "isinstance", "(", "bcc", ",", "basestring", ")", ":", "bcc", "=", "bcc", ".", "split", "(", "','", ")", "self", ".", "_bcc", "=", "bcc" ]
29.75
16
def get_object(self, name, description): """ Get object for the statement. """ return Activity( id=X_API_ACTIVITY_COURSE, definition=ActivityDefinition( name=LanguageMap({'en-US': (name or '').encode("ascii", "ignore").decode('ascii')}), ...
[ "def", "get_object", "(", "self", ",", "name", ",", "description", ")", ":", "return", "Activity", "(", "id", "=", "X_API_ACTIVITY_COURSE", ",", "definition", "=", "ActivityDefinition", "(", "name", "=", "LanguageMap", "(", "{", "'en-US'", ":", "(", "name", ...
39.909091
19.545455
def prune(self): """ Prune the scenario ephemeral directory files and returns None. "safe files" will not be pruned, including the ansible configuration and inventory used by this scenario, the scenario state file, and files declared as "safe_files" in the ``driver`` configurati...
[ "def", "prune", "(", "self", ")", ":", "LOG", ".", "info", "(", "'Pruning extra files from scenario ephemeral directory'", ")", "safe_files", "=", "[", "self", ".", "config", ".", "provisioner", ".", "config_file", ",", "self", ".", "config", ".", "provisioner",...
39.148148
17.740741
def run_step(context): """pypyr step that checks if a file or directory path exists. Args: context: pypyr.context.Context. Mandatory. The following context key must exist - pathsToCheck. str/path-like or list of str/paths. Path to file on...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'pathCheck'", ",", "caller", "=", "__name__", ")", "paths_to_check", "=", "context", "[", "'pathCheck'", "...
34.540541
24.621622
def setup_db(connection_string): """ Sets up the database schema and adds defaults. :param connection_string: Database URL. e.g: sqlite:///filename.db This is usually taken from the config file. """ global DB_Session, engine new_database = False if connectio...
[ "def", "setup_db", "(", "connection_string", ")", ":", "global", "DB_Session", ",", "engine", "new_database", "=", "False", "if", "connection_string", "==", "'sqlite://'", "or", "not", "database_exists", "(", "connection_string", ")", ":", "new_database", "=", "Tr...
52.265306
24.632653
def weld_aggregate(array, weld_type, operation): """Returns operation on the elements in the array. Arguments --------- array : WeldObject or numpy.ndarray Input array. weld_type : WeldType Weld type of each element in the input array. operation : {'+', '*', 'min', 'max'} ...
[ "def", "weld_aggregate", "(", "array", ",", "weld_type", ",", "operation", ")", ":", "obj_id", ",", "weld_obj", "=", "create_weld_object", "(", "array", ")", "weld_template", "=", "_weld_aggregate_code", "weld_obj", ".", "weld_code", "=", "weld_template", ".", "...
26.296296
20.259259
def ftp_login(folder=None): """return an "FTP" object after logging in.""" pwDir=os.path.realpath(__file__) for i in range(3): pwDir=os.path.dirname(pwDir) pwFile = os.path.join(pwDir,"passwd.txt") print(" -- looking for login information in:\n [%s]"%pwFile) try: with open(pwFi...
[ "def", "ftp_login", "(", "folder", "=", "None", ")", ":", "pwDir", "=", "os", ".", "path", ".", "realpath", "(", "__file__", ")", "for", "i", "in", "range", "(", "3", ")", ":", "pwDir", "=", "os", ".", "path", ".", "dirname", "(", "pwDir", ")", ...
35.5
14.125
def delt(self, *args, **kargs): """delt(host|net, gw|dev)""" self.invalidate_cache() route = self.make_route(*args, **kargs) try: i = self.routes.index(route) del(self.routes[i]) except ValueError: warning("no matching route found")
[ "def", "delt", "(", "self", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "self", ".", "invalidate_cache", "(", ")", "route", "=", "self", ".", "make_route", "(", "*", "args", ",", "*", "*", "kargs", ")", "try", ":", "i", "=", "self", "."...
33.333333
9.111111
def hash(self, key, message=None): """ Return digest of the given message and key :param key: secret HMAC key :param message: code (message) to authenticate :return: bytes """ hmac_obj = hmac.HMAC(key, self.__digest_generator, backend=default_backend()) if message is not None: hmac_obj.update(message...
[ "def", "hash", "(", "self", ",", "key", ",", "message", "=", "None", ")", ":", "hmac_obj", "=", "hmac", ".", "HMAC", "(", "key", ",", "self", ".", "__digest_generator", ",", "backend", "=", "default_backend", "(", ")", ")", "if", "message", "is", "no...
28.25
17.333333
def _parse(data): """Recursively convert a json into python data types""" if not data: return [] elif isinstance(data, (tuple, list)): return [_parse(subdata) for subdata in data] # extract the nested dict. ex. {"tournament": {"url": "7k1safq" ...}} d = {ik: v for k in data.keys() ...
[ "def", "_parse", "(", "data", ")", ":", "if", "not", "data", ":", "return", "[", "]", "elif", "isinstance", "(", "data", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "[", "_parse", "(", "subdata", ")", "for", "subdata", "in", "data", ...
31.878788
17.060606
def future(self,in_days=None,in_hours=None,in_minutes=None,in_seconds=None): """ Function to return a future timestep """ future = None # Initialize variables to 0 dd, hh, mm, ss = [0 for i in range(4)] if (in_days != None): dd = dd + in_days ...
[ "def", "future", "(", "self", ",", "in_days", "=", "None", ",", "in_hours", "=", "None", ",", "in_minutes", "=", "None", ",", "in_seconds", "=", "None", ")", ":", "future", "=", "None", "# Initialize variables to 0", "dd", ",", "hh", ",", "mm", ",", "s...
34.65
16.85
def _iter_module_files(): """This iterates over all relevant Python files. It goes through all loaded files from modules, all files in folders of already loaded modules as well as all files reachable through a package. """ # The list call is necessary on Python 3 in case the module # dictionary...
[ "def", "_iter_module_files", "(", ")", ":", "# The list call is necessary on Python 3 in case the module", "# dictionary modifies during iteration.", "for", "module", "in", "list", "(", "sys", ".", "modules", ".", "values", "(", ")", ")", ":", "if", "module", "is", "N...
38.814815
14.814815
def create_global_secondary_index(table_name, global_index, region=None, key=None, keyid=None, profile=None): ''' Creates a single global secondary index on a DynamoDB table. CLI Example: .. code-block:: bash salt myminion boto_dynamodb.create_global_secondary...
[ "def", "create_global_secondary_index", "(", "table_name", ",", "global_index", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ...
38.285714
28
def plot_annotation(ann_samp, n_annot, ann_sym, signal, n_sig, fs, time_units, ann_style, axes): "Plot annotations, possibly overlaid on signals" # Extend annotation style if necesary if len(ann_style) == 1: ann_style = n_annot * ann_style # Figure out downsample factor for ...
[ "def", "plot_annotation", "(", "ann_samp", ",", "n_annot", ",", "ann_sym", ",", "signal", ",", "n_sig", ",", "fs", ",", "time_units", ",", "ann_style", ",", "axes", ")", ":", "# Extend annotation style if necesary", "if", "len", "(", "ann_style", ")", "==", ...
38.485714
18.942857
def save(self): """ save or update this node in Ariane server :return: """ LOGGER.debug("Node.save") if self.container is not None: if self.container.id is None: self.container.save() self.container_id = self.container.id i...
[ "def", "save", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"Node.save\"", ")", "if", "self", ".", "container", "is", "not", "None", ":", "if", "self", ".", "container", ".", "id", "is", "None", ":", "self", ".", "container", ".", "save", ...
41.943925
17.495327
def get_real_field(model, field_name): ''' Get the real field from a model given its name. Handle nested models recursively (aka. ``__`` lookups) ''' parts = field_name.split('__') field = model._meta.get_field(parts[0]) if len(parts) == 1: return model._meta.get_field(field_name) ...
[ "def", "get_real_field", "(", "model", ",", "field_name", ")", ":", "parts", "=", "field_name", ".", "split", "(", "'__'", ")", "field", "=", "model", ".", "_meta", ".", "get_field", "(", "parts", "[", "0", "]", ")", "if", "len", "(", "parts", ")", ...
34.857143
18
def interpolate(self, lat, lon, var): """ Interpolate each var on the coordinates requested """ subset, dims = self.crop(lat, lon, var) if np.all([y in dims['lat'] for y in lat]) & \ np.all([x in dims['lon'] for x in lon]): yn = np.nonzero([y in lat...
[ "def", "interpolate", "(", "self", ",", "lat", ",", "lon", ",", "var", ")", ":", "subset", ",", "dims", "=", "self", ".", "crop", "(", "lat", ",", "lon", ",", "var", ")", "if", "np", ".", "all", "(", "[", "y", "in", "dims", "[", "'lat'", "]",...
37.118644
18.949153
async def restore_storage_configuration(self): """ Restore machine's storage configuration to its initial state. """ self._data = await self._handler.restore_storage_configuration( system_id=self.system_id)
[ "async", "def", "restore_storage_configuration", "(", "self", ")", ":", "self", ".", "_data", "=", "await", "self", ".", "_handler", ".", "restore_storage_configuration", "(", "system_id", "=", "self", ".", "system_id", ")" ]
40.833333
11.5
def set_items_shuffled(self, shuffle): """Sets the shuffle flag. The shuffle flag may be overidden by other assessment sequencing rules. arg: shuffle (boolean): ``true`` if the items are shuffled, ``false`` if the items appear in the designated order raise: ...
[ "def", "set_items_shuffled", "(", "self", ",", "shuffle", ")", ":", "# Implemented from template for osid.resource.ResourceForm.set_group_template", "if", "self", ".", "get_items_shuffled_metadata", "(", ")", ".", "is_read_only", "(", ")", ":", "raise", "errors", ".", "...
42.684211
20.684211
def send(self, msg_p): """ Send a zmsg message to the actor, take ownership of the message and destroy when it has been sent. """ return lib.zactor_send(self._as_parameter_, byref(zmsg_p.from_param(msg_p)))
[ "def", "send", "(", "self", ",", "msg_p", ")", ":", "return", "lib", ".", "zactor_send", "(", "self", ".", "_as_parameter_", ",", "byref", "(", "zmsg_p", ".", "from_param", "(", "msg_p", ")", ")", ")" ]
38.833333
16.5
def start_background_task(self, target, *args, **kwargs): """Start a background task. This is a utility function that applications can use to start a background task. :param target: the target function to execute. :param args: arguments to pass to the function. :param k...
[ "def", "start_background_task", "(", "self", ",", "target", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "th", "=", "threading", ".", "Thread", "(", "target", "=", "target", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "th", ...
39.352941
22.647059
def _insert_stmt(self, name, value, timestamp, interval, config): '''Helper to generate the insert statement.''' # Calculate the TTL and abort if inserting into the past expire, ttl = config['expire'], config['ttl'](timestamp) if expire and not ttl: return None i_time = config['i_calc'].to_bu...
[ "def", "_insert_stmt", "(", "self", ",", "name", ",", "value", ",", "timestamp", ",", "interval", ",", "config", ")", ":", "# Calculate the TTL and abort if inserting into the past", "expire", ",", "ttl", "=", "config", "[", "'expire'", "]", ",", "config", "[", ...
36.45
21.75
def queue(self, queue_, value): """Puts a value into a queue but aborts if this thread is closed.""" while not self.closed: try: queue_.put(value, block=True, timeout=1) return except queue.Full: continue
[ "def", "queue", "(", "self", ",", "queue_", ",", "value", ")", ":", "while", "not", "self", ".", "closed", ":", "try", ":", "queue_", ".", "put", "(", "value", ",", "block", "=", "True", ",", "timeout", "=", "1", ")", "return", "except", "queue", ...
35.625
12.875
def flux_r(q_vars: List[fl.Var], i: int, j: int): """Make Fluxion with the distance between body i and j""" return fl.sqrt(flux_r2(q_vars, i, j))
[ "def", "flux_r", "(", "q_vars", ":", "List", "[", "fl", ".", "Var", "]", ",", "i", ":", "int", ",", "j", ":", "int", ")", ":", "return", "fl", ".", "sqrt", "(", "flux_r2", "(", "q_vars", ",", "i", ",", "j", ")", ")" ]
50.333333
3.333333
def convert_kwargs_to_cmd_line_args(kwargs): """Helper function to build command line arguments out of dict.""" args = [] for k in sorted(kwargs.keys()): v = kwargs[k] args.append('-{}'.format(k)) if v is not None: args.append('{}'.format(v)) return args
[ "def", "convert_kwargs_to_cmd_line_args", "(", "kwargs", ")", ":", "args", "=", "[", "]", "for", "k", "in", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", ":", "v", "=", "kwargs", "[", "k", "]", "args", ".", "append", "(", "'-{}'", ".", "form...
33.111111
11.111111
def FromReplica(self, replica): """ Get AccountState object from a replica. Args: replica (obj): must have ScriptHash, IsFrozen, Votes and Balances members. Returns: AccountState: """ return AccountState(replica.ScriptHash, replica.IsFrozen, repli...
[ "def", "FromReplica", "(", "self", ",", "replica", ")", ":", "return", "AccountState", "(", "replica", ".", "ScriptHash", ",", "replica", ".", "IsFrozen", ",", "replica", ".", "Votes", ",", "replica", ".", "Balances", ")" ]
33.8
22.6
def lisp_to_nested_expression(lisp_string: str) -> List: """ Takes a logical form as a lisp string and returns a nested list representation of the lisp. For example, "(count (division first))" would get mapped to ['count', ['division', 'first']]. """ stack: List = [] current_expression: List = [...
[ "def", "lisp_to_nested_expression", "(", "lisp_string", ":", "str", ")", "->", "List", ":", "stack", ":", "List", "=", "[", "]", "current_expression", ":", "List", "=", "[", "]", "tokens", "=", "lisp_string", ".", "split", "(", ")", "for", "token", "in",...
40.7
13.9
def run(self, fitness_function, n=None): """ Runs NEAT's genetic algorithm for at most n generations. If n is None, run until solution is found or extinction occurs. The user-provided fitness_function must take only two arguments: 1. The population as a list of (genome id, ...
[ "def", "run", "(", "self", ",", "fitness_function", ",", "n", "=", "None", ")", ":", "if", "self", ".", "config", ".", "no_fitness_termination", "and", "(", "n", "is", "None", ")", ":", "raise", "RuntimeError", "(", "\"Cannot have no generational limit with no...
43.653846
27.576923
def present_active(self): """ Strong verbs I >>> verb = StrongOldNorseVerb() >>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"]) >>> verb.present_active() ['lít', 'lítr', 'lítr', 'lítum', 'lítið', 'líta'] II >>> verb = StrongOl...
[ "def", "present_active", "(", "self", ")", ":", "forms", "=", "[", "]", "singular_stem", "=", "self", ".", "sfg3en", "[", ":", "-", "1", "]", "forms", ".", "append", "(", "singular_stem", ")", "forms", ".", "append", "(", "self", ".", "sfg3en", ")", ...
34.189655
19.948276
def _notify(p, **data): """The callback func that will be hooked to the ``notify`` command""" message = data.get("message") if not message and not sys.stdin.isatty(): message = click.get_text_stream("stdin").read() data["message"] = message data = clean_data(data) ctx = click.get_curre...
[ "def", "_notify", "(", "p", ",", "*", "*", "data", ")", ":", "message", "=", "data", ".", "get", "(", "\"message\"", ")", "if", "not", "message", "and", "not", "sys", ".", "stdin", ".", "isatty", "(", ")", ":", "message", "=", "click", ".", "get_...
33.3125
17.125
def _heartbeat_loop(self): """A main run loop thread to do work""" self.logger.debug("running main heartbeat thread") while not self.closed: time.sleep(self.settings['SLEEP_TIME']) self._report_self()
[ "def", "_heartbeat_loop", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"running main heartbeat thread\"", ")", "while", "not", "self", ".", "closed", ":", "time", ".", "sleep", "(", "self", ".", "settings", "[", "'SLEEP_TIME'", "]", "...
40.5
10.333333
def bind(self) -> None: """Bind the metadata to the engine and session.""" self.base.metadata.bind = self.engine self.base.query = self.session.query_property()
[ "def", "bind", "(", "self", ")", "->", "None", ":", "self", ".", "base", ".", "metadata", ".", "bind", "=", "self", ".", "engine", "self", ".", "base", ".", "query", "=", "self", ".", "session", ".", "query_property", "(", ")" ]
45.25
9.25
def _get_SRF_phi(self, imt_per): """ Table 7 and equation 19 of 2013 report. NB change in notation, 2013 report calls this term 'sigma' but it is referred to here as phi. """ if imt_per < 0.6: srf = 0.8 elif 0.6 <= imt_per < 1: srf = self._...
[ "def", "_get_SRF_phi", "(", "self", ",", "imt_per", ")", ":", "if", "imt_per", "<", "0.6", ":", "srf", "=", "0.8", "elif", "0.6", "<=", "imt_per", "<", "1", ":", "srf", "=", "self", ".", "_interp_function", "(", "0.7", ",", "0.8", ",", "1", ",", ...
31.25
19
def build(cls, shape_y, shape_z, sids, initvalue=0., dtype=F64): """ :param shape_y: the total number of intensity measure levels :param shape_z: the number of inner levels :param sids: a set of site indices :param initvalue: the initial value of the probability (default 0) ...
[ "def", "build", "(", "cls", ",", "shape_y", ",", "shape_z", ",", "sids", ",", "initvalue", "=", "0.", ",", "dtype", "=", "F64", ")", ":", "dic", "=", "cls", "(", "shape_y", ",", "shape_z", ")", "for", "sid", "in", "sids", ":", "dic", ".", "setdef...
40.916667
12.916667
def pre_send(self, request_params): """Override this method to modify sent request parameters""" for adapter in itervalues(self.adapters): adapter.max_retries = request_params.get('max_retries', 0) return request_params
[ "def", "pre_send", "(", "self", ",", "request_params", ")", ":", "for", "adapter", "in", "itervalues", "(", "self", ".", "adapters", ")", ":", "adapter", ".", "max_retries", "=", "request_params", ".", "get", "(", "'max_retries'", ",", "0", ")", "return", ...
41.833333
15.833333
def upload(self, resource_id, data): """Update the request URI to upload the a document to this resource. Args: resource_id (integer): The group id. data (any): The raw data to upload. """ self.body = data self.content_type = 'application/octet-stream' ...
[ "def", "upload", "(", "self", ",", "resource_id", ",", "data", ")", ":", "self", ".", "body", "=", "data", "self", ".", "content_type", "=", "'application/octet-stream'", "self", ".", "resource_id", "(", "str", "(", "resource_id", ")", ")", "self", ".", ...
37.818182
13
def _send_method(self, method_sig, args=bytes(), content=None): """ Send a method for our channel. """ if isinstance(args, AMQPWriter): args = args.getvalue() self.connection.method_writer.write_method(self.channel_id, method_sig, args, content)
[ "def", "_send_method", "(", "self", ",", "method_sig", ",", "args", "=", "bytes", "(", ")", ",", "content", "=", "None", ")", ":", "if", "isinstance", "(", "args", ",", "AMQPWriter", ")", ":", "args", "=", "args", ".", "getvalue", "(", ")", "self", ...
30.2
14
def addEntity(self, model, number, customFieldFormatters=None): """ Add an order for the generation of $number records for $entity. :param model: mixed A Django Model classname, or a faker.orm.django.EntityPopulator instance :type model: Model :param number: int The number of en...
[ "def", "addEntity", "(", "self", ",", "model", ",", "number", ",", "customFieldFormatters", "=", "None", ")", ":", "if", "not", "isinstance", "(", "model", ",", "ModelPopulator", ")", ":", "model", "=", "ModelPopulator", "(", "model", ")", "model", ".", ...
41.318182
20.045455
def listdir(self, path, start_time=None, end_time=None, return_key=False): """ Get an iterable with S3 folder contents. Iterable contains paths relative to queried path. :param path: URL for target S3 location :param start_time: Optional argument to list files with modified (offs...
[ "def", "listdir", "(", "self", ",", "path", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ",", "return_key", "=", "False", ")", ":", "(", "bucket", ",", "key", ")", "=", "self", ".", "_path_to_bucket_and_key", "(", "path", ")", "# grab ...
50.0625
22.8125
def types(self, ids = None, query = None, filter = None, offset = None, limit = None, sample = None, sort = None, order = None, facet = None, works = False, select = None, cursor = None, cursor_max = 5000, **kwargs): ''' Search Crossref types :param ids...
[ "def", "types", "(", "self", ",", "ids", "=", "None", ",", "query", "=", "None", ",", "filter", "=", "None", ",", "offset", "=", "None", ",", "limit", "=", "None", ",", "sample", "=", "None", ",", "sort", "=", "None", ",", "order", "=", "None", ...
58.433962
32.09434
def load(self, key_filter=None, header_preproc=None): """Load data table from tsv file, from default location Args: key_filter (str): additional filter for key column - regex matching key values to include; None for no filter header_preproc (func): function to a...
[ "def", "load", "(", "self", ",", "key_filter", "=", "None", ",", "header_preproc", "=", "None", ")", ":", "# read file, keep all values as strings", "df", "=", "pd", ".", "read_csv", "(", "self", ".", "input_file", ",", "sep", "=", "'\\t'", ",", "dtype", "...
40.071429
25.214286
def _getTempFile(self, jobStoreID=None): """ :rtype : file-descriptor, string, string is the absolute path to a temporary file within the given job's (referenced by jobStoreID's) temporary file directory. The file-descriptor is integer pointing to open operating system file handle. Shoul...
[ "def", "_getTempFile", "(", "self", ",", "jobStoreID", "=", "None", ")", ":", "if", "jobStoreID", "!=", "None", ":", "# Make a temporary file within the job's directory", "self", ".", "_checkJobStoreId", "(", "jobStoreID", ")", "return", "tempfile", ".", "mkstemp", ...
56.8
25.6
def pyfiles(callername, level=2): "All python files caller's dir without the path and trailing .py" d = os.path.dirname(callername) # Get the name of our directory. # A glob pattern that will get all *.py files but not __init__.py glob(os.path.join(d, '[a-zA-Z]*.py')) py_files = glob(os.path.joi...
[ "def", "pyfiles", "(", "callername", ",", "level", "=", "2", ")", ":", "d", "=", "os", ".", "path", ".", "dirname", "(", "callername", ")", "# Get the name of our directory.", "# A glob pattern that will get all *.py files but not __init__.py", "glob", "(", "os", "....
50.875
14.875
def add_history(self, filename): """ Add new history tab Slot for add_history signal emitted by shell instance """ filename = encoding.to_unicode_from_fs(filename) if filename in self.filenames: return editor = codeeditor.CodeEditor(self) ...
[ "def", "add_history", "(", "self", ",", "filename", ")", ":", "filename", "=", "encoding", ".", "to_unicode_from_fs", "(", "filename", ")", "if", "filename", "in", "self", ".", "filenames", ":", "return", "editor", "=", "codeeditor", ".", "CodeEditor", "(", ...
40.8125
14.479167
def get_mod(cls): '''Returns the string identifying the module that cls is defined in. ''' if isinstance(cls, (type, types.FunctionType)): ret = cls.__module__ else: ret = cls.__class__.__module__ return ret
[ "def", "get_mod", "(", "cls", ")", ":", "if", "isinstance", "(", "cls", ",", "(", "type", ",", "types", ".", "FunctionType", ")", ")", ":", "ret", "=", "cls", ".", "__module__", "else", ":", "ret", "=", "cls", ".", "__class__", ".", "__module__", "...
26.222222
23.333333
def _title_uptodate(self,fullfile,pid,_title): """Check fb photo title against provided title, returns true if they match""" i=self.fb.get_object(pid) if i.has_key('name'): if _title == i['name']: return True return False
[ "def", "_title_uptodate", "(", "self", ",", "fullfile", ",", "pid", ",", "_title", ")", ":", "i", "=", "self", ".", "fb", ".", "get_object", "(", "pid", ")", "if", "i", ".", "has_key", "(", "'name'", ")", ":", "if", "_title", "==", "i", "[", "'na...
31.333333
11.333333
def commitVersion(self): ''' return a GithubComponentVersion object for a specific commit if valid ''' import re commit_match = re.match('^[a-f0-9]{7,40}$', self.tagOrBranchSpec(), re.I) if commit_match: return GithubComponentVersion( '', '', _getComm...
[ "def", "commitVersion", "(", "self", ")", ":", "import", "re", "commit_match", "=", "re", ".", "match", "(", "'^[a-f0-9]{7,40}$'", ",", "self", ".", "tagOrBranchSpec", "(", ")", ",", "re", ".", "I", ")", "if", "commit_match", ":", "return", "GithubComponen...
34.833333
30.166667
def p_term_list(self, p): '''term_list : term_list COMMA term | term | empty''' if p[1] is None: p[0] = [] elif len(p) == 4: p[1].append(p[3]) p[0] = p[1] elif len(p) == 2: p[0] = [p[1]]
[ "def", "p_term_list", "(", "self", ",", "p", ")", ":", "if", "p", "[", "1", "]", "is", "None", ":", "p", "[", "0", "]", "=", "[", "]", "elif", "len", "(", "p", ")", "==", "4", ":", "p", "[", "1", "]", ".", "append", "(", "p", "[", "3", ...
27.090909
13.454545
def model_changed(self, model): """Apply the model to the combobox When a level instance is created, the model is None. So it has to be set afterwards. Then this method will be called and your level should somehow use the model :param model: the model that the level should use ...
[ "def", "model_changed", "(", "self", ",", "model", ")", ":", "self", ".", "setModel", "(", "model", ")", "# to update all lists belwo", "# current changed is not triggered by setModel somehow", "if", "model", "is", "not", "None", ":", "self", ".", "setCurrentIndex", ...
37.470588
19.529412
def create_apirack(self): """Get an instance of Api Rack Variables services facade.""" return ApiRack( self.networkapi_url, self.user, self.password, self.user_ldap)
[ "def", "create_apirack", "(", "self", ")", ":", "return", "ApiRack", "(", "self", ".", "networkapi_url", ",", "self", ".", "user", ",", "self", ".", "password", ",", "self", ".", "user_ldap", ")" ]
31.857143
12.142857
def tableexists(tablename): """Test if a table exists.""" result = True try: t = table(tablename, ack=False) except: result = False return result
[ "def", "tableexists", "(", "tablename", ")", ":", "result", "=", "True", "try", ":", "t", "=", "table", "(", "tablename", ",", "ack", "=", "False", ")", "except", ":", "result", "=", "False", "return", "result" ]
21.75
17.375
def sqlvm_create(client, cmd, location, sql_virtual_machine_name, resource_group_name, sql_server_license_type='PAYG', sql_virtual_machine_group_resource_id=None, cluster_bootstrap_account_password=None, cluster_operator_account_password=None, sql_service_account_password=None, enable_...
[ "def", "sqlvm_create", "(", "client", ",", "cmd", ",", "location", ",", "sql_virtual_machine_name", ",", "resource_group_name", ",", "sql_server_license_type", "=", "'PAYG'", ",", "sql_virtual_machine_group_resource_id", "=", "None", ",", "cluster_bootstrap_account_password...
72.154639
49.123711
def __process_username_password(self): """ If indicated, process the username and password """ if self.use_username_password_store is not None: if self.args.clear_store: with load_config(sections=AUTH_SECTIONS) as config: config.remove_option(AUTH_SECTION...
[ "def", "__process_username_password", "(", "self", ")", ":", "if", "self", ".", "use_username_password_store", "is", "not", "None", ":", "if", "self", ".", "args", ".", "clear_store", ":", "with", "load_config", "(", "sections", "=", "AUTH_SECTIONS", ")", "as"...
52.375
22.4375
def from_query(query, engine=None, limit=None): """ Execute an ORM style query, and return the result in :class:`prettytable.PrettyTable`. :param query: an ``sqlalchemy.orm.Query`` object. :param engine: an ``sqlalchemy.engine.base.Engine`` object. :param limit: int, limit rows to return. ...
[ "def", "from_query", "(", "query", ",", "engine", "=", "None", ",", "limit", "=", "None", ")", ":", "if", "limit", "is", "not", "None", ":", "query", "=", "query", ".", "limit", "(", "limit", ")", "result_proxy", "=", "execute_query_return_result_proxy", ...
30.157895
16.578947
def is_control(input, model_file=None, model_proto=None, name=None): """Returns true if input id is control piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `mo...
[ "def", "is_control", "(", "input", ",", "model_file", "=", "None", ",", "model_proto", "=", "None", ",", "name", "=", "None", ")", ":", "return", "_gen_sentencepiece_processor_op", ".", "sentencepiece_get_piece_type", "(", "input", ",", "model_file", "=", "model...
38.9375
21.1875
def get(self, variable_path: str, default: t.Optional[t.Any] = None, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None, **kwargs): """ :param variable_path: a delimiter-separated path to a nested value :para...
[ "def", "get", "(", "self", ",", "variable_path", ":", "str", ",", "default", ":", "t", ".", "Optional", "[", "t", ".", "Any", "]", "=", "None", ",", "coerce_type", ":", "t", ".", "Optional", "[", "t", ".", "Type", "]", "=", "None", ",", "coercer"...
40.272727
24.681818