text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def df(self, version=None, tags=None, ext=None, **kwargs): """Loads an instance of this dataset into a dataframe. Parameters ---------- version: str, optional The version of the instance of this dataset. tags : list of str, optional The tags associated wi...
[ "def", "df", "(", "self", ",", "version", "=", "None", ",", "tags", "=", "None", ",", "ext", "=", "None", ",", "*", "*", "kwargs", ")", ":", "ext", "=", "self", ".", "_find_extension", "(", "version", "=", "version", ",", "tags", "=", "tags", ")"...
41.060606
0.001442
def set(self, folder: str, subscribed: bool) -> None: """Set the subscribed status of a folder.""" if subscribed: self.add(folder) else: self.remove(folder)
[ "def", "set", "(", "self", ",", "folder", ":", "str", ",", "subscribed", ":", "bool", ")", "->", "None", ":", "if", "subscribed", ":", "self", ".", "add", "(", "folder", ")", "else", ":", "self", ".", "remove", "(", "folder", ")" ]
33.166667
0.009804
def delete(self, context_id, address_list): """Delete the values associated with list of addresses, for a specific context referenced by context_id. Args: context_id (str): the return value of create_context, referencing a particular context. address_list...
[ "def", "delete", "(", "self", ",", "context_id", ",", "address_list", ")", ":", "if", "context_id", "not", "in", "self", ".", "_contexts", ":", "return", "False", "context", "=", "self", ".", "_contexts", "[", "context_id", "]", "for", "add", "in", "addr...
35.454545
0.001664
def not_one_of(these): """Returns the current token if it is not found in the collection provided. The negative of one_of. """ ch = peek() desc = "not_one_of" + repr(these) try: if (ch is EndOfFile) or (ch in these): fail([desc]) except TypeError: if ch != t...
[ "def", "not_one_of", "(", "these", ")", ":", "ch", "=", "peek", "(", ")", "desc", "=", "\"not_one_of\"", "+", "repr", "(", "these", ")", "try", ":", "if", "(", "ch", "is", "EndOfFile", ")", "or", "(", "ch", "in", "these", ")", ":", "fail", "(", ...
24.066667
0.008
def convert_inputfiles(cls, folder=None, inputfile=None, session=None, lod_threshold=None, qtls_file='qtls.csv', matrix_file='qtls_matrix.csv', ...
[ "def", "convert_inputfiles", "(", "cls", ",", "folder", "=", "None", ",", "inputfile", "=", "None", ",", "session", "=", "None", ",", "lod_threshold", "=", "None", ",", "qtls_file", "=", "'qtls.csv'", ",", "matrix_file", "=", "'qtls_matrix.csv'", ",", "map_f...
41.679012
0.002604
def to_dict(self): """Converts this object to an (ordered) dictionary of field-value pairs. >>> m = MRZ(['IDAUT10000999<6<<<<<<<<<<<<<<<', '7109094F1112315AUT<<<<<<<<<<<6', 'MUSTERFRAU<<ISOLDE<<<<<<<<<<<<']).to_dict() >>> assert m['type'] == 'ID' and m['country'] == 'AUT' and m['number'] == '10...
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "OrderedDict", "(", ")", "result", "[", "'mrz_type'", "]", "=", "self", ".", "mrz_type", "result", "[", "'valid_score'", "]", "=", "self", ".", "valid_score", "if", "self", ".", "mrz_type", "is", ...
51.977778
0.002518
def _try_fetch(self, size=None): """Try to start fetching data, if not yet started. Mutates self to indicate that iteration has started. """ if self._query_job is None: raise exceptions.InterfaceError( "No query results: execute() must be called before fetch....
[ "def", "_try_fetch", "(", "self", ",", "size", "=", "None", ")", ":", "if", "self", ".", "_query_job", "is", "None", ":", "raise", "exceptions", ".", "InterfaceError", "(", "\"No query results: execute() must be called before fetch.\"", ")", "is_dml", "=", "(", ...
33.538462
0.00223
def stacked_graph(labels, data, normal_data, len_categories, args, colors): """Prepare the horizontal stacked graph. Each row is printed through the print_row function.""" val_min = find_min(data) for i in range(len(labels)): if args['no_labels']: # Hide the labels. l...
[ "def", "stacked_graph", "(", "labels", ",", "data", ",", "normal_data", ",", "len_categories", ",", "args", ",", "colors", ")", ":", "val_min", "=", "find_min", "(", "data", ")", "for", "i", "in", "range", "(", "len", "(", "labels", ")", ")", ":", "i...
33.826087
0.00125
def get_athlete_clubs(self): """ List the clubs for the currently authenticated athlete. http://strava.github.io/api/v3/clubs/#get-athletes :return: A list of :class:`stravalib.model.Club` :rtype: :py:class:`list` """ club_structs = self.protocol.get('/athlete/c...
[ "def", "get_athlete_clubs", "(", "self", ")", ":", "club_structs", "=", "self", ".", "protocol", ".", "get", "(", "'/athlete/clubs'", ")", "return", "[", "model", ".", "Club", ".", "deserialize", "(", "raw", ",", "bind_client", "=", "self", ")", "for", "...
36.636364
0.007264
def read_handle(self, handle: int) -> bytes: """Read a handle from the device.""" if not self.is_connected(): raise BluetoothBackendException('Not connected to device!') return self._device.char_read_handle(handle)
[ "def", "read_handle", "(", "self", ",", "handle", ":", "int", ")", "->", "bytes", ":", "if", "not", "self", ".", "is_connected", "(", ")", ":", "raise", "BluetoothBackendException", "(", "'Not connected to device!'", ")", "return", "self", ".", "_device", "....
49.2
0.008
def serial_starfeatures(lclist, outdir, lc_catalog_pickle, neighbor_radius_arcsec, maxobjects=None, deredden=True, custom_bandpasses=None, lcformat='hat...
[ "def", "serial_starfeatures", "(", "lclist", ",", "outdir", ",", "lc_catalog_pickle", ",", "neighbor_radius_arcsec", ",", "maxobjects", "=", "None", ",", "deredden", "=", "True", ",", "custom_bandpasses", "=", "None", ",", "lcformat", "=", "'hat-sql'", ",", "lcf...
38.710526
0.001326
def trigger_event(self, event, *args): """Dispatch an event to the proper handler method. In the most common usage, this method is not overloaded by subclasses, as it performs the routing of events to methods. However, this method can be overriden if special dispatching rules are needed...
[ "def", "trigger_event", "(", "self", ",", "event", ",", "*", "args", ")", ":", "handler_name", "=", "'on_'", "+", "event", "if", "hasattr", "(", "self", ",", "handler_name", ")", ":", "return", "getattr", "(", "self", ",", "handler_name", ")", "(", "*"...
47.909091
0.003724
def _load_csv(self, file_name, folder_name, head_row, index_col, convert_col, concat_files): """ Load single csv file. Parameters ---------- file_name : str CSV file to be imported. Defaults to '*' - all csv files in the folder. folder_name : str ...
[ "def", "_load_csv", "(", "self", ",", "file_name", ",", "folder_name", ",", "head_row", ",", "index_col", ",", "convert_col", ",", "concat_files", ")", ":", "# Denotes all csv files", "if", "file_name", "==", "\"*\"", ":", "if", "not", "os", ".", "path", "."...
39.971014
0.0046
def _call_fan(branch, calls, executable): """Appends a list of callees to the branch for each parent in the call list that calls this executable. """ #Since we don't keep track of the specific logic in the executables #it is possible that we could get a infinite recursion of executables #that ke...
[ "def", "_call_fan", "(", "branch", ",", "calls", ",", "executable", ")", ":", "#Since we don't keep track of the specific logic in the executables", "#it is possible that we could get a infinite recursion of executables", "#that keep calling each other.", "if", "executable", "in", "b...
35.5625
0.008562
def getURL(self, CorpNum, UserID, ToGo): """ 문자 관련 팝빌 URL args CorpNum : 팝빌회원 사업자번호 UserID : 팝빌회원 아이디 TOGO : BOX (전송내역조회 팝업) return 팝빌 URL raise PopbillException """ if ...
[ "def", "getURL", "(", "self", ",", "CorpNum", ",", "UserID", ",", "ToGo", ")", ":", "if", "ToGo", "==", "None", "or", "ToGo", "==", "''", ":", "raise", "PopbillException", "(", "-", "99999999", ",", "\"TOGO값이 입력되지 않았습니다.\")\r", "", "result", "=", "self",...
29.647059
0.005769
def delete(self, dataset_name): """ Delete a Cached Dataset. Master Key must be set. """ url = "{0}/{1}".format(self._cached_datasets_url, dataset_name) self._get_json(HTTPMethods.DELETE, url, self._get_master_key()) return True
[ "def", "delete", "(", "self", ",", "dataset_name", ")", ":", "url", "=", "\"{0}/{1}\"", ".", "format", "(", "self", ".", "_cached_datasets_url", ",", "dataset_name", ")", "self", ".", "_get_json", "(", "HTTPMethods", ".", "DELETE", ",", "url", ",", "self",...
43.833333
0.007463
def save(self, filename, options=None, text=None): """Renders the barcode and saves it in `filename`. :parameters: filename : String Filename to save the barcode in (without filename extension). options : Dict The same as in `self....
[ "def", "save", "(", "self", ",", "filename", ",", "options", "=", "None", ",", "text", "=", "None", ")", ":", "if", "text", ":", "output", "=", "self", ".", "render", "(", "options", ",", "text", ")", "else", ":", "output", "=", "self", ".", "ren...
31.454545
0.002805
def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Return a Pandas Series of every file for chosen satellite data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are '1min' and '5min'. (default=None) sat_id : (s...
[ "def", "list_files", "(", "tag", "=", "None", ",", "sat_id", "=", "None", ",", "data_path", "=", "None", ",", "format_str", "=", "None", ")", ":", "if", "format_str", "is", "None", "and", "data_path", "is", "not", "None", ":", "if", "(", "tag", "==",...
44.8
0.001456
def serialize(self, data, format=None): """Serializes the data into this response using a serializer. @param[in] data The data to be serialized. @param[in] format A specific format to serialize in; if provided, no detection is done. If not provided, the acce...
[ "def", "serialize", "(", "self", ",", "data", ",", "format", "=", "None", ")", ":", "return", "self", ".", "_resource", ".", "serialize", "(", "data", ",", "response", "=", "self", ",", "format", "=", "format", ")" ]
38.1875
0.003195
def init_scheduler(db_uri): """Initialise and configure the scheduler.""" global scheduler scheduler = apscheduler.Scheduler() scheduler.misfire_grace_time = 3600 scheduler.add_jobstore( sqlalchemy_store.SQLAlchemyJobStore(url=db_uri), 'default') scheduler.add_listener( job_liste...
[ "def", "init_scheduler", "(", "db_uri", ")", ":", "global", "scheduler", "scheduler", "=", "apscheduler", ".", "Scheduler", "(", ")", "scheduler", ".", "misfire_grace_time", "=", "3600", "scheduler", ".", "add_jobstore", "(", "sqlalchemy_store", ".", "SQLAlchemyJo...
35.666667
0.002278
def _validate_pdf_file(self): """Validate that the pdf_path configuration is set and the referenced file exists. Exits the program with status 1 if validation fails. """ if self['pdf_path'] is None: self._logger.error('--pdf argument must be set') sys.exi...
[ "def", "_validate_pdf_file", "(", "self", ")", ":", "if", "self", "[", "'pdf_path'", "]", "is", "None", ":", "self", ".", "_logger", ".", "error", "(", "'--pdf argument must be set'", ")", "sys", ".", "exit", "(", "1", ")", "if", "not", "os", ".", "pat...
38
0.004283
def get_object_closure(subject, object_category=None, **kwargs): """ Find all terms used to annotate subject plus ancestors """ results = search_associations(subject=subject, object_category=object_category, select_fields=[], ...
[ "def", "get_object_closure", "(", "subject", ",", "object_category", "=", "None", ",", "*", "*", "kwargs", ")", ":", "results", "=", "search_associations", "(", "subject", "=", "subject", ",", "object_category", "=", "object_category", ",", "select_fields", "=",...
47.166667
0.001733
async def run(self, state: ConnectionState) -> None: """Start the socket communication with the IMAP greeting, and then enter the command/response cycle. Args: state: Defines the interaction with the backend plugin. """ self._print('%d +++| %s', bytes(socket_info.ge...
[ "async", "def", "run", "(", "self", ",", "state", ":", "ConnectionState", ")", "->", "None", ":", "self", ".", "_print", "(", "'%d +++| %s'", ",", "bytes", "(", "socket_info", ".", "get", "(", ")", ")", ")", "bad_commands", "=", "0", "try", ":", "gre...
43
0.000576
def msvs_parse_version(s): """ Split a Visual Studio version, which may in fact be something like '7.0Exp', into is version number (returned as a float) and trailing "suite" portion. """ num, suite = version_re.match(s).groups() return float(num), suite
[ "def", "msvs_parse_version", "(", "s", ")", ":", "num", ",", "suite", "=", "version_re", ".", "match", "(", "s", ")", ".", "groups", "(", ")", "return", "float", "(", "num", ")", ",", "suite" ]
34.25
0.003559
def pauseMovie(self): """Pause button handler.""" if self.state == self.PLAYING: self.sendRtspRequest(self.PAUSE)
[ "def", "pauseMovie", "(", "self", ")", ":", "if", "self", ".", "state", "==", "self", ".", "PLAYING", ":", "self", ".", "sendRtspRequest", "(", "self", ".", "PAUSE", ")" ]
31
0.015748
def delete(self, obj, id): """ Function delete Delete an object by id @param obj: object name ('hosts', 'puppetclasses'...) @param id: the id of the object (name or id) @return RETURN: the server response """ self.url = '{}{}/{}'.format(self.base_url, obj, id) ...
[ "def", "delete", "(", "self", ",", "obj", ",", "id", ")", ":", "self", ".", "url", "=", "'{}{}/{}'", ".", "format", "(", "self", ".", "base_url", ",", "obj", ",", "id", ")", "self", ".", "method", "=", "'DELETE'", "self", ".", "resp", "=", "reque...
39.714286
0.003515
def func_old_kwargs(a, b=None, **kwargs): # pylint: disable=invalid-name """Old function, defined with **kwargs.""" # We extract a specific optional parameter from **kwargs try: c = kwargs['c'] except KeyError: c = None return a, b, c
[ "def", "func_old_kwargs", "(", "a", ",", "b", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=invalid-name", "# We extract a specific optional parameter from **kwargs", "try", ":", "c", "=", "kwargs", "[", "'c'", "]", "except", "KeyError", ":", ...
26.4
0.003663
def grid_str(self, path=None, start=None, end=None, border=True, start_chr='s', end_chr='e', path_chr='x', empty_chr=' ', block_chr='#', show_weight=False): """ create a printable string from the grid using ASCII characters :param path: list of...
[ "def", "grid_str", "(", "self", ",", "path", "=", "None", ",", "start", "=", "None", ",", "end", "=", "None", ",", "border", "=", "True", ",", "start_chr", "=", "'s'", ",", "end_chr", "=", "'e'", ",", "path_chr", "=", "'x'", ",", "empty_chr", "=", ...
41.574468
0.0025
def _find_files(directory): """ Find XML files in the directory """ pattern = "{directory}/*.xml".format( directory=directory, ) files = glob(pattern) return files
[ "def", "_find_files", "(", "directory", ")", ":", "pattern", "=", "\"{directory}/*.xml\"", ".", "format", "(", "directory", "=", "directory", ",", ")", "files", "=", "glob", "(", "pattern", ")", "return", "files" ]
21.222222
0.005025
def _remove_duplicates(self, items): """ Remove duplicates, while keeping the order. (Sometimes we have duplicates, because the there several matches of the same grammar, each yielding similar completions.) """ result = [] for i in items: if i not in r...
[ "def", "_remove_duplicates", "(", "self", ",", "items", ")", ":", "result", "=", "[", "]", "for", "i", "in", "items", ":", "if", "i", "not", "in", "result", ":", "result", ".", "append", "(", "i", ")", "return", "result" ]
33.727273
0.005249
def create(self): """ Create a new ConfigurationInstance :returns: Newly created ConfigurationInstance :rtype: twilio.rest.flex_api.v1.configuration.ConfigurationInstance """ data = values.of({}) payload = self._version.create( 'POST', se...
[ "def", "create", "(", "self", ")", ":", "data", "=", "values", ".", "of", "(", "{", "}", ")", "payload", "=", "self", ".", "_version", ".", "create", "(", "'POST'", ",", "self", ".", "_uri", ",", "data", "=", "data", ",", ")", "return", "Configur...
25.625
0.004706
def _convert_to_indexer(self, obj, axis=None, is_setter=False, raise_missing=False): """ Convert indexing key into something we can use to do actual fancy indexing on an ndarray Examples ix[:5] -> slice(0, 5) ix[[1,2,3]] -> [1,2,3] ix[...
[ "def", "_convert_to_indexer", "(", "self", ",", "obj", ",", "axis", "=", "None", ",", "is_setter", "=", "False", ",", "raise_missing", "=", "False", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "self", ".", "axis", "or", "0", "labels", "="...
32.815217
0.000965
def numeric_map(lookup, numeric_stops, default=0.0): """Return a number value interpolated from given numeric_stops """ # if no numeric_stops, use default if len(numeric_stops) == 0: return default # dictionary to lookup value from match-type numeric_stops match_map = dict((x, y) fo...
[ "def", "numeric_map", "(", "lookup", ",", "numeric_stops", ",", "default", "=", "0.0", ")", ":", "# if no numeric_stops, use default", "if", "len", "(", "numeric_stops", ")", "==", "0", ":", "return", "default", "# dictionary to lookup value from match-type numeric_stop...
35.4
0.005497
def get_resource(collection, key): """Return the appropriate *Response* for retrieving a single resource. :param string collection: a :class:`sandman.model.Model` endpoint :param string key: the primary key for the :class:`sandman.model.Model` :rtype: :class:`flask.Response` """ resource = ret...
[ "def", "get_resource", "(", "collection", ",", "key", ")", ":", "resource", "=", "retrieve_resource", "(", "collection", ",", "key", ")", "_validate", "(", "endpoint_class", "(", "collection", ")", ",", "request", ".", "method", ",", "resource", ")", "return...
37.333333
0.002179
def inspect_io_obj(obj): """ :param obj: a path string, a pathlib.Path or a file / file-like object :return: A tuple of (objtype, objpath, objopener) :raises: UnknownFileTypeError """ itype = guess_io_type(obj) if itype == IOI_PATH_STR: ipath = anyconfig.utils.normpath(obj) ...
[ "def", "inspect_io_obj", "(", "obj", ")", ":", "itype", "=", "guess_io_type", "(", "obj", ")", "if", "itype", "==", "IOI_PATH_STR", ":", "ipath", "=", "anyconfig", ".", "utils", ".", "normpath", "(", "obj", ")", "ext", "=", "anyconfig", ".", "utils", "...
33.035714
0.00105
def _setup_signal_handler(self): """ Register signal handlers """ signal.signal(signal.SIGTERM, self._signal_handler) signal.signal(signal.SIGINT, self._signal_handler) signal.signal(signal.SIGQUIT, self._signal_handler)
[ "def", "_setup_signal_handler", "(", "self", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "self", ".", "_signal_handler", ")", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "self", ".", "_signal_handler", ")", "signa...
49.6
0.007937
def append_string(t, string): """Append a string to a node, as text or tail of last child.""" node = t.tree if string: if len(node) == 0: if node.text is not None: node.text += string else: node.text = string else: # Get last child ...
[ "def", "append_string", "(", "t", ",", "string", ")", ":", "node", "=", "t", ".", "tree", "if", "string", ":", "if", "len", "(", "node", ")", "==", "0", ":", "if", "node", ".", "text", "is", "not", "None", ":", "node", ".", "text", "+=", "strin...
31.133333
0.002079
def has_capabilities(self, *caps): """ Overrides original :meth:`.WCapabilitiesHolder.has_capabilities` method to support :class:`.WNetworkClientCapabilities` as a capability value """ for cap in caps: if isinstance(cap, WNetworkClientCapabilities) is True: cap = cap.value if WCapabilitiesHolder.has_c...
[ "def", "has_capabilities", "(", "self", ",", "*", "caps", ")", ":", "for", "cap", "in", "caps", ":", "if", "isinstance", "(", "cap", ",", "WNetworkClientCapabilities", ")", "is", "True", ":", "cap", "=", "cap", ".", "value", "if", "WCapabilitiesHolder", ...
37.4
0.031332
def from_array(cls, content_type, extensions=[], encoding=None, system=None, is_obsolete=False, docs=None, url=None, is_registered=False): """ Creates a MIME::Type from an array in the form of: [type-name, [extensions], encoding, system] +extension...
[ "def", "from_array", "(", "cls", ",", "content_type", ",", "extensions", "=", "[", "]", ",", "encoding", "=", "None", ",", "system", "=", "None", ",", "is_obsolete", "=", "False", ",", "docs", "=", "None", ",", "url", "=", "None", ",", "is_registered",...
38.695652
0.005482
def default_security_rule_get(name, security_group, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 Get details about a default security rule within a security group. :param name: The name of the security rule to query. :param security_group: The network security group containing the ...
[ "def", "default_security_rule_get", "(", "name", ",", "security_group", ",", "resource_group", ",", "*", "*", "kwargs", ")", ":", "result", "=", "{", "}", "default_rules", "=", "default_security_rules_list", "(", "security_group", "=", "security_group", ",", "reso...
27.6
0.002333
def get_erase_size(self, offset, size): """ Calculate an erase size given a specific size in bytes. Provides a workaround for the bootloader erase bug.""" sectors_per_block = 16 sector_size = self.FLASH_SECTOR_SIZE num_sectors = (size + sector_size - 1) // sector_size s...
[ "def", "get_erase_size", "(", "self", ",", "offset", ",", "size", ")", ":", "sectors_per_block", "=", "16", "sector_size", "=", "self", ".", "FLASH_SECTOR_SIZE", "num_sectors", "=", "(", "size", "+", "sector_size", "-", "1", ")", "//", "sector_size", "start_...
37.277778
0.002907
def bars(self, symbol='000001', category='9', start='0', offset='100'): ''' 获取实时日K线数据 :param symbol: 股票代码 :param category: 数据类别 :param market: 证券市场 :param start: 开始位置 :param offset: 每次获取条数 :return: pd.dataFrame or None ''' market = get_sto...
[ "def", "bars", "(", "self", ",", "symbol", "=", "'000001'", ",", "category", "=", "'9'", ",", "start", "=", "'0'", ",", "offset", "=", "'100'", ")", ":", "market", "=", "get_stock_market", "(", "symbol", ")", "with", "self", ".", "client", ".", "conn...
32.058824
0.005348
def tgread_bytes(self): """ Reads a Telegram-encoded byte array, without the need of specifying its length. """ first_byte = self.read_byte() if first_byte == 254: length = self.read_byte() | (self.read_byte() << 8) | ( self.read_byte() << 16) ...
[ "def", "tgread_bytes", "(", "self", ")", ":", "first_byte", "=", "self", ".", "read_byte", "(", ")", "if", "first_byte", "==", "254", ":", "length", "=", "self", ".", "read_byte", "(", ")", "|", "(", "self", ".", "read_byte", "(", ")", "<<", "8", "...
28.1
0.003442
def depolarizeCells(self, basalInput, apicalInput, learn): """ Calculate predictions. @param basalInput (numpy array) List of active input bits for the basal dendrite segments @param apicalInput (numpy array) List of active input bits for the apical dendrite segments @param learn (bool) ...
[ "def", "depolarizeCells", "(", "self", ",", "basalInput", ",", "apicalInput", ",", "learn", ")", ":", "# Calculate predictions for this timestep", "(", "activeApicalSegments", ",", "matchingApicalSegments", ",", "apicalPotentialOverlaps", ")", "=", "self", ".", "_calcul...
41.470588
0.005081
def run(self): """ Write the input/data files and run LAMMPS. """ lammps_cmd = self.lammps_bin + ['-in', self.input_filename] print("Running: {}".format(" ".join(lammps_cmd))) p = Popen(lammps_cmd, stdout=PIPE, stderr=PIPE) (stdout, stderr) = p.communicate() ...
[ "def", "run", "(", "self", ")", ":", "lammps_cmd", "=", "self", ".", "lammps_bin", "+", "[", "'-in'", ",", "self", ".", "input_filename", "]", "print", "(", "\"Running: {}\"", ".", "format", "(", "\" \"", ".", "join", "(", "lammps_cmd", ")", ")", ")", ...
37.333333
0.005814
def confirm_operation(prompt, prefix=None, assume_yes=False, err=False): """Prompt the user for confirmation for dangerous actions.""" if assume_yes: return True prefix = prefix or click.style( "Are you %s certain you want to" % (click.style("absolutely", bold=True)) ) prompt = "%(...
[ "def", "confirm_operation", "(", "prompt", ",", "prefix", "=", "None", ",", "assume_yes", "=", "False", ",", "err", "=", "False", ")", ":", "if", "assume_yes", ":", "return", "True", "prefix", "=", "prefix", "or", "click", ".", "style", "(", "\"Are you %...
31.294118
0.00365
def precision(self, precision): """ For queries that should run faster, you may specify a lower precision, and for those that need to be more precise, a higher precision: ```python # faster queries query.range('2014-01-01', '2014-01-31', precision=0) query.range(...
[ "def", "precision", "(", "self", ",", "precision", ")", ":", "if", "isinstance", "(", "precision", ",", "int", ")", ":", "precision", "=", "self", ".", "PRECISION_LEVELS", "[", "precision", "]", "if", "precision", "not", "in", "self", ".", "PRECISION_LEVEL...
39.5
0.001647
def save_dataframes(self, outdir, prefix='df_'): """Save all attributes that start with "df" into a specified directory. Args: outdir (str): Path to output directory prefix (str): Prefix that dataframe attributes start with """ # Get list of attributes that star...
[ "def", "save_dataframes", "(", "self", ",", "outdir", ",", "prefix", "=", "'df_'", ")", ":", "# Get list of attributes that start with \"df_\"", "dfs", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", ".", "startswith", "(", "prefix", ")", ",", "dir...
38.692308
0.00388
def update(d, e): """Return a copy of dict `d` updated with dict `e`.""" res = copy.copy(d) res.update(e) return res
[ "def", "update", "(", "d", ",", "e", ")", ":", "res", "=", "copy", ".", "copy", "(", "d", ")", "res", ".", "update", "(", "e", ")", "return", "res" ]
25.6
0.007576
def keyPressEvent(self, event): """Reimplement Qt methods""" if event.key() == Qt.Key_Delete: self.remove_item() elif event.key() == Qt.Key_F2: self.rename_item() elif event == QKeySequence.Copy: self.copy() elif event == QKeySequence.P...
[ "def", "keyPressEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_Delete", ":", "self", ".", "remove_item", "(", ")", "elif", "event", ".", "key", "(", ")", "==", "Qt", ".", "Key_F2", ":", "se...
33.833333
0.004796
def RedirectDemo(handler, t): """ Demonstration of redirecting to another number. """ # t.say ("One moment please.") t.redirect(SIP_PHONE) json = t.RenderJson() logging.info ("RedirectDemo json: %s" % json) handler.response.out.write(json)
[ "def", "RedirectDemo", "(", "handler", ",", "t", ")", ":", "# t.say (\"One moment please.\")", "t", ".", "redirect", "(", "SIP_PHONE", ")", "json", "=", "t", ".", "RenderJson", "(", ")", "logging", ".", "info", "(", "\"RedirectDemo json: %s\"", "%", "json", ...
29.222222
0.00738
def get_django_user(self, username, password=None): """ Get the Django user with the given username, or create one if it doesn't already exist. If `password` is given, then set the user's password to that (regardless of whether the user was created or not). """ try: ...
[ "def", "get_django_user", "(", "self", ",", "username", ",", "password", "=", "None", ")", ":", "try", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "username", "=", "username", ")", "except", "User", ".", "DoesNotExist", ":", "user", "=",...
34.375
0.00354
def RecreateInstanceDisks(r, instance, disks=None, nodes=None): """Recreate an instance's disks. @type instance: string @param instance: Instance name @type disks: list of int @param disks: List of disk indexes @type nodes: list of string @param nodes: New instance nodes, if relocation is d...
[ "def", "RecreateInstanceDisks", "(", "r", ",", "instance", ",", "disks", "=", "None", ",", "nodes", "=", "None", ")", ":", "body", "=", "{", "}", "if", "disks", "is", "not", "None", ":", "body", "[", "\"disks\"", "]", "=", "disks", "if", "nodes", "...
26.818182
0.001637
def refresh_metrics(self): """Refresh metrics based on the column metadata""" metrics = self.get_metrics() dbmetrics = ( db.session.query(DruidMetric) .filter(DruidMetric.datasource_id == self.datasource_id) .filter(DruidMetric.metric_name.in_(metrics.keys()))...
[ "def", "refresh_metrics", "(", "self", ")", ":", "metrics", "=", "self", ".", "get_metrics", "(", ")", "dbmetrics", "=", "(", "db", ".", "session", ".", "query", "(", "DruidMetric", ")", ".", "filter", "(", "DruidMetric", ".", "datasource_id", "==", "sel...
44.277778
0.002457
def write(self, diadefs): """write files for <project> according to <diadefs> """ for diagram in diadefs: basename = diagram.title.strip().replace(" ", "_") file_name = "%s.%s" % (basename, self.config.output_format) self.set_printer(file_name, basename) ...
[ "def", "write", "(", "self", ",", "diadefs", ")", ":", "for", "diagram", "in", "diadefs", ":", "basename", "=", "diagram", ".", "title", ".", "strip", "(", ")", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", "file_name", "=", "\"%s.%s\"", "%", "(",...
40.083333
0.004065
def regularizer(name, regularization_fn, name_filter='weights'): """Wraps a regularizer in a parameter-function. Args: name: The name scope for this regularizer. regularization_fn: A function with signature: fn(variable) -> loss `Tensor` or `None`. name_filter: A regex that will be used to filter...
[ "def", "regularizer", "(", "name", ",", "regularization_fn", ",", "name_filter", "=", "'weights'", ")", ":", "regex", "=", "re", ".", "compile", "(", "name_filter", ")", "def", "fn", "(", "var_name", ",", "variable", ",", "phase", ")", ":", "if", "phase"...
35.909091
0.009864
def context_lookup(self, vars): """ Lookup the variables in the provided dictionary, resolve with entries in the context """ while isinstance(vars, IscmExpr): vars = vars.resolve(self.context) # for (k,v) in vars.items(): if isinstance(v, I...
[ "def", "context_lookup", "(", "self", ",", "vars", ")", ":", "while", "isinstance", "(", "vars", ",", "IscmExpr", ")", ":", "vars", "=", "vars", ".", "resolve", "(", "self", ".", "context", ")", "#", "for", "(", "k", ",", "v", ")", "in", "vars", ...
32.333333
0.007519
def create_template(self): """Create template (main function called by Stacker).""" template = self.template # variables = self.get_variables() template.add_version('2010-09-09') template.add_description('Static Website - Dependencies') # Resources awslogbucket =...
[ "def", "create_template", "(", "self", ")", ":", "template", "=", "self", ".", "template", "# variables = self.get_variables()", "template", ".", "add_version", "(", "'2010-09-09'", ")", "template", ".", "add_description", "(", "'Static Website - Dependencies'", ")", ...
35.594203
0.000792
def polygon_diameter(points): ''' Compute the maximun euclidian distance between any two points in a list of points ''' return max(point_dist(p0, p1) for (p0, p1) in combinations(points, 2))
[ "def", "polygon_diameter", "(", "points", ")", ":", "return", "max", "(", "point_dist", "(", "p0", ",", "p1", ")", "for", "(", "p0", ",", "p1", ")", "in", "combinations", "(", "points", ",", "2", ")", ")" ]
40.4
0.004854
def _doc_make(*make_args): """Run make in sphinx' docs directory. :return: exit code """ if sys.platform == 'win32': # Windows make_cmd = ['make.bat'] else: # Linux, Mac OS X, and others make_cmd = ['make'] make_cmd.extend(make_args) # Account for a stupid P...
[ "def", "_doc_make", "(", "*", "make_args", ")", ":", "if", "sys", ".", "platform", "==", "'win32'", ":", "# Windows", "make_cmd", "=", "[", "'make.bat'", "]", "else", ":", "# Linux, Mac OS X, and others", "make_cmd", "=", "[", "'make'", "]", "make_cmd", ".",...
25.611111
0.002092
def add_index(self, field, value): """ add_index(field, value) Tag this object with the specified field/value pair for indexing. :param field: The index field. :type field: string :param value: The index value. :type value: string or integer :rty...
[ "def", "add_index", "(", "self", ",", "field", ",", "value", ")", ":", "if", "field", "[", "-", "4", ":", "]", "not", "in", "(", "\"_bin\"", ",", "\"_int\"", ")", ":", "raise", "RiakError", "(", "\"Riak 2i fields must end with either '_bin'\"", "\" or '_int'...
30.05
0.003226
def observeState(self, call=None): """ Registers an observer to the any changes. The called function should have 2 parameters: - previousState, - actualState :param func call: The function to call. When not given, decorator usage is ...
[ "def", "observeState", "(", "self", ",", "call", "=", "None", ")", ":", "def", "_observe", "(", "call", ")", ":", "self", ".", "__observers", ".", "add", "(", "\"*\"", ",", "call", ")", "return", "call", "if", "call", "is", "not", "None", ":", "ret...
30.613636
0.001439
def load_creds_file(self, path, profile=None): """Load the credentials config file.""" config_cls = self.get_creds_reader() return config_cls.load_config(self, path, profile=profile)
[ "def", "load_creds_file", "(", "self", ",", "path", ",", "profile", "=", "None", ")", ":", "config_cls", "=", "self", ".", "get_creds_reader", "(", ")", "return", "config_cls", ".", "load_config", "(", "self", ",", "path", ",", "profile", "=", "profile", ...
50.75
0.009709
def get_option_def(self, opt): """return the dictionary defining an option given its name""" assert self.options for option in self.options: if option[0] == opt: return option[1] raise optparse.OptionError( "no such option %s in section %r" % (opt,...
[ "def", "get_option_def", "(", "self", ",", "opt", ")", ":", "assert", "self", ".", "options", "for", "option", "in", "self", ".", "options", ":", "if", "option", "[", "0", "]", "==", "opt", ":", "return", "option", "[", "1", "]", "raise", "optparse",...
37.555556
0.00578
def apply_exclude(self, high): ''' Read in the __exclude__ list and remove all excluded objects from the high data ''' if '__exclude__' not in high: return high ex_sls = set() ex_id = set() exclude = high.pop('__exclude__') for exc in e...
[ "def", "apply_exclude", "(", "self", ",", "high", ")", ":", "if", "'__exclude__'", "not", "in", "high", ":", "return", "high", "ex_sls", "=", "set", "(", ")", "ex_id", "=", "set", "(", ")", "exclude", "=", "high", ".", "pop", "(", "'__exclude__'", ")...
35.628571
0.001561
def add_context(self, name, indices, level=None): """ Add a new context level to the hierarchy. By default, new contexts are added to the lowest level of the hierarchy. To insert the context elsewhere in the hierarchy, use the ``level`` argument. For example, ``level=0`` would i...
[ "def", "add_context", "(", "self", ",", "name", ",", "indices", ",", "level", "=", "None", ")", ":", "self", ".", "_validate_context", "(", "(", "name", ",", "indices", ")", ")", "if", "level", "is", "None", ":", "level", "=", "len", "(", "self", "...
34.423077
0.003261
def classic_email_send(self, subject, from_address, to, consent_to_track, client_id=None, cc=None, bcc=None, html=None, text=None, attachments=None, track_opens=True, track_clicks=True, inline_css=True, group=None, add_recipients_to_list=None): """Sends a classic email.""" validate_consent_to_track(cons...
[ "def", "classic_email_send", "(", "self", ",", "subject", ",", "from_address", ",", "to", ",", "consent_to_track", ",", "client_id", "=", "None", ",", "cc", "=", "None", ",", "bcc", "=", "None", ",", "html", "=", "None", ",", "text", "=", "None", ",", ...
43.346154
0.003472
def make_clean_html(raw, stream_item=None, encoding=None): '''Get a clean text representation of presumed HTML. Treat `raw` as though it is HTML, even if we have no idea what it really is, and attempt to get a properly formatted HTML document with all HTML-escaped characters converted to their unicode....
[ "def", "make_clean_html", "(", "raw", ",", "stream_item", "=", "None", ",", "encoding", "=", "None", ")", ":", "# Fix emails by protecting the <,> from HTML", "raw", "=", "fix_emails", "(", "raw", ")", "raw_decoded", "=", "nice_decode", "(", "raw", ",", "stream_...
37.364865
0.000352
def set_env(self, key, value): """Sets environment variables by prepending the app_name to `key`. Also registers the environment variable with the instance object preventing an otherwise-required call to `reload()`. """ os.environ[make_env_key(self.appname, key)] = str(value) # ...
[ "def", "set_env", "(", "self", ",", "key", ",", "value", ")", ":", "os", ".", "environ", "[", "make_env_key", "(", "self", ".", "appname", ",", "key", ")", "]", "=", "str", "(", "value", ")", "# must coerce to string", "self", ".", "_registered_env_keys"...
51.375
0.011962
def set_unset(self, interface_id, attribute, address=None): """ Set attribute to True and unset the same attribute for all other interfaces. This is used for interface options that can only be set on one engine interface. :raises InterfaceNotFound: raise if specified ad...
[ "def", "set_unset", "(", "self", ",", "interface_id", ",", "attribute", ",", "address", "=", "None", ")", ":", "interface", "=", "self", ".", "get", "(", "interface_id", ")", "if", "interface_id", "is", "not", "None", "else", "None", "if", "address", "is...
50.864865
0.006778
def _make_stream_transport(self): """Create an AdbStreamTransport with a newly allocated local_id.""" msg_queue = queue.Queue() with self._stream_transport_map_lock: # Start one past the last id we used, and grab the first available one. # This mimics the ADB behavior of 'increment an unsigned a...
[ "def", "_make_stream_transport", "(", "self", ")", ":", "msg_queue", "=", "queue", ".", "Queue", "(", ")", "with", "self", ".", "_stream_transport_map_lock", ":", "# Start one past the last id we used, and grab the first available one.", "# This mimics the ADB behavior of 'incr...
54.814815
0.011952
def holding_pnl(self): """ [float] 浮动盈亏 """ return sum(position.holding_pnl for position in six.itervalues(self._positions))
[ "def", "holding_pnl", "(", "self", ")", ":", "return", "sum", "(", "position", ".", "holding_pnl", "for", "position", "in", "six", ".", "itervalues", "(", "self", ".", "_positions", ")", ")" ]
30.4
0.019231
def _previous(self, **kwargs): """ Get the previous item in any particular category """ spec = self._pagination_default_spec(kwargs) spec.update(kwargs) query = queries.build_query(spec) query = queries.where_before_entry(query, self._record) for record in query.order_b...
[ "def", "_previous", "(", "self", ",", "*", "*", "kwargs", ")", ":", "spec", "=", "self", ".", "_pagination_default_spec", "(", "kwargs", ")", "spec", ".", "update", "(", "kwargs", ")", "query", "=", "queries", ".", "build_query", "(", "spec", ")", "que...
38.75
0.004202
def update(self, iterable={}, **kwargs): """ Updates recursively a self with a given iterable. TODO: rewrite this ugly stuff """ def _merge(a, *args): for key, value in itertools.chain(*args): if key in a and isinstance(value, (dict, Conf)): ...
[ "def", "update", "(", "self", ",", "iterable", "=", "{", "}", ",", "*", "*", "kwargs", ")", ":", "def", "_merge", "(", "a", ",", "*", "args", ")", ":", "for", "key", ",", "value", "in", "itertools", ".", "chain", "(", "*", "args", ")", ":", "...
34.157895
0.002999
def run(): """CLI endpoint.""" sys.path.insert(0, os.getcwd()) logging.basicConfig(level=logging.INFO, handlers=[logging.StreamHandler()]) parser = argparse.ArgumentParser(description="Manage Application", add_help=False) parser.add_argument('app', metavar='app', type=str, h...
[ "def", "run", "(", ")", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "os", ".", "getcwd", "(", ")", ")", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "handlers", "=", "[", "logging", ".", "StreamHandler",...
35.137931
0.00191
def get_element_types(obj, **kwargs): """Get element types as a set.""" max_iterable_length = kwargs.get('max_iterable_length', 10000) consume_generator = kwargs.get('consume_generator', False) if not isiterable(obj): return None if isgenerator(obj) and not consume_generator: retu...
[ "def", "get_element_types", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "max_iterable_length", "=", "kwargs", ".", "get", "(", "'max_iterable_length'", ",", "10000", ")", "consume_generator", "=", "kwargs", ".", "get", "(", "'consume_generator'", ",", "Fals...
32.809524
0.004231
def read_value_from_path(value): """Enables translators to read values from files. The value can be referred to with the `file://` prefix. ie: conf_key: ${kms file://kms_value.txt} """ if value.startswith('file://'): path = value.split('file://', 1)[1] config_directory = get_c...
[ "def", "read_value_from_path", "(", "value", ")", ":", "if", "value", ".", "startswith", "(", "'file://'", ")", ":", "path", "=", "value", ".", "split", "(", "'file://'", ",", "1", ")", "[", "1", "]", "config_directory", "=", "get_config_directory", "(", ...
32.333333
0.002004
def _error_is_decreasing(self, last_error): """True if current error is less than last_error.""" current_error = self._compute_error() is_decreasing = current_error < last_error return is_decreasing, current_error
[ "def", "_error_is_decreasing", "(", "self", ",", "last_error", ")", ":", "current_error", "=", "self", ".", "_compute_error", "(", ")", "is_decreasing", "=", "current_error", "<", "last_error", "return", "is_decreasing", ",", "current_error" ]
48.2
0.008163
def movie(self, **kwargs): """ Search for movies by title. Args: query: CGI escpaed string. page: (optional) Minimum value of 1. Expected value is an integer. language: (optional) ISO 639-1 code. include_adult: (optional) Toggle the inclusion of a...
[ "def", "movie", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_path", "(", "'movie'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_attrs_to_values", "(", "response", "...
45.482759
0.007424
def items(self): """ Request URL and parse response. Yield a ``Torrent`` for every torrent on page. """ request = get(str(self.url), headers={'User-Agent' : "Magic Browser","origin_req_host" : "thepiratebay.se"}) root = html.fromstring(request.text) items = [self....
[ "def", "items", "(", "self", ")", ":", "request", "=", "get", "(", "str", "(", "self", ".", "url", ")", ",", "headers", "=", "{", "'User-Agent'", ":", "\"Magic Browser\"", ",", "\"origin_req_host\"", ":", "\"thepiratebay.se\"", "}", ")", "root", "=", "ht...
39.727273
0.013423
def get_reverse(self): """By default, Cable entries are sorted by rating and Broadcast ratings are sorted by time. By default, float attributes are sorted from highest to lowest and non-float attributes are sorted alphabetically (show, net) or chronologically (time). """ ...
[ "def", "get_reverse", "(", "self", ")", ":", "if", "self", ".", "sort", "in", "FLOAT_ATTRIBUTES", ":", "return", "True", "elif", "self", ".", "sort", "in", "NONFLOAT_ATTRIBUTES", ":", "return", "False", "else", ":", "raise", "InvalidSortError", "(", "self", ...
41.5
0.009823
def read_messages(self) -> str: """ returns a string of new device messages separated by newlines :return: """ if self.backend == Backends.grc: errors = self.__dev.read_errors() if "FATAL: " in errors: self.fatal_error_occurred.emit(error...
[ "def", "read_messages", "(", "self", ")", "->", "str", ":", "if", "self", ".", "backend", "==", "Backends", ".", "grc", ":", "errors", "=", "self", ".", "__dev", ".", "read_errors", "(", ")", "if", "\"FATAL: \"", "in", "errors", ":", "self", ".", "fa...
33.1
0.003914
def _get_error_reason(response): """Extract error reason from the response. It might be either the 'reason' or the entire response """ try: body = response.json() if body and 'reason' in body: return body['reason'] except ValueError: ...
[ "def", "_get_error_reason", "(", "response", ")", ":", "try", ":", "body", "=", "response", ".", "json", "(", ")", "if", "body", "and", "'reason'", "in", "body", ":", "return", "body", "[", "'reason'", "]", "except", "ValueError", ":", "pass", "return", ...
32
0.005525
def _client_tagged(self, tags): '''ensure that the client name is included in a list of tags. This is important for matching builders to the correct client. We exit on fail. Parameters ========== tags: a list of tags to look for client name in ...
[ "def", "_client_tagged", "(", "self", ",", "tags", ")", ":", "# We must match the client to a tag", "name", "=", "self", ".", "client_name", ".", "lower", "(", ")", "tags", "=", "[", "t", ".", "lower", "(", ")", "for", "t", "in", "tags", "]", "if", "na...
31.444444
0.006861
def hirise_edr(self, pid, chunk_size=1024*1024): """ Download a HiRISE EDR set of .IMG files to the CWD You must know the full id to specifiy the filter to use, ie: PSP_XXXXXX_YYYY will download every EDR IMG file available PSP_XXXXXX_YYYY_R will download every EDR...
[ "def", "hirise_edr", "(", "self", ",", "pid", ",", "chunk_size", "=", "1024", "*", "1024", ")", ":", "productid", "=", "\"{}*\"", ".", "format", "(", "pid", ")", "query", "=", "{", "\"target\"", ":", "\"mars\"", ",", "\"query\"", ":", "\"product\"", ",...
40.432432
0.007833
def visit_tryexcept(self, node): """return an astroid.TryExcept node as string""" trys = ["try:\n%s" % self._stmt_list(node.body)] for handler in node.handlers: trys.append(handler.accept(self)) if node.orelse: trys.append("else:\n%s" % self._stmt_list(node.orelse...
[ "def", "visit_tryexcept", "(", "self", ",", "node", ")", ":", "trys", "=", "[", "\"try:\\n%s\"", "%", "self", ".", "_stmt_list", "(", "node", ".", "body", ")", "]", "for", "handler", "in", "node", ".", "handlers", ":", "trys", ".", "append", "(", "ha...
43.25
0.005666
def delete_user_avatar(self, username, avatar): """Delete a user's avatar. :param username: the user to delete the avatar from :param avatar: ID of the avatar to remove """ params = {'username': username} url = self._get_url('user/avatar/' + avatar) return self._...
[ "def", "delete_user_avatar", "(", "self", ",", "username", ",", "avatar", ")", ":", "params", "=", "{", "'username'", ":", "username", "}", "url", "=", "self", ".", "_get_url", "(", "'user/avatar/'", "+", "avatar", ")", "return", "self", ".", "_session", ...
38.444444
0.00565
def get_collection(self, key, using_name=True): """Get :class:`Collection` instance. :param key: object_key or object_name :param using_name: True if getting object by object name """ object_ = self.application.get_object(key, using_name=using_name) collection = ...
[ "def", "get_collection", "(", "self", ",", "key", ",", "using_name", "=", "True", ")", ":", "object_", "=", "self", ".", "application", ".", "get_object", "(", "key", ",", "using_name", "=", "using_name", ")", "collection", "=", "Collection", ".", "from_di...
46.818182
0.007619
def bbox(self): """BBox""" return self.left, self.top, self.right, self.bottom
[ "def", "bbox", "(", "self", ")", ":", "return", "self", ".", "left", ",", "self", ".", "top", ",", "self", ".", "right", ",", "self", ".", "bottom" ]
30.666667
0.021277
def frame_from_fsnative(arg): """Takes item from argv and returns ascii native str or raises ValueError. """ assert isinstance(arg, fsnative) text = fsn2text(arg, strict=True) if PY2: return text.encode("ascii") else: return text.encode("ascii").decode("ascii")
[ "def", "frame_from_fsnative", "(", "arg", ")", ":", "assert", "isinstance", "(", "arg", ",", "fsnative", ")", "text", "=", "fsn2text", "(", "arg", ",", "strict", "=", "True", ")", "if", "PY2", ":", "return", "text", ".", "encode", "(", "\"ascii\"", ")"...
24.666667
0.003257
def run_analysis(self, catalogue, config, completeness_table=None, smoothing_kernel=None): ''' Runs an analysis of smoothed seismicity in the manner originally implemented by Frankel (1995) :param catalogue: Instance of the openquake.hmtk.seismicity.cata...
[ "def", "run_analysis", "(", "self", ",", "catalogue", ",", "config", ",", "completeness_table", "=", "None", ",", "smoothing_kernel", "=", "None", ")", ":", "self", ".", "catalogue", "=", "catalogue", "if", "smoothing_kernel", ":", "self", ".", "kernel", "="...
43.025
0.000852
def nla_next(nla, remaining): """Return next attribute in a stream of attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L171 Calculates the offset to the next attribute based on the attribute given. The attribute provided is assumed to be accessible, the caller is responsible to...
[ "def", "nla_next", "(", "nla", ",", "remaining", ")", ":", "totlen", "=", "int", "(", "NLA_ALIGN", "(", "nla", ".", "nla_len", ")", ")", "remaining", ".", "value", "-=", "totlen", "return", "nlattr", "(", "bytearray_ptr", "(", "nla", ".", "bytearray", ...
40.5
0.004386
def update_user(self, id, **kwargs): # noqa: E501 """Update user with given user groups and permissions. # 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.updat...
[ "def", "update_user", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "update_user_with...
48.5
0.001838
def processFinishedJob(self, batchSystemID, resultStatus, wallTime=None): """ Function reads a processed jobGraph file and updates its state. """ jobNode = self.removeJob(batchSystemID) jobStoreID = jobNode.jobStoreID if wallTime is not None and self.clusterScaler is not ...
[ "def", "processFinishedJob", "(", "self", ",", "batchSystemID", ",", "resultStatus", ",", "wallTime", "=", "None", ")", ":", "jobNode", "=", "self", ".", "removeJob", "(", "batchSystemID", ")", "jobStoreID", "=", "jobNode", ".", "jobStoreID", "if", "wallTime",...
63.480769
0.006862
def branches(self): """Get basic block branches. """ branches = [] if self._taken_branch: branches += [(self._taken_branch, 'taken')] if self._not_taken_branch: branches += [(self._not_taken_branch, 'not-taken')] if self._direct_branch: ...
[ "def", "branches", "(", "self", ")", ":", "branches", "=", "[", "]", "if", "self", ".", "_taken_branch", ":", "branches", "+=", "[", "(", "self", ".", "_taken_branch", ",", "'taken'", ")", "]", "if", "self", ".", "_not_taken_branch", ":", "branches", "...
25.333333
0.005076
def opponent_name(self): """ Returns a ``string`` of the opponent's name, such as the 'Purdue Boilermakers'. """ name = re.sub(r'\(\d+\)', '', self._opponent_name) name = name.replace(u'\xa0', '') return name
[ "def", "opponent_name", "(", "self", ")", ":", "name", "=", "re", ".", "sub", "(", "r'\\(\\d+\\)'", ",", "''", ",", "self", ".", "_opponent_name", ")", "name", "=", "name", ".", "replace", "(", "u'\\xa0'", ",", "''", ")", "return", "name" ]
32.125
0.007576
def list_pkgs(versions_as_list=False, removed=False, purge_desired=False, **kwargs): # pylint: disable=W0613 ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} removed If ``True``, then only packages which have b...
[ "def", "list_pkgs", "(", "versions_as_list", "=", "False", ",", "removed", "=", "False", ",", "purge_desired", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=W0613", "versions_as_list", "=", "salt", ".", "utils", ".", "data", ".", "is_tr...
37.102041
0.000268
def _convert_exception(e): '''Convert an ldap backend exception to an LDAPError and raise it.''' args = ('exception in ldap backend: {0}'.format(repr(e)), e) if six.PY2: six.reraise(LDAPError, args, sys.exc_info()[2]) else: six.raise_from(LDAPError(*args), e)
[ "def", "_convert_exception", "(", "e", ")", ":", "args", "=", "(", "'exception in ldap backend: {0}'", ".", "format", "(", "repr", "(", "e", ")", ")", ",", "e", ")", "if", "six", ".", "PY2", ":", "six", ".", "reraise", "(", "LDAPError", ",", "args", ...
40.714286
0.003436
def phi_cause_mip(self, mechanism, purview): """Return the |small_phi| of the cause MIP. This is the distance between the unpartitioned cause repertoire and the MIP cause repertoire. """ mip = self.cause_mip(mechanism, purview) return mip.phi if mip else 0
[ "def", "phi_cause_mip", "(", "self", ",", "mechanism", ",", "purview", ")", ":", "mip", "=", "self", ".", "cause_mip", "(", "mechanism", ",", "purview", ")", "return", "mip", ".", "phi", "if", "mip", "else", "0" ]
37.25
0.006557
def _add_plots_to_output(out, data): """Add CNVkit plots summarizing called copy number values. """ out["plot"] = {} diagram_plot = _add_diagram_plot(out, data) if diagram_plot: out["plot"]["diagram"] = diagram_plot scatter = _add_scatter_plot(out, data) if scatter: out["plot...
[ "def", "_add_plots_to_output", "(", "out", ",", "data", ")", ":", "out", "[", "\"plot\"", "]", "=", "{", "}", "diagram_plot", "=", "_add_diagram_plot", "(", "out", ",", "data", ")", "if", "diagram_plot", ":", "out", "[", "\"plot\"", "]", "[", "\"diagram\...
34.285714
0.002028