text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def generate(converter, input_file, format='xml', encoding='utf8'): """ Given a converter (as returned by compile()), this function reads the given input file and converts it to the requested output format. Supported output formats are 'xml', 'yaml', 'json', or 'none'. :type converter: compiler.C...
[ "def", "generate", "(", "converter", ",", "input_file", ",", "format", "=", "'xml'", ",", "encoding", "=", "'utf8'", ")", ":", "with", "codecs", ".", "open", "(", "input_file", ",", "encoding", "=", "encoding", ")", "as", "thefile", ":", "return", "gener...
38.6
0.001264
def _from_dict(cls, _dict): """Initialize a Tables object from a json dictionary.""" args = {} if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'section_title' in ...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'location'", "in", "_dict", ":", "args", "[", "'location'", "]", "=", "Location", ".", "_from_dict", "(", "_dict", ".", "get", "(", "'location'", ")", ")", "if", ...
39.333333
0.002256
def get_interface_detail_output_interface_ip_mtu(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "output") ...
[ "def", "get_interface_detail_output_interface_ip_mtu", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_interface_detail", "=", "ET", ".", "Element", "(", "\"get_interface_detail\"", ")", "config", ...
47.529412
0.002427
async def createOffer(self): """ Create an SDP offer for the purpose of starting a new WebRTC connection to a remote peer. :rtype: :class:`RTCSessionDescription` """ # check state is valid self.__assertNotClosed() if not self.__sctp and not self.__transc...
[ "async", "def", "createOffer", "(", "self", ")", ":", "# check state is valid", "self", ".", "__assertNotClosed", "(", ")", "if", "not", "self", ".", "__sctp", "and", "not", "self", ".", "__transceivers", ":", "raise", "InternalError", "(", "'Cannot create an of...
42.049383
0.002295
def append(self, item): """ append item and print it to stdout """ print(item) super(MyList, self).append(item)
[ "def", "append", "(", "self", ",", "item", ")", ":", "print", "(", "item", ")", "super", "(", "MyList", ",", "self", ")", ".", "append", "(", "item", ")" ]
33
0.014815
async def _delete_agent(self, agent_addr): """ Deletes an agent """ self._available_agents = [agent for agent in self._available_agents if agent != agent_addr] del self._registered_agents[agent_addr] await self._recover_jobs(agent_addr)
[ "async", "def", "_delete_agent", "(", "self", ",", "agent_addr", ")", ":", "self", ".", "_available_agents", "=", "[", "agent", "for", "agent", "in", "self", ".", "_available_agents", "if", "agent", "!=", "agent_addr", "]", "del", "self", ".", "_registered_a...
52.8
0.011194
def Kdiag(self, X): """I've used the fact that we call this method for K_ff when finding the covariance as a hack so I know if I should return K_ff or K_xx. In this case we're returning K_ff!! $K_{ff}^{post} = K_{ff} - K_{fx} K_{xx}^{-1} K_{xf}$""" K_ff = np.zeros(X.shape[0]) for...
[ "def", "Kdiag", "(", "self", ",", "X", ")", ":", "K_ff", "=", "np", ".", "zeros", "(", "X", ".", "shape", "[", "0", "]", ")", "for", "i", ",", "x", "in", "enumerate", "(", "X", ")", ":", "K_ff", "[", "i", "]", "=", "self", ".", "k_ff", "(...
54.625
0.015766
def pid(self): """Return the pool ID used for connection pooling. :rtype: str """ return hashlib.md5(':'.join([self.__class__.__name__, self._uri]).encode('utf-8')).hexdigest()
[ "def", "pid", "(", "self", ")", ":", "return", "hashlib", ".", "md5", "(", "':'", ".", "join", "(", "[", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "_uri", "]", ")", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "("...
30
0.008097
def _package_top_dir(self): """ Find one or more directories that we think may be the top-level directory of the package; return a list of their absolute paths. :return: list of possible package top-level directories (absolute paths) :rtype: list """ r = [self.pa...
[ "def", "_package_top_dir", "(", "self", ")", ":", "r", "=", "[", "self", ".", "package_dir", "]", "for", "l", "in", "self", ".", "_pip_locations", ":", "if", "l", "is", "not", "None", ":", "r", ".", "append", "(", "l", ")", "for", "l", "in", "sel...
34.5625
0.008803
def recvfrom(self, bufsize, flags=0): """receive data on a socket that isn't necessarily a 1-1 connection .. note:: this method will block until data is available to be read :param bufsize: the maximum number of bytes to receive. fewer may be returned, however :...
[ "def", "recvfrom", "(", "self", ",", "bufsize", ",", "flags", "=", "0", ")", ":", "with", "self", ".", "_registered", "(", "'re'", ")", ":", "while", "1", ":", "if", "self", ".", "_closed", ":", "raise", "socket", ".", "error", "(", "errno", ".", ...
41.1875
0.001483
def tasks(self): """Return task objects of the task control.""" return [StartActionItem( self._task, i, self.state, self.path, self.raw) for i in range(len(self.raw))]
[ "def", "tasks", "(", "self", ")", ":", "return", "[", "StartActionItem", "(", "self", ".", "_task", ",", "i", ",", "self", ".", "state", ",", "self", ".", "path", ",", "self", ".", "raw", ")", "for", "i", "in", "range", "(", "len", "(", "self", ...
29.5
0.00823
def _generate_trials(self, experiment_spec, output_path=""): """Generates trials with configurations from `_suggest`. Creates a trial_id that is passed into `_suggest`. Yields: Trial objects constructed according to `spec` """ if "run" not in experiment_spec: ...
[ "def", "_generate_trials", "(", "self", ",", "experiment_spec", ",", "output_path", "=", "\"\"", ")", ":", "if", "\"run\"", "not", "in", "experiment_spec", ":", "raise", "TuneError", "(", "\"Must specify `run` in {}\"", ".", "format", "(", "experiment_spec", ")", ...
39.9
0.001631
def unmajority(p, a, b, c): """Unmajority gate.""" p.ccx(a, b, c) p.cx(c, a) p.cx(a, b)
[ "def", "unmajority", "(", "p", ",", "a", ",", "b", ",", "c", ")", ":", "p", ".", "ccx", "(", "a", ",", "b", ",", "c", ")", "p", ".", "cx", "(", "c", ",", "a", ")", "p", ".", "cx", "(", "a", ",", "b", ")" ]
19.8
0.009709
def _generate(self, message): """Given a message in message, return a response in the appropriate format.""" raw_params = {"INPUT_TEXT" : message.encode('UTF8'), "INPUT_TYPE" : self.input_type, "OUTPUT_TYPE" : self.output_type, ...
[ "def", "_generate", "(", "self", ",", "message", ")", ":", "raw_params", "=", "{", "\"INPUT_TEXT\"", ":", "message", ".", "encode", "(", "'UTF8'", ")", ",", "\"INPUT_TYPE\"", ":", "self", ".", "input_type", ",", "\"OUTPUT_TYPE\"", ":", "self", ".", "output...
39.037037
0.011111
def warn_if_nans_exist(X): """Warn if nans exist in a numpy array.""" null_count = count_rows_with_nans(X) total = len(X) percent = 100 * null_count / total if null_count > 0: warning_message = \ 'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \ 'com...
[ "def", "warn_if_nans_exist", "(", "X", ")", ":", "null_count", "=", "count_rows_with_nans", "(", "X", ")", "total", "=", "len", "(", "X", ")", "percent", "=", "100", "*", "null_count", "/", "total", "if", "null_count", ">", "0", ":", "warning_message", "...
38.636364
0.002299
def _hexvalue_to_hsv(hexvalue): """ Converts the hexvalue used by tuya for colour representation into an HSV value. Args: hexvalue(string): The hex representation generated by BulbDevice._rgb_to_hexvalue() """ h = int(hexvalue[7:10], 16) / 360 ...
[ "def", "_hexvalue_to_hsv", "(", "hexvalue", ")", ":", "h", "=", "int", "(", "hexvalue", "[", "7", ":", "10", "]", ",", "16", ")", "/", "360", "s", "=", "int", "(", "hexvalue", "[", "10", ":", "12", "]", ",", "16", ")", "/", "255", "v", "=", ...
31.692308
0.009434
def headers(self): """Return the headers for the resource. Returns the AltName, if specified; if not, then the Name, and if that is empty, a name based on the column position. These headers are specifically applicable to the output table, and may not apply to the resource source. FOr those heade...
[ "def", "headers", "(", "self", ")", ":", "t", "=", "self", ".", "schema_term", "if", "t", ":", "return", "[", "self", ".", "_name_for_col_term", "(", "c", ",", "i", ")", "for", "i", ",", "c", "in", "enumerate", "(", "t", ".", "children", ",", "1"...
43.153846
0.010471
def set_text(self, text): '''Update the time indicator in the interface. ''' self.traj_controls.timelabel.setText(self.traj_controls._label_tmp.format(text))
[ "def", "set_text", "(", "self", ",", "text", ")", ":", "self", ".", "traj_controls", ".", "timelabel", ".", "setText", "(", "self", ".", "traj_controls", ".", "_label_tmp", ".", "format", "(", "text", ")", ")" ]
35.6
0.016484
def mann_whitney(a_distribution, b_distribution, use_continuity=True): """Returns (u, p_value)""" MINIMUM_VALUES = 20 all_values = sorted(set(a_distribution) | set(b_distribution)) count_so_far = 0 a_rank_sum = 0 b_rank_sum = 0 a_count = 0 b_count = 0 variance_adjustment = 0 ...
[ "def", "mann_whitney", "(", "a_distribution", ",", "b_distribution", ",", "use_continuity", "=", "True", ")", ":", "MINIMUM_VALUES", "=", "20", "all_values", "=", "sorted", "(", "set", "(", "a_distribution", ")", "|", "set", "(", "b_distribution", ")", ")", ...
32.036364
0.000551
def generate(self, root_element=None): """Create <url> element under root_element.""" if root_element is not None: url = etree.SubElement(root_element, 'url') else: url = etree.Element('url') etree.SubElement(url, 'loc').text = self.loc if self.lastmod: ...
[ "def", "generate", "(", "self", ",", "root_element", "=", "None", ")", ":", "if", "root_element", "is", "not", "None", ":", "url", "=", "etree", ".", "SubElement", "(", "root_element", ",", "'url'", ")", "else", ":", "url", "=", "etree", ".", "Element"...
48.166667
0.002262
def get_additional_occurrences(self, start, end): """ Return persisted occurrences which are now in the period """ return [occ for _, occ in list(self.lookup.items()) if (occ.start < end and occ.end >= start and not occ.cancelled)]
[ "def", "get_additional_occurrences", "(", "self", ",", "start", ",", "end", ")", ":", "return", "[", "occ", "for", "_", ",", "occ", "in", "list", "(", "self", ".", "lookup", ".", "items", "(", ")", ")", "if", "(", "occ", ".", "start", "<", "end", ...
51.8
0.011407
def weighted_choice(self, probabilities, key): """Makes a weighted choice between several options. Probabilities is a list of 2-tuples, (probability, option). The probabilties don't need to add up to anything, they are automatically scaled.""" try: choice = self.val...
[ "def", "weighted_choice", "(", "self", ",", "probabilities", ",", "key", ")", ":", "try", ":", "choice", "=", "self", ".", "values", "[", "key", "]", ".", "lower", "(", ")", "except", "KeyError", ":", "# override not set.", "return", "super", "(", "Recor...
35.92
0.002169
def download(url, filename=None): """ Download a file from a url and save it to disk. :param str url: The URL to fetch the file from. :param str filename: The destination file to write the data to. """ # requirements os, shutil, urllib.parse, urllib.request if not filename: url_parts = urllib.parse.urlparse(u...
[ "def", "download", "(", "url", ",", "filename", "=", "None", ")", ":", "# requirements os, shutil, urllib.parse, urllib.request", "if", "not", "filename", ":", "url_parts", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "filename", "=", "os", "...
30.5
0.029821
def set(self, path, value): """Sets and returns new data for the specified node.""" _log.debug( "ZK: Setting {path} to {value}".format(path=path, value=value) ) return self.zk.set(path, value)
[ "def", "set", "(", "self", ",", "path", ",", "value", ")", ":", "_log", ".", "debug", "(", "\"ZK: Setting {path} to {value}\"", ".", "format", "(", "path", "=", "path", ",", "value", "=", "value", ")", ")", "return", "self", ".", "zk", ".", "set", "(...
38.5
0.008475
def streaming(self, remotefile, localpipe, fmt = 'M3U8_480_360', chunk = 4 * const.OneM): ''' Usage: stream <remotefile> <localpipe> [format] [chunk] - \ stream a video / audio file converted to M3U format at cloud side, to a pipe. remotefile - remote file at Baidu Yun (after app root directory at Baidu Yun) loca...
[ "def", "streaming", "(", "self", ",", "remotefile", ",", "localpipe", ",", "fmt", "=", "'M3U8_480_360'", ",", "chunk", "=", "4", "*", "const", ".", "OneM", ")", ":", "pars", "=", "{", "'method'", ":", "'streaming'", ",", "'path'", ":", "get_pcs_path", ...
43.904762
0.025478
def get_environ(self): """Return WSGI environ entries to be merged into each request.""" ssl_environ = { 'HTTPS': 'on', # pyOpenSSL doesn't provide access to any of these AFAICT # 'SSL_PROTOCOL': 'SSLv2', # SSL_CIPHER string The cipher specification na...
[ "def", "get_environ", "(", "self", ")", ":", "ssl_environ", "=", "{", "'HTTPS'", ":", "'on'", ",", "# pyOpenSSL doesn't provide access to any of these AFAICT", "# 'SSL_PROTOCOL': 'SSLv2',", "# SSL_CIPHER string The cipher specification name", "# SSL_VERSION_INTERFACE string ...
43.395833
0.000939
def bulk_write(self, requests, ordered=True, bypass_document_validation=False, session=None): """Send a batch of write operations to the server. Requests are passed as a list of write operation instances ( :class:`~pymongo.operations.InsertOne`, :class:`~pymongo.opera...
[ "def", "bulk_write", "(", "self", ",", "requests", ",", "ordered", "=", "True", ",", "bypass_document_validation", "=", "False", ",", "session", "=", "None", ")", ":", "common", ".", "validate_list", "(", "\"requests\"", ",", "requests", ")", "blk", "=", "...
40.345679
0.001195
def edit_content(self, original_lines, file_name): """Processes a file contents. First processes the contents line by line applying the registered expressions, then process the resulting contents using the registered functions. Arguments: original_lines (list of str):...
[ "def", "edit_content", "(", "self", ",", "original_lines", ",", "file_name", ")", ":", "lines", "=", "[", "self", ".", "edit_line", "(", "line", ")", "for", "line", "in", "original_lines", "]", "for", "function", "in", "self", ".", "_functions", ":", "tr...
39.375
0.002066
def restore(self, request): """ Push the request back onto the queue. Args: request (Request): Reference to a request object that should be pushed back onto the request queue. """ self._connection.connection.rpush(self._request_key, pickle.dump...
[ "def", "restore", "(", "self", ",", "request", ")", ":", "self", ".", "_connection", ".", "connection", ".", "rpush", "(", "self", ".", "_request_key", ",", "pickle", ".", "dumps", "(", "request", ")", ")" ]
40.5
0.012085
def create_participant(worker_id, hit_id, assignment_id, mode): """Create a participant. This route will be hit very early on as any nodes the participant creates will be defined in reference to the participant object. You must specify the worker_id, hit_id, assignment_id and mode in the url. """ ...
[ "def", "create_participant", "(", "worker_id", ",", "hit_id", ",", "assignment_id", ",", "mode", ")", ":", "# check this worker hasn't already taken part", "parts", "=", "models", ".", "Participant", ".", "query", ".", "filter_by", "(", "worker_id", "=", "worker_id"...
41.787879
0.000709
def _get_type_name(target_thing): """ Functions, bound methods and unbound methods change significantly in Python 3. For instance: class SomeObject(object): def method(): pass In Python 2: - Unbound method inspect.ismethod(SomeObject.method) returns True - Unbound insp...
[ "def", "_get_type_name", "(", "target_thing", ")", ":", "thing", "=", "target_thing", "if", "hasattr", "(", "thing", ",", "'im_class'", ")", ":", "# only works in Python 2", "return", "thing", ".", "im_class", ".", "__name__", "if", "inspect", ".", "ismethod", ...
41.113636
0.00108
def roc_auc_cv(self,features,labels): """returns an roc auc score depending on the underlying estimator.""" if callable(getattr(self.ml, "decision_function", None)): return np.mean([self.scoring_function(labels[test], self.pipeline.fit(features[train],labe...
[ "def", "roc_auc_cv", "(", "self", ",", "features", ",", "labels", ")", ":", "if", "callable", "(", "getattr", "(", "self", ".", "ml", ",", "\"decision_function\"", ",", "None", ")", ")", ":", "return", "np", ".", "mean", "(", "[", "self", ".", "scori...
68.8
0.013384
def add_user_to_user_groups(self, id, **kwargs): # noqa: E501 """Adds specific user groups to the user # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.add_use...
[ "def", "add_user_to_user_groups", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "add_...
44.045455
0.00202
def stop(self): """ Stop all threads and modules of the client. :return: """ super(BitfinexWSS, self).stop() log.info("BitfinexWSS.stop(): Stopping client..") log.info("BitfinexWSS.stop(): Joining receiver thread..") try: self.receiver_thread...
[ "def", "stop", "(", "self", ")", ":", "super", "(", "BitfinexWSS", ",", "self", ")", ".", "stop", "(", ")", "log", ".", "info", "(", "\"BitfinexWSS.stop(): Stopping client..\"", ")", "log", ".", "info", "(", "\"BitfinexWSS.stop(): Joining receiver thread..\"", "...
30.74359
0.001617
def DeserializeUnsignedWithoutType(self, reader): """ Deserialize object without reading transaction type data. Args: reader (neo.IO.BinaryReader): """ self.Version = reader.ReadByte() self.DeserializeExclusiveData(reader) self.Attributes = reader.Rea...
[ "def", "DeserializeUnsignedWithoutType", "(", "self", ",", "reader", ")", ":", "self", ".", "Version", "=", "reader", ".", "ReadByte", "(", ")", "self", ".", "DeserializeExclusiveData", "(", "reader", ")", "self", ".", "Attributes", "=", "reader", ".", "Read...
50.307692
0.009009
def _inner_read_config(path): ''' Helper to read a named config file. The grossness with the global is a workaround for this python bug: https://bugs.python.org/issue21591 The bug prevents us from defining either a local function or a lambda in the scope of read_fbcode_builder_config below. ...
[ "def", "_inner_read_config", "(", "path", ")", ":", "global", "_project_dir", "full_path", "=", "os", ".", "path", ".", "join", "(", "_project_dir", ",", "path", ")", "return", "read_fbcode_builder_config", "(", "full_path", ")" ]
39.545455
0.002247
def parse_from_iterable(grm, data, **kwargs): """ Parse each sentence in *data* with ACE using grammar *grm*. Args: grm (str): path to a compiled grammar image data (iterable): the sentences to parse **kwargs: additional keyword arguments to pass to the AceParser Yields: ...
[ "def", "parse_from_iterable", "(", "grm", ",", "data", ",", "*", "*", "kwargs", ")", ":", "with", "AceParser", "(", "grm", ",", "*", "*", "kwargs", ")", "as", "parser", ":", "for", "datum", "in", "data", ":", "yield", "parser", ".", "interact", "(", ...
37.222222
0.001456
def health_percentage(self) -> Union[int, float]: """ Does not include shields """ if self._proto.health_max == 0: return 0 return self._proto.health / self._proto.health_max
[ "def", "health_percentage", "(", "self", ")", "->", "Union", "[", "int", ",", "float", "]", ":", "if", "self", ".", "_proto", ".", "health_max", "==", "0", ":", "return", "0", "return", "self", ".", "_proto", ".", "health", "/", "self", ".", "_proto"...
41.2
0.009524
def CreateNewZipWithSignedLibs(z_in, z_out, ignore_files=None, signer=None, skip_signing_files=None): """Copies files from one zip to another, signing all qualifying files.""" ignore_files = i...
[ "def", "CreateNewZipWithSignedLibs", "(", "z_in", ",", "z_out", ",", "ignore_files", "=", "None", ",", "signer", "=", "None", ",", "skip_signing_files", "=", "None", ")", ":", "ignore_files", "=", "ignore_files", "or", "[", "]", "skip_signing_files", "=", "ski...
36.147059
0.014263
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile): """ Storm Pipe Network File Read from File Method """ # Set file extension property self.fileExtension = extension # Dictionary of keywords/cards and pars...
[ "def", "_read", "(", "self", ",", "directory", ",", "filename", ",", "session", ",", "path", ",", "name", ",", "extension", ",", "spatial", ",", "spatialReferenceID", ",", "replaceParamFile", ")", ":", "# Set file extension property", "self", ".", "fileExtension...
34.717949
0.002155
def intercept_service(self, continuation, handler_call_details): """Intercepts incoming RPCs before handing them over to a handler See `grpc.ServerInterceptor.intercept_service`. """ rpc_method_handler = self._get_rpc_handler(handler_call_details) if rpc_method_handler.response...
[ "def", "intercept_service", "(", "self", ",", "continuation", ",", "handler_call_details", ")", ":", "rpc_method_handler", "=", "self", ".", "_get_rpc_handler", "(", "handler_call_details", ")", "if", "rpc_method_handler", ".", "response_streaming", ":", "if", "self",...
43.6
0.002245
def dump(): """Print current environment Environment is outputted in a YAML-friendly format \b Usage: $ be dump Prefixed: - BE_TOPICS=hulk bruce animation - ... """ if not self.isactive(): lib.echo("ERROR: Enter a project first") sys.exit(lib.U...
[ "def", "dump", "(", ")", ":", "if", "not", "self", ".", "isactive", "(", ")", ":", "lib", ".", "echo", "(", "\"ERROR: Enter a project first\"", ")", "sys", ".", "exit", "(", "lib", ".", "USER_ERROR", ")", "# Print custom environment variables first", "custom",...
28.478261
0.000738
def generator(self, output, target): "Evaluate the `output` with the critic then uses `self.loss_funcG` to combine it with `target`." fake_pred = self.gan_model.critic(output) return self.loss_funcG(fake_pred, target, output)
[ "def", "generator", "(", "self", ",", "output", ",", "target", ")", ":", "fake_pred", "=", "self", ".", "gan_model", ".", "critic", "(", "output", ")", "return", "self", ".", "loss_funcG", "(", "fake_pred", ",", "target", ",", "output", ")" ]
61.5
0.012048
def hook_imports(): """Hook into Python's import machinery with a custom Basilisp code importer. Once this is called, Basilisp code may be called from within Python code using standard `import module.submodule` syntax.""" if any([isinstance(o, BasilispImporter) for o in sys.meta_path]): ret...
[ "def", "hook_imports", "(", ")", ":", "if", "any", "(", "[", "isinstance", "(", "o", ",", "BasilispImporter", ")", "for", "o", "in", "sys", ".", "meta_path", "]", ")", ":", "return", "sys", ".", "meta_path", ".", "insert", "(", "0", ",", "BasilispImp...
38.272727
0.00232
def apply_magnitude_interpolation(self, mag, iml_table): """ Interpolates the tables to the required magnitude level :param float mag: Magnitude :param iml_table: Intensity measure level table """ # do not allow "mag" to exceed maximum table magni...
[ "def", "apply_magnitude_interpolation", "(", "self", ",", "mag", ",", "iml_table", ")", ":", "# do not allow \"mag\" to exceed maximum table magnitude", "if", "mag", ">", "self", ".", "m_w", "[", "-", "1", "]", ":", "mag", "=", "self", ".", "m_w", "[", "-", ...
41.478261
0.002049
def unescape_utf8(msg): ''' convert escaped unicode web entities to unicode ''' def sub(m): text = m.group(0) if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) return re.sub("&#?\w+;", sub, urllib.unquote(msg))
[ "def", "unescape_utf8", "(", "msg", ")", ":", "def", "sub", "(", "m", ")", ":", "text", "=", "m", ".", "group", "(", "0", ")", "if", "text", "[", ":", "3", "]", "==", "\"&#x\"", ":", "return", "unichr", "(", "int", "(", "text", "[", "3", ":",...
42.857143
0.01634
def _infer_type_impl(self, partial, *args, **kwargs): """The actual implementation for calling type inference API.""" # pylint: disable=too-many-locals if len(args) != 0 and len(kwargs) != 0: raise ValueError('Can only specify known argument \ types either by posi...
[ "def", "_infer_type_impl", "(", "self", ",", "partial", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=too-many-locals", "if", "len", "(", "args", ")", "!=", "0", "and", "len", "(", "kwargs", ")", "!=", "0", ":", "raise", "Valu...
41.344828
0.002444
def filter_excluded_fields(fields, Meta, exclude_dump_only): """Filter fields that should be ignored in the OpenAPI spec :param dict fields: A dictionary of fields name field object pairs :param Meta: the schema's Meta class :param bool exclude_dump_only: whether to filter fields in Meta.dump_only ...
[ "def", "filter_excluded_fields", "(", "fields", ",", "Meta", ",", "exclude_dump_only", ")", ":", "exclude", "=", "list", "(", "getattr", "(", "Meta", ",", "\"exclude\"", ",", "[", "]", ")", ")", "if", "exclude_dump_only", ":", "exclude", ".", "extend", "("...
36.5
0.001669
def factory(cls, ap, cmpid, address): """! @brief Common CoreSightComponent factory.""" cmp = cls(ap, cmpid, address) if ap.core: ap.core.add_child(cmp) return cmp
[ "def", "factory", "(", "cls", ",", "ap", ",", "cmpid", ",", "address", ")", ":", "cmp", "=", "cls", "(", "ap", ",", "cmpid", ",", "address", ")", "if", "ap", ".", "core", ":", "ap", ".", "core", ".", "add_child", "(", "cmp", ")", "return", "cmp...
33.666667
0.009662
def main(): """ Prototype to see how an RPG simulation might be used in the AIKIF framework. The idea is to build a simple character and run a simulation to see how it succeeds in a random world against another players character character stats world locations ""...
[ "def", "main", "(", ")", ":", "character1", "=", "Character", "(", "'Albogh'", ",", "str", "=", "4", ",", "int", "=", "7", ",", "sta", "=", "50", ")", "character2", "=", "Character", "(", "'Zoltor'", ",", "str", "=", "6", ",", "int", "=", "6", ...
28.909091
0.010654
def resume(profile_process='worker'): """ Resume paused profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ ...
[ "def", "resume", "(", "profile_process", "=", "'worker'", ")", ":", "profile_process2int", "=", "{", "'worker'", ":", "0", ",", "'server'", ":", "1", "}", "check_call", "(", "_LIB", ".", "MXProcessProfilePause", "(", "int", "(", "0", ")", ",", "profile_pro...
36.933333
0.001761
def display(self): """ Get screen width and height """ w, h = self.session.window_size() return Display(w*self.scale, h*self.scale)
[ "def", "display", "(", "self", ")", ":", "w", ",", "h", "=", "self", ".", "session", ".", "window_size", "(", ")", "return", "Display", "(", "w", "*", "self", ".", "scale", ",", "h", "*", "self", ".", "scale", ")" ]
38
0.012903
def _setTypes(self, encoderSpec): """Set up the dataTypes and initialize encoders""" if self.encoderType is None: if self.dataType in ['int','float']: self.encoderType='adaptiveScalar' elif self.dataType=='string': self.encoderType='category' elif self.dataType in ['date', 'da...
[ "def", "_setTypes", "(", "self", ",", "encoderSpec", ")", ":", "if", "self", ".", "encoderType", "is", "None", ":", "if", "self", ".", "dataType", "in", "[", "'int'", ",", "'float'", "]", ":", "self", ".", "encoderType", "=", "'adaptiveScalar'", "elif", ...
35.555556
0.024353
def __ensure_suffix_stem(t, suffix): """ Ensure that the target t has the given suffix, and return the file's stem. """ tpath = str(t) if not tpath.endswith(suffix): stem = tpath tpath += suffix return tpath, stem else: stem, ext = os.path.splitext(tpath) ...
[ "def", "__ensure_suffix_stem", "(", "t", ",", "suffix", ")", ":", "tpath", "=", "str", "(", "t", ")", "if", "not", "tpath", ".", "endswith", "(", "suffix", ")", ":", "stem", "=", "tpath", "tpath", "+=", "suffix", "return", "tpath", ",", "stem", "else...
27.083333
0.011905
def parse_all_reduce_spec(all_reduce_spec): """Parse all_reduce_spec. Args: all_reduce_spec: a string specifying a combination of all-reduce algorithms to apply for gradient reduction. Returns: a list of AllReduceSpecTuple. Raises: ValueError: all_reduce_spec is not well-formed. An all...
[ "def", "parse_all_reduce_spec", "(", "all_reduce_spec", ")", ":", "range_parts", "=", "all_reduce_spec", ".", "split", "(", "\":\"", ")", "+", "[", "\"-1\"", "]", "if", "len", "(", "range_parts", ")", "%", "2", ":", "raise", "ValueError", "(", "\"all_reduce_...
44.295455
0.000251
def ght(img, template): r""" Implementation of the general hough transform for all dimensions. Providing a template, this method searches in the image for structures similar to the one depicted by the template. The returned hough image denotes how well the structure fit in each index. ...
[ "def", "ght", "(", "img", ",", "template", ")", ":", "# cast template to bool and img to numpy array", "img", "=", "numpy", ".", "asarray", "(", "img", ")", "template", "=", "numpy", ".", "asarray", "(", "template", ")", ".", "astype", "(", "numpy", ".", "...
42.616438
0.009739
def add_ms1_quant_from_top3_mzidtsv(proteins, psms, headerfields, protcol): """Collects PSMs with the highes precursor quant values, adds sum of the top 3 of these to a protein table""" if not protcol: protcol = mzidtsvdata.HEADER_MASTER_PROT top_ms1_psms = generate_top_psms(psms, protcol) f...
[ "def", "add_ms1_quant_from_top3_mzidtsv", "(", "proteins", ",", "psms", ",", "headerfields", ",", "protcol", ")", ":", "if", "not", "protcol", ":", "protcol", "=", "mzidtsvdata", ".", "HEADER_MASTER_PROT", "top_ms1_psms", "=", "generate_top_psms", "(", "psms", ","...
50.846154
0.001486
def init_ns_var(which_ns: str = CORE_NS, ns_var_name: str = NS_VAR_NAME) -> Var: """Initialize the dynamic `*ns*` variable in the Namespace `which_ns`.""" core_sym = sym.Symbol(which_ns) core_ns = Namespace.get_or_create(core_sym) ns_var = Var.intern(core_sym, sym.Symbol(ns_var_name), core_ns, dynamic=T...
[ "def", "init_ns_var", "(", "which_ns", ":", "str", "=", "CORE_NS", ",", "ns_var_name", ":", "str", "=", "NS_VAR_NAME", ")", "->", "Var", ":", "core_sym", "=", "sym", ".", "Symbol", "(", "which_ns", ")", "core_ns", "=", "Namespace", ".", "get_or_create", ...
60.428571
0.009324
def t_float(self, s): r' ((\d*\.\d+)|(\d+\.d*)|(\d+)) ([eE][-+]?\d+)?' self.rv.append(Token(type='FLOAT', attr=s))
[ "def", "t_float", "(", "self", ",", "s", ")", ":", "self", ".", "rv", ".", "append", "(", "Token", "(", "type", "=", "'FLOAT'", ",", "attr", "=", "s", ")", ")" ]
43.333333
0.015152
def ORFs(self, openORFs=False): """ Find all ORFs in our sequence. @param openORFs: If C{True} allow ORFs that do not have a start codon and/or do not have a stop codon. @return: A generator that yields AAReadORF instances that correspond to the ORFs found in the...
[ "def", "ORFs", "(", "self", ",", "openORFs", "=", "False", ")", ":", "# Return open ORFs to the left and right and closed ORFs within the", "# sequence.", "if", "openORFs", ":", "ORFStart", "=", "0", "inOpenORF", "=", "True", "# open on the left", "inORF", "=", "False...
38.714286
0.0009
def _get_region(self, contig, start, end, fout, min_length=250): '''Writes reads mapping to given region of contig, trimming part of read not in the region''' sam_reader = pysam.Samfile(self.bam, "rb") trimming_end = (start == 0) for read in sam_reader.fetch(contig, start, end): ...
[ "def", "_get_region", "(", "self", ",", "contig", ",", "start", ",", "end", ",", "fout", ",", "min_length", "=", "250", ")", ":", "sam_reader", "=", "pysam", ".", "Samfile", "(", "self", ".", "bam", ",", "\"rb\"", ")", "trimming_end", "=", "(", "star...
50.782609
0.008403
def schedule(func, *args, **kwargs): """ Create a schedule. :param func: function to schedule. :param args: function arguments. :param name: optional name for the schedule. :param hook: optional result hook function. :type schedule_type: Schedule.TYPE :param repeats: how many times to r...
[ "def", "schedule", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "name", "=", "kwargs", ".", "pop", "(", "'name'", ",", "None", ")", "hook", "=", "kwargs", ".", "pop", "(", "'hook'", ",", "None", ")", "schedule_type", "=", "kw...
39.552632
0.000649
def copyto(self, query): """ Gets data from a table into a Response object that can be iterated :param query: The "COPY { table_name [(column_name[, ...])] | (query) } TO STDOUT [WITH(option[,...])]" query to execute :type query: str :return: response...
[ "def", "copyto", "(", "self", ",", "query", ")", ":", "url", "=", "self", ".", "api_url", "+", "'/copyto'", "params", "=", "{", "'api_key'", ":", "self", ".", "api_key", ",", "'q'", ":", "query", "}", "try", ":", "response", "=", "self", ".", "clie...
35.378378
0.001487
def polynomial(target, a, prop, **kwargs): r""" Calculates a property as a polynomial function of a given property Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provid...
[ "def", "polynomial", "(", "target", ",", "a", ",", "prop", ",", "*", "*", "kwargs", ")", ":", "x", "=", "target", "[", "prop", "]", "value", "=", "0.0", "for", "i", "in", "range", "(", "0", ",", "len", "(", "a", ")", ")", ":", "value", "+=", ...
32.153846
0.001161
def beautify(self, string): """ Wraps together all actions needed to beautify a string, i.e. parse the string and then stringify the phrases (replace tags with formatting codes). Arguments: string (str): The string to beautify/parse. Returns: The parsed, stringified and ultimately beautified string....
[ "def", "beautify", "(", "self", ",", "string", ")", ":", "if", "not", "string", ":", "return", "string", "# string may differ because of escaped characters", "string", ",", "phrases", "=", "self", ".", "parse", "(", "string", ")", "if", "not", "phrases", ":", ...
24.419355
0.033037
def _compute_style_of_faulting_term(self, rup, C): """ Computes the coefficient to scale for reverse or strike-slip events Fault type (Strike-slip, Normal, Thrust/reverse) is derived from rake angle. Rakes angles within 30 of horizontal are strike-slip, angles from 30 to ...
[ "def", "_compute_style_of_faulting_term", "(", "self", ",", "rup", ",", "C", ")", ":", "if", "np", ".", "abs", "(", "rup", ".", "rake", ")", "<=", "30.0", "or", "(", "180.0", "-", "np", ".", "abs", "(", "rup", ".", "rake", ")", ")", "<=", "30.0",...
40.571429
0.002294
def _parse_style(self): """Parse wiki-style formatting (``''``/``'''`` for italics/bold).""" self._head += 2 ticks = 2 while self._read() == "'": self._head += 1 ticks += 1 italics = self._context & contexts.STYLE_ITALICS bold = self._context & con...
[ "def", "_parse_style", "(", "self", ")", ":", "self", ".", "_head", "+=", "2", "ticks", "=", "2", "while", "self", ".", "_read", "(", ")", "==", "\"'\"", ":", "self", ".", "_head", "+=", "1", "ticks", "+=", "1", "italics", "=", "self", ".", "_con...
34.405405
0.001528
def validateObjectPath(p): """ Ensures that the provided object path conforms to the DBus standard. Throws a L{error.MarshallingError} if non-conformant @type p: C{string} @param p: A DBus object path """ if not p.startswith('/'): raise MarshallingError('Object paths must begin with...
[ "def", "validateObjectPath", "(", "p", ")", ":", "if", "not", "p", ".", "startswith", "(", "'/'", ")", ":", "raise", "MarshallingError", "(", "'Object paths must begin with a \"/\"'", ")", "if", "len", "(", "p", ")", ">", "1", "and", "p", "[", "-", "1", ...
38.875
0.00157
def get(cls, parent, url_id): """Get an instance matching the parent and url_id""" return cls.query.filter_by(parent=parent, url_id=url_id).one_or_none()
[ "def", "get", "(", "cls", ",", "parent", ",", "url_id", ")", ":", "return", "cls", ".", "query", ".", "filter_by", "(", "parent", "=", "parent", ",", "url_id", "=", "url_id", ")", ".", "one_or_none", "(", ")" ]
55.666667
0.011834
async def get_messages(self, name): """Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: list(ServiceMessage): A list of the messages stored for this service """ resp = await self.send_command...
[ "async", "def", "get_messages", "(", "self", ",", "name", ")", ":", "resp", "=", "await", "self", ".", "send_command", "(", "OPERATIONS", ".", "CMD_QUERY_MESSAGES", ",", "{", "'name'", ":", "name", "}", ",", "MESSAGES", ".", "QueryMessagesResponse", ",", "...
36.428571
0.00956
def assign_grade_system_to_gradebook(self, grade_system_id, gradebook_id): """Adds an existing ``GradeSystem`` to a ``Gradebook``. arg: grade_system_id (osid.id.Id): the ``Id`` of the ``GradeSystem`` arg: gradebook_id (osid.id.Id): the ``Id`` of the ``Grade...
[ "def", "assign_grade_system_to_gradebook", "(", "self", ",", "grade_system_id", ",", "gradebook_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinAssignmentSession.assign_resource_to_bin", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'GRADIN...
50.041667
0.001634
def write_code(self, name, code): """ Writes code to a python file called 'name', erasing the previous contents. Files are created in a directory specified by gen_dir_name (see function gen_file_path) File name is second argument of path """ file_path = self.gen_f...
[ "def", "write_code", "(", "self", ",", "name", ",", "code", ")", ":", "file_path", "=", "self", ".", "gen_file_path", "(", "name", ")", "with", "open", "(", "file_path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "code", ")" ]
39
0.010025
def unpackmar(marfile, destdir): """Unpack marfile into destdir""" marfile = cygpath(os.path.abspath(marfile)) nullfd = open(os.devnull, "w") try: check_call([MAR, '-x', marfile], cwd=destdir, stdout=nullfd, preexec_fn=_noumask) except Exception: log.exception("Err...
[ "def", "unpackmar", "(", "marfile", ",", "destdir", ")", ":", "marfile", "=", "cygpath", "(", "os", ".", "path", ".", "abspath", "(", "marfile", ")", ")", "nullfd", "=", "open", "(", "os", ".", "devnull", ",", "\"w\"", ")", "try", ":", "check_call", ...
35.727273
0.002481
def extract_default_init_vals(orig_model_obj, mnl_point_series, num_params): """ Get the default initial values for the desired model type, based on the point estimate of the MNL model that is 'closest' to the desired model. Parameters ---------- orig_model_obj : an instance or sublcass of the ...
[ "def", "extract_default_init_vals", "(", "orig_model_obj", ",", "mnl_point_series", ",", "num_params", ")", ":", "# Initialize the initial values", "init_vals", "=", "np", ".", "zeros", "(", "num_params", ",", "dtype", "=", "float", ")", "# Figure out which values in mn...
44.629032
0.000354
def appendDatastore(self, store): '''Appends datastore `store` to this collection.''' if not isinstance(store, Datastore): raise TypeError("stores must be of type %s" % Datastore) self._stores.append(store)
[ "def", "appendDatastore", "(", "self", ",", "store", ")", ":", "if", "not", "isinstance", "(", "store", ",", "Datastore", ")", ":", "raise", "TypeError", "(", "\"stores must be of type %s\"", "%", "Datastore", ")", "self", ".", "_stores", ".", "append", "(",...
36.666667
0.008889
def process_config(self): """ Intended to put any code that should be run after any config reload event """ if 'byte_unit' in self.config: if isinstance(self.config['byte_unit'], basestring): self.config['byte_unit'] = self.config['byte_unit'].split() ...
[ "def", "process_config", "(", "self", ")", ":", "if", "'byte_unit'", "in", "self", ".", "config", ":", "if", "isinstance", "(", "self", ".", "config", "[", "'byte_unit'", "]", ",", "basestring", ")", ":", "self", ".", "config", "[", "'byte_unit'", "]", ...
43.344828
0.001556
def get(self, identifier, default=None): """Get a node of the AttrTree using its path string. Args: identifier: Path string of the node to return default: Value to return if no node is found Returns: The indexed node of the AttrTree """ split...
[ "def", "get", "(", "self", ",", "identifier", ",", "default", "=", "None", ")", ":", "split_label", "=", "(", "tuple", "(", "identifier", ".", "split", "(", "'.'", ")", ")", "if", "isinstance", "(", "identifier", ",", "str", ")", "else", "tuple", "("...
37.380952
0.002484
def make_serviceitem_description(description, condition='contains', negate=False, preserve_case=False): """ Create a node for ServiceItem/description :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/description' content_type = 's...
[ "def", "make_serviceitem_description", "(", "description", ",", "condition", "=", "'contains'", ",", "negate", "=", "False", ",", "preserve_case", "=", "False", ")", ":", "document", "=", "'ServiceItem'", "search", "=", "'ServiceItem/description'", "content_type", "...
42.076923
0.008945
def p_sigtypes(self, p): 'sigtypes : sigtypes sigtype' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
[ "def", "p_sigtypes", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "+", "(", "p", "[", "2", "]", ",", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lineno", "(", "1", ")", ")" ]
31.5
0.015504
def simulate_source(self, src_dict=None): """ Inject simulated source counts into the data. Parameters ---------- src_dict : dict Dictionary defining the spatial and spectral properties of the source that will be injected. """ self._fitcac...
[ "def", "simulate_source", "(", "self", ",", "src_dict", "=", "None", ")", ":", "self", ".", "_fitcache", "=", "None", "if", "src_dict", "is", "None", ":", "src_dict", "=", "{", "}", "else", ":", "src_dict", "=", "copy", ".", "deepcopy", "(", "src_dict"...
31.555556
0.001366
def sort(self, by, ascending=[]): """ Return a new Frame that is sorted by column(s) in ascending order. A fully distributed and parallel sort. However, the original frame can contain String columns but sorting cannot be done on String columns. Default sorting direction is ascending. ...
[ "def", "sort", "(", "self", ",", "by", ",", "ascending", "=", "[", "]", ")", ":", "assert_is_type", "(", "by", ",", "str", ",", "int", ",", "[", "str", ",", "int", "]", ")", "if", "type", "(", "by", ")", "!=", "list", ":", "by", "=", "[", "...
59.56
0.015202
def smooth_rectangle(x, y, rec_w, rec_h, gaussian_width_x, gaussian_width_y): """ Rectangle with a solid central region, then Gaussian fall-off at the edges. """ gaussian_x_coord = abs(x)-rec_w/2.0 gaussian_y_coord = abs(y)-rec_h/2.0 box_x=np.less(gaussian_x_coord,0.0) box_y=np.less(gaussi...
[ "def", "smooth_rectangle", "(", "x", ",", "y", ",", "rec_w", ",", "rec_h", ",", "gaussian_width_x", ",", "gaussian_width_y", ")", ":", "gaussian_x_coord", "=", "abs", "(", "x", ")", "-", "rec_w", "/", "2.0", "gaussian_y_coord", "=", "abs", "(", "y", ")",...
38.95
0.018797
def parse_sidebar(self, media_page): """Parses the DOM and returns media attributes in the sidebar. :type media_page: :class:`bs4.BeautifulSoup` :param media_page: MAL media page's DOM :rtype: dict :return: media attributes. :raises: InvalidMediaError, MalformedMediaPageError """ med...
[ "def", "parse_sidebar", "(", "self", ",", "media_page", ")", ":", "media_info", "=", "{", "}", "# if MAL says the series doesn't exist, raise an InvalidMediaError.", "error_tag", "=", "media_page", ".", "find", "(", "u'div'", ",", "{", "'class'", ":", "'badresult'", ...
37.119205
0.016507
def p_statement_randomize_expr(p): """ statement : RANDOMIZE expr """ p[0] = make_sentence('RANDOMIZE', make_typecast(TYPE.ulong, p[2], p.lineno(1)))
[ "def", "p_statement_randomize_expr", "(", "p", ")", ":", "p", "[", "0", "]", "=", "make_sentence", "(", "'RANDOMIZE'", ",", "make_typecast", "(", "TYPE", ".", "ulong", ",", "p", "[", "2", "]", ",", "p", ".", "lineno", "(", "1", ")", ")", ")" ]
39.5
0.012422
def toSimModel(unit, targetPlatform=DummyPlatform(), dumpModelIn=None): """ Create a simulation model for unit :param unit: interface level unit which you wont prepare for simulation :param targetPlatform: target platform for this synthes :param dumpModelIn: folder to where put sim model files ...
[ "def", "toSimModel", "(", "unit", ",", "targetPlatform", "=", "DummyPlatform", "(", ")", ",", "dumpModelIn", "=", "None", ")", ":", "sim_code", "=", "toRtl", "(", "unit", ",", "targetPlatform", "=", "targetPlatform", ",", "saveTo", "=", "dumpModelIn", ",", ...
37.387097
0.000841
def template(relative_path, *args, **kwargs): """ A decorator for easily rendering templates. Use as follows: main.py: from mustache import (template) @template('../tests/static/say_hello.html') def index(): context = {'name' : 'world'} partials = {} ...
[ "def", "template", "(", "relative_path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "directory", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "relative_path", ")", "partials_dir", "=", "os", ".", "path", ".", "abspath", "(", ...
30.22
0.001282
def get_cookiecutter_config(template, default_config=None, version=None): """Obtains the configuration used for cookiecutter templating Args: template: Path to the template default_config (dict, optional): The default configuration version (str, optional): The git SHA or branch to use w...
[ "def", "get_cookiecutter_config", "(", "template", ",", "default_config", "=", "None", ",", "version", "=", "None", ")", ":", "default_config", "=", "default_config", "or", "{", "}", "config_dict", "=", "cc_config", ".", "get_user_config", "(", ")", "repo_dir", ...
42.04
0.00093
def initFormatB(self): """ Initialize B read :class:`~ekmmeters.SerialBlock`.""" self.m_blk_b["reserved_5"] = [1, FieldType.Hex, ScaleType.No, "", 0, False, False] self.m_blk_b[Field.Model] = [2, FieldType.Hex, ScaleType.No, "", 0, False, True] self.m_blk_b[Field.Firmware] = [1, FieldTyp...
[ "def", "initFormatB", "(", "self", ")", ":", "self", ".", "m_blk_b", "[", "\"reserved_5\"", "]", "=", "[", "1", ",", "FieldType", ".", "Hex", ",", "ScaleType", ".", "No", ",", "\"\"", ",", "0", ",", "False", ",", "False", "]", "self", ".", "m_blk_b...
94.647059
0.010252
def check_env(self, envar, value): '''ensure that variable envar is set to some value, otherwise exit on error. Parameters ========== envar: the environment variable name value: the setting that shouldn't be None ''' if value is No...
[ "def", "check_env", "(", "self", ",", "envar", ",", "value", ")", ":", "if", "value", "is", "None", ":", "bot", ".", "error", "(", "'You must export %s to use Discourse'", "%", "envar", ")", "print", "(", "'https://vsoch.github.io/helpme/helper-discourse'", ")", ...
36.384615
0.008247
def get_checkpoints_for_actor(actor_id): """Get the available checkpoints for the given actor ID, return a list sorted by checkpoint timestamp in descending order. """ checkpoint_info = ray.worker.global_state.actor_checkpoint_info(actor_id) if checkpoint_info is None: return [] checkpoi...
[ "def", "get_checkpoints_for_actor", "(", "actor_id", ")", ":", "checkpoint_info", "=", "ray", ".", "worker", ".", "global_state", ".", "actor_checkpoint_info", "(", "actor_id", ")", "if", "checkpoint_info", "is", "None", ":", "return", "[", "]", "checkpoints", "...
37.0625
0.001645
def cross_list(*sequences): """ From: http://book.opensourceproject.org.cn/lamp/python/pythoncook2/opensource/0596007973/pythoncook2-chp-19-sect-9.html """ result = [[ ]] for seq in sequences: result = [sublist+[item] for sublist in result for item in seq] return result
[ "def", "cross_list", "(", "*", "sequences", ")", ":", "result", "=", "[", "[", "]", "]", "for", "seq", "in", "sequences", ":", "result", "=", "[", "sublist", "+", "[", "item", "]", "for", "sublist", "in", "result", "for", "item", "in", "seq", "]", ...
34.875
0.024476
def _factorize_from_iterable(values): """ Factorize an input `values` into `categories` and `codes`. Preserves categorical dtype in `categories`. *This is an internal function* Parameters ---------- values : list-like Returns ------- codes : ndarray categories : Index ...
[ "def", "_factorize_from_iterable", "(", "values", ")", ":", "from", "pandas", ".", "core", ".", "indexes", ".", "category", "import", "CategoricalIndex", "if", "not", "is_list_like", "(", "values", ")", ":", "raise", "TypeError", "(", "\"Input must be list-like\""...
33.055556
0.000816
def row(self): """ Game Dataset(Row) :return: { 'retro_game_id': Retrosheet Game id 'game_type': Game Type(S/R/F/D/L/W) 'game_type_des': Game Type Description (Spring Training or Regular Season or Wild-card Game or Divisional Series or LCS or World...
[ "def", "row", "(", "self", ")", ":", "row", "=", "OrderedDict", "(", ")", "row", "[", "'retro_game_id'", "]", "=", "self", ".", "retro_game_id", "row", "[", "'game_type'", "]", "=", "self", ".", "game_type", "row", "[", "'game_type_des'", "]", "=", "se...
42.836735
0.001397
def occurrence_fingerprint( word, n_bits=16, most_common=MOST_COMMON_LETTERS_CG ): """Return the occurrence fingerprint. This is a wrapper for :py:meth:`Occurrence.fingerprint`. Parameters ---------- word : str The word to fingerprint n_bits : int Number of bits in the fing...
[ "def", "occurrence_fingerprint", "(", "word", ",", "n_bits", "=", "16", ",", "most_common", "=", "MOST_COMMON_LETTERS_CG", ")", ":", "return", "Occurrence", "(", ")", ".", "fingerprint", "(", "word", ",", "n_bits", ",", "most_common", ")" ]
25.361111
0.001055
def with_subchannel(f,*args): "conditionally monitor subchannel" def f_with_update(*args): try: f(*args) if monitor_subchannel: update_subchannel_msgs(force=True) except AttributeError: #if kc is None echo("not connected to IPython", 'Error') ...
[ "def", "with_subchannel", "(", "f", ",", "*", "args", ")", ":", "def", "f_with_update", "(", "*", "args", ")", ":", "try", ":", "f", "(", "*", "args", ")", "if", "monitor_subchannel", ":", "update_subchannel_msgs", "(", "force", "=", "True", ")", "exce...
33.4
0.011662
def from_spcm(filepath, name=None, *, delimiter=",", parent=None, verbose=True) -> Data: """Create a ``Data`` object from a Becker & Hickl spcm file (ASCII-exported, ``.asc``). If provided, setup parameters are stored in the ``attrs`` dictionary of the ``Data`` object. See the `spcm`__ software hompage fo...
[ "def", "from_spcm", "(", "filepath", ",", "name", "=", "None", ",", "*", ",", "delimiter", "=", "\",\"", ",", "parent", "=", "None", ",", "verbose", "=", "True", ")", "->", "Data", ":", "filestr", "=", "os", ".", "fspath", "(", "filepath", ")", "fi...
35.991525
0.001833
def putResourceValue(self,ep,res,data,cbfn=""): """ Put a value to a resource on an endpoint :param str ep: name of endpoint :param str res: name of resource :param str data: data to send via PUT :param fnptr cbfn: Optional - callback funtion to call when operation is completed :return: successful ``.s...
[ "def", "putResourceValue", "(", "self", ",", "ep", ",", "res", ",", "data", ",", "cbfn", "=", "\"\"", ")", ":", "result", "=", "asyncResult", "(", "callback", "=", "cbfn", ")", "result", ".", "endpoint", "=", "ep", "result", ".", "resource", "=", "re...
35.346154
0.041314
def postpone(self, record): """ Postpone (if required) the given task. The real action is depended on task postpone policy :param record: record to postpone :return: None """ maximum_records = self.maximum_records() if maximum_records is not None and len(self.__records) >= maximum_records: record.task_...
[ "def", "postpone", "(", "self", ",", "record", ")", ":", "maximum_records", "=", "self", ".", "maximum_records", "(", ")", "if", "maximum_records", "is", "not", "None", "and", "len", "(", "self", ".", "__records", ")", ">=", "maximum_records", ":", "record...
30.5
0.028235
def ticket_incidents(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/tickets#listing-ticket-incidents" api_path = "/api/v2/tickets/{id}/incidents.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "ticket_incidents", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/tickets/{id}/incidents.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "ap...
54.6
0.01083
def _basic_return(self, args, msg): """Return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or an unroutable message published with the "mandatory" flag set. The reply code and text provide information about the r...
[ "def", "_basic_return", "(", "self", ",", "args", ",", "msg", ")", ":", "self", ".", "returned_messages", ".", "put", "(", "basic_return_t", "(", "args", ".", "read_short", "(", ")", ",", "args", ".", "read_shortstr", "(", ")", ",", "args", ".", "read_...
29.4
0.001646