text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def shut_down_instance(self, instances=None): """Shut down a list of instances, if provided. If no instance is provided, the last instance started up will be shut down. """ if instances and len(self.instances) > 0: print(instances) try: print([i....
[ "def", "shut_down_instance", "(", "self", ",", "instances", "=", "None", ")", ":", "if", "instances", "and", "len", "(", "self", ".", "instances", ")", ">", "0", ":", "print", "(", "instances", ")", "try", ":", "print", "(", "[", "i", ".", "id", "f...
40.347826
19.695652
def parse_stats_file(self, file_name): """ Read and parse given file_name, return config as a dictionary """ stats = {} try: with open(file_name, "r") as fhandle: fbuffer = [] save_buffer = False for line in fhandle: ...
[ "def", "parse_stats_file", "(", "self", ",", "file_name", ")", ":", "stats", "=", "{", "}", "try", ":", "with", "open", "(", "file_name", ",", "\"r\"", ")", "as", "fhandle", ":", "fbuffer", "=", "[", "]", "save_buffer", "=", "False", "for", "line", "...
39.190476
14.309524
def _renameClasses(classes, prefix): """ Replace class IDs with nice strings. """ renameMap = {} for classID, glyphList in classes.items(): if len(glyphList) == 0: groupName = "%s_empty_lu.%d_st.%d_cl.%d" % (prefix, classID[0], classID[1], classID[2]) elif len(glyphList) ...
[ "def", "_renameClasses", "(", "classes", ",", "prefix", ")", ":", "renameMap", "=", "{", "}", "for", "classID", ",", "glyphList", "in", "classes", ".", "items", "(", ")", ":", "if", "len", "(", "glyphList", ")", "==", "0", ":", "groupName", "=", "\"%...
34.8
11.333333
def _get_more(collection_name, num_to_return, cursor_id): """Get an OP_GET_MORE message.""" return b"".join([ _ZERO_32, _make_c_string(collection_name), _pack_int(num_to_return), _pack_long_long(cursor_id)])
[ "def", "_get_more", "(", "collection_name", ",", "num_to_return", ",", "cursor_id", ")", ":", "return", "b\"\"", ".", "join", "(", "[", "_ZERO_32", ",", "_make_c_string", "(", "collection_name", ")", ",", "_pack_int", "(", "num_to_return", ")", ",", "_pack_lon...
34.428571
10
def update(self, title, rulegroups): """Updates this segment.""" body = { "Title": title, "RuleGroups": rulegroups} response = self._put("/segments/%s.json" % self.segment_id, json.dumps(body))
[ "def", "update", "(", "self", ",", "title", ",", "rulegroups", ")", ":", "body", "=", "{", "\"Title\"", ":", "title", ",", "\"RuleGroups\"", ":", "rulegroups", "}", "response", "=", "self", ".", "_put", "(", "\"/segments/%s.json\"", "%", "self", ".", "se...
37.714286
11
def reparentDirectories(self): ''' Helper method for :func:`~exhale.graph.ExhaleRoot.reparentAll`. Adds subdirectories as children to the relevant directory ExhaleNode. If a node in ``self.dirs`` is added as a child to a different directory node, it is removed from the ``self.d...
[ "def", "reparentDirectories", "(", "self", ")", ":", "dir_parts", "=", "[", "]", "dir_ranks", "=", "[", "]", "for", "d", "in", "self", ".", "dirs", ":", "parts", "=", "d", ".", "name", ".", "split", "(", "os", ".", "sep", ")", "for", "p", "in", ...
38.852941
17.029412
def getPortNumberList(self): """ Get the port number of each hub toward device. """ port_list = (c_uint8 * PATH_MAX_DEPTH)() result = libusb1.libusb_get_port_numbers( self.device_p, port_list, len(port_list)) mayRaiseUSBError(result) return list(port_l...
[ "def", "getPortNumberList", "(", "self", ")", ":", "port_list", "=", "(", "c_uint8", "*", "PATH_MAX_DEPTH", ")", "(", ")", "result", "=", "libusb1", ".", "libusb_get_port_numbers", "(", "self", ".", "device_p", ",", "port_list", ",", "len", "(", "port_list",...
36.111111
7.222222
def linkify_es_by_h(self, hosts): """Add each escalation object into host.escalation attribute :param hosts: host list, used to look for a specific host :type hosts: alignak.objects.host.Hosts :return: None """ for escal in self: # If no host, no hope of havi...
[ "def", "linkify_es_by_h", "(", "self", ",", "hosts", ")", ":", "for", "escal", "in", "self", ":", "# If no host, no hope of having a service", "if", "(", "not", "hasattr", "(", "escal", ",", "'host_name'", ")", "or", "escal", ".", "host_name", ".", "strip", ...
45.444444
16.611111
def postpro_standardize(data, report=None): """ Standardizes everything in data (along axis -1). If report variable is passed, this is added to the report. """ if not report: report = {} # First make dim 1 = time. data = np.transpose(data, [2, 0, 1]) standardized_data = (data - ...
[ "def", "postpro_standardize", "(", "data", ",", "report", "=", "None", ")", ":", "if", "not", "report", ":", "report", "=", "{", "}", "# First make dim 1 = time.", "data", "=", "np", ".", "transpose", "(", "data", ",", "[", "2", ",", "0", ",", "1", "...
36.666667
13.111111
def _PrintProcessingTime(self, processing_status): """Prints the processing time. Args: processing_status (ProcessingStatus): processing status. """ if not processing_status: processing_time = '00:00:00' else: processing_time = time.time() - processing_status.start_time time...
[ "def", "_PrintProcessingTime", "(", "self", ",", "processing_status", ")", ":", "if", "not", "processing_status", ":", "processing_time", "=", "'00:00:00'", "else", ":", "processing_time", "=", "time", ".", "time", "(", ")", "-", "processing_status", ".", "start...
33.533333
18.666667
def set_date_bounds(self, date): ''' Pass in the date used in the original query. :param date: Date (date range) that was queried: date -> 'd', '~d', 'd~', 'd~d' d -> '%Y-%m-%d %H:%M:%S,%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d' ''' if date is not None: ...
[ "def", "set_date_bounds", "(", "self", ",", "date", ")", ":", "if", "date", "is", "not", "None", ":", "split", "=", "date", ".", "split", "(", "'~'", ")", "if", "len", "(", "split", ")", "==", "1", ":", "self", ".", "_lbound", "=", "ts2dt", "(", ...
37.5
14.9
def create_pipfile(self, python=None): """Creates the Pipfile, filled with juicy defaults.""" from .vendor.pip_shims.shims import ( ConfigOptionParser, make_option_group, index_group ) config_parser = ConfigOptionParser(name=self.name) config_parser.add_option_group(...
[ "def", "create_pipfile", "(", "self", ",", "python", "=", "None", ")", ":", "from", ".", "vendor", ".", "pip_shims", ".", "shims", "import", "(", "ConfigOptionParser", ",", "make_option_group", ",", "index_group", ")", "config_parser", "=", "ConfigOptionParser",...
36.761905
19
def has_methods(*method_names): """Return a test function that, when given an object (class or an instance), returns ``True`` if that object has all of the (regular) methods in ``method_names``. Note: this is testing for regular methods only and the test function will correctly return ``False`` if an in...
[ "def", "has_methods", "(", "*", "method_names", ")", ":", "def", "test", "(", "obj", ")", ":", "for", "method_name", "in", "method_names", ":", "try", ":", "method", "=", "getattr", "(", "obj", ",", "method_name", ")", "except", "AttributeError", ":", "r...
40.366667
17.766667
def update_token(self, token, secret): """Update token with new values. :param token: The token value. :param secret: The secret key. """ if self.access_token != token or self.secret != secret: with db.session.begin_nested(): self.access_token = token...
[ "def", "update_token", "(", "self", ",", "token", ",", "secret", ")", ":", "if", "self", ".", "access_token", "!=", "token", "or", "self", ".", "secret", "!=", "secret", ":", "with", "db", ".", "session", ".", "begin_nested", "(", ")", ":", "self", "...
34.909091
7.363636
def whiten(self, segment_duration, max_filter_duration, trunc_method='hann', remove_corrupted=True, low_frequency_cutoff=None, return_psd=False, **kwds): """ Return a whitened time series Parameters ---------- segment_duration: float ...
[ "def", "whiten", "(", "self", ",", "segment_duration", ",", "max_filter_duration", ",", "trunc_method", "=", "'hann'", ",", "remove_corrupted", "=", "True", ",", "low_frequency_cutoff", "=", "None", ",", "return_psd", "=", "False", ",", "*", "*", "kwds", ")", ...
41.618182
20.927273
def _create_transmissions(self, content_metadata_item_map): """ Create ContentMetadataItemTransmision models for the given content metadata items. """ # pylint: disable=invalid-name ContentMetadataItemTransmission = apps.get_model( 'integrated_channel', 'C...
[ "def", "_create_transmissions", "(", "self", ",", "content_metadata_item_map", ")", ":", "# pylint: disable=invalid-name", "ContentMetadataItemTransmission", "=", "apps", ".", "get_model", "(", "'integrated_channel'", ",", "'ContentMetadataItemTransmission'", ")", "transmission...
45.8
19.8
def apply_getters(self, task): """ This function is called when we specify the task dependencies with the syntax: deps={node: "@property"} In this case the task has to the get `property` from `node` before starting the calculation. At present, the following properties are ...
[ "def", "apply_getters", "(", "self", ",", "task", ")", ":", "if", "not", "self", ".", "getters", ":", "return", "for", "getter", "in", "self", ".", "getters", ":", "if", "getter", "==", "\"@structure\"", ":", "task", ".", "history", ".", "info", "(", ...
34.857143
22.857143
def quotes_by_instrument_urls(cls, client, urls): """ fetch and return results """ instruments = ",".join(urls) params = {"instruments": instruments} url = "https://api.robinhood.com/marketdata/quotes/" data = client.get(url, params=params) results = data[...
[ "def", "quotes_by_instrument_urls", "(", "cls", ",", "client", ",", "urls", ")", ":", "instruments", "=", "\",\"", ".", "join", "(", "urls", ")", "params", "=", "{", "\"instruments\"", ":", "instruments", "}", "url", "=", "\"https://api.robinhood.com/marketdata/...
36.615385
6.769231
def get_vulnerability_functions_05(node, fname): """ :param node: a vulnerabilityModel node :param fname: path of the vulnerability filter :returns: a dictionary imt, vf_id -> vulnerability function """ # NB: the IMTs can be duplicated and with different levels, each ...
[ "def", "get_vulnerability_functions_05", "(", "node", ",", "fname", ")", ":", "# NB: the IMTs can be duplicated and with different levels, each", "# vulnerability function in a set will get its own levels", "vf_ids", "=", "set", "(", ")", "vmodel", "=", "scientific", ".", "Vuln...
43.184615
12.876923
def _layout(self, node): """ETE calls this function to style each node before rendering. - ETE terms: - A Style is a specification for how to render the node itself - A Face defines extra information that is rendered outside of the node - Face objects are used here to provide mo...
[ "def", "_layout", "(", "self", ",", "node", ")", ":", "def", "set_edge_style", "(", ")", ":", "\"\"\"Set the style for edges and make the node invisible.\"\"\"", "node_style", "=", "ete3", ".", "NodeStyle", "(", ")", "node_style", "[", "\"vt_line_color\"", "]", "=",...
36.461538
16.584615
def fit(self, X, y, sample_weight=None): """ Fit a binary classifier with sample weights to data. Note ---- Examples at each sample are accepted with probability = weight/Z, where Z = max(weight) + extra_rej_const. Larger values for extra_rej_const ensure...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "sample_weight", "=", "None", ")", ":", "assert", "self", ".", "extra_rej_const", ">=", "0", "if", "sample_weight", "is", "None", ":", "sample_weight", "=", "np", ".", "ones", "(", "y", ".", "shape"...
47.342105
22.289474
def segments_from_numpy(segments): """reverses segments_to_numpy""" segments = segments if SEGMENTS_DIRECTION == 0 else segments.tranpose() segments = [map(int, s) for s in segments] return segments
[ "def", "segments_from_numpy", "(", "segments", ")", ":", "segments", "=", "segments", "if", "SEGMENTS_DIRECTION", "==", "0", "else", "segments", ".", "tranpose", "(", ")", "segments", "=", "[", "map", "(", "int", ",", "s", ")", "for", "s", "in", "segment...
42
13.6
def items(self): """Get all the message's header fields and values. These will be sorted in the order they appeared in the original message, or were added to the message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. ...
[ "def", "items", "(", "self", ")", ":", "return", "[", "(", "k", ",", "self", ".", "policy", ".", "header_fetch_parse", "(", "k", ",", "v", ")", ")", "for", "k", ",", "v", "in", "self", ".", "_headers", "]" ]
41.8
21.1
def feed_packets(self, binary_packets, linktype=LinkTypes.ETHERNET): """ Gets a list of binary packets, parses them using tshark and returns their parsed values. Keeps the packets in the internal packet list as well. By default, assumes the packets are ethernet packets. For another link...
[ "def", "feed_packets", "(", "self", ",", "binary_packets", ",", "linktype", "=", "LinkTypes", ".", "ETHERNET", ")", ":", "self", ".", "_current_linktype", "=", "linktype", "parsed_packets", "=", "self", ".", "parse_packets", "(", "binary_packets", ")", "self", ...
46.461538
21.846154
def setSystemVariable(self, remote, name, value): """Set a system variable on CCU / Homegear""" if self.remotes[remote]['username'] and self.remotes[remote]['password']: LOG.debug( "ServerThread.setSystemVariable: Setting System variable via JSON-RPC") session = s...
[ "def", "setSystemVariable", "(", "self", ",", "remote", ",", "name", ",", "value", ")", ":", "if", "self", ".", "remotes", "[", "remote", "]", "[", "'username'", "]", "and", "self", ".", "remotes", "[", "remote", "]", "[", "'password'", "]", ":", "LO...
52.684211
25.289474
def upload(cls, file_obj, store=None): """Uploads a file and returns ``File`` instance. Args: - file_obj: file object to upload to - store (Optional[bool]): Should the file be automatically stored upon upload. Defaults to None. - False - do not st...
[ "def", "upload", "(", "cls", ",", "file_obj", ",", "store", "=", "None", ")", ":", "if", "store", "is", "None", ":", "store", "=", "'auto'", "elif", "store", ":", "store", "=", "'1'", "else", ":", "store", "=", "'0'", "data", "=", "{", "'UPLOADCARE...
29.419355
19.387097
def runSwarm(self, workingDirPath): """ Runs a swarm with data within a working directory. This assumes that the user has already run prepareSwarm(). :param workingDirPath: absolute or relative path to working directory """ if not os.path.exists(workingDirPath): raise Exception("Working d...
[ "def", "runSwarm", "(", "self", ",", "workingDirPath", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "workingDirPath", ")", ":", "raise", "Exception", "(", "\"Working directory %s does not exist!\"", "%", "workingDirPath", ")", "banner", "(", "...
43.1
13.3
def setDateTimeStart(self, dtime): """ Sets the starting date time for this gantt chart. :param dtime | <QDateTime> """ self._dateStart = dtime.date() self._timeStart = dtime.time() self._allDay = False
[ "def", "setDateTimeStart", "(", "self", ",", "dtime", ")", ":", "self", ".", "_dateStart", "=", "dtime", ".", "date", "(", ")", "self", ".", "_timeStart", "=", "dtime", ".", "time", "(", ")", "self", ".", "_allDay", "=", "False" ]
30.222222
7.555556
def from_connections(cls, caption, connections): """Create a new Data Source give a list of Connections.""" root = ET.Element('datasource', caption=caption, version='10.0', inline='true') outer_connection = ET.SubElement(root, 'connection') outer_connection.set('class', 'federated') ...
[ "def", "from_connections", "(", "cls", ",", "caption", ",", "connections", ")", ":", "root", "=", "ET", ".", "Element", "(", "'datasource'", ",", "caption", "=", "caption", ",", "version", "=", "'10.0'", ",", "inline", "=", "'true'", ")", "outer_connection...
49.642857
16.928571
def _gcs_get_key_names(bucket, pattern): """ Get names of all Google Cloud Storage keys in a specified bucket that match a pattern. """ return [obj.metadata.name for obj in _gcs_get_keys(bucket, pattern)]
[ "def", "_gcs_get_key_names", "(", "bucket", ",", "pattern", ")", ":", "return", "[", "obj", ".", "metadata", ".", "name", "for", "obj", "in", "_gcs_get_keys", "(", "bucket", ",", "pattern", ")", "]" ]
68.666667
10
def getLogicalLines(fp, allowQP=True, findBegin=False): """ Iterate through a stream, yielding one logical line at a time. Because many applications still use vCard 2.1, we have to deal with the quoted-printable encoding for long lines, as well as the vCard 3.0 and vCalendar line folding technique,...
[ "def", "getLogicalLines", "(", "fp", ",", "allowQP", "=", "True", ",", "findBegin", "=", "False", ")", ":", "if", "not", "allowQP", ":", "val", "=", "fp", ".", "read", "(", "-", "1", ")", "#Shouldn't need this anymore...", "\"\"\"\n if len(val) > 0:\n ...
35.659794
16.793814
def get_divisions(self): """ Get the "current" division and return a dictionary of divisions so the user can select the right one. """ ret = self.rest(GET('v1/current/Me?$select=CurrentDivision')) current_division = ret[0]['CurrentDivision'] assert isinstance(curr...
[ "def", "get_divisions", "(", "self", ")", ":", "ret", "=", "self", ".", "rest", "(", "GET", "(", "'v1/current/Me?$select=CurrentDivision'", ")", ")", "current_division", "=", "ret", "[", "0", "]", "[", "'CurrentDivision'", "]", "assert", "isinstance", "(", "...
40
16.933333
def _parse_response(self, respond): """parse text of response for HTTP errors This parses the text of the response to decide whether to retry request or raise exception. At the moment this only detects an exception condition. Args: respond (Response): requests.Respo...
[ "def", "_parse_response", "(", "self", ",", "respond", ")", ":", "# convert error messages into exceptions", "mobj", "=", "self", ".", "_max_qubit_error_re", ".", "match", "(", "respond", ".", "text", ")", "if", "mobj", ":", "raise", "RegisterSizeError", "(", "'...
31.782609
20.391304
def clone(src, dst_path, skip_globals, skip_dimensions, skip_variables): """ Mostly ripped from nc3tonc4 in netCDF4-python. Added ability to skip dimension and variables. Removed all of the unpacking logic for shorts. """ if os.path.exists(dst_path): os.unlink(dst_path) ...
[ "def", "clone", "(", "src", ",", "dst_path", ",", "skip_globals", ",", "skip_dimensions", ",", "skip_variables", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "dst_path", ")", ":", "os", ".", "unlink", "(", "dst_path", ")", "dst", "=", "netCDF...
28.564706
18.376471
def _init_client(): '''Setup client and init datastore. ''' global client, path_prefix if client is not None: return etcd_kwargs = { 'host': __opts__.get('etcd.host', '127.0.0.1'), 'port': __opts__.get('etcd.port', 2379), 'protocol': __opts__.get('etcd.pr...
[ "def", "_init_client", "(", ")", ":", "global", "client", ",", "path_prefix", "if", "client", "is", "not", "None", ":", "return", "etcd_kwargs", "=", "{", "'host'", ":", "__opts__", ".", "get", "(", "'etcd.host'", ",", "'127.0.0.1'", ")", ",", "'port'", ...
42.566667
20.233333
def dir(self, path='/', slash=True, bus=False, timeout=0): """list entities at path""" if slash: msg = MSG_DIRALLSLASH else: msg = MSG_DIRALL if bus: flags = self.flags | FLG_BUS_RET else: flags = self.flags & ~FLG_BUS_RET ...
[ "def", "dir", "(", "self", ",", "path", "=", "'/'", ",", "slash", "=", "True", ",", "bus", "=", "False", ",", "timeout", "=", "0", ")", ":", "if", "slash", ":", "msg", "=", "MSG_DIRALLSLASH", "else", ":", "msg", "=", "MSG_DIRALL", "if", "bus", ":...
29.157895
20.157895
def run_analysis( named_analysis, prepared_analyses=None,log_dir=default_log_dir): """ Runs just the named analysis. Otherwise just like run_analyses """ if prepared_analyses == None: prepared_analyses = prepare_analyses() state_collection = funtool.state_collection.StateCollection([],{}) ...
[ "def", "run_analysis", "(", "named_analysis", ",", "prepared_analyses", "=", "None", ",", "log_dir", "=", "default_log_dir", ")", ":", "if", "prepared_analyses", "==", "None", ":", "prepared_analyses", "=", "prepare_analyses", "(", ")", "state_collection", "=", "f...
46.818182
16.818182
def _prefix_from_prefix_string(self, prefixlen_str): """Turn a prefix length string into an integer. Args: prefixlen_str: A decimal string containing the prefix length. Returns: The prefix length as an integer. Raises: NetmaskValueError: If the inpu...
[ "def", "_prefix_from_prefix_string", "(", "self", ",", "prefixlen_str", ")", ":", "try", ":", "if", "not", "_BaseV4", ".", "_DECIMAL_DIGITS", ".", "issuperset", "(", "prefixlen_str", ")", ":", "raise", "ValueError", "prefixlen", "=", "int", "(", "prefixlen_str",...
33.391304
21.043478
def GetPathFromLink(resource_link, resource_type=''): """Gets path from resource link with optional resource type :param str resource_link: :param str resource_type: :return: Path from resource link with resource type appended (if provided). :rtype: str """ resource_link = TrimBegi...
[ "def", "GetPathFromLink", "(", "resource_link", ",", "resource_type", "=", "''", ")", ":", "resource_link", "=", "TrimBeginningAndEndingSlashes", "(", "resource_link", ")", "if", "IsNameBased", "(", "resource_link", ")", ":", "# Replace special characters in string using ...
42.909091
28.363636
def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = _dict_getitem(self, key) for val in vals[1:]: yield vals[0], val
[ "def", "iteritems", "(", "self", ")", ":", "for", "key", "in", "self", ":", "vals", "=", "_dict_getitem", "(", "self", ",", "key", ")", "for", "val", "in", "vals", "[", "1", ":", "]", ":", "yield", "vals", "[", "0", "]", ",", "val" ]
37.166667
8.833333
def merge(old_df, new_df, return_index=False): """ Merge two dataframes of buildings. The old dataframe is usually the buildings dataset and the new dataframe is a modified (by the user) version of what is returned by the pick method. Parameters ---------- old_d...
[ "def", "merge", "(", "old_df", ",", "new_df", ",", "return_index", "=", "False", ")", ":", "maxind", "=", "np", ".", "max", "(", "old_df", ".", "index", ".", "values", ")", "new_df", "=", "new_df", ".", "reset_index", "(", "drop", "=", "True", ")", ...
37.166667
20.055556
def getServiceModuleName(self): '''return module name. ''' name = GetModuleBaseNameFromWSDL(self.wsdl) if not name: raise WsdlGeneratorError, 'could not determine a service name' if self.server_module_suffix is None: return name return '%s...
[ "def", "getServiceModuleName", "(", "self", ")", ":", "name", "=", "GetModuleBaseNameFromWSDL", "(", "self", ".", "wsdl", ")", "if", "not", "name", ":", "raise", "WsdlGeneratorError", ",", "'could not determine a service name'", "if", "self", ".", "server_module_suf...
34.9
18.3
def _load_extensions(self): """ Load all extension files into the namespace pykwalify.ext """ log.debug(u"loading all extensions : %s", self.extensions) self.loaded_extensions = [] for f in self.extensions: if not os.path.isabs(f): f = os.pat...
[ "def", "_load_extensions", "(", "self", ")", ":", "log", ".", "debug", "(", "u\"loading all extensions : %s\"", ",", "self", ".", "extensions", ")", "self", ".", "loaded_extensions", "=", "[", "]", "for", "f", "in", "self", ".", "extensions", ":", "if", "n...
31.947368
19.631579
def run(self, args=None): """ Runs the main command or sub command based on user input """ if not args: args = self.parse(sys.argv[1:]) if getattr(args, 'verbose', False): self.logger.setLevel(logging.DEBUG) try: if hasattr(args, 'ru...
[ "def", "run", "(", "self", ",", "args", "=", "None", ")", ":", "if", "not", "args", ":", "args", "=", "self", ".", "parse", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "if", "getattr", "(", "args", ",", "'verbose'", ",", "False", ")", "...
29.869565
15.695652
def doesIntersect(self, other): ''' :param: other - Circle class Returns True iff: self.center.distance(other.center) <= self.radius+other.radius ''' otherType = type(other) if issubclass(otherType, Ellipse): distance = self.center.distance(other....
[ "def", "doesIntersect", "(", "self", ",", "other", ")", ":", "otherType", "=", "type", "(", "other", ")", "if", "issubclass", "(", "otherType", ",", "Ellipse", ")", ":", "distance", "=", "self", ".", "center", ".", "distance", "(", "other", ".", "cente...
30.631579
21.894737
def MethodCalled(self, mock_method): """Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raise...
[ "def", "MethodCalled", "(", "self", ",", "mock_method", ")", ":", "# Check to see if this method exists, and if so add it to the set of", "# called methods.", "for", "method", "in", "self", ".", "_methods", ":", "if", "method", "==", "mock_method", ":", "self", ".", "...
29.40625
22.96875
def get_url_rev_options(self, url): # type: (str) -> Tuple[str, RevOptions] """ Return the URL and RevOptions object to use in obtain() and in some cases export(), as a tuple (url, rev_options). """ url, rev, user_pass = self.get_url_rev_and_auth(url) username, pa...
[ "def", "get_url_rev_options", "(", "self", ",", "url", ")", ":", "# type: (str) -> Tuple[str, RevOptions]", "url", ",", "rev", ",", "user_pass", "=", "self", ".", "get_url_rev_and_auth", "(", "url", ")", "username", ",", "password", "=", "user_pass", "extra_args",...
41
15.166667
def db_to_df(db_file, slabs=None, facet=None): """Transforms database to data frame. Parameters ---------- db_file : Path to database slabs : Which metals (slabs) to select. facet : Which facets to select. Returns ------- df : Data frame. """ systems = [] data = [] ...
[ "def", "db_to_df", "(", "db_file", ",", "slabs", "=", "None", ",", "facet", "=", "None", ")", ":", "systems", "=", "[", "]", "data", "=", "[", "]", "if", "slabs", ":", "for", "slab", "in", "slabs", ":", "data_tmp", "=", "select_data", "(", "db_file...
30.77551
19.714286
def agent_run(args): """A version of `wandb run` that the agent uses to run things. """ run = wandb.wandb_run.Run.from_environment_or_defaults() run.enable_logging() api = wandb.apis.InternalApi() api.set_current_run_id(run.id) # TODO: better failure handling root = api.git.root # ...
[ "def", "agent_run", "(", "args", ")", ":", "run", "=", "wandb", ".", "wandb_run", ".", "Run", ".", "from_environment_or_defaults", "(", ")", "run", ".", "enable_logging", "(", ")", "api", "=", "wandb", ".", "apis", ".", "InternalApi", "(", ")", "api", ...
35.083333
16.388889
def com_google_fonts_check_canonical_filename(font): """Checking file is named canonically. A font's filename must be composed in the following manner: <familyname>-<stylename>.ttf e.g. Nunito-Regular.ttf, Oswald-BoldItalic.ttf Variable fonts must use the "-VF" suffix: e.g. Roboto-VF.ttf, ...
[ "def", "com_google_fonts_check_canonical_filename", "(", "font", ")", ":", "from", "fontTools", ".", "ttLib", "import", "TTFont", "from", "fontbakery", ".", "profiles", ".", "shared_conditions", "import", "is_variable_font", "from", "fontbakery", ".", "constants", "im...
38.555556
17.972222
def message(self, message, thread_id=None): """Message the user associated with this profile. :param message: The message to send to this user. :param thread_id: The id of the thread to respond to, if any. """ return_value = helpers.Messager(self._session).send( self...
[ "def", "message", "(", "self", ",", "message", ",", "thread_id", "=", "None", ")", ":", "return_value", "=", "helpers", ".", "Messager", "(", "self", ".", "_session", ")", ".", "send", "(", "self", ".", "username", ",", "message", ",", "self", ".", "...
38.818182
16.272727
def get_methods(self): """ Return all method objects :rtype: a list of :class:`EncodedMethod` objects """ if self.__cache_all_methods is None: self.__cache_all_methods = [] for i in self.get_classes(): for j in i.get_methods(): ...
[ "def", "get_methods", "(", "self", ")", ":", "if", "self", ".", "__cache_all_methods", "is", "None", ":", "self", ".", "__cache_all_methods", "=", "[", "]", "for", "i", "in", "self", ".", "get_classes", "(", ")", ":", "for", "j", "in", "i", ".", "get...
32.666667
8.5
def search(query, data, replacements=None): """Yield objects from 'data' that match the 'query'.""" query = q.Query(query, params=replacements) for entry in data: if solve.solve(query, entry).value: yield entry
[ "def", "search", "(", "query", ",", "data", ",", "replacements", "=", "None", ")", ":", "query", "=", "q", ".", "Query", "(", "query", ",", "params", "=", "replacements", ")", "for", "entry", "in", "data", ":", "if", "solve", ".", "solve", "(", "qu...
39.5
8
def convert_json_str_to_dict(i): """ Input: { str - string (use ' instead of ", i.e. {'a':'b'} to avoid issues in CMD in Windows and Linux!) (skip_quote_replacement) - if 'yes', do not make above replacement ...
[ "def", "convert_json_str_to_dict", "(", "i", ")", ":", "s", "=", "i", "[", "'str'", "]", "if", "i", ".", "get", "(", "'skip_quote_replacement'", ",", "''", ")", "!=", "'yes'", ":", "s", "=", "s", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")", "...
29.266667
24.533333
def get_contract(self, contract_name: str) -> Dict: """ Return ABI, BIN of the given contract. """ assert self.contracts, 'ContractManager should have contracts compiled' return self.contracts[contract_name]
[ "def", "get_contract", "(", "self", ",", "contract_name", ":", "str", ")", "->", "Dict", ":", "assert", "self", ".", "contracts", ",", "'ContractManager should have contracts compiled'", "return", "self", ".", "contracts", "[", "contract_name", "]" ]
57
13.5
def extract_tiff_thumbnail(self, thumb_ifd): """ Extract uncompressed TIFF thumbnail. Take advantage of the pre-existing layout in the thumbnail IFD as much as possible """ thumb = self.tags.get('Thumbnail Compression') if not thumb or thumb.printable != 'Uncompr...
[ "def", "extract_tiff_thumbnail", "(", "self", ",", "thumb_ifd", ")", ":", "thumb", "=", "self", ".", "tags", ".", "get", "(", "'Thumbnail Compression'", ")", "if", "not", "thumb", "or", "thumb", ".", "printable", "!=", "'Uncompressed TIFF'", ":", "return", "...
42.387097
14.645161
def vertical_padding(self, padding=None): """Returns or sets (if a value is provided) the chart's vertical padding. This determines how much space will be above and below the display area, as a proportion of overall height, and should be a value between 0 and 0.5 :param float pa...
[ "def", "vertical_padding", "(", "self", ",", "padding", "=", "None", ")", ":", "if", "padding", "is", "None", ":", "return", "self", ".", "_vertical_padding", "else", ":", "if", "not", "isinstance", "(", "padding", ",", "float", ")", ":", "raise", "TypeE...
43.571429
19.952381
def bytes2iec(size, compact=False): """ Convert a size value in bytes to its equivalent in IEC notation. See `<http://physics.nist.gov/cuu/Units/binary.html>`_. Parameters: size (int): Number of bytes. compact (bool): If ``True``, the result contains no spaces. Ret...
[ "def", "bytes2iec", "(", "size", ",", "compact", "=", "False", ")", ":", "postfn", "=", "lambda", "text", ":", "text", ".", "replace", "(", "' '", ",", "''", ")", "if", "compact", "else", "text", "if", "size", "<", "0", ":", "raise", "ValueError", ...
32.321429
22.428571
def example_add_line_to_file(): """ Different methods to append a given line to the file, all work the same. """ my_file = FileAsObj('/tmp/example_file.txt') my_file.add('foo') my_file.append('bar') # Add a new line to my_file that contains the word 'lol' and print True|False if my_file was changed....
[ "def", "example_add_line_to_file", "(", ")", ":", "my_file", "=", "FileAsObj", "(", "'/tmp/example_file.txt'", ")", "my_file", ".", "add", "(", "'foo'", ")", "my_file", ".", "append", "(", "'bar'", ")", "# Add a new line to my_file that contains the word 'lol' and print...
44.2
17.4
def add_actions(target, actions, insert_before=None): """Add actions to a QMenu or a QToolBar.""" previous_action = None target_actions = list(target.actions()) if target_actions: previous_action = target_actions[-1] if previous_action.isSeparator(): previous_action = ...
[ "def", "add_actions", "(", "target", ",", "actions", ",", "insert_before", "=", "None", ")", ":", "previous_action", "=", "None", "target_actions", "=", "list", "(", "target", ".", "actions", "(", ")", ")", "if", "target_actions", ":", "previous_action", "="...
41.694444
11.805556
def jwt_proccessor(): """Context processor for jwt.""" def jwt(): """Context processor function to generate jwt.""" token = current_accounts.jwt_creation_factory() return Markup( render_template( current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'], ...
[ "def", "jwt_proccessor", "(", ")", ":", "def", "jwt", "(", ")", ":", "\"\"\"Context processor function to generate jwt.\"\"\"", "token", "=", "current_accounts", ".", "jwt_creation_factory", "(", ")", "return", "Markup", "(", "render_template", "(", "current_app", "."...
27.5
19.9
def dispatch(self, message): """ dispatch """ handlers = [] for handler in self.handlers: if handler["method"] != message.method: continue handlers.append(handler) return handlers
[ "def", "dispatch", "(", "self", ",", "message", ")", ":", "handlers", "=", "[", "]", "for", "handler", "in", "self", ".", "handlers", ":", "if", "handler", "[", "\"method\"", "]", "!=", "message", ".", "method", ":", "continue", "handlers", ".", "appen...
23.454545
13.272727
def show(cls, msg=None): """ Show the log interface on the page. """ if msg: cls.add(msg) cls.overlay.show() cls.overlay.el.bind("click", lambda x: cls.hide()) cls.el.style.display = "block" cls.bind()
[ "def", "show", "(", "cls", ",", "msg", "=", "None", ")", ":", "if", "msg", ":", "cls", ".", "add", "(", "msg", ")", "cls", ".", "overlay", ".", "show", "(", ")", "cls", ".", "overlay", ".", "el", ".", "bind", "(", "\"click\"", ",", "lambda", ...
22.333333
16.333333
def add_arg(self, arg): """ Add an argument """ if not isinstance(arg, File): arg = str(arg) self._args += [arg]
[ "def", "add_arg", "(", "self", ",", "arg", ")", ":", "if", "not", "isinstance", "(", "arg", ",", "File", ")", ":", "arg", "=", "str", "(", "arg", ")", "self", ".", "_args", "+=", "[", "arg", "]" ]
21.571429
12.428571
def get_objects(self, subject=None, predicate=None): """Returns a generator of objects that correspond to the specified subjects and predicates.""" for triple in self.triples: # Filter out non-matches if ((subject and triple['subject'] != subject) or (pr...
[ "def", "get_objects", "(", "self", ",", "subject", "=", "None", ",", "predicate", "=", "None", ")", ":", "for", "triple", "in", "self", ".", "triples", ":", "# Filter out non-matches", "if", "(", "(", "subject", "and", "triple", "[", "'subject'", "]", "!...
34.75
17.5
def calc_asymptotic_covariance(hessian, fisher_info_matrix): """ Parameters ---------- hessian : 2D ndarray. It should have shape `(num_vars, num_vars)`. It is the matrix of second derivatives of the total loss across the dataset, with respect to each pair of coefficients being e...
[ "def", "calc_asymptotic_covariance", "(", "hessian", ",", "fisher_info_matrix", ")", ":", "# Calculate the inverse of the hessian", "hess_inv", "=", "scipy", ".", "linalg", ".", "inv", "(", "hessian", ")", "return", "np", ".", "dot", "(", "hess_inv", ",", "np", ...
41.84
21.52
async def _readline(self, timeout: NumType = None): """ Wraps reader.readuntil() with error handling. """ if self._stream_reader is None or self._stream_writer is None: raise SMTPServerDisconnected("Client not connected") read_task = asyncio.Task( self._s...
[ "async", "def", "_readline", "(", "self", ",", "timeout", ":", "NumType", "=", "None", ")", ":", "if", "self", ".", "_stream_reader", "is", "None", "or", "self", ".", "_stream_writer", "is", "None", ":", "raise", "SMTPServerDisconnected", "(", "\"Client not ...
38.612903
16.419355
def generate_user(self): '''generate a new user in the database, still session based so we create a new identifier. This function is called from the users new entrypoint, and it assumes we want a user generated with a token. ''' token = str(uuid.uuid4()) return self.generate_subid(token=t...
[ "def", "generate_user", "(", "self", ")", ":", "token", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "return", "self", ".", "generate_subid", "(", "token", "=", "token", ",", "return_user", "=", "True", ")" ]
48.142857
25.285714
def import_class(class_path): """ Returns class from the given path. For example, in order to get class located at ``mypackage.subpackage.MyClass``: try: hgrepo = import_class('mypackage.subpackage.MyClass') except ImportError: # hadle error """ splitted...
[ "def", "import_class", "(", "class_path", ")", ":", "splitted", "=", "class_path", ".", "split", "(", "'.'", ")", "mod_path", "=", "'.'", ".", "join", "(", "splitted", "[", ":", "-", "1", "]", ")", "class_name", "=", "splitted", "[", "-", "1", "]", ...
29.227273
14.681818
def _compute_threshold(x): """ ref: https://github.com/XJTUWYD/TWN Computing the threshold. """ x_sum = tf.reduce_sum(tf.abs(x), reduction_indices=None, keepdims=False, name=None) threshold = tf.div(x_sum, tf.cast(tf.size(x), tf.float32), name=None) threshold = tf.multiply(0.7, threshold, na...
[ "def", "_compute_threshold", "(", "x", ")", ":", "x_sum", "=", "tf", ".", "reduce_sum", "(", "tf", ".", "abs", "(", "x", ")", ",", "reduction_indices", "=", "None", ",", "keepdims", "=", "False", ",", "name", "=", "None", ")", "threshold", "=", "tf",...
37.888889
15.666667
def main(): """ Wrapper for OGR """ parser = argparse.ArgumentParser( description='Command line interface to python-ontobio.golr library' """ Provides command line interface onto the ontobio.golr python library, a high level abstraction layer over Monarch and GO solr in...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Command line interface to python-ontobio.golr library'", "\"\"\"\n\n Provides command line interface onto the ontobio.golr python library, a high level\n abstraction l...
37.430769
20.253846
def info(args): " Show information about site. " site = find_site(args.PATH) print_header("%s -- install information" % site.get_name()) LOGGER.debug(site.get_info(full=True)) return True
[ "def", "info", "(", "args", ")", ":", "site", "=", "find_site", "(", "args", ".", "PATH", ")", "print_header", "(", "\"%s -- install information\"", "%", "site", ".", "get_name", "(", ")", ")", "LOGGER", ".", "debug", "(", "site", ".", "get_info", "(", ...
28.857143
18.285714
def AddKeywordsForName(self, name, keywords): """Associates keywords with name. Records that keywords are associated with name. Args: name: A name which should be associated with some keywords. keywords: A collection of keywords to associate with name. """ data_store.DB.IndexAddKeyword...
[ "def", "AddKeywordsForName", "(", "self", ",", "name", ",", "keywords", ")", ":", "data_store", ".", "DB", ".", "IndexAddKeywordsForName", "(", "self", ".", "urn", ",", "name", ",", "keywords", ")" ]
34.5
20.3
def default(python=None, runas=None): ''' Returns or sets the currently defined default python. python=None The version to set as the default. Should match one of the versions listed by :mod:`pyenv.versions <salt.modules.pyenv.versions>`. Leave blank to return the current default. ...
[ "def", "default", "(", "python", "=", "None", ",", "runas", "=", "None", ")", ":", "if", "python", ":", "_pyenv_exec", "(", "'global'", ",", "python", ",", "runas", "=", "runas", ")", "return", "True", "else", ":", "ret", "=", "_pyenv_exec", "(", "'g...
28.045455
22.863636
def transition(trname='', field='', check=None, before=None, after=None): """Decorator to declare a function as a transition implementation.""" if is_callable(trname): raise ValueError( "The @transition decorator should be called as " "@transition(['transition_name'], **kwargs)")...
[ "def", "transition", "(", "trname", "=", "''", ",", "field", "=", "''", ",", "check", "=", "None", ",", "before", "=", "None", ",", "after", "=", "None", ")", ":", "if", "is_callable", "(", "trname", ")", ":", "raise", "ValueError", "(", "\"The @tran...
51.357143
20.142857
def create_instance(self, name, moduleName, settings): """ Creates an instance of <moduleName> at <name> with <settings>. """ if name in self.insts: raise ValueError("There's already an instance named %s" % name) if moduleName not in self.modu...
[ "def", "create_instance", "(", "self", ",", "name", ",", "moduleName", ",", "settings", ")", ":", "if", "name", "in", "self", ".", "insts", ":", "raise", "ValueError", "(", "\"There's already an instance named %s\"", "%", "name", ")", "if", "moduleName", "not"...
44.75
12.40625
def random_sample(self, k=1): """ Return a *k* length list of unique elements chosen from the Set. Elements are not removed. Similar to :func:`random.sample` function from standard library. :param k: Size of the sample, defaults to 1. :rtype: :class:`list` """ ...
[ "def", "random_sample", "(", "self", ",", "k", "=", "1", ")", ":", "# k == 0: no work to do", "if", "k", "==", "0", ":", "results", "=", "[", "]", "# k == 1: same behavior on all versions of Redis", "elif", "k", "==", "1", ":", "results", "=", "[", "self", ...
32.904762
19.095238
def from_dict(template_name, template_values_dict): """ Parses the input and returns an instance of this class. :param string template_name: Name of the template :param dict template_values_dict: Dictionary containing the value of the template. This dict must have passed the...
[ "def", "from_dict", "(", "template_name", ",", "template_values_dict", ")", ":", "parameters", "=", "template_values_dict", ".", "get", "(", "\"Parameters\"", ",", "{", "}", ")", "definition", "=", "template_values_dict", ".", "get", "(", "\"Definition\"", ",", ...
45.357143
26.785714
def build_stats(counts): """Return stats information from counts structure.""" stats = { 'status': 0, 'reportnum': counts['reportnum'], 'title': counts['title'], 'author': counts['auth_group'], 'url': counts['url'], 'doi': counts['doi'], 'misc': counts['mi...
[ "def", "build_stats", "(", "counts", ")", ":", "stats", "=", "{", "'status'", ":", "0", ",", "'reportnum'", ":", "counts", "[", "'reportnum'", "]", ",", "'title'", ":", "counts", "[", "'title'", "]", ",", "'author'", ":", "counts", "[", "'auth_group'", ...
35.3125
15.875
def tidy_eggs_list(eggs_list): """Tidy the given eggs list """ tmp = [] for line in eggs_list: line = line.lstrip().rstrip() line = line.replace('\'', '') line = line.replace(',', '') if line.endswith('site-packages'): continue tmp.append(line) ret...
[ "def", "tidy_eggs_list", "(", "eggs_list", ")", ":", "tmp", "=", "[", "]", "for", "line", "in", "eggs_list", ":", "line", "=", "line", ".", "lstrip", "(", ")", ".", "rstrip", "(", ")", "line", "=", "line", ".", "replace", "(", "'\\''", ",", "''", ...
26.333333
10.5
def load_from_file(cls, file_path): """Load the meta data given a file_path or empty meta data""" data = None if os.path.exists(file_path): metadata_file = open(file_path) data = json.loads(metadata_file.read()) return cls(initial=data)
[ "def", "load_from_file", "(", "cls", ",", "file_path", ")", ":", "data", "=", "None", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "metadata_file", "=", "open", "(", "file_path", ")", "data", "=", "json", ".", "loads", "(", "me...
40.857143
7.285714
def _merge_a_into_b(self, a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ from easydict import EasyDict as edict if type(a) is not edict: return for k, v in a.items(): ...
[ "def", "_merge_a_into_b", "(", "self", ",", "a", ",", "b", ")", ":", "from", "easydict", "import", "EasyDict", "as", "edict", "if", "type", "(", "a", ")", "is", "not", "edict", ":", "return", "for", "k", ",", "v", "in", "a", ".", "items", "(", ")...
36.878788
17
def _printAvailableCheckpoints(experimentDir): """List available checkpoints for the specified experiment.""" checkpointParentDir = getCheckpointParentDir(experimentDir) if not os.path.exists(checkpointParentDir): print "No available checkpoints." return checkpointDirs = [x for x in os.listdir(checkpo...
[ "def", "_printAvailableCheckpoints", "(", "experimentDir", ")", ":", "checkpointParentDir", "=", "getCheckpointParentDir", "(", "experimentDir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "checkpointParentDir", ")", ":", "print", "\"No available checkpoi...
35.769231
21
def moves_from_last_n_games(self, n, moves, shuffle, column_family, column): """Randomly choose a given number of moves from the last n games. Args: n: number of games at the end of this GameQueue to source. moves: number of moves to be sampled from...
[ "def", "moves_from_last_n_games", "(", "self", ",", "n", ",", "moves", ",", "shuffle", ",", "column_family", ",", "column", ")", ":", "self", ".", "wait_for_fresh_games", "(", ")", "latest_game", "=", "self", ".", "latest_game_number", "utils", ".", "dbg", "...
43.375
20.791667
def logsumexp(x): """Numerically stable log(sum(exp(x))), also defined in scipy.misc""" max_x = np.max(x) return max_x + np.log(np.sum(np.exp(x - max_x)))
[ "def", "logsumexp", "(", "x", ")", ":", "max_x", "=", "np", ".", "max", "(", "x", ")", "return", "max_x", "+", "np", ".", "log", "(", "np", ".", "sum", "(", "np", ".", "exp", "(", "x", "-", "max_x", ")", ")", ")" ]
40.75
13.5
def get_paged(self, endpoint, params=None, page_size=50, merge=False): """ GET with paging (for large payloads). :param page_size: how many objects per page :param endpoint: DHIS2 API endpoint :param params: HTTP parameters (dict), defaults to None :param merge: If true, ...
[ "def", "get_paged", "(", "self", ",", "endpoint", ",", "params", "=", "None", ",", "page_size", "=", "50", ",", "merge", "=", "False", ")", ":", "try", ":", "if", "not", "isinstance", "(", "page_size", ",", "(", "string_types", ",", "int", ")", ")", ...
41.380952
22.119048
def _reset_changes(self): """Stores current values for comparison later""" self._original = {} if self.last_updated is not None: self._original['last_updated'] = self.last_updated
[ "def", "_reset_changes", "(", "self", ")", ":", "self", ".", "_original", "=", "{", "}", "if", "self", ".", "last_updated", "is", "not", "None", ":", "self", ".", "_original", "[", "'last_updated'", "]", "=", "self", ".", "last_updated" ]
42.2
10.2
def add_vtarg_and_adv(seg, gamma, lam): """ Compute target value using TD(lambda) estimator, and advantage with GAE(lambda) """ new = np.append(seg["new"], 0) # last element is only used for last vtarg, but we already zeroed it if last new = 1 vpred = np.append(seg["vpred"], seg["nextvpred"]) T ...
[ "def", "add_vtarg_and_adv", "(", "seg", ",", "gamma", ",", "lam", ")", ":", "new", "=", "np", ".", "append", "(", "seg", "[", "\"new\"", "]", ",", "0", ")", "# last element is only used for last vtarg, but we already zeroed it if last new = 1", "vpred", "=", "np",...
45
19.533333
def create(self, name, **request_parameters): """Create a team. The authenticated user is automatically added as a member of the team. Args: name(basestring): A user-friendly name for the team. **request_parameters: Additional request parameters (provides ...
[ "def", "create", "(", "self", ",", "name", ",", "*", "*", "request_parameters", ")", ":", "check_type", "(", "name", ",", "basestring", ",", "may_be_none", "=", "False", ")", "post_data", "=", "dict_from_items_with_values", "(", "request_parameters", ",", "nam...
32.8
25.8
def scannerData(self, reqId, rank, contractDetails, distance, benchmark, projection, legsStr): """scannerData(EWrapper self, int reqId, int rank, ContractDetails contractDetails, IBString const & distance, IBString const & benchmark, IBString const & projection, IBString const & legsStr)""" return _swig...
[ "def", "scannerData", "(", "self", ",", "reqId", ",", "rank", ",", "contractDetails", ",", "distance", ",", "benchmark", ",", "projection", ",", "legsStr", ")", ":", "return", "_swigibpy", ".", "EWrapper_scannerData", "(", "self", ",", "reqId", ",", "rank", ...
140.333333
45.666667
def items_get(self, session, **kwargs): '''taobao.fenxiao.distributor.items.get 查询商品下载记录 供应商查询分销商商品下载记录。''' request = TOPRequest('taobao.fenxiao.distributor.items.get') for k, v in kwargs.iteritems(): if k not in ('distributor_id', 'start_modified', 'end_modified', '...
[ "def", "items_get", "(", "self", ",", "session", ",", "*", "*", "kwargs", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.fenxiao.distributor.items.get'", ")", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ")", ":", "if", "k", "not",...
55
30
def create_unique_id(src, ase): # type: (blobxfer.models.upload.LocalPath, # blobxfer.models.azure.StorageEntity) -> str """Create a unique id given a LocalPath and StorageEntity :param blobxfer.models.upload.LocalPath src: local path :param blobxfer.models.azure.StorageEn...
[ "def", "create_unique_id", "(", "src", ",", "ase", ")", ":", "# type: (blobxfer.models.upload.LocalPath,", "# blobxfer.models.azure.StorageEntity) -> str", "return", "';'", ".", "join", "(", "(", "str", "(", "src", ".", "absolute_path", ")", ",", "ase", ".", ...
43.25
17.25
def unpickle(filepath): """Decompress and unpickle.""" arr = [] with open(filepath, 'rb') as f: carr = f.read(blosc.MAX_BUFFERSIZE) while len(carr) > 0: arr.append(blosc.decompress(carr)) carr = f.read(blosc.MAX_BUFFERSIZE) return pkl.loads(b"".join(arr))
[ "def", "unpickle", "(", "filepath", ")", ":", "arr", "=", "[", "]", "with", "open", "(", "filepath", ",", "'rb'", ")", "as", "f", ":", "carr", "=", "f", ".", "read", "(", "blosc", ".", "MAX_BUFFERSIZE", ")", "while", "len", "(", "carr", ")", ">",...
33.666667
9.222222
def growth_curve(self, method='best', **method_options): """ Return QMED estimate using best available methodology depending on what catchment attributes are available. ====================== ====================== ================================================================== `meth...
[ "def", "growth_curve", "(", "self", ",", "method", "=", "'best'", ",", "*", "*", "method_options", ")", ":", "if", "method", "==", "'best'", ":", "if", "self", ".", "catchment", ".", "amax_records", ":", "# Gauged catchment, use enhanced single site", "self", ...
61.631579
34
def neighbors((x, y)): """Return the (possibly out of bounds) neighbors of a point.""" yield x + 1, y yield x - 1, y yield x, y + 1 yield x, y - 1 yield x + 1, y + 1 yield x + 1, y - 1 yield x - 1, y + 1 yield x - 1, y - 1
[ "def", "neighbors", "(", "(", "x", ",", "y", ")", ")", ":", "yield", "x", "+", "1", ",", "y", "yield", "x", "-", "1", ",", "y", "yield", "x", ",", "y", "+", "1", "yield", "x", ",", "y", "-", "1", "yield", "x", "+", "1", ",", "y", "+", ...
24.9
17.8
def _get_url(self, url): """Build provider's url. Join with base_url part if needed.""" if self.base_url and not url.startswith(('http://', 'https://')): return urljoin(self.base_url, url) return url
[ "def", "_get_url", "(", "self", ",", "url", ")", ":", "if", "self", ".", "base_url", "and", "not", "url", ".", "startswith", "(", "(", "'http://'", ",", "'https://'", ")", ")", ":", "return", "urljoin", "(", "self", ".", "base_url", ",", "url", ")", ...
46.2
15.4
def do_updatereplication(self, line): """updatereplication <identifier> [identifier ...] Update the Replication Policy on one or more existing Science Data Objects.""" pids = self._split_args(line, 1, -1) self._command_processor.update_replication_policy(pids) self._print_info_if...
[ "def", "do_updatereplication", "(", "self", ",", "line", ")", ":", "pids", "=", "self", ".", "_split_args", "(", "line", ",", "1", ",", "-", "1", ")", "self", ".", "_command_processor", ".", "update_replication_policy", "(", "pids", ")", "self", ".", "_p...
47.4
15.8
def register(cls, subclass): """Register a virtual subclass of an ABC.""" if not isinstance(cls, type): raise TypeError("Can only register classes") if issubclass(subclass, cls): return # Already a subclass # Subtle: test for cycles *after* testing for "already a...
[ "def", "register", "(", "cls", ",", "subclass", ")", ":", "if", "not", "isinstance", "(", "cls", ",", "type", ")", ":", "raise", "TypeError", "(", "\"Can only register classes\"", ")", "if", "issubclass", "(", "subclass", ",", "cls", ")", ":", "return", ...
51.461538
13.923077
def get_team_id(team_name): """ Returns the team ID associated with the team name that is passed in. Parameters ---------- team_name : str The team name whose ID we want. NOTE: Only pass in the team name (e.g. "Lakers"), not the city, or city and team name, or the team abbrevia...
[ "def", "get_team_id", "(", "team_name", ")", ":", "df", "=", "get_all_team_ids", "(", ")", "df", "=", "df", "[", "df", ".", "TEAM_NAME", "==", "team_name", "]", "if", "len", "(", "df", ")", "==", "0", ":", "er", "=", "\"Invalid team name or there is no t...
28
21.173913
def run_processes(self, procdetails: List[ProcessDetails], subproc_run_timeout_sec: float = 1, stop_event_timeout_ms: int = 1000, kill_timeout_sec: float = 5) -> None: """ Run multiple child processes. Args:...
[ "def", "run_processes", "(", "self", ",", "procdetails", ":", "List", "[", "ProcessDetails", "]", ",", "subproc_run_timeout_sec", ":", "float", "=", "1", ",", "stop_event_timeout_ms", ":", "int", "=", "1000", ",", "kill_timeout_sec", ":", "float", "=", "5", ...
37.581395
17.860465