text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _raise_corsair_error(self, error=None, message=""): """ Raise error message based on the last reported error from the SDK :param error: specify error type :type error: int :param message: specify error message :type message: str """ if error is None: ...
[ "def", "_raise_corsair_error", "(", "self", ",", "error", "=", "None", ",", "message", "=", "\"\"", ")", ":", "if", "error", "is", "None", ":", "error", "=", "self", ".", "last_error", "(", ")", "raise", "error", "(", "message", ")" ]
31.25
12.75
def can_attend_meetings(intervals): """ :type intervals: List[Interval] :rtype: bool """ intervals = sorted(intervals, key=lambda x: x.start) for i in range(1, len(intervals)): if intervals[i].start < intervals[i - 1].end: return False return True
[ "def", "can_attend_meetings", "(", "intervals", ")", ":", "intervals", "=", "sorted", "(", "intervals", ",", "key", "=", "lambda", "x", ":", "x", ".", "start", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "intervals", ")", ")", ":", "...
28.6
10.6
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ sites.vs30 = 600 * np.ones(len(sites.vs30)) mean, stddevs = ...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "sites", ".", "vs30", "=", "600", "*", "np", ".", "ones", "(", "len", "(", "sites", ".", "vs30", ")", ")", "mean", ",", ...
36.35
20.05
def _build_full_partition( optional_parts, sequence_var_partition: Sequence[int], subjects: Sequence[Expression], operation: Operation ) -> List[Sequence[Expression]]: """Distribute subject operands among pattern operands. Given a partitoning for the variable part of the operands (i.e. a list of how ma...
[ "def", "_build_full_partition", "(", "optional_parts", ",", "sequence_var_partition", ":", "Sequence", "[", "int", "]", ",", "subjects", ":", "Sequence", "[", "Expression", "]", ",", "operation", ":", "Operation", ")", "->", "List", "[", "Sequence", "[", "Expr...
38.342105
24.210526
def makeSong(self): """Render abstract animation """ self.makeVisualSong() self.makeAudibleSong() if self.make_video: self.makeAnimation()
[ "def", "makeSong", "(", "self", ")", ":", "self", ".", "makeVisualSong", "(", ")", "self", ".", "makeAudibleSong", "(", ")", "if", "self", ".", "make_video", ":", "self", ".", "makeAnimation", "(", ")" ]
26.285714
9
def db(self, request): '''Single Database Query''' with self.mapper.begin() as session: world = session.query(World).get(randint(1, 10000)) return Json(self.get_json(world)).http_response(request)
[ "def", "db", "(", "self", ",", "request", ")", ":", "with", "self", ".", "mapper", ".", "begin", "(", ")", "as", "session", ":", "world", "=", "session", ".", "query", "(", "World", ")", ".", "get", "(", "randint", "(", "1", ",", "10000", ")", ...
45.6
14.8
def get_autosave_filename(self, filename): """ Get name of autosave file for specified file name. This function uses the dict in `self.name_mapping`. If `filename` is in the mapping, then return the corresponding autosave file name. Otherwise, construct a unique file name and up...
[ "def", "get_autosave_filename", "(", "self", ",", "filename", ")", ":", "try", ":", "autosave_filename", "=", "self", ".", "name_mapping", "[", "filename", "]", "except", "KeyError", ":", "autosave_dir", "=", "get_conf_path", "(", "'autosave'", ")", "if", "not...
42.758621
17.103448
def translate(self, dx, dy): """ Move the text from one place to another Parameters ---------- dx : float distance to move in the x-direction dy : float distance to move in the y-direction Returns ------- out : ``Label`` ...
[ "def", "translate", "(", "self", ",", "dx", ",", "dy", ")", ":", "self", ".", "position", "=", "numpy", ".", "array", "(", "(", "dx", "+", "self", ".", "position", "[", "0", "]", ",", "dy", "+", "self", ".", "position", "[", "1", "]", ")", ")...
24.038462
18.961538
def add(self, rd, ttl=None): """Add the specified rdata to the rdataset. If the optional I{ttl} parameter is supplied, then self.update_ttl(ttl) will be called prior to adding the rdata. @param rd: The rdata @type rd: dns.rdata.Rdata object @param ttl: The TTL @...
[ "def", "add", "(", "self", ",", "rd", ",", "ttl", "=", "None", ")", ":", "#", "# If we're adding a signature, do some special handling to", "# check that the signature covers the same type as the", "# other rdatas in this rdataset. If this is the first rdata", "# in the set, initial...
38.225806
16.419355
def tn_mean(tasmin, freq='YS'): r"""Mean minimum temperature. Mean of daily minimum temperature. Parameters ---------- tasmin : xarray.DataArray Minimum daily temperature [℃] or [K] freq : str, optional Resampling frequency Returns ------- xarray.DataArray Mean o...
[ "def", "tn_mean", "(", "tasmin", ",", "freq", "=", "'YS'", ")", ":", "arr", "=", "tasmin", ".", "resample", "(", "time", "=", "freq", ")", "if", "freq", "else", "tasmin", "return", "arr", ".", "mean", "(", "dim", "=", "'time'", ",", "keep_attrs", "...
23.068966
22.448276
def join (self, timeout=None): """Blocks until all items in the Queue have been gotten and processed. The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer thread calls task_done() to indicate the item was retrieved and all...
[ "def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "with", "self", ".", "all_tasks_done", ":", "if", "timeout", "is", "None", ":", "while", "self", ".", "unfinished_tasks", ":", "self", ".", "all_tasks_done", ".", "wait", "(", ")", "els...
44.136364
16.363636
def check(ctx): """ Check built package is valid. """ check_command = f"twine check {ctx.directory!s}/dist/*" report.info(ctx, "package.check", "checking package") ctx.run(check_command)
[ "def", "check", "(", "ctx", ")", ":", "check_command", "=", "f\"twine check {ctx.directory!s}/dist/*\"", "report", ".", "info", "(", "ctx", ",", "\"package.check\"", ",", "\"checking package\"", ")", "ctx", ".", "run", "(", "check_command", ")" ]
28.714286
16.428571
def nla_put_u32(msg, attrtype, value): """Add 32 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L613 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to sto...
[ "def", "nla_put_u32", "(", "msg", ",", "attrtype", ",", "value", ")", ":", "data", "=", "bytearray", "(", "value", "if", "isinstance", "(", "value", ",", "c_uint32", ")", "else", "c_uint32", "(", "value", ")", ")", "return", "nla_put", "(", "msg", ",",...
35.933333
19.133333
def fetch_plaintext(self, msg_nums): """ Given a message number that we found with imap_search, get the text/plain content. @Params msg_nums - message number to get message for @Returns Plaintext content of message matched by message number """ if ...
[ "def", "fetch_plaintext", "(", "self", ",", "msg_nums", ")", ":", "if", "not", "msg_nums", ":", "raise", "Exception", "(", "\"Invalid Message Number!\"", ")", "return", "self", ".", "__imap_fetch_content_type", "(", "msg_nums", ",", "self", ".", "PLAIN", ")" ]
34.230769
16.230769
def fetch_tweets(account_file, outfile, limit): """ Fetch up to limit tweets for each account in account_file and write to outfile. """ print('fetching tweets for accounts in', account_file) outf = io.open(outfile, 'wt') for screen_name in iter_lines(account_file): print('\nFetching tweets f...
[ "def", "fetch_tweets", "(", "account_file", ",", "outfile", ",", "limit", ")", ":", "print", "(", "'fetching tweets for accounts in'", ",", "account_file", ")", "outf", "=", "io", ".", "open", "(", "outfile", ",", "'wt'", ")", "for", "screen_name", "in", "it...
50.454545
13.363636
def __stream_format_allowed(self, stream): """ Check whether a stream allows formatting such as coloring. Inspired from Python cookbook, #475186 """ # curses isn't available on all platforms try: import curses as CURSES except: return False...
[ "def", "__stream_format_allowed", "(", "self", ",", "stream", ")", ":", "# curses isn't available on all platforms", "try", ":", "import", "curses", "as", "CURSES", "except", ":", "return", "False", "try", ":", "CURSES", ".", "setupterm", "(", ")", "return", "CU...
29.4
13.666667
def values(self): """Gets the parameter values :returns: dict of inputs: | *'nfft'*: int -- length, in samples, of FFT chunks | *'window'*: str -- name of window to apply to FFT chunks | *'overlap'*: float -- percent overlap of windows """ s...
[ "def", "values", "(", "self", ")", ":", "self", ".", "vals", "[", "'nfft'", "]", "=", "self", ".", "ui", ".", "nfftSpnbx", ".", "value", "(", ")", "self", ".", "vals", "[", "'window'", "]", "=", "str", "(", "self", ".", "ui", ".", "windowCmbx", ...
42.833333
19.916667
def _unpaginated(what): '''Returns a dictionary with all <what>, unpaginated''' page = data(what) results = page['results'] count = page['count'] while page['next']: page = data(page['next']) results += page['results'] count += page['count'] return {'results': results, 'c...
[ "def", "_unpaginated", "(", "what", ")", ":", "page", "=", "data", "(", "what", ")", "results", "=", "page", "[", "'results'", "]", "count", "=", "page", "[", "'count'", "]", "while", "page", "[", "'next'", "]", ":", "page", "=", "data", "(", "page...
32.4
12.8
def do_fake( formatter, *args, **kwargs ): """ call a faker format uses: {% fake "formatterName" *args **kwargs as myvar %} {{ myvar }} or: {% fake 'name' %} """ return Faker.getGenerator().format( formatter, *args, **kwargs )
[ "def", "do_fake", "(", "formatter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "Faker", ".", "getGenerator", "(", ")", ".", "format", "(", "formatter", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
22.538462
20.692308
def infer_object_subtype(self, api, pid=None, create=False, default_pidspace=None): """Construct a DigitalObject or appropriate subclass, inferring the appropriate subtype using :meth:`best_subtype_for_object`. Note that this method signature has been selected to match the :class:`~eulfe...
[ "def", "infer_object_subtype", "(", "self", ",", "api", ",", "pid", "=", "None", ",", "create", "=", "False", ",", "default_pidspace", "=", "None", ")", ":", "obj", "=", "DigitalObject", "(", "api", ",", "pid", ",", "create", ",", "default_pidspace", ")"...
42.789474
23.210526
def word_frequency(word, lang, wordlist='best', minimum=0.): """ Get the frequency of `word` in the language with code `lang`, from the specified `wordlist`. These wordlists can be specified: - 'large': a wordlist built from at least 5 sources, containing word frequencies of 10^-8 and higher...
[ "def", "word_frequency", "(", "word", ",", "lang", ",", "wordlist", "=", "'best'", ",", "minimum", "=", "0.", ")", ":", "args", "=", "(", "word", ",", "lang", ",", "wordlist", ",", "minimum", ")", "try", ":", "return", "_wf_cache", "[", "args", "]", ...
38.12
19
def main(): """Play Conway's Game of Life on the terminal.""" def die((x, y)): """Pretend any out-of-bounds cell is dead.""" if 0 <= x < width and 0 <= y < height: return x, y LOAD_FACTOR = 9 # Smaller means more crowded. NUDGING_LOAD_FACTOR = LOAD_FACTOR * 3 # Smaller mea...
[ "def", "main", "(", ")", ":", "def", "die", "(", "(", "x", ",", "y", ")", ")", ":", "\"\"\"Pretend any out-of-bounds cell is dead.\"\"\"", "if", "0", "<=", "x", "<", "width", "and", "0", "<=", "y", "<", "height", ":", "return", "x", ",", "y", "LOAD_F...
34.085714
17.628571
def get_server(self, UUID): """ Return a (populated) Server instance. """ server, IPAddresses, storages = self.get_server_data(UUID) return Server( server, ip_addresses=IPAddresses, storage_devices=storages, populated=True, ...
[ "def", "get_server", "(", "self", ",", "UUID", ")", ":", "server", ",", "IPAddresses", ",", "storages", "=", "self", ".", "get_server_data", "(", "UUID", ")", "return", "Server", "(", "server", ",", "ip_addresses", "=", "IPAddresses", ",", "storage_devices",...
26.230769
14.076923
def open_medium(self, location, device_type, access_mode, force_new_uuid): """Finds existing media or opens a medium from an existing storage location. Once a medium has been opened, it can be passed to other VirtualBox methods, in particular to :py:func:`IMachine.attach_device` . ...
[ "def", "open_medium", "(", "self", ",", "location", ",", "device_type", ",", "access_mode", ",", "force_new_uuid", ")", ":", "if", "not", "isinstance", "(", "location", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"location can only be an instance of ...
49.148515
26.564356
def _generate_initial_model(self): """Creates the initial model for the optimistation. Raises ------ TypeError Raised if the model failed to build. This could be due to parameters being passed to the specification in the wrong format. """ ...
[ "def", "_generate_initial_model", "(", "self", ")", ":", "initial_parameters", "=", "[", "p", ".", "current_value", "for", "p", "in", "self", ".", "current_parameters", "]", "try", ":", "initial_model", "=", "self", ".", "specification", "(", "*", "initial_par...
42.416667
21.5
def allLinesMatchingPattern(pattern, lines): """ Like lineMatchingPattern, but returns all lines that match the specified pattern :type pattern: Compiled regular expression pattern to use :type lines: List of lines to search :return: list of re.Match objects for each line matched, or an empty list if ...
[ "def", "allLinesMatchingPattern", "(", "pattern", ",", "lines", ")", ":", "result", "=", "[", "]", "for", "line", "in", "lines", ":", "m", "=", "pattern", ".", "match", "(", "line", ")", "if", "m", ":", "result", ".", "append", "(", "m", ")", "retu...
31.666667
19.733333
def function_call_action(self, text, loc, fun): """Code executed after recognising the whole function call""" exshared.setpos(loc, text) if DEBUG > 0: print("FUN_CALL:",fun) if DEBUG == 2: self.symtab.display() if DEBUG > 2: return #check number...
[ "def", "function_call_action", "(", "self", ",", "text", ",", "loc", ",", "fun", ")", ":", "exshared", ".", "setpos", "(", "loc", ",", "text", ")", "if", "DEBUG", ">", "0", ":", "print", "(", "\"FUN_CALL:\"", ",", "fun", ")", "if", "DEBUG", "==", "...
56.727273
20.545455
def calmarnorm(sharpe, T, tau = 1.0): ''' Multiplicator for normalizing calmar ratio to period tau ''' return calmar(sharpe,tau)/calmar(sharpe,T)
[ "def", "calmarnorm", "(", "sharpe", ",", "T", ",", "tau", "=", "1.0", ")", ":", "return", "calmar", "(", "sharpe", ",", "tau", ")", "/", "calmar", "(", "sharpe", ",", "T", ")" ]
31.4
19
def _phi0(self, tau, delta): """Ideal gas Helmholtz free energy and derivatives Parameters ---------- tau : float Inverse reduced temperature Tc/T, [-] delta : float Reduced density rho/rhoc, [-] Returns ------- prop : dictionary ...
[ "def", "_phi0", "(", "self", ",", "tau", ",", "delta", ")", ":", "Fi0", "=", "self", ".", "Fi0", "fio", "=", "Fi0", "[", "\"ao_log\"", "]", "[", "0", "]", "*", "log", "(", "delta", ")", "+", "Fi0", "[", "\"ao_log\"", "]", "[", "1", "]", "*", ...
30.546875
18.09375
def draw_sample(self, Xstar, n=0, num_samp=1, rand_vars=None, rand_type='standard normal', diag_factor=1e3, method='cholesky', num_eig=None, mean=None, cov=None, modify_sign=None, **kwargs): """Draw a sample evaluated at the given points `Xstar`. ...
[ "def", "draw_sample", "(", "self", ",", "Xstar", ",", "n", "=", "0", ",", "num_samp", "=", "1", ",", "rand_vars", "=", "None", ",", "rand_type", "=", "'standard normal'", ",", "diag_factor", "=", "1e3", ",", "method", "=", "'cholesky'", ",", "num_eig", ...
51.028409
22.482955
def getGolangPackages(self): """Get a list of all golang packages for all available branches """ packages = {} # get all packages url = "%s/packages" % self.base_url params = {"pattern": "golang-*", "limit": 200} response = requests.get(url, params=params) if response.status_code != requests.codes.ok:...
[ "def", "getGolangPackages", "(", "self", ")", ":", "packages", "=", "{", "}", "# get all packages", "url", "=", "\"%s/packages\"", "%", "self", ".", "base_url", "params", "=", "{", "\"pattern\"", ":", "\"golang-*\"", ",", "\"limit\"", ":", "200", "}", "respo...
30.659574
18.957447
def _infer_interval_breaks(coord): """ >>> _infer_interval_breaks(np.arange(5)) array([-0.5, 0.5, 1.5, 2.5, 3.5, 4.5]) Taken from xarray.plotting.plot module """ coord = np.asarray(coord) deltas = 0.5 * (coord[1:] - coord[:-1]) first = coord[0] - deltas[0] last = coord[-1] + de...
[ "def", "_infer_interval_breaks", "(", "coord", ")", ":", "coord", "=", "np", ".", "asarray", "(", "coord", ")", "deltas", "=", "0.5", "*", "(", "coord", "[", "1", ":", "]", "-", "coord", "[", ":", "-", "1", "]", ")", "first", "=", "coord", "[", ...
31
8.5
def usufyToXlsExport(d, fPath): """ Workaround to export to a .xls file. Args: ----- d: Data to export. fPath: File path for the output file. """ from pyexcel_xls import get_data try: #oldData = get_data(fPath) # A change in the API now returns only an array ...
[ "def", "usufyToXlsExport", "(", "d", ",", "fPath", ")", ":", "from", "pyexcel_xls", "import", "get_data", "try", ":", "#oldData = get_data(fPath)", "# A change in the API now returns only an array of arrays if there is only one sheet.", "oldData", "=", "{", "\"OSRFramework\"", ...
29
15.347826
def addItem( self, item ): """ Overloaded from the base QGraphicsScene class to set the modified \ state for this scene to being modified. :param item <QGraphicsItem> :return <bool> success """ result = super(XNodeScen...
[ "def", "addItem", "(", "self", ",", "item", ")", ":", "result", "=", "super", "(", "XNodeScene", ",", "self", ")", ".", "addItem", "(", "item", ")", "self", ".", "setModified", "(", ")", "self", ".", "_cache", ".", "add", "(", "item", ")", "return"...
29.785714
15.071429
def write_long(self, n, pack=Struct('>I').pack): """ Write an integer as an unsigned 32-bit value. """ if 0 <= n <= 0xFFFFFFFF: self._output_buffer.extend(pack(n)) else: raise ValueError('Long %d out of range 0..0xFFFFFFFF', n) return self
[ "def", "write_long", "(", "self", ",", "n", ",", "pack", "=", "Struct", "(", "'>I'", ")", ".", "pack", ")", ":", "if", "0", "<=", "n", "<=", "0xFFFFFFFF", ":", "self", ".", "_output_buffer", ".", "extend", "(", "pack", "(", "n", ")", ")", "else",...
33.666667
12.555556
def _iexplode_path(path): """Iterate over all the parts of a path. Splits path recursively with os.path.split(). """ (head, tail) = os.path.split(path) if not head or (not tail and head == path): if head: yield head if tail or not head: yield tail ret...
[ "def", "_iexplode_path", "(", "path", ")", ":", "(", "head", ",", "tail", ")", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "not", "head", "or", "(", "not", "tail", "and", "head", "==", "path", ")", ":", "if", "head", ":", "yie...
25
15.2
def crackOCR(self, image): """ Attempts to crack the given OCR Uses the "darkest pixel" method to find the darkest pixel in the image. Once found it generates a virtual box around the rest of the pet and returns the x and y coordinate of the middle of the virtual box. About 98.7...
[ "def", "crackOCR", "(", "self", ",", "image", ")", ":", "try", ":", "im", "=", "Image", ".", "open", "(", "image", ")", "# Convert to greyscale, and find darkest pixel", "im", "=", "im", ".", "convert", "(", "\"L\"", ")", "lo", ",", "hi", "=", "im", "....
36.25
21.75
def serialize(self, node: SchemaNode, value: Any) -> Union[str, ColanderNullType]: """ Serializes Python object to string representation. """ if value is None: retval = '' else: # noinspection PyUnresolvedReferences retval = s...
[ "def", "serialize", "(", "self", ",", "node", ":", "SchemaNode", ",", "value", ":", "Any", ")", "->", "Union", "[", "str", ",", "ColanderNullType", "]", ":", "if", "value", "is", "None", ":", "retval", "=", "''", "else", ":", "# noinspection PyUnresolved...
36.583333
14.916667
def get_children(self, request): """Return all children of the node retrieved by the given request. :rtype: A two-tuple with one list containing the children that reference other nodes and another containing the leaf children. """ node = decode_node(request.data) return ...
[ "def", "get_children", "(", "self", ",", "request", ")", ":", "node", "=", "decode_node", "(", "request", ".", "data", ")", "return", "_get_children", "(", "node", ",", "request", ".", "depth", ")" ]
43.375
14.75
def span_tokenize(self, s): """Return a list of integer offsets that identify sentences in the given text. :param string s: The text to tokenize into sentences. :rtype: iter(tuple(int, int)) """ if self._tokenizer is None: self._tokenizer = load_model(self.model) ...
[ "def", "span_tokenize", "(", "self", ",", "s", ")", ":", "if", "self", ".", "_tokenizer", "is", "None", ":", "self", ".", "_tokenizer", "=", "load_model", "(", "self", ".", "model", ")", "# for debug in tokenizer.debug_decisions(s):", "# log.debug(format_debug...
41.909091
11.454545
def addElement(self, parent, tag, value): """Add an RSS item.""" elem = self.rss.createElement(tag) node = self.rss.createTextNode(value) return parent.appendChild(elem).appendChild(node)
[ "def", "addElement", "(", "self", ",", "parent", ",", "tag", ",", "value", ")", ":", "elem", "=", "self", ".", "rss", ".", "createElement", "(", "tag", ")", "node", "=", "self", ".", "rss", ".", "createTextNode", "(", "value", ")", "return", "parent"...
43
5
def guess_file_type(kind, filepath=None, youtube_id=None, web_url=None, encoding=None): """ guess_file_class: determines what file the content is Args: filepath (str): filepath of file to check Returns: string indicating file's class """ if youtube_id: return FileTypes.YO...
[ "def", "guess_file_type", "(", "kind", ",", "filepath", "=", "None", ",", "youtube_id", "=", "None", ",", "web_url", "=", "None", ",", "encoding", "=", "None", ")", ":", "if", "youtube_id", ":", "return", "FileTypes", ".", "YOUTUBE_VIDEO_FILE", "elif", "we...
37.470588
16.411765
def create_country(cls, country, **kwargs): """Create Country Create a new Country This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.create_country(country, async=True) >>> result = thre...
[ "def", "create_country", "(", "cls", ",", "country", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_create_country_with_http_info",...
38.809524
18.333333
def groestlHash(data): """Groestl-512 compound hash.""" try: import groestlcoin_hash except ImportError: t = 'Groestlcoin requires the groestlcoin_hash package ("pip install groestlcoin_hash").' print(t) raise ImportError(t) return bytes_as_revhex(groestlcoin_hash.getHas...
[ "def", "groestlHash", "(", "data", ")", ":", "try", ":", "import", "groestlcoin_hash", "except", "ImportError", ":", "t", "=", "'Groestlcoin requires the groestlcoin_hash package (\"pip install groestlcoin_hash\").'", "print", "(", "t", ")", "raise", "ImportError", "(", ...
33
23.8
def connect(token, protocol=RtmProtocol, factory=WebSocketClientFactory, factory_kwargs=None, api_url=None, debug=False): """ Creates a new connection to the Slack Real-Time API. Returns (connection) which represents this connection to the API server. """ if factory_kwargs is None: factory_kwargs = dict() me...
[ "def", "connect", "(", "token", ",", "protocol", "=", "RtmProtocol", ",", "factory", "=", "WebSocketClientFactory", ",", "factory_kwargs", "=", "None", ",", "api_url", "=", "None", ",", "debug", "=", "False", ")", ":", "if", "factory_kwargs", "is", "None", ...
33.833333
25.166667
def import_class(klass): '''Import the named class and return that class''' mod = __import__(klass.rpartition('.')[0]) for segment in klass.split('.')[1:-1]: mod = getattr(mod, segment) return getattr(mod, klass.rpartition('.')[2])
[ "def", "import_class", "(", "klass", ")", ":", "mod", "=", "__import__", "(", "klass", ".", "rpartition", "(", "'.'", ")", "[", "0", "]", ")", "for", "segment", "in", "klass", ".", "split", "(", "'.'", ")", "[", "1", ":", "-", "1", "]", ":", "m...
41.666667
8.666667
def results(self, names=None, alpha=_alpha, mode='peak', **kwargs): """ Calculate the results for a set of parameters. """ if names is None: names = self.names ret = odict() for n in names: ret[n] = getattr(self,'%s_interval'%mode)(n, **kwargs) return ...
[ "def", "results", "(", "self", ",", "names", "=", "None", ",", "alpha", "=", "_alpha", ",", "mode", "=", "'peak'", ",", "*", "*", "kwargs", ")", ":", "if", "names", "is", "None", ":", "names", "=", "self", ".", "names", "ret", "=", "odict", "(", ...
35
14.333333
def get_PSD(self, NPerSegment=1000000, window="hann", timeStart=None, timeEnd=None, override=False): """ Extracts the power spectral density (PSD) from the data. Parameters ---------- NPerSegment : int, optional Length of each segment used in scipy.welch ...
[ "def", "get_PSD", "(", "self", ",", "NPerSegment", "=", "1000000", ",", "window", "=", "\"hann\"", ",", "timeStart", "=", "None", ",", "timeEnd", "=", "None", ",", "override", "=", "False", ")", ":", "if", "timeStart", "==", "None", "and", "timeEnd", "...
38
22.204082
def login_user(server, login, password): """Get the login session. :param server: The Geonode server URL. :type server: basestring :param login: The login to use on Geonode. :type login: basestring :param password: The password to use on Geonode. :type password: basestring """ log...
[ "def", "login_user", "(", "server", ",", "login", ",", "password", ")", ":", "login_url", "=", "urljoin", "(", "server", ",", "login_url_prefix", ")", "# Start the web session", "session", "=", "requests", ".", "session", "(", ")", "result", "=", "session", ...
29.942308
18.019231
def mergeall(filename, snrmin, snrmax, bdfdir): """ Merge cands/noise files over all scans Tries to find scans from filename, but will fall back to finding relevant files if it does not exist. """ filename = os.path.abspath(filename) bignumber = 500 if os.path.exists(filename): scans ...
[ "def", "mergeall", "(", "filename", ",", "snrmin", ",", "snrmax", ",", "bdfdir", ")", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "bignumber", "=", "500", "if", "os", ".", "path", ".", "exists", "(", "filename", ")"...
43.538462
29.115385
async def connect( host, port=22223, version="1.19", on_event=None, on_disconnect=None, timeout=5, loop=None, ) -> QRTConnection: """Async function to connect to QTM :param host: Address of the computer running QTM. :param port: Port number to connect to, should be the port conf...
[ "async", "def", "connect", "(", "host", ",", "port", "=", "22223", ",", "version", "=", "\"1.19\"", ",", "on_event", "=", "None", ",", "on_disconnect", "=", "None", ",", "timeout", "=", "5", ",", "loop", "=", "None", ",", ")", "->", "QRTConnection", ...
33.021739
23.673913
def logoNotebook(symbol, token='', version=''): '''This is a helper function, but the google APIs url is standardized. https://iexcloud.io/docs/api/#logo 8am UTC daily Args: symbol (string); Ticker to request token (string); Access token version (string); API version Retur...
[ "def", "logoNotebook", "(", "symbol", ",", "token", "=", "''", ",", "version", "=", "''", ")", ":", "_raiseIfNotStr", "(", "symbol", ")", "url", "=", "logo", "(", "symbol", ",", "token", ",", "version", ")", "[", "'url'", "]", "return", "ImageI", "("...
25.705882
19.941176
def followed_columns(self): """获取用户关注的专栏. :return: 用户关注的专栏,返回生成器 :rtype: Column.Iterable """ from .column import Column if self.url is None: return if self.followed_column_num > 0: tag = self.soup.find('div', class_='zm-profile-side-column...
[ "def", "followed_columns", "(", "self", ")", ":", "from", ".", "column", "import", "Column", "if", "self", ".", "url", "is", "None", ":", "return", "if", "self", ".", "followed_column_num", ">", "0", ":", "tag", "=", "self", ".", "soup", ".", "find", ...
40.675
12.025
def handle_shot(self, obj): """Handle a shot event. :param obj: A :py:class:`~turberfield.dialogue.model.Model.Shot` object. :return: The supplied object. """ print( "{t.dim}{shot}{t.normal}".format( shot=obj.name.capitalize(), t=self.terminal ...
[ "def", "handle_shot", "(", "self", ",", "obj", ")", ":", "print", "(", "\"{t.dim}{shot}{t.normal}\"", ".", "format", "(", "shot", "=", "obj", ".", "name", ".", "capitalize", "(", ")", ",", "t", "=", "self", ".", "terminal", ")", ",", "end", "=", "\"\...
27.133333
18.866667
def on_page_markdown(self, markdown, page, config, site_navigation=None, **kwargs): "Provide a hook for defining functions from an external module" # the site_navigation argument has been made optional # (deleted in post 1.0 mkdocs, but maintained here # for ba...
[ "def", "on_page_markdown", "(", "self", ",", "markdown", ",", "page", ",", "config", ",", "site_navigation", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# the site_navigation argument has been made optional", "# (deleted in post 1.0 mkdocs, but maintained here", "# f...
33.666667
21.777778
def _schedule(self, action: Callable, seconds: int=0) -> int: """ Schedule an action to be executed after `seconds` seconds. :param action: a callable to be scheduled :param seconds: the time in seconds after which the action must be executed """ self.aid += 1 if...
[ "def", "_schedule", "(", "self", ",", "action", ":", "Callable", ",", "seconds", ":", "int", "=", "0", ")", "->", "int", ":", "self", ".", "aid", "+=", "1", "if", "seconds", ">", "0", ":", "nxt", "=", "time", ".", "perf_counter", "(", ")", "+", ...
41.269231
19.269231
def boundary_maximum_division(graph, xxx_todo_changeme5): r""" Boundary term processing adjacent voxels maximum value using a division relationship. An implementation of a boundary term, suitable to be used with the `~medpy.graphcut.generate.graph_from_voxels` function. The same as `bound...
[ "def", "boundary_maximum_division", "(", "graph", ",", "xxx_todo_changeme5", ")", ":", "(", "gradient_image", ",", "sigma", ",", "spacing", ")", "=", "xxx_todo_changeme5", "gradient_image", "=", "scipy", ".", "asarray", "(", "gradient_image", ")", "def", "boundary...
38.837209
22.534884
def get_model(self): """ Return the class Model used by this Agnocomplete """ if hasattr(self, 'model') and self.model: return self.model # Give me a "none" queryset try: none = self.get_queryset().none() return none.model excep...
[ "def", "get_model", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'model'", ")", "and", "self", ".", "model", ":", "return", "self", ".", "model", "# Give me a \"none\" queryset", "try", ":", "none", "=", "self", ".", "get_queryset", "(", ")...
34.928571
12.071429
def list_subadres_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Subadres` to json. """ return { 'id': obj.id, 'subadres': obj.subadres, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'defi...
[ "def", "list_subadres_adapter", "(", "obj", ",", "request", ")", ":", "return", "{", "'id'", ":", "obj", ".", "id", ",", "'subadres'", ":", "obj", ".", "subadres", ",", "'status'", ":", "{", "'id'", ":", "obj", ".", "status", ".", "id", ",", "'naam'"...
25.071429
12.357143
def sign_certificate(): """ Get the new certificate. Returns the signed bytes. """ LOGGER.info("Signing certificate...") cmd = [ 'openssl', 'req', '-in', os.path.join(gettempdir(), 'domain.csr'), '-outform', 'DER' ] devnull = open(os.devnull, 'wb') csr_der = ...
[ "def", "sign_certificate", "(", ")", ":", "LOGGER", ".", "info", "(", "\"Signing certificate...\"", ")", "cmd", "=", "[", "'openssl'", ",", "'req'", ",", "'-in'", ",", "os", ".", "path", ".", "join", "(", "gettempdir", "(", ")", ",", "'domain.csr'", ")",...
28.086957
18.608696
def newton_solver(f, x0, lb=None, ub=None, infos=False, verbose=False, maxit=50, tol=1e-8, eps=1e-5, numdiff=False): '''Solves many independent systems f(x)=0 simultaneously using a simple gradient descent. :param f: objective function to be solved with values p x N . The second output argument represents the d...
[ "def", "newton_solver", "(", "f", ",", "x0", ",", "lb", "=", "None", ",", "ub", "=", "None", ",", "infos", "=", "False", ",", "verbose", "=", "False", ",", "maxit", "=", "50", ",", "tol", "=", "1e-8", ",", "eps", "=", "1e-5", ",", "numdiff", "=...
31.170732
26.731707
def aot40_vegetation(df, nb_an): """ Calcul de l'AOT40 du 1er mai au 31 juillet *AOT40 : AOT 40 ( exprimé en micro g/m³ par heure ) signifie la somme des différences entre les concentrations horaires supérieures à 40 parties par milliard ( 40 ppb soit 80 micro g/m³ ), durant une période donnée en ...
[ "def", "aot40_vegetation", "(", "df", ",", "nb_an", ")", ":", "return", "_aot", "(", "df", ".", "tshift", "(", "1", ")", ",", "nb_an", "=", "nb_an", ",", "limite", "=", "80", ",", "mois_debut", "=", "5", ",", "mois_fin", "=", "7", ",", "heure_debut...
40.652174
24.652174
def match(self, request): """ Matches an outgoing HTTP request against the current mock matchers. This method acts like a delegator to `pook.MatcherEngine`. Arguments: request (pook.Request): request instance to match. Raises: Exception: if the mock has...
[ "def", "match", "(", "self", ",", "request", ")", ":", "# If mock already expired, fail it", "if", "self", ".", "_times", "<=", "0", ":", "raise", "PookExpiredMock", "(", "'Mock expired'", ")", "# Trigger mock filters", "for", "test", "in", "self", ".", "filters...
29.964286
19.785714
def assign(self, institute, case, user, link): """Assign a user to a case. This function will create an Event to log that a person has been assigned to a case. Also the user will be added to case "assignees". Arguments: institute (dict): A institute case (dict):...
[ "def", "assign", "(", "self", ",", "institute", ",", "case", ",", "user", ",", "link", ")", ":", "LOG", ".", "info", "(", "\"Creating event for assigning {0} to {1}\"", ".", "format", "(", "user", "[", "'name'", "]", ".", "encode", "(", "'utf-8'", ")", "...
33.222222
19.222222
def install_package_and_wait( package_name, package_version=None, service_name=None, options_file=None, options_json=None, wait_for_completion=True, timeout_sec=600, expected_running_tasks=0 ): """ Install a package via the DC/OS library and wait for c...
[ "def", "install_package_and_wait", "(", "package_name", ",", "package_version", "=", "None", ",", "service_name", "=", "None", ",", "options_file", "=", "None", ",", "options_json", "=", "None", ",", "wait_for_completion", "=", "True", ",", "timeout_sec", "=", "...
23.652174
16.26087
def findArgs(args, prefixes): """ Extracts the list of arguments that start with any of the specified prefix values """ return list([ arg for arg in args if len([p for p in prefixes if arg.lower().startswith(p.lower())]) > 0 ])
[ "def", "findArgs", "(", "args", ",", "prefixes", ")", ":", "return", "list", "(", "[", "arg", "for", "arg", "in", "args", "if", "len", "(", "[", "p", "for", "p", "in", "prefixes", "if", "arg", ".", "lower", "(", ")", ".", "startswith", "(", "p", ...
29.5
20.75
def main(): '''This is the main function of this script. The current script args are shown below :: Usage: checkplotlist [-h] [--search SEARCH] [--sortby SORTBY] [--filterby FILTERBY] [--splitout SPLITOUT] [--outprefix OUTPREFIX] [--maxkeyworke...
[ "def", "main", "(", ")", ":", "####################", "## PARSE THE ARGS ##", "####################", "aparser", "=", "argparse", ".", "ArgumentParser", "(", "epilog", "=", "PROGEPILOG", ",", "description", "=", "PROGDESC", ",", "formatter_class", "=", "argparse", "...
38.147114
23.137803
def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser(description=( 'Calculates a message digest hash for every file in a directory or ' 'storage media image.')) argument_parser.add_argument( 'source',...
[ "def", "Main", "(", ")", ":", "argument_parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "(", "'Calculates a message digest hash for every file in a directory or '", "'storage media image.'", ")", ")", "argument_parser", ".", "add_argument", "(", ...
25.490909
23.709091
def libvlc_media_player_set_video_title_display(p_mi, position, timeout): '''Set if, and how, the video title will be shown when media is played. @param p_mi: the media player. @param position: position at which to display the title, or libvlc_position_disable to prevent the title from being displayed. ...
[ "def", "libvlc_media_player_set_video_title_display", "(", "p_mi", ",", "position", ",", "timeout", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_media_player_set_video_title_display'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_media_player_set_...
65.636364
34
def get_all_analytics(user, job_id): """Get all analytics of a job.""" args = schemas.args(flask.request.args.to_dict()) v1_utils.verify_existence_and_get(job_id, models.JOBS) query = v1_utils.QueryBuilder(_TABLE, args, _A_COLUMNS) # If not admin nor rh employee then restrict the view to the team ...
[ "def", "get_all_analytics", "(", "user", ",", "job_id", ")", ":", "args", "=", "schemas", ".", "args", "(", "flask", ".", "request", ".", "args", ".", "to_dict", "(", ")", ")", "v1_utils", ".", "verify_existence_and_get", "(", "job_id", ",", "models", "....
39.444444
22.388889
def tune_auth_method(self, path, default_lease_ttl=None, max_lease_ttl=None, description=None, audit_non_hmac_request_keys=None, audit_non_hmac_response_keys=None, listing_visibility='', passthrough_request_headers=None): """Tune configuration parameters for a g...
[ "def", "tune_auth_method", "(", "self", ",", "path", ",", "default_lease_ttl", "=", "None", ",", "max_lease_ttl", "=", "None", ",", "description", "=", "None", ",", "audit_non_hmac_request_keys", "=", "None", ",", "audit_non_hmac_response_keys", "=", "None", ",", ...
53.536232
29.188406
def mds(means, weights, d): """ Dimensionality reduction using MDS. Args: means (array): genes x clusters weights (array): clusters x cells d (int): desired dimensionality Returns: W_reduced (array): array of shape (d, cells) """ X = dim_reduce(means, weights, d...
[ "def", "mds", "(", "means", ",", "weights", ",", "d", ")", ":", "X", "=", "dim_reduce", "(", "means", ",", "weights", ",", "d", ")", "if", "X", ".", "shape", "[", "0", "]", "==", "2", ":", "return", "X", ".", "dot", "(", "weights", ")", "else...
23.470588
14.176471
def create_timer(cb: Callable[[float], None], interval: float, delay_policy: TimerDelayPolicy = TimerDelayPolicy.DEFAULT, loop: Optional[asyncio.BaseEventLoop] = None) -> asyncio.Task: ''' Schedule a timer with the given callable and the interval in seconds. The interval va...
[ "def", "create_timer", "(", "cb", ":", "Callable", "[", "[", "float", "]", ",", "None", "]", ",", "interval", ":", "float", ",", "delay_policy", ":", "TimerDelayPolicy", "=", "TimerDelayPolicy", ".", "DEFAULT", ",", "loop", ":", "Optional", "[", "asyncio",...
36.769231
19.538462
def init_app(self, app, session=None, parameters=None): """Initializes snow extension Set config default and find out which client type to use :param app: App passed from constructor or directly to init_app (factory) :param session: requests-compatible session to pass along to init_app...
[ "def", "init_app", "(", "self", ",", "app", ",", "session", "=", "None", ",", "parameters", "=", "None", ")", ":", "if", "parameters", "is", "not", "None", "and", "not", "isinstance", "(", "parameters", ",", "ParamsBuilder", ")", ":", "raise", "InvalidUs...
47.53125
27.46875
def _find_glob_matches(in_files, metadata): """Group files that match by globs for merging, rather than by explicit pairs. """ reg_files = copy.deepcopy(in_files) glob_files = [] for glob_search in [x for x in metadata.keys() if "*" in x]: cur = [] for fname in in_files: ...
[ "def", "_find_glob_matches", "(", "in_files", ",", "metadata", ")", ":", "reg_files", "=", "copy", ".", "deepcopy", "(", "in_files", ")", "glob_files", "=", "[", "]", "for", "glob_search", "in", "[", "x", "for", "x", "in", "metadata", ".", "keys", "(", ...
40.142857
11.214286
def iteritems(self): """ Iterate through the property names and values of this CIM instance. Each iteration item is a tuple of the property name (in the original lexical case) and the property value. The order of properties is preserved. """ for key, val in self...
[ "def", "iteritems", "(", "self", ")", ":", "for", "key", ",", "val", "in", "self", ".", "properties", ".", "iteritems", "(", ")", ":", "yield", "(", "key", ",", "val", ".", "value", ")" ]
33.545455
18.090909
def revoke_access(self): """Revoke all access to this path.""" reading = PERMISSIONS['user']['execute'] + PERMISSIONS['group']['execute'] + PERMISSIONS['other']['execute'] os.chmod(self.file_path, reading)
[ "def", "revoke_access", "(", "self", ")", ":", "reading", "=", "PERMISSIONS", "[", "'user'", "]", "[", "'execute'", "]", "+", "PERMISSIONS", "[", "'group'", "]", "[", "'execute'", "]", "+", "PERMISSIONS", "[", "'other'", "]", "[", "'execute'", "]", "os",...
56.5
23.25
def _statuscode2string(status_code): """Return a short message for a CIM status code.""" try: s = _STATUSCODE2STRING[status_code] except KeyError: s = _format("Invalid status code {0}", status_code) return s
[ "def", "_statuscode2string", "(", "status_code", ")", ":", "try", ":", "s", "=", "_STATUSCODE2STRING", "[", "status_code", "]", "except", "KeyError", ":", "s", "=", "_format", "(", "\"Invalid status code {0}\"", ",", "status_code", ")", "return", "s" ]
33.285714
15.142857
def get_ssh_credentials(self, id, **kwargs): """ Gets ssh credentials for a build This GET request is for authenticated users only. The path for the endpoint is not restful to be able to authenticate this GET request only. This method makes a synchronous HTTP request by default. To make ...
[ "def", "get_ssh_credentials", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'callback'", ")", ":", "return", "self", ".", "get_ssh_credentials_with_ht...
46.64
19.12
def jsonp(func): """Wraps JSONified output for JSONP requests. http://flask.pocoo.org/snippets/79/ """ @functools.wraps(func) def decorated_view(*args, **kwargs): callback = request.args.get('callback', None) if callback: data = str(func(*args, **kwargs)) con...
[ "def", "jsonp", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "decorated_view", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "request", ".", "args", ".", "get", "(", "'callback'", ",", "Non...
34.1875
13.3125
def as_check_request(self, timer=datetime.utcnow): """Makes a `ServicecontrolServicesCheckRequest` from this instance Returns: a ``ServicecontrolServicesCheckRequest`` Raises: ValueError: if the fields in this instance are insufficient to to create a valid ``Ser...
[ "def", "as_check_request", "(", "self", ",", "timer", "=", "datetime", ".", "utcnow", ")", ":", "if", "not", "self", ".", "service_name", ":", "raise", "ValueError", "(", "u'the service name must be set'", ")", "if", "not", "self", ".", "operation_id", ":", ...
41.6
23.4
def to_dict(self): """ to_dict: puts Topic or Content node data into the format that Kolibri Studio expects Args: None Returns: dict of channel data """ return { "title": self.title, "language" : self.language, "description": self.descr...
[ "def", "to_dict", "(", "self", ")", ":", "return", "{", "\"title\"", ":", "self", ".", "title", ",", "\"language\"", ":", "self", ".", "language", ",", "\"description\"", ":", "self", ".", "description", ",", "\"node_id\"", ":", "self", ".", "get_node_id",...
38.24
10.76
def arrays_to_hdf5(filename="cache.hdf5"): """Returns registry for serialising arrays to a HDF5 reference.""" return Registry( types={ numpy.ndarray: SerNumpyArrayToHDF5(filename, "cache.lock") }, hooks={ '<ufunc>': SerUFunc() }, hook_fn=_numpy_hoo...
[ "def", "arrays_to_hdf5", "(", "filename", "=", "\"cache.hdf5\"", ")", ":", "return", "Registry", "(", "types", "=", "{", "numpy", ".", "ndarray", ":", "SerNumpyArrayToHDF5", "(", "filename", ",", "\"cache.lock\"", ")", "}", ",", "hooks", "=", "{", "'<ufunc>'...
28.818182
19.727273
def psturng(q, r, v): """Evaluates the probability from 0 to q for a studentized range having v degrees of freedom and r samples. Parameters ---------- q : (scalar, array_like) quantile value of Studentized Range q >= 0. r : (scalar, array_like) The number of samples ...
[ "def", "psturng", "(", "q", ",", "r", ",", "v", ")", ":", "if", "all", "(", "map", "(", "_isfloat", ",", "[", "q", ",", "r", ",", "v", "]", ")", ")", ":", "return", "_psturng", "(", "q", ",", "r", ",", "v", ")", "return", "_vpsturng", "(", ...
29.53125
17.3125
def update_startup_byteman_script(self, byteman_startup_script): """ Update the byteman startup script, i.e., rule injected before the node starts. :param byteman_startup_script: the relative path to the script :raise common.LoadError: if the node does not have byteman installed ...
[ "def", "update_startup_byteman_script", "(", "self", ",", "byteman_startup_script", ")", ":", "if", "self", ".", "byteman_port", "==", "'0'", ":", "raise", "common", ".", "LoadError", "(", "'Byteman is not installed'", ")", "self", ".", "byteman_startup_script", "="...
46.363636
20.727273
def inspect(self, **kwargs): """ Plot the Phonon SCF cycle results with matplotlib. Returns: `matplotlib` figure, None if some error occurred. """ scf_cycle = abiinspect.PhononScfCycle.from_file(self.output_file.path) if scf_cycle is not None: if ...
[ "def", "inspect", "(", "self", ",", "*", "*", "kwargs", ")", ":", "scf_cycle", "=", "abiinspect", ".", "PhononScfCycle", ".", "from_file", "(", "self", ".", "output_file", ".", "path", ")", "if", "scf_cycle", "is", "not", "None", ":", "if", "\"title\"", ...
36.727273
17.090909
def check_boto_reqs(boto_ver=None, boto3_ver=None, botocore_ver=None, check_boto=True, check_boto3=True): ''' Checks for the version of various required boto libs in one central location. Most boto states and modules rely on a s...
[ "def", "check_boto_reqs", "(", "boto_ver", "=", "None", ",", "boto3_ver", "=", "None", ",", "botocore_ver", "=", "None", ",", "check_boto", "=", "True", ",", "check_boto3", "=", "True", ")", ":", "if", "check_boto", "is", "True", ":", "try", ":", "# Late...
39.117647
28.470588
def create_datacenter(call=None, kwargs=None): ''' Creates a virtual datacenter based on supplied parameters. CLI Example: .. code-block:: bash salt-cloud -f create_datacenter profitbricks name=mydatacenter location=us/las description="my description" ''' if call != 'function'...
[ "def", "create_datacenter", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'The create_address function must be called with -f or --function.'", ")", "if", "kwargs", "is", ...
30.088235
25.617647
def __reorganize_geo(self): """ Concat geo value and units, and reorganize the rest References geo data from self.noaa_data_sorted Places new data into self.noaa_geo temporarily, and then back into self.noaa_data_sorted. :return: """ logger_lpd_noaa.info("enter re...
[ "def", "__reorganize_geo", "(", "self", ")", ":", "logger_lpd_noaa", ".", "info", "(", "\"enter reorganize_geo\"", ")", "try", ":", "# Geo -> Properties", "for", "k", ",", "v", "in", "self", ".", "noaa_data_sorted", "[", "\"Site_Information\"", "]", "[", "'prope...
40.52
22.84
def download_pac(candidate_urls, timeout=1, allowed_content_types=None): """ Try to download a PAC file from one of the given candidate URLs. :param list[str] candidate_urls: URLs that are expected to return a PAC file. Requests are made in order, one by one. :param timeout: Time to wait ...
[ "def", "download_pac", "(", "candidate_urls", ",", "timeout", "=", "1", ",", "allowed_content_types", "=", "None", ")", ":", "if", "not", "allowed_content_types", ":", "allowed_content_types", "=", "{", "'application/x-ns-proxy-autoconfig'", ",", "'application/x-javascr...
52.9
28.566667
def add_ini_opts(self, cp, sec): """Add job-specific options from configuration file. Parameters ----------- cp : ConfigParser object The ConfigParser object holding the workflow configuration settings sec : string The section containing options for this ...
[ "def", "add_ini_opts", "(", "self", ",", "cp", ",", "sec", ")", ":", "for", "opt", "in", "cp", ".", "options", "(", "sec", ")", ":", "value", "=", "string", ".", "strip", "(", "cp", ".", "get", "(", "sec", ",", "opt", ")", ")", "opt", "=", "'...
43.985714
17.628571
def get(self, sid): """ Constructs a EventContext :param sid: The sid :returns: twilio.rest.taskrouter.v1.workspace.event.EventContext :rtype: twilio.rest.taskrouter.v1.workspace.event.EventContext """ return EventContext(self._version, workspace_sid=self._solut...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "EventContext", "(", "self", ".", "_version", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspace_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
34.3
24.3
def save_tiles(tiles, prefix='', directory=os.getcwd(), format='png'): """ Write image files to disk. Create specified folder(s) if they don't exist. Return list of :class:`Tile` instance. Args: tiles (list): List, tuple or set of :class:`Tile` objects to save. prefix (str): Filename...
[ "def", "save_tiles", "(", "tiles", ",", "prefix", "=", "''", ",", "directory", "=", "os", ".", "getcwd", "(", ")", ",", "format", "=", "'png'", ")", ":", "# Causes problems in CLI script.", "# if not os.path.exists(directory):", "# os.makedirs(directory)"...
37.25
21.583333
def add_event_data(self, section, data): """ Add template or complement basecalled event data. :param section: Either template or complement. :param data: Event data table to be written. """ event_group = 'BaseCalled_{}'.format(section) if not event_group in self...
[ "def", "add_event_data", "(", "self", ",", "section", ",", "data", ")", ":", "event_group", "=", "'BaseCalled_{}'", ".", "format", "(", "section", ")", "if", "not", "event_group", "in", "self", ".", "handle", ".", "handle", "[", "'Analyses/{}'", ".", "form...
54.4
21.6
def delete(filething): """ delete(filething) Arguments: filething (filething) Raises: mutagen.MutagenError Remove tags from a file. """ t = OggTheora(filething) filething.fileobj.seek(0) t.delete(filething)
[ "def", "delete", "(", "filething", ")", ":", "t", "=", "OggTheora", "(", "filething", ")", "filething", ".", "fileobj", ".", "seek", "(", "0", ")", "t", ".", "delete", "(", "filething", ")" ]
17.428571
19.142857
def angle(self, center1_x, center1_y, center2_x, center2_y): """ compute the rotation angle of the dipole :return: """ phi_G = np.arctan2(center2_y - center1_y, center2_x - center1_x) return phi_G
[ "def", "angle", "(", "self", ",", "center1_x", ",", "center1_y", ",", "center2_x", ",", "center2_y", ")", ":", "phi_G", "=", "np", ".", "arctan2", "(", "center2_y", "-", "center1_y", ",", "center2_x", "-", "center1_x", ")", "return", "phi_G" ]
34
14.857143
def get_env(working_directory=None): """get_env This function grabs key/value pair items and assigns them for the config.JSON. This essentially checks the environment for key locations within the filesystem. """ working = working_directory if working_directory else os.getcwd() dist_dirs = glob.glob(wo...
[ "def", "get_env", "(", "working_directory", "=", "None", ")", ":", "working", "=", "working_directory", "if", "working_directory", "else", "os", ".", "getcwd", "(", ")", "dist_dirs", "=", "glob", ".", "glob", "(", "working", "+", "\"/f5-*-dist\"", ")", "prin...
38.411765
15.558824
def _gen_rollback_cfg(self): """Save a configuration that can be used for rollback.""" cfg_file = self._gen_full_path(self.rollback_cfg) cmd = 'copy running-config {}'.format(cfg_file) self._disable_confirm() self.device.send_command_expect(cmd) self._enable_confirm()
[ "def", "_gen_rollback_cfg", "(", "self", ")", ":", "cfg_file", "=", "self", ".", "_gen_full_path", "(", "self", ".", "rollback_cfg", ")", "cmd", "=", "'copy running-config {}'", ".", "format", "(", "cfg_file", ")", "self", ".", "_disable_confirm", "(", ")", ...
44.285714
9.571429
def shelter_find(self, **kwargs): """ shelter.find wrapper. Returns a generator of shelter record dicts matching your search criteria. :rtype: generator :returns: A generator of shelter record dicts. :raises: :py:exc:`petfinder.exceptions.LimitExceeded` once you have ...
[ "def", "shelter_find", "(", "self", ",", "*", "*", "kwargs", ")", ":", "def", "shelter_find_parser", "(", "root", ",", "has_records", ")", ":", "\"\"\"\n The parser that is used with the ``_do_autopaginating_api_call``\n method for auto-pagination.\n\n ...
38.483871
18.806452
def image_upload_to(self, filename): """ Compute the upload path for the image field. """ now = timezone.now() filename, extension = os.path.splitext(filename) return os.path.join( UPLOAD_TO, now.strftime('%Y'), now.strftime('%m'), ...
[ "def", "image_upload_to", "(", "self", ",", "filename", ")", ":", "now", "=", "timezone", ".", "now", "(", ")", "filename", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "return", "os", ".", "path", ".", "join", "("...
29.923077
11.769231