text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def inspect_swarm(self): """ Retrieve low-level information about the current swarm. Returns: A dictionary containing data about the swarm. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ url = self....
[ "def", "inspect_swarm", "(", "self", ")", ":", "url", "=", "self", ".", "_url", "(", "'/swarm'", ")", "return", "self", ".", "_result", "(", "self", ".", "_get", "(", "url", ")", ",", "True", ")" ]
28.615385
16.461538
def add_slave(self, slave, container_name="widget"): """Add a slave delegate """ cont = getattr(self, container_name, None) if cont is None: raise AttributeError( 'Container name must be a member of the delegate') cont.add(slave.widget) self.sl...
[ "def", "add_slave", "(", "self", ",", "slave", ",", "container_name", "=", "\"widget\"", ")", ":", "cont", "=", "getattr", "(", "self", ",", "container_name", ",", "None", ")", "if", "cont", "is", "None", ":", "raise", "AttributeError", "(", "'Container na...
35
10.8
def load(cls, path, vocab=None, dtype=np.float32, max_vocab=None, format=None, binary=False): """ Load pretrained word embedding from a file. Args: path (str): Path of file to load. vocab (str or None): Path to vocabulary file created by word2vec ...
[ "def", "load", "(", "cls", ",", "path", ",", "vocab", "=", "None", ",", "dtype", "=", "np", ".", "float32", ",", "max_vocab", "=", "None", ",", "format", "=", "None", ",", "binary", "=", "False", ")", ":", "freqs", "=", "None", "if", "vocab", "is...
45.071429
21.107143
def sort_values(self, inplace=False, ascending=True, na_position='last'): """ Sort the Categorical by category value returning a new Categorical by default. While an ordering is applied to the category values, sorting in this context refers more to organizing and grouping togeth...
[ "def", "sort_values", "(", "self", ",", "inplace", "=", "False", ",", "ascending", "=", "True", ",", "na_position", "=", "'last'", ")", ":", "inplace", "=", "validate_bool_kwarg", "(", "inplace", ",", "'inplace'", ")", "if", "na_position", "not", "in", "["...
33.966292
17.359551
def publish(self, value): """ Accepts: float Returns: float """ value = super(Float, self).publish(value) if isinstance(value, int): value = float(value) return value
[ "def", "publish", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", "Float", ",", "self", ")", ".", "publish", "(", "value", ")", "if", "isinstance", "(", "value", ",", "int", ")", ":", "value", "=", "float", "(", "value", ")", "re...
25.111111
10.444444
def parse_time_tuple(start, end): """ Parse a time tuple. These can be: relative in seconds, e.g. (-4, 0) relative in timedelta, e.g. (timedelta(seconds=-4), timedelta(0)) absolute in date/datetime, e.g. (datetime(2016, 4, 28, 20, 0, 0, 0, UTC), datetime(2016, 4, 28, 21, 0, 0, 0, UTC...
[ "def", "parse_time_tuple", "(", "start", ",", "end", ")", ":", "if", "isinstance", "(", "start", ",", "int", ")", ":", "start_time", "=", "timedelta", "(", "seconds", "=", "start", ")", "elif", "isinstance", "(", "start", ",", "timedelta", ")", ":", "s...
40.934783
18.152174
def compute_features(self): """Actual implementation of the features. Returns ------- mfcc: np.array(N, F) The features, each row representing a feature vector for a give time frame/beat. """ S = librosa.feature.melspectrogram(self._audio, ...
[ "def", "compute_features", "(", "self", ")", ":", "S", "=", "librosa", ".", "feature", ".", "melspectrogram", "(", "self", ".", "_audio", ",", "sr", "=", "self", ".", "sr", ",", "n_fft", "=", "self", ".", "n_fft", ",", "hop_length", "=", "self", ".",...
40.941176
19.529412
def route_directions(self, rt): """ Return a list of directions for a route. The directions seem to always be INBOUND and OUTBOUND for the busses currently, where INBOUND is towards downtown and OUTBOUND is away from downtown. (No idea if this is going to change.) ...
[ "def", "route_directions", "(", "self", ",", "rt", ")", ":", "url", "=", "self", ".", "endpoint", "(", "'R_DIRECTIONS'", ",", "dict", "(", "rt", "=", "rt", ")", ")", "return", "self", ".", "response", "(", "url", ")" ]
37.666667
22.111111
def classify(self): """ *classify the transients selected from the transient selection query in the settings file or passed in via the CL or other code* **Return:** - ``crossmatches`` -- list of dictionaries of crossmatched associated sources - ``classifications`` -- the...
[ "def", "classify", "(", "self", ")", ":", "global", "theseBatches", "global", "crossmatchArray", "self", ".", "log", ".", "debug", "(", "'starting the ``classify`` method'", ")", "remaining", "=", "1", "# THE COLUMN MAPS - WHICH COLUMNS IN THE CATALOGUE TABLES = RA, DEC,", ...
37.217742
21.241935
def isVisible(self, instance, mode='view', default=None, field=None): """ This function returns the visibility of the widget depending on whether the rejection workflow is enabled or not. """ vis = super(RejectionWidget, self).isVisible( instance=instance, mode=mode, ...
[ "def", "isVisible", "(", "self", ",", "instance", ",", "mode", "=", "'view'", ",", "default", "=", "None", ",", "field", "=", "None", ")", ":", "vis", "=", "super", "(", "RejectionWidget", ",", "self", ")", ".", "isVisible", "(", "instance", "=", "in...
42.545455
17.818182
def getbydatatype(data_type, besteffort=True): """Get schema class by data type. :param type data_type: data type from where get schema class. :param bool besteffort: if True and data_type not registered, parse all registered data_types and stop when once data_type is a subclass of input da...
[ "def", "getbydatatype", "(", "data_type", ",", "besteffort", "=", "True", ")", ":", "return", "_REGISTRY", ".", "getbydatatype", "(", "data_type", "=", "data_type", ",", "besteffort", "=", "besteffort", ")" ]
41.454545
20.545455
def dump(self, zone, output_dir, lenient, split, source, *sources): ''' Dump zone data from the specified source ''' self.log.info('dump: zone=%s, sources=%s', zone, sources) # We broke out source to force at least one to be passed, add it to any # others we got. ...
[ "def", "dump", "(", "self", ",", "zone", ",", "output_dir", ",", "lenient", ",", "split", ",", "source", ",", "*", "sources", ")", ":", "self", ".", "log", ".", "info", "(", "'dump: zone=%s, sources=%s'", ",", "zone", ",", "sources", ")", "# We broke out...
32.035714
20.821429
def get_default(self, node): """ If not explicitly set, check if onread sets the equivalent """ if node.inst.properties.get("onread", None) == rdltypes.OnReadType.rset: return True else: return self.default
[ "def", "get_default", "(", "self", ",", "node", ")", ":", "if", "node", ".", "inst", ".", "properties", ".", "get", "(", "\"onread\"", ",", "None", ")", "==", "rdltypes", ".", "OnReadType", ".", "rset", ":", "return", "True", "else", ":", "return", "...
32.875
16.375
def text(self): """Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of ...
[ "def", "text", "(", "self", ")", ":", "# Try charset from content-type", "content", "=", "None", "encoding", "=", "self", ".", "encoding", "if", "not", "self", ".", "content", ":", "return", "str", "(", "''", ")", "# Fallback to auto-detected encoding.", "if", ...
34.5
22.055556
def _parse_relation(chunk, type="O"): """ Returns a string of the roles and relations parsed from the given <chunk> element. The chunk type (which is part of the relation string) can be given as parameter. """ r1 = chunk.get(XML_RELATION) r2 = chunk.get(XML_ID, chunk.get(XML_OF)) r1 = [x != ...
[ "def", "_parse_relation", "(", "chunk", ",", "type", "=", "\"O\"", ")", ":", "r1", "=", "chunk", ".", "get", "(", "XML_RELATION", ")", "r2", "=", "chunk", ".", "get", "(", "XML_ID", ",", "chunk", ".", "get", "(", "XML_OF", ")", ")", "r1", "=", "[...
65.25
25.666667
def max(self): """ :returns the maximum of the column """ res = self._qexec("max(%s)" % self._name) if len(res) > 0: self._max = res[0][0] return self._max
[ "def", "max", "(", "self", ")", ":", "res", "=", "self", ".", "_qexec", "(", "\"max(%s)\"", "%", "self", ".", "_name", ")", "if", "len", "(", "res", ")", ">", "0", ":", "self", ".", "_max", "=", "res", "[", "0", "]", "[", "0", "]", "return", ...
26
9.5
def get_autotype(arr): """ Attempts to return a numpy array converted to the most sensible dtype Value errors will be caught and simply return the original array Tries to make dtype int, then float, then no change """ try: narr = arr.astype('float') if (narr < sys.maxsize).all() ...
[ "def", "get_autotype", "(", "arr", ")", ":", "try", ":", "narr", "=", "arr", ".", "astype", "(", "'float'", ")", "if", "(", "narr", "<", "sys", ".", "maxsize", ")", ".", "all", "(", ")", "and", "(", "narr", "%", "1", ")", ".", "sum", "(", ")"...
32.214286
17.357143
def get_objective_admin_session(self, proxy, *args, **kwargs): """Gets the ``OsidSession`` associated with the objective administration service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ObjectiveAdminSession`` :rtype: ``osid.learning.ObjectiveAdminSe...
[ "def", "get_objective_admin_session", "(", "self", ",", "proxy", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "supports_objective_admin", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "impor...
40.884615
19.423077
async def build_get_revoc_reg_request(submitter_did: Optional[str], revoc_reg_def_id: str, timestamp: int) -> str: """ Builds a GET_REVOC_REG request. Request to get the accumulated state of the Revocation Registry by ID. The state ...
[ "async", "def", "build_get_revoc_reg_request", "(", "submitter_did", ":", "Optional", "[", "str", "]", ",", "revoc_reg_def_id", ":", "str", ",", "timestamp", ":", "int", ")", "->", "str", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")",...
50.617647
29.205882
def get_absolute_url_link(self, text=None, cls=None, icon_class=None, **attrs): """Gets the html link for the object.""" if text is None: text = self.get_link_text() return build_link(href=self.get_absolute_url(), text=text, ...
[ "def", "get_absolute_url_link", "(", "self", ",", "text", "=", "None", ",", "cls", "=", "None", ",", "icon_class", "=", "None", ",", "*", "*", "attrs", ")", ":", "if", "text", "is", "None", ":", "text", "=", "self", ".", "get_link_text", "(", ")", ...
38.727273
11.454545
def destroy(self): """ Destroy the tk widget. """ # if this widget has a master remove the it from the master if self.master is not None: self.master._remove_child(self) self.tk.destroy()
[ "def", "destroy", "(", "self", ")", ":", "# if this widget has a master remove the it from the master", "if", "self", ".", "master", "is", "not", "None", ":", "self", ".", "master", ".", "_remove_child", "(", "self", ")", "self", ".", "tk", ".", "destroy", "("...
26.666667
13.555556
def ssh_session(key_filename, username, ip_address, *cli): """ opens a ssh shell to the host """ local('ssh -t -i %s %s@%s %s' % (key_filename, username, ip_address, ...
[ "def", "ssh_session", "(", "key_filename", ",", "username", ",", "ip_address", ",", "*", "cli", ")", ":", "local", "(", "'ssh -t -i %s %s@%s %s'", "%", "(", "key_filename", ",", "username", ",", "ip_address", ",", "\"\"", ".", "join", "(", "chain", ".", "f...
40
12.555556
def createSparseCNNModel(self): """ Create a sparse network composed of two CNN / MaxPool layers followed by a sparse linear layer with using k-winner activation between the layers """ # Create sparseCNN2 model model = nn.Sequential( nn.Conv2d(in_channels=self.in_channels, out_channels=sel...
[ "def", "createSparseCNNModel", "(", "self", ")", ":", "# Create sparseCNN2 model", "model", "=", "nn", ".", "Sequential", "(", "nn", ".", "Conv2d", "(", "in_channels", "=", "self", ".", "in_channels", ",", "out_channels", "=", "self", ".", "out_channels", "[",...
39.931818
20.568182
def register(self, request, **kwargs): """ Create and immediately log in a new user. Only require a email to register, username is generated automatically and a password is random generated and emailed to the user. Activation is still required for accou...
[ "def", "register", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "if", "Site", ".", "_meta", ".", "installed", ":", "site", "=", "Site", ".", "objects", ".", "get_current", "(", ")", "else", ":", "site", "=", "RequestSite", "(", "...
40.176471
20.088235
def load_modules(self, modules_list, user_modules): """ Load the given modules from the list (contains instance name) with respect to the user provided modules dict. modules_list: ['weather_yahoo paris', 'net_rate'] user_modules: { 'weather_yahoo': ('/etc/py3status.d...
[ "def", "load_modules", "(", "self", ",", "modules_list", ",", "user_modules", ")", ":", "for", "module", "in", "modules_list", ":", "# ignore already provided modules (prevents double inclusion)", "if", "module", "in", "self", ".", "modules", ":", "continue", "try", ...
42.76
17.48
def part_studio_stl(self, did, wid, eid): ''' Exports STL export from a part studio Args: - did (str): Document ID - wid (str): Workspace ID - eid (str): Element ID Returns: - requests.Response: Onshape response data ''' ...
[ "def", "part_studio_stl", "(", "self", ",", "did", ",", "wid", ",", "eid", ")", ":", "req_headers", "=", "{", "'Accept'", ":", "'application/vnd.onshape.v1+octet-stream'", "}", "return", "self", ".", "_api", ".", "request", "(", "'get'", ",", "'/api/partstudio...
30.588235
24.588235
def _build_context(self, request, enterprise_customer_uuid): """ Build common context parts used by different handlers in this view. """ enterprise_customer = EnterpriseCustomer.objects.get(uuid=enterprise_customer_uuid) # pylint: disable=no-member context = { self....
[ "def", "_build_context", "(", "self", ",", "request", ",", "enterprise_customer_uuid", ")", ":", "enterprise_customer", "=", "EnterpriseCustomer", ".", "objects", ".", "get", "(", "uuid", "=", "enterprise_customer_uuid", ")", "# pylint: disable=no-member", "context", ...
44.833333
28
def _create_pbuilders(env, runas='root'): ''' Create the .pbuilder family of files in user's home directory env A list or dictionary of environment variables to be set prior to execution. Example: .. code-block:: yaml - env: - DEB_BUILD_OPTIONS: 'noche...
[ "def", "_create_pbuilders", "(", "env", ",", "runas", "=", "'root'", ")", ":", "home", "=", "os", ".", "path", ".", "expanduser", "(", "'~{0}'", ".", "format", "(", "runas", ")", ")", "pbuilderrc", "=", "os", ".", "path", ".", "join", "(", "home", ...
34.7
24.58
def getUTMzone(geom): """Determine UTM Zone for input geometry """ #If geom has srs properly defined, can do this #geom.TransformTo(wgs_srs) #Get centroid lat/lon lon, lat = geom.Centroid().GetPoint_2D() #Make sure we're -180 to 180 lon180 = (lon+180) - np.floor((lon+180)/360)*360 - 180 ...
[ "def", "getUTMzone", "(", "geom", ")", ":", "#If geom has srs properly defined, can do this", "#geom.TransformTo(wgs_srs)", "#Get centroid lat/lon", "lon", ",", "lat", "=", "geom", ".", "Centroid", "(", ")", ".", "GetPoint_2D", "(", ")", "#Make sure we're -180 to 180", ...
33.142857
13.035714
def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """A helper method to register a rule (and optionally a view function) to the application. The endpoint is automatically prefixed with the blueprint's name. The URL rule is registered twice. """ # St...
[ "def", "add_url_rule", "(", "self", ",", "rule", ",", "endpoint", "=", "None", ",", "view_func", "=", "None", ",", "*", "*", "options", ")", ":", "# Static assets are not localized", "if", "endpoint", "==", "'static'", ":", "return", "super", "(", "I18nBluep...
46.638298
16.06383
def get_controller_state(self): """Returns the current state of the 3d mouse, a dictionary of pos, orn, grasp, and reset.""" dpos = self.control[:3] * 0.005 roll, pitch, yaw = self.control[3:] * 0.005 self.grasp = self.control_gripper # convert RPY to an absolute orientation ...
[ "def", "get_controller_state", "(", "self", ")", ":", "dpos", "=", "self", ".", "control", "[", ":", "3", "]", "*", "0.005", "roll", ",", "pitch", ",", "yaw", "=", "self", ".", "control", "[", "3", ":", "]", "*", "0.005", "self", ".", "grasp", "=...
47.0625
25.9375
def _to_unicode_soft(self, s): """ Convert a basestring to unicode, preserving any unicode subclass. """ # We type-check to avoid "TypeError: decoding Unicode is not supported". # We avoid the Python ternary operator for Python 2.4 support. if isinstance(s, unicode): ...
[ "def", "_to_unicode_soft", "(", "self", ",", "s", ")", ":", "# We type-check to avoid \"TypeError: decoding Unicode is not supported\".", "# We avoid the Python ternary operator for Python 2.4 support.", "if", "isinstance", "(", "s", ",", "unicode", ")", ":", "return", "s", "...
35.9
18.9
def read_phase(ph_file): """ Read hypoDD phase files into Obspy catalog class. :type ph_file: str :param ph_file: Phase file to read event info from. :returns: Catalog of events from file. :rtype: :class:`obspy.core.event.Catalog` >>> from obspy.core.event.catalog import Catalog >>> #...
[ "def", "read_phase", "(", "ph_file", ")", ":", "ph_catalog", "=", "Catalog", "(", ")", "f", "=", "open", "(", "ph_file", ",", "'r'", ")", "# Topline of each event is marked by # in position 0", "for", "line", "in", "f", ":", "if", "line", "[", "0", "]", "=...
33.428571
16
def show_vcs_output_vcs_nodes_vcs_node_info_node_serial_num(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_vcs = ET.Element("show_vcs") config = show_vcs output = ET.SubElement(show_vcs, "output") vcs_nodes = ET.SubElement(output, "...
[ "def", "show_vcs_output_vcs_nodes_vcs_node_info_node_serial_num", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_vcs", "=", "ET", ".", "Element", "(", "\"show_vcs\"", ")", "config", "=", "show...
43.571429
15.928571
def get_plugin_icon(self): """Return widget icon""" path = osp.join(self.PLUGIN_PATH, self.IMG_PATH) return ima.icon('pylint', icon_path=path)
[ "def", "get_plugin_icon", "(", "self", ")", ":", "path", "=", "osp", ".", "join", "(", "self", ".", "PLUGIN_PATH", ",", "self", ".", "IMG_PATH", ")", "return", "ima", ".", "icon", "(", "'pylint'", ",", "icon_path", "=", "path", ")" ]
41.5
9.75
def load(target, source_module=None): """Get the actual implementation of the target.""" module, klass, function = _get_module(target) if not module and source_module: module = source_module if not module: raise MissingModule( "No module name supplied or source_module provide...
[ "def", "load", "(", "target", ",", "source_module", "=", "None", ")", ":", "module", ",", "klass", ",", "function", "=", "_get_module", "(", "target", ")", "if", "not", "module", "and", "source_module", ":", "module", "=", "source_module", "if", "not", "...
34.5625
13.1875
def _do_api_call(self, endpoint_info, json): """ Utility function to perform an API call with retries :param endpoint_info: Tuple of method and endpoint :type endpoint_info: tuple[string, string] :param json: Parameters for this API call. :type json: dict :return...
[ "def", "_do_api_call", "(", "self", ",", "endpoint_info", ",", "json", ")", ":", "method", ",", "endpoint", "=", "endpoint_info", "url", "=", "'https://{host}/{endpoint}'", ".", "format", "(", "host", "=", "self", ".", "_parse_host", "(", "self", ".", "datab...
40.25
17.25
def certain_kind_tap(data_items): """ :param data_items: A sequence of unicode strings """ fruit_spigot = Bucket(get_fruit) metal_spigot = Bucket(get_metal) items = stream_tap((fruit_spigot, metal_spigot), data_items) # consume iterator. for item in items: print item retur...
[ "def", "certain_kind_tap", "(", "data_items", ")", ":", "fruit_spigot", "=", "Bucket", "(", "get_fruit", ")", "metal_spigot", "=", "Bucket", "(", "get_metal", ")", "items", "=", "stream_tap", "(", "(", "fruit_spigot", ",", "metal_spigot", ")", ",", "data_items...
25.5
17.642857
def _transitive_download_remote_libs(self, go_remote_libs, all_known_remote_libs=None): """Recursively attempt to resolve / download all remote transitive deps of go_remote_libs. Returns a dict<GoRemoteLibrary, set<tuple<str, Address>>>, which maps a go remote library to a set of unresolved remote dependen...
[ "def", "_transitive_download_remote_libs", "(", "self", ",", "go_remote_libs", ",", "all_known_remote_libs", "=", "None", ")", ":", "if", "not", "go_remote_libs", ":", "return", "{", "}", "all_known_remote_libs", "=", "all_known_remote_libs", "or", "set", "(", ")", ...
58.145161
34.322581
def ctrl_transfer(self, bmRequestType, bRequest, wValue=0, wIndex=0, data_or_wLength = None, timeout = None): r"""Do a control transfer on the endpoint 0. This method is used to issue a control transfer over the endpoint 0 (endpoint 0 is required to always be a control endpoint). ...
[ "def", "ctrl_transfer", "(", "self", ",", "bmRequestType", ",", "bRequest", ",", "wValue", "=", "0", ",", "wIndex", "=", "0", ",", "data_or_wLength", "=", "None", ",", "timeout", "=", "None", ")", ":", "try", ":", "buff", "=", "util", ".", "create_buff...
45.436364
20.981818
def copy_layer_keywords(layer_keywords): """Helper to make a deep copy of a layer keywords. :param layer_keywords: A dictionary of layer's keywords. :type layer_keywords: dict :returns: A deep copy of layer keywords. :rtype: dict """ copy_keywords = {} for key, value in list(layer_keyw...
[ "def", "copy_layer_keywords", "(", "layer_keywords", ")", ":", "copy_keywords", "=", "{", "}", "for", "key", ",", "value", "in", "list", "(", "layer_keywords", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "value", ",", "QUrl", ")", ":", "...
35.04
13.8
def message(self): """The message contents""" if self.type == 'cleartext': return self.bytes_to_text(self._message) if self.type == 'literal': return self._message.contents if self.type == 'encrypted': return self._message
[ "def", "message", "(", "self", ")", ":", "if", "self", ".", "type", "==", "'cleartext'", ":", "return", "self", ".", "bytes_to_text", "(", "self", ".", "_message", ")", "if", "self", ".", "type", "==", "'literal'", ":", "return", "self", ".", "_message...
28.3
13.7
def set_completions(self, completions, go_to_first=True, go_to_last=False): """ Start completions. (Generate list of completions and initialize.) """ assert not (go_to_first and go_to_last) # Generate list of all completions. if completions is None: if self.c...
[ "def", "set_completions", "(", "self", ",", "completions", ",", "go_to_first", "=", "True", ",", "go_to_last", "=", "False", ")", ":", "assert", "not", "(", "go_to_first", "and", "go_to_last", ")", "# Generate list of all completions.", "if", "completions", "is", ...
33.766667
15.766667
def resolve(self, key, keylist): """Hook to resolve ambiguities in selected keys""" raise AmbiguousKeyError("Ambiguous key "+ repr(key) + ", could be any of " + str(sorted(keylist)))
[ "def", "resolve", "(", "self", ",", "key", ",", "keylist", ")", ":", "raise", "AmbiguousKeyError", "(", "\"Ambiguous key \"", "+", "repr", "(", "key", ")", "+", "\", could be any of \"", "+", "str", "(", "sorted", "(", "keylist", ")", ")", ")" ]
52.75
12.25
def best_match(self, req, working_set, installer=None): """Find distribution best matching `req` and usable on `working_set` This calls the ``find(req)`` method of the `working_set` to see if a suitable distribution is already active. (This may raise ``VersionConflict`` if an unsuitabl...
[ "def", "best_match", "(", "self", ",", "req", ",", "working_set", ",", "installer", "=", "None", ")", ":", "dist", "=", "working_set", ".", "find", "(", "req", ")", "if", "dist", "is", "not", "None", ":", "return", "dist", "for", "dist", "in", "self"...
47.809524
20.333333
def merge_headers(event): """ Merge the values of headers and multiValueHeaders into a single dict. Opens up support for multivalue headers via API Gateway and ALB. See: https://github.com/Miserlou/Zappa/pull/1756 """ headers = event.get('headers') or {} multi_headers = (event.get('multiValu...
[ "def", "merge_headers", "(", "event", ")", ":", "headers", "=", "event", ".", "get", "(", "'headers'", ")", "or", "{", "}", "multi_headers", "=", "(", "event", ".", "get", "(", "'multiValueHeaders'", ")", "or", "{", "}", ")", ".", "copy", "(", ")", ...
39.928571
11.785714
def sort_url(self): """ Return the URL to sort the linked table by this column. If the table is already sorted by this column, the order is reversed. Since there is no canonical URL for a table the current URL (via the HttpRequest linked to the Table instance) is reused, and any...
[ "def", "sort_url", "(", "self", ")", ":", "prefix", "=", "(", "self", ".", "sort_direction", "==", "\"asc\"", ")", "and", "\"-\"", "or", "\"\"", "return", "self", ".", "table", ".", "get_url", "(", "order_by", "=", "prefix", "+", "self", ".", "name", ...
42.333333
24
def implementation(self, commands_module: arg(short_option='-m') = DEFAULT_COMMANDS_MODULE, config_file: arg(short_option='-f') = None, # Globals globals_: arg( container=dict, ...
[ "def", "implementation", "(", "self", ",", "commands_module", ":", "arg", "(", "short_option", "=", "'-m'", ")", "=", "DEFAULT_COMMANDS_MODULE", ",", "config_file", ":", "arg", "(", "short_option", "=", "'-f'", ")", "=", "None", ",", "# Globals", "globals_", ...
43.075581
20.976744
def share(self, plotters, keys=None, draw=None, auto_update=False): """ Share the formatoptions of this plotter with others This method shares the formatoptions of this :class:`Plotter` instance with others to make sure that, if the formatoption of this changes, those of the oth...
[ "def", "share", "(", "self", ",", "plotters", ",", "keys", "=", "None", ",", "draw", "=", "None", ",", "auto_update", "=", "False", ")", ":", "auto_update", "=", "auto_update", "or", "not", "self", ".", "no_auto_update", "if", "isinstance", "(", "plotter...
41.074074
18.018519
async def destroy(self): ''' Destroys the compute session. Since the server literally kills the container(s), all ongoing executions are forcibly interrupted. ''' params = {} if self.owner_access_key: params['owner_access_key'] = self.owner_access_key ...
[ "async", "def", "destroy", "(", "self", ")", ":", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "rqst", "=", "Request", "(", "self", ".", "session", ",...
37.8
15
def tag_release(message): # type: (str, bool) -> None """ Tag the current commit with as the current version release. This should be the same commit as the one that's uploaded as the release (to pypi for example). **Example Config**:: \b version_file: 'src/mypkg/__init__.py' ...
[ "def", "tag_release", "(", "message", ")", ":", "# type: (str, bool) -> None", "from", "peltak", ".", "extra", ".", "gitflow", "import", "logic", "logic", ".", "release", ".", "tag", "(", "message", ")" ]
24.736842
22.947368
def clean_undefined(obj): """ Convert Undefined array entries to None (null) """ if isinstance(obj, list): return [ None if isinstance(item, Undefined) else item for item in obj ] if isinstance(obj, dict): for key in obj: obj[key] = clean_u...
[ "def", "clean_undefined", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "[", "None", "if", "isinstance", "(", "item", ",", "Undefined", ")", "else", "item", "for", "item", "in", "obj", "]", "if", "isinstance", ...
26.230769
14.076923
def relaxed_clock(self, slack=None, coupling=None, **kwargs): """ Allow the mutation rate to vary on the tree (relaxed molecular clock). Changes of the mutation rates from one branch to another are penalized. In addition, deviation of the mutation rate from the mean rate is penal...
[ "def", "relaxed_clock", "(", "self", ",", "slack", "=", "None", ",", "coupling", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "slack", "is", "None", ":", "slack", "=", "ttconf", ".", "MU_ALPHA", "if", "coupling", "is", "None", ":", "coupling...
50.843137
28.098039
def draw(self, milliseconds, surface): """Render each of the collision objects onto the specified surface.""" if self.is_visible: global collidable_objects for obj in collidable_objects: if obj.is_visible: obj.draw(milliseconds, surface) ...
[ "def", "draw", "(", "self", ",", "milliseconds", ",", "surface", ")", ":", "if", "self", ".", "is_visible", ":", "global", "collidable_objects", "for", "obj", "in", "collidable_objects", ":", "if", "obj", ".", "is_visible", ":", "obj", ".", "draw", "(", ...
47
8.25
def disclaimer_title_header_element(feature, parent): """Retrieve disclaimer title header string from definitions.""" _ = feature, parent # NOQA header = disclaimer_title_header['string_format'] return header.capitalize()
[ "def", "disclaimer_title_header_element", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "header", "=", "disclaimer_title_header", "[", "'string_format'", "]", "return", "header", ".", "capitalize", "(", ")" ]
46.8
9
def rweibull(alpha, beta, size=None): """ Weibull random variates. """ tmp = -np.log(runiform(0, 1, size)) return beta * (tmp ** (1. / alpha))
[ "def", "rweibull", "(", "alpha", ",", "beta", ",", "size", "=", "None", ")", ":", "tmp", "=", "-", "np", ".", "log", "(", "runiform", "(", "0", ",", "1", ",", "size", ")", ")", "return", "beta", "*", "(", "tmp", "**", "(", "1.", "/", "alpha",...
26.166667
2.833333
def pop_all(self): """ NON-BLOCKING POP ALL IN QUEUE, IF ANY """ with self.lock: output = list(self.queue) self.queue.clear() return output
[ "def", "pop_all", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "output", "=", "list", "(", "self", ".", "queue", ")", "self", ".", "queue", ".", "clear", "(", ")", "return", "output" ]
21.777778
12.888889
def euler_trans_matrix(etheta, elongan, eincl): """ Get the transformation matrix R to translate/rotate a mesh according to euler angles. The matrix is R(long,incl,theta) = Rz(pi).Rz(long).Rx(incl).Rz(theta) Rz(long).Rx(-incl).Rz(theta).Rz(pi) where Rx(u) = 1, 0, ...
[ "def", "euler_trans_matrix", "(", "etheta", ",", "elongan", ",", "eincl", ")", ":", "s1", "=", "sin", "(", "eincl", ")", "c1", "=", "cos", "(", "eincl", ")", "s2", "=", "sin", "(", "elongan", ")", "c2", "=", "cos", "(", "elongan", ")", "s3", "=",...
24.09434
19.603774
def inverseHistogram(hist, bin_range): """sample data from given histogram and min, max values within range Returns: np.array: data that would create the same histogram as given """ data = hist.astype(float) / np.min(hist[np.nonzero(hist)]) new_data = np.empty(shape=np.sum(data, dtype=int))...
[ "def", "inverseHistogram", "(", "hist", ",", "bin_range", ")", ":", "data", "=", "hist", ".", "astype", "(", "float", ")", "/", "np", ".", "min", "(", "hist", "[", "np", ".", "nonzero", "(", "hist", ")", "]", ")", "new_data", "=", "np", ".", "emp...
34.571429
17.642857
def create_record(self, dns_type, name, content, **kwargs): """ Create a dns record :param dns_type: :param name: :param content: :param kwargs: :return: """ data = { 'type': dns_type, 'name': name, 'content': co...
[ "def", "create_record", "(", "self", ",", "dns_type", ",", "name", ",", "content", ",", "*", "*", "kwargs", ")", ":", "data", "=", "{", "'type'", ":", "dns_type", ",", "'name'", ":", "name", ",", "'content'", ":", "content", "}", "if", "kwargs", ".",...
28
14.296296
def add_site_list(dir_list): """Add a list of pseudo site-packages to :data:`python:sys.path`. This centers the list on ``sys.path`` around the current environment. I.e. if this environment is in the list, then directories before it in the list will be prepended to ``sys.path``, and directories after i...
[ "def", "add_site_list", "(", "dir_list", ")", ":", "our_site_packages", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "sys", ".", "prefix", ",", "site_package_postfix", ")", ")", "dir_list", "=", "[", "os", ".", "pat...
33.538462
21.923077
def upload_part(Body=None, Bucket=None, ContentLength=None, ContentMD5=None, Key=None, PartNumber=None, UploadId=None, SSECustomerAlgorithm=None, SSECustomerKey=None, SSECustomerKeyMD5=None, RequestPayer=None): """ Uploads a part in a multipart upload. Note: After you initiate multipart upload and upload on...
[ "def", "upload_part", "(", "Body", "=", "None", ",", "Bucket", "=", "None", ",", "ContentLength", "=", "None", ",", "ContentMD5", "=", "None", ",", "Key", "=", "None", ",", "PartNumber", "=", "None", ",", "UploadId", "=", "None", ",", "SSECustomerAlgorit...
56.487179
49.153846
def parse_all(self): """Parse the __all__ definition in a module.""" assert self.current.value == "__all__" self.consume(tk.NAME) if self.current.value != "=": raise AllError("Could not evaluate contents of __all__. ") self.consume(tk.OP) if self.current.value...
[ "def", "parse_all", "(", "self", ")", ":", "assert", "self", ".", "current", ".", "value", "==", "\"__all__\"", "self", ".", "consume", "(", "tk", ".", "NAME", ")", "if", "self", ".", "current", ".", "value", "!=", "\"=\"", ":", "raise", "AllError", ...
38.147059
17.647059
def files_rm(self, path, recursive=False, **kwargs): """Removes a file from the MFS. .. code-block:: python >>> c.files_rm("/bla/file") b'' Parameters ---------- path : str Filepath within the MFS recursive : bool Recursi...
[ "def", "files_rm", "(", "self", ",", "path", ",", "recursive", "=", "False", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "\"opts\"", ",", "{", "\"recursive\"", ":", "recursive", "}", ")", "args", "=", "(", "path", ",", ")", ...
25.631579
18.894737
def settings_get(self, block_id, settings): '''Returns a list of key/value pairs (str, str).''' block = self._get_blocks([block_id.hex()])[0] block_header = BlockHeader() block_header.ParseFromString(block.header) try: settings_view = self._settings_view_factory.cr...
[ "def", "settings_get", "(", "self", ",", "block_id", ",", "settings", ")", ":", "block", "=", "self", ".", "_get_blocks", "(", "[", "block_id", ".", "hex", "(", ")", "]", ")", "[", "0", "]", "block_header", "=", "BlockHeader", "(", ")", "block_header",...
34.09375
21.03125
def postprocess_alignment(data): """Perform post-processing steps required on full BAM files. Prepares list of callable genome regions allowing subsequent parallelization. """ data = cwlutils.normalize_missing(utils.to_single_data(data)) data = cwlutils.unpack_tarballs(data, data) bam_file = dat...
[ "def", "postprocess_alignment", "(", "data", ")", ":", "data", "=", "cwlutils", ".", "normalize_missing", "(", "utils", ".", "to_single_data", "(", "data", ")", ")", "data", "=", "cwlutils", ".", "unpack_tarballs", "(", "data", ",", "data", ")", "bam_file", ...
57.181818
19.575758
def as_list(func): """ A decorator used to return a JSON response of a list of model objects. It expects the decorated function to return a list of model instances. It then converts the instances to dicts and serializes them into a json response Examples: >>> @app.route...
[ "def", "as_list", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "r...
31.434783
16.565217
def set_time_rate(self, value): ''' setter Time rate. ''' if isinstance(value, float) is False: raise TypeError("The type of __time_rate must be float.") if value <= 0.0: raise ValueError("The value of __time_rate must be greater than 0.0") ...
[ "def", "set_time_rate", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "float", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __time_rate must be float.\"", ")", "if", "value", "<=", "0.0", ":", "raise", "Val...
28
24.5
def update_project(project): """Update a project instance. :param project: PYBOSSA project :type project: PYBOSSA Project :returns: True -- the response status code """ try: project_id = project.id project = _forbidden_attributes(project) res = _pybossa_req('put', 'proj...
[ "def", "update_project", "(", "project", ")", ":", "try", ":", "project_id", "=", "project", ".", "id", "project", "=", "_forbidden_attributes", "(", "project", ")", "res", "=", "_pybossa_req", "(", "'put'", ",", "'project'", ",", "project_id", ",", "payload...
26.833333
16.722222
def decommission_brokers(self, broker_ids): """Decommission a list of brokers trying to keep the replication group the brokers belong to balanced. :param broker_ids: list of string representing valid broker ids in the cluster :raises: InvalidBrokerIdError when the id is invalid. ...
[ "def", "decommission_brokers", "(", "self", ",", "broker_ids", ")", ":", "groups", "=", "set", "(", ")", "for", "b_id", "in", "broker_ids", ":", "try", ":", "broker", "=", "self", ".", "cluster_topology", ".", "brokers", "[", "b_id", "]", "except", "KeyE...
42.26087
17.434783
def currentSchema( self ): """ Returns the schema found at the current index for this combo box. :return <orb.TableSchema> || None """ index = self.currentIndex() if ( 0 <= index and index < len(self._schemas) ): return self._schemas[in...
[ "def", "currentSchema", "(", "self", ")", ":", "index", "=", "self", ".", "currentIndex", "(", ")", "if", "(", "0", "<=", "index", "and", "index", "<", "len", "(", "self", ".", "_schemas", ")", ")", ":", "return", "self", ".", "_schemas", "[", "ind...
33.6
13
def account_balance_before(self): """Get the balance of the account associated with this leg before the transaction""" # TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support transaction_date = self.transaction.date return self.account.bala...
[ "def", "account_balance_before", "(", "self", ")", ":", "# TODO: Consider moving to annotation, particularly once we can count on Django 1.11's subquery support", "transaction_date", "=", "self", ".", "transaction", ".", "date", "return", "self", ".", "account", ".", "balance",...
46.076923
22.076923
def assign_methods(self, resource_class): """ Given a resource_class and it's Meta.methods tuple, assign methods for communicating with that resource. Args: resource_class: A single resource class """ assert all([ x.upper() in VALID_METHODS for x ...
[ "def", "assign_methods", "(", "self", ",", "resource_class", ")", ":", "assert", "all", "(", "[", "x", ".", "upper", "(", ")", "in", "VALID_METHODS", "for", "x", "in", "resource_class", ".", "Meta", ".", "methods", "]", ")", "for", "method", "in", "res...
31.1875
17.4375
def lstm(nlstm=128, layer_norm=False): """ Builds LSTM (Long-Short Term Memory) network to be used in a policy. Note that the resulting function returns not only the output of the LSTM (i.e. hidden state of lstm for each step in the sequence), but also a dictionary with auxiliary tensors to be set a...
[ "def", "lstm", "(", "nlstm", "=", "128", ",", "layer_norm", "=", "False", ")", ":", "def", "network_fn", "(", "X", ",", "nenv", "=", "1", ")", ":", "nbatch", "=", "X", ".", "shape", "[", "0", "]", "nsteps", "=", "nbatch", "//", "nenv", "h", "="...
34.673077
30.134615
def decode_preflist(self, item): """ Decodes a preflist response :param preflist: a bucket/key preflist :type preflist: list of riak.pb.riak_kv_pb2.RpbBucketKeyPreflistItem :rtype dict """ result = {'partition': item.partition, ...
[ "def", "decode_preflist", "(", "self", ",", "item", ")", ":", "result", "=", "{", "'partition'", ":", "item", ".", "partition", ",", "'node'", ":", "bytes_to_str", "(", "item", ".", "node", ")", ",", "'primary'", ":", "item", ".", "primary", "}", "retu...
31.769231
11.923077
def find_doi(self, curr_dict): """ Recursively search the file for the DOI id. More taxing, but more flexible when dictionary structuring isn't absolute :param dict curr_dict: Current dictionary being searched :return dict bool: Recursive - Current dictionary, False flag that DOI was not...
[ "def", "find_doi", "(", "self", ",", "curr_dict", ")", ":", "try", ":", "if", "'id'", "in", "curr_dict", ":", "return", "curr_dict", "[", "'id'", "]", ",", "True", "elif", "isinstance", "(", "curr_dict", ",", "list", ")", ":", "for", "i", "in", "curr...
44.73913
15.521739
def autopilot_version_encode(self, capabilities, flight_sw_version, middleware_sw_version, os_sw_version, board_version, flight_custom_version, middleware_custom_version, os_custom_version, vendor_id, product_id, uid): ''' Version and capability of autopilot software cap...
[ "def", "autopilot_version_encode", "(", "self", ",", "capabilities", ",", "flight_sw_version", ",", "middleware_sw_version", ",", "os_sw_version", ",", "board_version", ",", "flight_custom_version", ",", "middleware_custom_version", ",", "os_custom_version", ",", "vendor_id...
113.222222
86.777778
def get_top_n_action_types(self, top_n): """Returns the top N actions by count.""" # Count action types action_type_to_counts = dict() for action in self.actions: actiontype = action.actiontype if actiontype not in action_type_to_counts: action_typ...
[ "def", "get_top_n_action_types", "(", "self", ",", "top_n", ")", ":", "# Count action types", "action_type_to_counts", "=", "dict", "(", ")", "for", "action", "in", "self", ".", "actions", ":", "actiontype", "=", "action", ".", "actiontype", "if", "actiontype", ...
39.1
14.525
def plotnorm(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None, tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400): """ Make a light-weight norm figure """ fields = ['zs', 'sizes', 'colors', 'abssnr', 'key', 'snrs'] if not circleinds...
[ "def", "plotnorm", "(", "data", ",", "circleinds", "=", "[", "]", ",", "crossinds", "=", "[", "]", ",", "edgeinds", "=", "[", "]", ",", "url_path", "=", "None", ",", "fileroot", "=", "None", ",", "tools", "=", "\"hover,tap,pan,box_select,wheel_zoom,reset\"...
56.393939
40.727273
def get_os_type(self, version_text): # pylint: disable=no-self-use """Return the OS type information from the device.""" os_type = None if version_text is None: return os_type match = re.search("(XR|XE|NX-OS)", version_text) if match: os_type = match.gro...
[ "def", "get_os_type", "(", "self", ",", "version_text", ")", ":", "# pylint: disable=no-self-use", "os_type", "=", "None", "if", "version_text", "is", "None", ":", "return", "os_type", "match", "=", "re", ".", "search", "(", "\"(XR|XE|NX-OS)\"", ",", "version_te...
32.15
18
def check_conventions_are_cf_16(self, ds): ''' Check the global attribute conventions to contain CF-1.6 CF §2.6.1 the NUG defined global attribute Conventions to the string value "CF-1.6" :param netCDF4.Dataset ds: An open netCDF dataset :rtype: compliance_checker.base....
[ "def", "check_conventions_are_cf_16", "(", "self", ",", "ds", ")", ":", "valid", "=", "False", "reasoning", "=", "[", "]", "if", "hasattr", "(", "ds", ",", "'Conventions'", ")", ":", "conventions", "=", "regex", ".", "split", "(", "r',|\\s+'", ",", "geta...
38.814815
22.740741
def clear(self): """Clear the contents of the ROI.""" self._srcs = [] self._diffuse_srcs = [] self._src_dict = collections.defaultdict(list) self._src_radius = []
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_srcs", "=", "[", "]", "self", ".", "_diffuse_srcs", "=", "[", "]", "self", ".", "_src_dict", "=", "collections", ".", "defaultdict", "(", "list", ")", "self", ".", "_src_radius", "=", "[", "]" ]
32.833333
12.5
def remove_image_info_cb(self, gshell, channel, iminfo): """Delete entries related to deleted image.""" chname = channel.name if chname not in self.name_dict: return fileDict = self.name_dict[chname] name = iminfo.name if name not in fileDict: re...
[ "def", "remove_image_info_cb", "(", "self", ",", "gshell", ",", "channel", ",", "iminfo", ")", ":", "chname", "=", "channel", ".", "name", "if", "chname", "not", "in", "self", ".", "name_dict", ":", "return", "fileDict", "=", "self", ".", "name_dict", "[...
26.35
19.25
def create(**kwargs): """ Create and a return a specialized contract based on the given secType, or a general Contract if secType is not given. """ secType = kwargs.get('secType', '') cls = { '': Contract, 'STK': Stock, 'OPT': Option, ...
[ "def", "create", "(", "*", "*", "kwargs", ")", ":", "secType", "=", "kwargs", ".", "get", "(", "'secType'", ",", "''", ")", "cls", "=", "{", "''", ":", "Contract", ",", "'STK'", ":", "Stock", ",", "'OPT'", ":", "Option", ",", "'FUT'", ":", "Futur...
29.518519
12.407407
def resize_image(fullfile,fullfile_resized,_megapixels): """Resizes image (fullfile), saves to fullfile_resized. Image aspect ratio is conserved, will be scaled to be close to _megapixels in size. Eg if _megapixels=2, will resize 2560x1920 so each dimension is scaled by ((2**(20+1*MP))/float(2560*1920)...
[ "def", "resize_image", "(", "fullfile", ",", "fullfile_resized", ",", "_megapixels", ")", ":", "logger", ".", "debug", "(", "\"%s - Resizing to %s MP\"", "%", "(", "fullfile", ",", "_megapixels", ")", ")", "img", "=", "Image", ".", "open", "(", "fullfile", "...
36.657143
22.571429
def do_delete_config(self, line): """delete_config <peer> <source> eg. delete_config sw1 startup """ def f(p, args): try: source = args[0] except: print("argument error") return print(p.delete_config(sou...
[ "def", "do_delete_config", "(", "self", ",", "line", ")", ":", "def", "f", "(", "p", ",", "args", ")", ":", "try", ":", "source", "=", "args", "[", "0", "]", "except", ":", "print", "(", "\"argument error\"", ")", "return", "print", "(", "p", ".", ...
24.571429
13.642857
def get_tokens(condition): """ Get AST tokens for Python condition. Returns: list: list of AST tokens """ try: ast_tokens = list(ast.walk(ast.parse(condition.strip()))) except SyntaxError as exception: Logger.get_logger(__name__).error...
[ "def", "get_tokens", "(", "condition", ")", ":", "try", ":", "ast_tokens", "=", "list", "(", "ast", ".", "walk", "(", "ast", ".", "parse", "(", "condition", ".", "strip", "(", ")", ")", ")", ")", "except", "SyntaxError", "as", "exception", ":", "Logg...
30.230769
15.923077
def fillna(data, other, join="left", dataset_join="left"): """Fill missing values in this object with data from the other object. Follows normal broadcasting and alignment rules. Parameters ---------- join : {'outer', 'inner', 'left', 'right'}, optional Method for joining the indexes of the...
[ "def", "fillna", "(", "data", ",", "other", ",", "join", "=", "\"left\"", ",", "dataset_join", "=", "\"left\"", ")", ":", "from", ".", "computation", "import", "apply_ufunc", "return", "apply_ufunc", "(", "duck_array_ops", ".", "fillna", ",", "data", ",", ...
45.451613
17.741935
def write(self, suffix=None): """Write the collected coverage data to a file. `suffix` is a suffix to append to the base file name. This can be used for multiple or parallel execution, so that many coverage data files can exist simultaneously. A dot will be used to join the base name a...
[ "def", "write", "(", "self", ",", "suffix", "=", "None", ")", ":", "if", "self", ".", "use_file", ":", "filename", "=", "self", ".", "filename", "if", "suffix", ":", "filename", "+=", "\".\"", "+", "suffix", "self", ".", "write_file", "(", "filename", ...
36.214286
18.928571
def inheritdoc(method): """Set __doc__ of *method* to __doc__ of *method* in its parent class. Since this is used on :class:`.StringMixIn`, the "parent class" used is ``str``. This function can be used as a decorator. """ method.__doc__ = getattr(str, method.__name__).__doc__ return method
[ "def", "inheritdoc", "(", "method", ")", ":", "method", ".", "__doc__", "=", "getattr", "(", "str", ",", "method", ".", "__name__", ")", ".", "__doc__", "return", "method" ]
38.5
18.375
def merge(self, other): '''Merge another link into this one. Expected that each link was created from each mate from a pair. We only know both distances to contig ends when we have read info from both mappings in a BAM file. All other info should be the same.''' assert self.refnames == other.refnames ...
[ "def", "merge", "(", "self", ",", "other", ")", ":", "assert", "self", ".", "refnames", "==", "other", ".", "refnames", "assert", "self", ".", "dirs", "==", "other", ".", "dirs", "assert", "self", ".", "lengths", "==", "other", ".", "lengths", "for", ...
56.928571
31.357143
def get_pos_hint(poshints, sizehintx, sizehinty): """Return a tuple of ``(pos_hint_x, pos_hint_y)`` even if neither of those keys are present in the provided ``poshints`` -- they can be computed using the available keys together with ``size_hint_x`` and ``size_hint_y``. """ return ( get...
[ "def", "get_pos_hint", "(", "poshints", ",", "sizehintx", ",", "sizehinty", ")", ":", "return", "(", "get_pos_hint_x", "(", "poshints", ",", "sizehintx", ")", ",", "get_pos_hint_y", "(", "poshints", ",", "sizehinty", ")", ")" ]
35.727273
17.454545
def onMargins(self, left=0.1, top=0.1, right=0.1, bottom=0.1): """ pass left/right margins on to bottom panel""" bconf = self.panel_bot.conf l, t, r, b = bconf.margins bconf.set_margins(left=left, top=t, right=right, bottom=b) bconf.canvas.draw()
[ "def", "onMargins", "(", "self", ",", "left", "=", "0.1", ",", "top", "=", "0.1", ",", "right", "=", "0.1", ",", "bottom", "=", "0.1", ")", ":", "bconf", "=", "self", ".", "panel_bot", ".", "conf", "l", ",", "t", ",", "r", ",", "b", "=", "bco...
46.833333
12
def conditionally_independent(tpm): """Validate that the TPM is conditionally independent.""" if not config.VALIDATE_CONDITIONAL_INDEPENDENCE: return True tpm = np.array(tpm) if is_state_by_state(tpm): there_and_back_again = convert.state_by_node2state_by_state( convert.state...
[ "def", "conditionally_independent", "(", "tpm", ")", ":", "if", "not", "config", ".", "VALIDATE_CONDITIONAL_INDEPENDENCE", ":", "return", "True", "tpm", "=", "np", ".", "array", "(", "tpm", ")", "if", "is_state_by_state", "(", "tpm", ")", ":", "there_and_back_...
44.352941
17.235294
def write(self, session, data): """Writes data to device or interface synchronously. Corresponds to viWrite function of the VISA library. :param session: Unique logical identifier to a session. :param data: data to be written. :type data: str :return: Number of bytes ac...
[ "def", "write", "(", "self", ",", "session", ",", "data", ")", ":", "# from the session handle, dispatch to the write method of the session object.", "try", ":", "ret", "=", "self", ".", "sessions", "[", "session", "]", ".", "write", "(", "data", ")", "except", ...
32.636364
22.045455
def _compute_raw_moments(self, n_counter, k_counter): # The symbols for expectations are simply the first order raw moments. """ :param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments :type n_counter: list[:class:`~means.core.descriptors.Momen...
[ "def", "_compute_raw_moments", "(", "self", ",", "n_counter", ",", "k_counter", ")", ":", "# The symbols for expectations are simply the first order raw moments.", "expectation_symbols", "=", "[", "pm", ".", "symbol", "for", "pm", "in", "k_counter", "if", "pm", ".", "...
56
39.954545
def on_balancer_remove(self, name): """ The removal of a load balancer config isn't supported just yet. If the balancer being removed is the only configured one we fire a critical log message saying so. A writer setup with no balancers is less than useless. """ ...
[ "def", "on_balancer_remove", "(", "self", ",", "name", ")", ":", "if", "len", "(", "self", ".", "configurables", "[", "Balancer", "]", ")", "==", "1", ":", "logger", ".", "critical", "(", "\"'%s' config file removed! It was the only balancer left!\"", ",", "name...
37.692308
19.846154
def object(self, infotype, key): "Return the encoding, idletime, or refcount about the key" return self.execute_command('OBJECT', infotype, key, infotype=infotype)
[ "def", "object", "(", "self", ",", "infotype", ",", "key", ")", ":", "return", "self", ".", "execute_command", "(", "'OBJECT'", ",", "infotype", ",", "key", ",", "infotype", "=", "infotype", ")" ]
59
24.333333
def find_collection_ids(self, search_pattern="", identifier="", fetched=0, page=1): """ Fetches a list of resource URLs for every resource in the database. :param string search_pattern: A search pattern to use in looking up resources by title or resourceid. The search will match any...
[ "def", "find_collection_ids", "(", "self", ",", "search_pattern", "=", "\"\"", ",", "identifier", "=", "\"\"", ",", "fetched", "=", "0", ",", "page", "=", "1", ")", ":", "params", "=", "{", "\"page\"", ":", "page", ",", "\"q\"", ":", "\"primary_type:reso...
48.027778
31.194444
def find_stream(self, **kwargs): """ Finds a single stream with the given meta data values. Useful for debugging purposes. :param kwargs: The meta data as keyword arguments :return: The stream found """ found = list(self.find_streams(**kwargs).values()) if not fo...
[ "def", "find_stream", "(", "self", ",", "*", "*", "kwargs", ")", ":", "found", "=", "list", "(", "self", ".", "find_streams", "(", "*", "*", "kwargs", ")", ".", "values", "(", ")", ")", "if", "not", "found", ":", "raise", "StreamNotFoundError", "(", ...
35.461538
16.076923