text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def rescorer(self, rescorer): """ Returns a new QuerySet with a set rescorer. """ clone = self._clone() clone._rescorer=rescorer return clone
[ "def", "rescorer", "(", "self", ",", "rescorer", ")", ":", "clone", "=", "self", ".", "_clone", "(", ")", "clone", ".", "_rescorer", "=", "rescorer", "return", "clone" ]
26.142857
0.015873
def colorize_ansi(msg, color=None, style=None): """colorize message by wrapping it with ansi escape codes :type msg: str or unicode :param msg: the message string to colorize :type color: str or None :param color: the color identifier (see `ANSI_COLORS` for available values) :type style...
[ "def", "colorize_ansi", "(", "msg", ",", "color", "=", "None", ",", "style", "=", "None", ")", ":", "# If both color and style are not defined, then leave the text as is", "if", "color", "is", "None", "and", "style", "is", "None", ":", "return", "msg", "escape_cod...
33.892857
0.001025
def xpnsl(h1, h2, use_threads=True): """Cross-population version of the NSL statistic. Parameters ---------- h1 : array_like, int, shape (n_variants, n_haplotypes) Haplotype array for the first population. h2 : array_like, int, shape (n_variants, n_haplotypes) Haplotype array for th...
[ "def", "xpnsl", "(", "h1", ",", "h2", ",", "use_threads", "=", "True", ")", ":", "# check inputs", "h1", "=", "asarray_ndim", "(", "h1", ",", "2", ")", "check_integer_dtype", "(", "h1", ")", "h2", "=", "asarray_ndim", "(", "h2", ",", "2", ")", "check...
25.171053
0.000503
def airwires(board, showgui=0): 'search for airwires in eagle board' board = Path(board).expand().abspath() file_out = tempfile.NamedTemporaryFile(suffix='.txt', delete=0) file_out.close() ulp = ulp_templ.replace('FILE_NAME', file_out.name) file_ulp = tempfile.NamedTemporaryFile(suffix='.ulp'...
[ "def", "airwires", "(", "board", ",", "showgui", "=", "0", ")", ":", "board", "=", "Path", "(", "board", ")", ".", "expand", "(", ")", ".", "abspath", "(", ")", "file_out", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.txt'", ","...
24.92
0.001546
def get_albums(self): """ Retrieves all the albums by the artist :return: List. Albums published by the artist """ return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['album'])[1:]
[ "def", "get_albums", "(", "self", ")", ":", "return", "itunespy", ".", "lookup", "(", "id", "=", "self", ".", "artist_id", ",", "entity", "=", "itunespy", ".", "entities", "[", "'album'", "]", ")", "[", "1", ":", "]" ]
38.333333
0.012766
def getcols(sheetMatch=None,colMatch="Decay"): """find every column in every sheet and put it in a new sheet or book.""" book=BOOK() if sheetMatch is None: matchingSheets=book.sheetNames print('all %d sheets selected '%(len(matchingSheets))) else: matchingSheets=[x for x in book....
[ "def", "getcols", "(", "sheetMatch", "=", "None", ",", "colMatch", "=", "\"Decay\"", ")", ":", "book", "=", "BOOK", "(", ")", "if", "sheetMatch", "is", "None", ":", "matchingSheets", "=", "book", ".", "sheetNames", "print", "(", "'all %d sheets selected '", ...
47.857143
0.020488
def fullvars(obj): ''' like `vars()` but support `__slots__`. ''' try: return vars(obj) except TypeError: pass # __slots__ slotsnames = set() for cls in type(obj).__mro__: __slots__ = getattr(cls, '__slots__', None) if __slots__: if isinstanc...
[ "def", "fullvars", "(", "obj", ")", ":", "try", ":", "return", "vars", "(", "obj", ")", "except", "TypeError", ":", "pass", "# __slots__", "slotsnames", "=", "set", "(", ")", "for", "cls", "in", "type", "(", "obj", ")", ".", "__mro__", ":", "__slots_...
23.2
0.00207
def XYZ_to_lbd(X,Y,Z,degree=False): """ NAME: XYZ_to_lbd PURPOSE: transform from rectangular Galactic coordinates to spherical Galactic coordinates (works with vector inputs) INPUT: X - component towards the Galactic Center (in kpc; though this obviously does not matter)) ...
[ "def", "XYZ_to_lbd", "(", "X", ",", "Y", ",", "Z", ",", "degree", "=", "False", ")", ":", "#Whether to use degrees and scalar input is handled by decorators", "d", "=", "nu", ".", "sqrt", "(", "X", "**", "2.", "+", "Y", "**", "2.", "+", "Z", "**", "2.", ...
23.73913
0.021108
def _has_actions(self, event): """Check if a notification type has any enabled actions.""" event_actions = self._aconfig.get(event) return event_actions is None or bool(event_actions)
[ "def", "_has_actions", "(", "self", ",", "event", ")", ":", "event_actions", "=", "self", ".", "_aconfig", ".", "get", "(", "event", ")", "return", "event_actions", "is", "None", "or", "bool", "(", "event_actions", ")" ]
51
0.009662
def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return # If several signatures present, take the last one while True: summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s...
[ "def", "_parse_summary", "(", "self", ")", ":", "if", "self", ".", "_is_at_section", "(", ")", ":", "return", "# If several signatures present, take the last one", "while", "True", ":", "summary", "=", "self", ".", "_doc", ".", "read_to_next_empty_line", "(", ")",...
36.05
0.010811
def GetInstanceInfo(r, instance, static=None): """ Gets information about an instance. @type instance: string @param instance: Instance name @rtype: string @return: Job ID """ if static is None: return r.request("get", "/2/instances/%s/info" % instance) else: return...
[ "def", "GetInstanceInfo", "(", "r", ",", "instance", ",", "static", "=", "None", ")", ":", "if", "static", "is", "None", ":", "return", "r", ".", "request", "(", "\"get\"", ",", "\"/2/instances/%s/info\"", "%", "instance", ")", "else", ":", "return", "r"...
27.266667
0.002364
def print2elog(author='', title='', text='', link=None, file=None, now=None): """ Prints to the elog. Parameters ---------- author : str, optional Author of the elog. title : str, optional Title of the elog. link : str, optional Path to a thumbnail. file : s...
[ "def", "print2elog", "(", "author", "=", "''", ",", "title", "=", "''", ",", "text", "=", "''", ",", "link", "=", "None", ",", "file", "=", "None", ",", "now", "=", "None", ")", ":", "# ============================", "# Get current time", "# ==============...
31.482143
0.0022
def toDict(self): """To Dictionary Returns the Array as a dictionary in the same format as is used in constructing it Returns: dict """ # Init the dictionary we will return dRet = {} # If either a min or a max is set if self._minimum or self._maximum: # Set the array element as it's own dic...
[ "def", "toDict", "(", "self", ")", ":", "# Init the dictionary we will return", "dRet", "=", "{", "}", "# If either a min or a max is set", "if", "self", ".", "_minimum", "or", "self", ".", "_maximum", ":", "# Set the array element as it's own dict", "dRet", "[", "'__...
20.341463
0.036613
def convert_spanstring(span_string): """ converts a span of tokens (str, e.g. 'word_88..word_91') into a list of token IDs (e.g. ['word_88', 'word_89', 'word_90', 'word_91'] Note: Please don't use this function directly, use spanstring2tokens() instead, which checks for non-existing tokens! Ex...
[ "def", "convert_spanstring", "(", "span_string", ")", ":", "prefix_err", "=", "\"All tokens must share the same prefix: {0} vs. {1}\"", "tokens", "=", "[", "]", "if", "not", "span_string", ":", "return", "tokens", "spans", "=", "span_string", ".", "split", "(", "','...
38.207547
0.000481
def weekday_series(self, start, end, weekday, return_date=False): """Generate a datetime series with same weekday number. ISO weekday number: Mon to Sun = 1 to 7 Usage:: >>> start, end = "2014-01-01 06:30:25", "2014-02-01 06:30:25" >>> rolex.weekday_series(start, end, ...
[ "def", "weekday_series", "(", "self", ",", "start", ",", "end", ",", "weekday", ",", "return_date", "=", "False", ")", ":", "start", "=", "self", ".", "parse_datetime", "(", "start", ")", "end", "=", "self", ".", "parse_datetime", "(", "end", ")", "if"...
29.228571
0.001892
def get_node_affiliations(self, jid, node): """ Return the affiliations of other jids at a node. :param jid: Address of the PubSub service. :type jid: :class:`aioxmpp.JID` :param node: Name of the node to query :type node: :class:`str` :raises aioxmpp.errors.XMPP...
[ "def", "get_node_affiliations", "(", "self", ",", "jid", ",", "node", ")", ":", "iq", "=", "aioxmpp", ".", "stanza", ".", "IQ", "(", "type_", "=", "aioxmpp", ".", "structs", ".", "IQType", ".", "GET", ",", "to", "=", "jid", ",", "payload", "=", "pu...
35.32
0.002205
def _extern_decl(return_type, arg_types): """A decorator for methods corresponding to extern functions. All types should be strings. The _FFISpecification class is able to automatically convert these into method declarations for cffi. """ def wrapper(func): signature = _ExternSignature( return_type...
[ "def", "_extern_decl", "(", "return_type", ",", "arg_types", ")", ":", "def", "wrapper", "(", "func", ")", ":", "signature", "=", "_ExternSignature", "(", "return_type", "=", "str", "(", "return_type", ")", ",", "method_name", "=", "str", "(", "func", ".",...
33.428571
0.012474
def read_sources_from_numpy_file(npfile): """ Open a numpy pickle file and read all the new sources into a dictionary Parameters ---------- npfile : file name The input numpy pickle file Returns ------- tab : `~astropy.table.Table` """ srcs = np.load(npfile).flat[0]['sources...
[ "def", "read_sources_from_numpy_file", "(", "npfile", ")", ":", "srcs", "=", "np", ".", "load", "(", "npfile", ")", ".", "flat", "[", "0", "]", "[", "'sources'", "]", "roi", "=", "ROIModel", "(", ")", "roi", ".", "load_sources", "(", "srcs", ".", "va...
23.176471
0.002439
def distance(self, x): """Compute the normalized distance to `x` from the center of the ellipsoid.""" d = x - self.ctr return np.sqrt(np.dot(np.dot(d, self.am), d))
[ "def", "distance", "(", "self", ",", "x", ")", ":", "d", "=", "x", "-", "self", ".", "ctr", "return", "np", ".", "sqrt", "(", "np", ".", "dot", "(", "np", ".", "dot", "(", "d", ",", "self", ".", "am", ")", ",", "d", ")", ")" ]
27.428571
0.010101
def base_url(self): """Like :attr:`url` but without the querystring See also: :attr:`trusted_hosts`. """ return get_current_url( self.environ, strip_querystring=True, trusted_hosts=self.trusted_hosts )
[ "def", "base_url", "(", "self", ")", ":", "return", "get_current_url", "(", "self", ".", "environ", ",", "strip_querystring", "=", "True", ",", "trusted_hosts", "=", "self", ".", "trusted_hosts", ")" ]
35.285714
0.011858
def retrieveVals(self): """Retrieve values for graphs.""" name = 'diskspace' if self.hasGraph(name): for fspath in self._fslist: if self._statsSpace.has_key(fspath): self.setGraphVal(name, fspath, self._statsSp...
[ "def", "retrieveVals", "(", "self", ")", ":", "name", "=", "'diskspace'", "if", "self", ".", "hasGraph", "(", "name", ")", ":", "for", "fspath", "in", "self", ".", "_fslist", ":", "if", "self", ".", "_statsSpace", ".", "has_key", "(", "fspath", ")", ...
44
0.009539
def typeset(self, container, text_align, last_line=False): """Typeset the line in `container` below its current cursor position. Advances the container's cursor to below the descender of this line. `justification` and `line_spacing` are passed on from the paragraph style. `last_descende...
[ "def", "typeset", "(", "self", ",", "container", ",", "text_align", ",", "last_line", "=", "False", ")", ":", "document", "=", "container", ".", "document", "# drop spaces (and empty spans) at the end of the line", "while", "len", "(", "self", ")", ">", "0", ":"...
42.0625
0.001089
def _get_policy_set(self, policy_set_id): """ Get a specific policy set by id. """ uri = self._get_policy_set_uri(guid=policy_set_id) return self.service._get(uri)
[ "def", "_get_policy_set", "(", "self", ",", "policy_set_id", ")", ":", "uri", "=", "self", ".", "_get_policy_set_uri", "(", "guid", "=", "policy_set_id", ")", "return", "self", ".", "service", ".", "_get", "(", "uri", ")" ]
33
0.009852
def setDoc(self, docs): """Sets the documentation to display :param docs: a list of the stimuli doc, which are dicts :type docs: list<dict> """ # sort stim by start time docs = sorted(docs, key=lambda k: k['start_s']) for doc in docs: stim_type = doc...
[ "def", "setDoc", "(", "self", ",", "docs", ")", ":", "# sort stim by start time", "docs", "=", "sorted", "(", "docs", ",", "key", "=", "lambda", "k", ":", "k", "[", "'start_s'", "]", ")", "for", "doc", "in", "docs", ":", "stim_type", "=", "doc", "[",...
36.666667
0.008863
def modulo_kfold_column(self, n_folds=3): """ Build a fold assignments column for cross-validation. Rows are assigned a fold according to the current row number modulo ``n_folds``. :param int n_folds: An integer specifying the number of validation sets to split the training data into. ...
[ "def", "modulo_kfold_column", "(", "self", ",", "n_folds", "=", "3", ")", ":", "return", "H2OFrame", ".", "_expr", "(", "expr", "=", "ExprNode", "(", "\"modulo_kfold_column\"", ",", "self", ",", "n_folds", ")", ")", ".", "_frame", "(", ")" ]
48.4
0.010142
def extract_view(view, decorators=None): """ Extract a view object out of any wrapping decorators. """ # http://stackoverflow.com/questions/9222129/python-inspect-getmembers-does-not-return-the-actual-function-when-used-with-dec if decorators is None: decorators = [] if getattr(view, 'fu...
[ "def", "extract_view", "(", "view", ",", "decorators", "=", "None", ")", ":", "# http://stackoverflow.com/questions/9222129/python-inspect-getmembers-does-not-return-the-actual-function-when-used-with-dec", "if", "decorators", "is", "None", ":", "decorators", "=", "[", "]", "...
37.421053
0.001372
def get_ehlo_lines(self): """Return the capabilities to be advertised after EHLO.""" lines = [] if self._authenticator != None: # TODO: Make the authentication pluggable but separate mechanism # from user look-up. lines.append('AUTH PLAIN') if self._po...
[ "def", "get_ehlo_lines", "(", "self", ")", ":", "lines", "=", "[", "]", "if", "self", ".", "_authenticator", "!=", "None", ":", "# TODO: Make the authentication pluggable but separate mechanism", "# from user look-up.", "lines", ".", "append", "(", "'AUTH PLAIN'", ")"...
40.272727
0.00883
def nysiis(word, max_length=6, modified=False): """Return the NYSIIS code for a word. This is a wrapper for :py:meth:`NYSIIS.encode`. Parameters ---------- word : str The word to transform max_length : int The maximum length (default 6) of the code to return modified : bool...
[ "def", "nysiis", "(", "word", ",", "max_length", "=", "6", ",", "modified", "=", "False", ")", ":", "return", "NYSIIS", "(", ")", ".", "encode", "(", "word", ",", "max_length", ",", "modified", ")" ]
21.795455
0.000998
def get_dimension_by_name(dimension_name,**kwargs): """ Given a dimension name returns all its data. Used in convert functions """ try: if dimension_name is None: dimension_name = '' dimension = db.DBSession.query(Dimension).filter(func.lower(Dimension.name)==func.lower(d...
[ "def", "get_dimension_by_name", "(", "dimension_name", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "dimension_name", "is", "None", ":", "dimension_name", "=", "''", "dimension", "=", "db", ".", "DBSession", ".", "query", "(", "Dimension", ")", "."...
37.5
0.009294
def activate_minion_cachedir(minion_id, base=None): ''' Moves a minion from the requested/ cachedir into the active/ cachedir. This means that Salt Cloud has verified that a requested instance properly exists, and should be expected to exist from here on out. ''' if base is None: base = ...
[ "def", "activate_minion_cachedir", "(", "minion_id", ",", "base", "=", "None", ")", ":", "if", "base", "is", "None", ":", "base", "=", "__opts__", "[", "'cachedir'", "]", "fname", "=", "'{0}.p'", ".", "format", "(", "minion_id", ")", "src", "=", "os", ...
37
0.002028
def send_text(self, text): """Send a plain text message to the room.""" return self.client.api.send_message(self.room_id, text)
[ "def", "send_text", "(", "self", ",", "text", ")", ":", "return", "self", ".", "client", ".", "api", ".", "send_message", "(", "self", ".", "room_id", ",", "text", ")" ]
47
0.013986
def remove_node(self, node): """ Remove node from the model. Removing a node also removes all the associated edges, removes the CPD of the node and marginalizes the CPDs of it's children. Parameters ---------- node : node Node which is to be removed ...
[ "def", "remove_node", "(", "self", ",", "node", ")", ":", "affected_nodes", "=", "[", "v", "for", "u", ",", "v", "in", "self", ".", "edges", "(", ")", "if", "u", "==", "node", "]", "for", "affected_node", "in", "affected_nodes", ":", "node_cpd", "=",...
36.744681
0.001692
def random_state(dim, seed=None): """ Return a random quantum state from the uniform (Haar) measure on state space. Args: dim (int): the dim of the state spaxe seed (int): Optional. To set a random seed. Returns: ndarray: state(2**num) a random quantum state. """ i...
[ "def", "random_state", "(", "dim", ",", "seed", "=", "None", ")", ":", "if", "seed", "is", "None", ":", "seed", "=", "np", ".", "random", ".", "randint", "(", "0", ",", "np", ".", "iinfo", "(", "np", ".", "int32", ")", ".", "max", ")", "rng", ...
27.681818
0.001587
def loads( source ): """Load json structure from meliae from source Supports only the required structures to support loading meliae memory dumps """ source = source.strip() assert source.startswith( '{' ) assert source.endswith( '}' ) source = source[1:-1] result = {} for match ...
[ "def", "loads", "(", "source", ")", ":", "source", "=", "source", ".", "strip", "(", ")", "assert", "source", ".", "startswith", "(", "'{'", ")", "assert", "source", ".", "endswith", "(", "'}'", ")", "source", "=", "source", "[", "1", ":", "-", "1"...
34.514286
0.029791
def dates(self, field_name, kind, order='ASC'): """ Returns a list of datetime objects representing all available dates for the given field_name, scoped to 'kind'. """ assert kind in ("month", "year", "day", "week", "hour", "minute"), \ "'kind' must be one of 'ye...
[ "def", "dates", "(", "self", ",", "field_name", ",", "kind", ",", "order", "=", "'ASC'", ")", ":", "assert", "kind", "in", "(", "\"month\"", ",", "\"year\"", ",", "\"day\"", ",", "\"week\"", ",", "\"hour\"", ",", "\"minute\"", ")", ",", "\"'kind' must be...
42.689655
0.009479
def verify_login(user, password=None, **connection_args): ''' Attempt to login using the provided credentials. If successful, return true. Otherwise, return False. CLI Example: .. code-block:: bash salt '*' mysql.verify_login root password ''' # Override the connection args for u...
[ "def", "verify_login", "(", "user", ",", "password", "=", "None", ",", "*", "*", "connection_args", ")", ":", "# Override the connection args for username and password", "connection_args", "[", "'connection_user'", "]", "=", "user", "connection_args", "[", "'connection_...
30.652174
0.001376
def initialize_from_checkpoint(state): """Initialize the reinforcement learning loop from a checkpoint.""" # The checkpoint's work_dir should contain the most recently trained model. model_paths = glob.glob(os.path.join(FLAGS.checkpoint_dir, 'work_dir/model.ckpt-*.pb')) i...
[ "def", "initialize_from_checkpoint", "(", "state", ")", ":", "# The checkpoint's work_dir should contain the most recently trained model.", "model_paths", "=", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "FLAGS", ".", "checkpoint_dir", ",", "'work_dir...
43.821429
0.013557
def map_udp_port(public_port, private_port, lifetime=3600, gateway_ip=None, retry=9, use_exception=True): """A high-level wrapper to map_port() that requests a mapping for a public UDP port on the NAT to a private UDP port on this host. Returns the complete response on success. ...
[ "def", "map_udp_port", "(", "public_port", ",", "private_port", ",", "lifetime", "=", "3600", ",", "gateway_ip", "=", "None", ",", "retry", "=", "9", ",", "use_exception", "=", "True", ")", ":", "return", "map_port", "(", "NATPMP_PROTOCOL_UDP", ",", "public_...
58.380952
0.001605
def get_new_connection(self, connection_params): """ Receives a dictionary connection_params to setup a connection to the database. Dictionary correct setup is made through the get_connection_params method. TODO: This needs to be made more generic to accept othe...
[ "def", "get_new_connection", "(", "self", ",", "connection_params", ")", ":", "name", "=", "connection_params", ".", "pop", "(", "'name'", ")", "es", "=", "connection_params", ".", "pop", "(", "'enforce_schema'", ")", "connection_params", "[", "'document_class'", ...
36.703704
0.001967
def complex_increases_activity(graph: BELGraph, u: BaseEntity, v: BaseEntity, key: str) -> bool: """Return if the formation of a complex with u increases the activity of v.""" return ( isinstance(u, (ComplexAbundance, NamedComplexAbundance)) and complex_has_member(graph, u, v) and part_h...
[ "def", "complex_increases_activity", "(", "graph", ":", "BELGraph", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "key", ":", "str", ")", "->", "bool", ":", "return", "(", "isinstance", "(", "u", ",", "(", "ComplexAbundance", ",", "Named...
52.428571
0.008043
def user_remove(username, **kwargs): ''' Removes an user. CLI Example: .. code-block:: bash salt minion mssql.user_remove USERNAME database=DBNAME ''' # 'database' argument is mandatory if 'database' not in kwargs: return False try: conn = _get_connection(**kwa...
[ "def", "user_remove", "(", "username", ",", "*", "*", "kwargs", ")", ":", "# 'database' argument is mandatory", "if", "'database'", "not", "in", "kwargs", ":", "return", "False", "try", ":", "conn", "=", "_get_connection", "(", "*", "*", "kwargs", ")", "conn...
24.826087
0.001686
def Page_setDeviceOrientationOverride(self, alpha, beta, gamma): """ Function path: Page.setDeviceOrientationOverride Domain: Page Method name: setDeviceOrientationOverride WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'alpha' (type: number) -> Mock alph...
[ "def", "Page_setDeviceOrientationOverride", "(", "self", ",", "alpha", ",", "beta", ",", "gamma", ")", ":", "assert", "isinstance", "(", "alpha", ",", "(", "float", ",", "int", ")", ")", ",", "\"Argument 'alpha' must be of type '['float', 'int']'. Received type: '%s'\...
35.517241
0.044423
def expand_abbreviations(template, abbreviations): """Expand abbreviations in a template name. :param template: The project template name. :param abbreviations: Abbreviation definitions. """ if template in abbreviations: return abbreviations[template] # Split on colon. If there is no c...
[ "def", "expand_abbreviations", "(", "template", ",", "abbreviations", ")", ":", "if", "template", "in", "abbreviations", ":", "return", "abbreviations", "[", "template", "]", "# Split on colon. If there is no colon, rest will be empty", "# and prefix will be the whole template"...
32.75
0.001855
def batch_predictions( self, images, greedy=False, strict=True, return_details=False): """Interface to model.batch_predictions for attacks. Parameters ---------- images : `numpy.ndarray` Batch of inputs with shape as expected by the model. greedy : bool ...
[ "def", "batch_predictions", "(", "self", ",", "images", ",", "greedy", "=", "False", ",", "strict", "=", "True", ",", "return_details", "=", "False", ")", ":", "if", "strict", ":", "in_bounds", "=", "self", ".", "in_bounds", "(", "images", ")", "assert",...
33.833333
0.001064
def _set_dxproject_id(self,latest_project=False): """ Searches for the project in DNAnexus based on the input arguments when instantiating the class. If multiple projects are found based on the search criteria, an exception will be raised. A few various search strategies are employed, ...
[ "def", "_set_dxproject_id", "(", "self", ",", "latest_project", "=", "False", ")", ":", "dx_project_props", "=", "{", "}", "if", "self", ".", "library_name", ":", "dx_project_props", "[", "\"library_name\"", "]", "=", "self", ".", "library_name", "if", "self",...
58.442857
0.013462
def get_dependencies_from_decl(decl, recursive=True): """ Returns the list of all types and declarations the declaration depends on. """ result = [] if isinstance(decl, typedef.typedef_t) or \ isinstance(decl, variable.variable_t): return [dependency_info_t(decl, decl.decl_type)...
[ "def", "get_dependencies_from_decl", "(", "decl", ",", "recursive", "=", "True", ")", ":", "result", "=", "[", "]", "if", "isinstance", "(", "decl", ",", "typedef", ".", "typedef_t", ")", "or", "isinstance", "(", "decl", ",", "variable", ".", "variable_t",...
38.289474
0.00067
def brent(seqs, f=None, start=None, key=lambda x: x): """Brent's Cycle Detector. See help(cycle_detector) for more context. Args: *args: Two iterators issueing the exact same sequence: -or- f, start: Function and starting state for finite state machine Yields: Values yielde...
[ "def", "brent", "(", "seqs", ",", "f", "=", "None", ",", "start", "=", "None", ",", "key", "=", "lambda", "x", ":", "x", ")", ":", "power", "=", "period", "=", "1", "tortise", ",", "hare", "=", "seqs", "yield", "hare", ".", "next", "(", ")", ...
26.75
0.001288
def _has_ipv6(host): """ Returns True if the system can bind an IPv6 address. """ sock = None has_ipv6 = False # App Engine doesn't support IPV6 sockets and actually has a quota on the # number of sockets that can be used, so just early out here instead of # creating a socket needlessly. # ...
[ "def", "_has_ipv6", "(", "host", ")", ":", "sock", "=", "None", "has_ipv6", "=", "False", "# App Engine doesn't support IPV6 sockets and actually has a quota on the", "# number of sockets that can be used, so just early out here instead of", "# creating a socket needlessly.", "# See ht...
34.5
0.001007
def setup( hosts, default_keyspace, consistency=ConsistencyLevel.ONE, lazy_connect=False, retry_connect=False, **kwargs): """ Records the hosts and connects to one of them :param hosts: list of hosts, see http://datastax.github.io/python-driver/api/cassandra/...
[ "def", "setup", "(", "hosts", ",", "default_keyspace", ",", "consistency", "=", "ConsistencyLevel", ".", "ONE", ",", "lazy_connect", "=", "False", ",", "retry_connect", "=", "False", ",", "*", "*", "kwargs", ")", ":", "global", "cluster", ",", "session", "...
35.188679
0.002087
def _setRTSDTR(port, RTS, DTR): """Set RTS and DTR to the requested state.""" port.setRTS(RTS) port.setDTR(DTR)
[ "def", "_setRTSDTR", "(", "port", ",", "RTS", ",", "DTR", ")", ":", "port", ".", "setRTS", "(", "RTS", ")", "port", ".", "setDTR", "(", "DTR", ")" ]
30
0.00813
def make_plot(self): """Generate the coherence plot from all time series """ args = self.args fftlength = float(args.secpfft) overlap = args.overlap self.log(2, "Calculating spectrum secpfft: %s, overlap: %s" % (fftlength, overlap)) if overlap is...
[ "def", "make_plot", "(", "self", ")", ":", "args", "=", "self", ".", "args", "fftlength", "=", "float", "(", "args", ".", "secpfft", ")", "overlap", "=", "args", ".", "overlap", "self", ".", "log", "(", "2", ",", "\"Calculating spectrum secpfft: %s, overla...
31.019608
0.001225
def re_sub(pattern, repl, string, count=0, flags=0, custom_flags=0): """Replace regular expression. Parameters ---------- pattern : `str` or `_sre.SRE_Pattern` Compiled regular expression. repl : `str` or `function` Replacement. string : `str` Input string. count: `i...
[ "def", "re_sub", "(", "pattern", ",", "repl", ",", "string", ",", "count", "=", "0", ",", "flags", "=", "0", ",", "custom_flags", "=", "0", ")", ":", "if", "custom_flags", "&", "ReFlags", ".", "OVERLAP", ":", "prev_string", "=", "None", "while", "str...
28.48
0.001359
def _connectToAPI(self): """ :return: A tweepy.API object that performs the queries """ #authorize twitter, initialize tweepy auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret) auth.set_access_token(self.access_key, self.access_secret) api = t...
[ "def", "_connectToAPI", "(", "self", ")", ":", "#authorize twitter, initialize tweepy", "auth", "=", "tweepy", ".", "OAuthHandler", "(", "self", ".", "consumer_key", ",", "self", ".", "consumer_secret", ")", "auth", ".", "set_access_token", "(", "self", ".", "ac...
38.444444
0.008475
def update_metadata(self, metadata): """Update cluster state given a MetadataResponse. Arguments: metadata (MetadataResponse): broker response to a metadata request Returns: None """ # In the common case where we ask for a single topic and get back an # erro...
[ "def", "update_metadata", "(", "self", ",", "metadata", ")", ":", "# In the common case where we ask for a single topic and get back an", "# error, we should fail the future", "if", "len", "(", "metadata", ".", "topics", ")", "==", "1", "and", "metadata", ".", "topics", ...
40.68932
0.000699
def get_logger(name=None): """ Get virtualchain's logger """ level = logging.CRITICAL if DEBUG: logging.disable(logging.NOTSET) level = logging.DEBUG if name is None: name = "<unknown>" log = logging.getLogger(name=name) log.setLevel( level ) console = logg...
[ "def", "get_logger", "(", "name", "=", "None", ")", ":", "level", "=", "logging", ".", "CRITICAL", "if", "DEBUG", ":", "logging", ".", "disable", "(", "logging", ".", "NOTSET", ")", "level", "=", "logging", ".", "DEBUG", "if", "name", "is", "None", "...
27.25
0.011392
def get_related_entry_admin_url(entry): """ Returns admin URL for specified entry instance. :param entry: the entry instance. :return: str. """ namespaces = { Document: 'wagtaildocs:edit', Link: 'wagtaillinks:edit', Page: 'wagtailadmin_pages:edit', } ...
[ "def", "get_related_entry_admin_url", "(", "entry", ")", ":", "namespaces", "=", "{", "Document", ":", "'wagtaildocs:edit'", ",", "Link", ":", "'wagtaillinks:edit'", ",", "Page", ":", "'wagtailadmin_pages:edit'", ",", "}", "for", "cls", ",", "url", "in", "namesp...
27.333333
0.001965
def remove_duplicates(self, configs=None): """remove duplicate entries from 4-point configurations. If no configurations are provided, then use self.configs. Unique configurations are only returned if configs is not None. Parameters ---------- configs: Nx4 numpy.ndarray,...
[ "def", "remove_duplicates", "(", "self", ",", "configs", "=", "None", ")", ":", "if", "configs", "is", "None", ":", "c", "=", "self", ".", "configs", "else", ":", "c", "=", "configs", "struct", "=", "c", ".", "view", "(", "c", ".", "dtype", ".", ...
32.814815
0.002193
def list_collections(self, session=None, filter=None, **kwargs): """Get a cursor over the collectons of this database. :Parameters: - `session` (optional): a :class:`~pymongo.client_session.ClientSession`. - `filter` (optional): A query document to filter the list of ...
[ "def", "list_collections", "(", "self", ",", "session", "=", "None", ",", "filter", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "filter", "is", "not", "None", ":", "kwargs", "[", "'filter'", "]", "=", "filter", "read_pref", "=", "(", "(", ...
40.806452
0.001544
def by_image_seq(blocks, image_seq): """Filter blocks to return only those associated with the provided image_seq number. Argument: List:blocks -- List of block objects to sort. Int:image_seq -- image_seq number found in ec_hdr. Returns: List -- List of block indexes matchi...
[ "def", "by_image_seq", "(", "blocks", ",", "image_seq", ")", ":", "return", "list", "(", "filter", "(", "lambda", "block", ":", "blocks", "[", "block", "]", ".", "ec_hdr", ".", "image_seq", "==", "image_seq", ",", "blocks", ")", ")" ]
39
0.009112
def set_site(request): """ Put the selected site ID into the session - posted to from the "Select site" drop-down in the header of the admin. The site ID is then used in favour of the current request's domain in ``yacms.core.managers.CurrentSiteManager``. """ site_id = int(request.GET["site_...
[ "def", "set_site", "(", "request", ")", ":", "site_id", "=", "int", "(", "request", ".", "GET", "[", "\"site_id\"", "]", ")", "if", "not", "request", ".", "user", ".", "is_superuser", ":", "try", ":", "SitePermission", ".", "objects", ".", "get", "(", ...
40.73913
0.001043
def to_csv(self): """ Renders a legend as a CSV string. No arguments. Returns: str: The legend as a CSV. """ # We can't delegate this to Decor because we need to know the superset # of all Decor properties. There may be lots of blanks. header...
[ "def", "to_csv", "(", "self", ")", ":", "# We can't delegate this to Decor because we need to know the superset", "# of all Decor properties. There may be lots of blanks.", "header", "=", "[", "]", "component_header", "=", "[", "]", "for", "row", "in", "self", ":", "for", ...
33.347826
0.001267
def get_keywords(self, pattern="*"): """Returns all keywords that match a glob-style pattern The pattern matching is insensitive to case. The function returns a list of (library_name, keyword_name, keyword_synopsis tuples) sorted by keyword name """ sql = """SELECT col...
[ "def", "get_keywords", "(", "self", ",", "pattern", "=", "\"*\"", ")", ":", "sql", "=", "\"\"\"SELECT collection.collection_id, collection.name,\n keyword.name, keyword.doc, keyword.args\n FROM collection_table as collection\n JOIN keywo...
41.909091
0.002121
def _single_orbit_find_actions(orbit, N_max, toy_potential=None, force_harmonic_oscillator=False): """ Find approximate actions and angles for samples of a phase-space orbit, `w`, at times `t`. Uses toy potentials with known, analytic action-angle transformations to approx...
[ "def", "_single_orbit_find_actions", "(", "orbit", ",", "N_max", ",", "toy_potential", "=", "None", ",", "force_harmonic_oscillator", "=", "False", ")", ":", "if", "orbit", ".", "norbits", ">", "1", ":", "raise", "ValueError", "(", "\"must be a single orbit\"", ...
33.663158
0.000911
def mini(description, applicationName='PythonMini', noteType="Message", title="Mini Message", applicationIcon=None, hostname='localhost', password=None, port=23053, sticky=False, priority=None, callback=None, notificationIcon=None, identifier=None, notifierFactory=GrowlNotifier): """Single notification fun...
[ "def", "mini", "(", "description", ",", "applicationName", "=", "'PythonMini'", ",", "noteType", "=", "\"Message\"", ",", "title", "=", "\"Mini Message\"", ",", "applicationIcon", "=", "None", ",", "hostname", "=", "'localhost'", ",", "password", "=", "None", ...
29.488372
0.033588
def _check_consistent_units_orbitInput(self,orb): """Internal function to check that the set of units for this object is consistent with that for an input orbit""" if self._roSet and orb._roSet: assert m.fabs(self._ro-orb._ro) < 10.**-10., 'Physical conversion for the actionAngle object is n...
[ "def", "_check_consistent_units_orbitInput", "(", "self", ",", "orb", ")", ":", "if", "self", ".", "_roSet", "and", "orb", ".", "_roSet", ":", "assert", "m", ".", "fabs", "(", "self", ".", "_ro", "-", "orb", ".", "_ro", ")", "<", "10.", "**", "-", ...
83
0.010221
def active(self): """ returns a dictionary of connections set as active. """ return {key: value for key, value in self.conns.items() if value.active}
[ "def", "active", "(", "self", ")", ":", "return", "{", "key", ":", "value", "for", "key", ",", "value", "in", "self", ".", "conns", ".", "items", "(", ")", "if", "value", ".", "active", "}" ]
37
0.010582
def walk(self, match=None, errors='strict'): """ D.walk() -> iterator over files and subdirs, recursively. The iterator yields Path objects naming each child item of this directory and its descendants. This requires that ``D.isdir()``. This performs a depth-first traversal of ...
[ "def", "walk", "(", "self", ",", "match", "=", "None", ",", "errors", "=", "'strict'", ")", ":", "class", "Handlers", ":", "def", "strict", "(", "msg", ")", ":", "raise", "def", "warn", "(", "msg", ")", ":", "warnings", ".", "warn", "(", "msg", "...
33.589286
0.001033
def point_lm(self, context): """ Supply point source lm coordinates to montblanc """ # Shape (npsrc, 2) (ls, us), _ = context.array_extents(context.name) return np.asarray(lm_coords[ls:us], dtype=context.dtype)
[ "def", "point_lm", "(", "self", ",", "context", ")", ":", "# Shape (npsrc, 2)", "(", "ls", ",", "us", ")", ",", "_", "=", "context", ".", "array_extents", "(", "context", ".", "name", ")", "return", "np", ".", "asarray", "(", "lm_coords", "[", "ls", ...
39.666667
0.00823
def Decode(self, encoded_data): """Decode the encoded data. Args: encoded_data (byte): encoded data. Returns: tuple(bytes, bytes): decoded data and remaining encoded data. Raises: BackEndError: if the base64 stream cannot be decoded. """ try: # TODO: replace by libuna ...
[ "def", "Decode", "(", "self", ",", "encoded_data", ")", ":", "try", ":", "# TODO: replace by libuna implementation or equivalent. The behavior of", "# base64.b64decode() does not raise TypeError for certain invalid base64", "# data e.g. b'\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08' these are s...
32.291667
0.008772
def parse_date(string, force_datetime=False): """ Takes a Xero formatted date, e.g. /Date(1426849200000+1300)/""" matches = DATE.match(string) if not matches: return None values = dict([ ( k, v if v[0] in '+-' else int(v) ) for k,v in matches.groupdict()....
[ "def", "parse_date", "(", "string", ",", "force_datetime", "=", "False", ")", ":", "matches", "=", "DATE", ".", "match", "(", "string", ")", "if", "not", "matches", ":", "return", "None", "values", "=", "dict", "(", "[", "(", "k", ",", "v", "if", "...
33.705882
0.001696
def p_null_literal(self, p): """null_literal : NULL""" p[0] = self.asttypes.Null(p[1]) p[0].setpos(p)
[ "def", "p_null_literal", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "self", ".", "asttypes", ".", "Null", "(", "p", "[", "1", "]", ")", "p", "[", "0", "]", ".", "setpos", "(", "p", ")" ]
30.5
0.016
def get_crime(self, persistent_id): """ Get a particular crime by persistent ID. Uses the outcomes-for-crime_ API call. .. _outcomes-for-crime: https://data.police.uk/docs/method/outcomes-for-crime/ :rtype: Crime :param str persistent_id: The persistent ID o...
[ "def", "get_crime", "(", "self", ",", "persistent_id", ")", ":", "method", "=", "'outcomes-for-crime/%s'", "%", "persistent_id", "response", "=", "self", ".", "service", ".", "request", "(", "'GET'", ",", "method", ")", "crime", "=", "Crime", "(", "self", ...
34.08
0.002283
def spintaylorf2(**kwds): """ Return a SpinTaylorF2 waveform using CUDA to generate the phase and amplitude """ #####Pull out the input arguments##### f_lower = double(kwds['f_lower']) delta_f = double(kwds['delta_f']) distance = double(kwds['distance']) mass1 = double(kwds['mass1']) mas...
[ "def", "spintaylorf2", "(", "*", "*", "kwds", ")", ":", "#####Pull out the input arguments#####", "f_lower", "=", "double", "(", "kwds", "[", "'f_lower'", "]", ")", "delta_f", "=", "double", "(", "kwds", "[", "'delta_f'", "]", ")", "distance", "=", "double",...
49.941935
0.012413
def persistence2stats(rev_docs, min_persisted=5, min_visible=1209600, include=None, exclude=None, verbose=False): """ Processes a sorted and page-partitioned sequence of revision documents into and adds statistics to the 'persistence' field each token "added" in the revision persis...
[ "def", "persistence2stats", "(", "rev_docs", ",", "min_persisted", "=", "5", ",", "min_visible", "=", "1209600", ",", "include", "=", "None", ",", "exclude", "=", "None", ",", "verbose", "=", "False", ")", ":", "rev_docs", "=", "mwxml", ".", "utilities", ...
39.97
0.000244
def sils(T,f,c,d,h): """sils -- LP lotsizing for the single item lot sizing problem Parameters: - T: number of periods - P: set of products - f[t]: set-up costs (on period t) - c[t]: variable costs - d[t]: demand values - h[t]: holding costs Returns a model, r...
[ "def", "sils", "(", "T", ",", "f", ",", "c", ",", "d", ",", "h", ")", ":", "model", "=", "Model", "(", "\"single item lotsizing\"", ")", "Ts", "=", "range", "(", "1", ",", "T", "+", "1", ")", "M", "=", "sum", "(", "d", "[", "t", "]", "for",...
30.193548
0.020704
def execute(self, message_in, measurement): """Process the message from RabbitMQ. To implement logic for processing a message, extend Consumer._process, not this method. This for internal use and should not be extended or used directly. :param message_in: The message to process ...
[ "def", "execute", "(", "self", ",", "message_in", ",", "measurement", ")", ":", "self", ".", "logger", ".", "debug", "(", "'Received: %r'", ",", "message_in", ")", "try", ":", "self", ".", "_preprocess", "(", "message_in", ",", "measurement", ")", "except"...
35.017241
0.000958
def get_interface(interface): """Support Centos standard physical interface, such as eth0. """ # Supported CentOS Version supported_dists = ['7.0', '6.5'] def format_centos_7_0(inf): pattern = r'<([A-Z]+)' state = re.search(pattern, stdout[0]).groups()[0] state = 'UP'...
[ "def", "get_interface", "(", "interface", ")", ":", "# Supported CentOS Version", "supported_dists", "=", "[", "'7.0'", ",", "'6.5'", "]", "def", "format_centos_7_0", "(", "inf", ")", ":", "pattern", "=", "r'<([A-Z]+)'", "state", "=", "re", ".", "search", "(",...
35.765625
0.000425
def maybe_convert_platform_interval(values): """ Try to do platform conversion, with special casing for IntervalArray. Wrapper around maybe_convert_platform that alters the default return dtype in certain cases to be compatible with IntervalArray. For example, empty lists return with integer dtype ...
[ "def", "maybe_convert_platform_interval", "(", "values", ")", ":", "if", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", "and", "len", "(", "values", ")", "==", "0", ":", "# GH 19016", "# empty lists/tuples get object dtype by default, but t...
33.92
0.001147
def get_models(args): """ Parse a list of ModelName, appname or appname.ModelName list, and return the list of model classes in the IndexRegistry. If the list if falsy, return all the models in the registry. """ if args: models = [] for arg in args: match_found = Fals...
[ "def", "get_models", "(", "args", ")", ":", "if", "args", ":", "models", "=", "[", "]", "for", "arg", "in", "args", ":", "match_found", "=", "False", "for", "model", "in", "registry", ".", "get_models", "(", ")", ":", "if", "model", ".", "_meta", "...
33.958333
0.002387
def get_route(self): """ Creates a session to find the URL for the loci and schemes """ # Create a new session session = OAuth1Session(self.consumer_key, self.consumer_secret, access_token=self.session_token, ...
[ "def", "get_route", "(", "self", ")", ":", "# Create a new session", "session", "=", "OAuth1Session", "(", "self", ".", "consumer_key", ",", "self", ".", "consumer_secret", ",", "access_token", "=", "self", ".", "session_token", ",", "access_token_secret", "=", ...
42.631579
0.002415
def state(self, context): """ Get instance state. :param resort.engine.execution.Context context: Current execution context. :rtype: str :return: Instance state name. """ state = None for line in self.read(context, [ "status", context.resolve(self.__name) ]): if line[2]...
[ "def", "state", "(", "self", ",", "context", ")", ":", "state", "=", "None", "for", "line", "in", "self", ".", "read", "(", "context", ",", "[", "\"status\"", ",", "context", ".", "resolve", "(", "self", ".", "__name", ")", "]", ")", ":", "if", "...
16.904762
0.074667
def _tzinfo_from_match(match_object): """ Create a timezone information object from a regular expression match. The regular expression match is expected to be from _RE_DATE, _RE_DATETIME or _RE_TIME. @param match_object: The regular expression match. @type match_object: B{re}.I{MatchObject} ...
[ "def", "_tzinfo_from_match", "(", "match_object", ")", ":", "tz_utc", "=", "match_object", ".", "group", "(", "\"tz_utc\"", ")", "if", "tz_utc", ":", "return", "UtcTimezone", "(", ")", "tz_sign", "=", "match_object", ".", "group", "(", "\"tz_sign\"", ")", "i...
31.194444
0.000864
def visit_FunctionDef(self, node): """Implement function/method walker.""" # [[[cog # cog.out("print(pcolor('Enter function visitor', 'magenta'))") # ]]] # [[[end]]] in_class = self._in_class(node) decorator_list = [ dobj.id if hasattr(dobj, "id") else...
[ "def", "visit_FunctionDef", "(", "self", ",", "node", ")", ":", "# [[[cog", "# cog.out(\"print(pcolor('Enter function visitor', 'magenta'))\")", "# ]]]", "# [[[end]]]", "in_class", "=", "self", ".", "_in_class", "(", "node", ")", "decorator_list", "=", "[", "dobj", "....
33.777778
0.001598
def replace_custom_resource_definition(self, name, body, **kwargs): # noqa: E501 """replace_custom_resource_definition # noqa: E501 replace the specified CustomResourceDefinition # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP reques...
[ "def", "replace_custom_resource_definition", "(", "self", ",", "name", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "ret...
61.375
0.001337
def ordered_by_replica(self, request_key): """ Should be called by each replica when request is ordered or replica is removed. """ state = self.get(request_key) if not state: return state.unordered_by_replicas_num -= 1
[ "def", "ordered_by_replica", "(", "self", ",", "request_key", ")", ":", "state", "=", "self", ".", "get", "(", "request_key", ")", "if", "not", "state", ":", "return", "state", ".", "unordered_by_replicas_num", "-=", "1" ]
33.875
0.010791
def validate(instance, schema, cls=None, *args, **kwargs): """ Validate an instance under the given schema. >>> validate([2, 3, 4], {"maxItems": 2}) Traceback (most recent call last): ... ValidationError: [2, 3, 4] is too long :func:`validate` will first verify that the...
[ "def", "validate", "(", "instance", ",", "schema", ",", "cls", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "cls", "is", "None", ":", "cls", "=", "validator_for", "(", "schema", ")", "cls", ".", "check_schema", "(", "sche...
31.921875
0.000475
def nilled(self, elt, ps): '''Is the element NIL, and is that okay? Parameters: elt -- the DOM element being parsed ps -- the ParsedSoap object. ''' if _find_nil(elt) not in [ "true", "1"]: return False if self.nillable is False: raise Evaluat...
[ "def", "nilled", "(", "self", ",", "elt", ",", "ps", ")", ":", "if", "_find_nil", "(", "elt", ")", "not", "in", "[", "\"true\"", ",", "\"1\"", "]", ":", "return", "False", "if", "self", ".", "nillable", "is", "False", ":", "raise", "EvaluateException...
37.272727
0.011905
def run_raxml(rax_out, boot, a_id_phylip, threads, aligned, model, cluster, node): """ run raxml """ # set ppn based on threads if threads > 24: ppn = 24 else: ppn = threads if 'raxml' in os.environ: raxml = os.environ['raxml'] threads = '-T %s' % (threads) ...
[ "def", "run_raxml", "(", "rax_out", ",", "boot", ",", "a_id_phylip", ",", "threads", ",", "aligned", ",", "model", ",", "cluster", ",", "node", ")", ":", "# set ppn based on threads", "if", "threads", ">", "24", ":", "ppn", "=", "24", "else", ":", "ppn",...
39.815789
0.009032
def explain(self, index, doc_type, id, body=None, **query_params): """ The explain api computes a score explanation for a query and a specific document. This can give useful feedback whether a document matches or didn't match a specific query. `<http://www.elastic.co/guide/en/ela...
[ "def", "explain", "(", "self", ",", "index", ",", "doc_type", ",", "id", ",", "body", "=", "None", ",", "*", "*", "query_params", ")", ":", "self", ".", "_es_parser", ".", "is_not_empty_params", "(", "index", ",", "doc_type", ",", "id", ")", "path", ...
53.333333
0.000818
def create_hparams(hparams_set, hparams_overrides_str="", data_dir=None, problem_name=None, hparams_path=None): """Create HParams with data_dir and problem hparams, if kwargs provided.""" hparams = registry.hparams(hparams_set) if hparams...
[ "def", "create_hparams", "(", "hparams_set", ",", "hparams_overrides_str", "=", "\"\"", ",", "data_dir", "=", "None", ",", "problem_name", "=", "None", ",", "hparams_path", "=", "None", ")", ":", "hparams", "=", "registry", ".", "hparams", "(", "hparams_set", ...
41.055556
0.010582
def arc_argmax(parse_probs, length, tokens_to_keep, ensure_tree=True): """MST Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py Parameters ---------- parse_probs : NDArray seq_len x seq_len, the probability of arcs length : NDArray real sen...
[ "def", "arc_argmax", "(", "parse_probs", ",", "length", ",", "tokens_to_keep", ",", "ensure_tree", "=", "True", ")", ":", "if", "ensure_tree", ":", "I", "=", "np", ".", "eye", "(", "len", "(", "tokens_to_keep", ")", ")", "# block loops and pad heads", "parse...
43.483146
0.001516
def Lookup(self, x): """Looks up x and returns the corresponding value of y.""" return self._Bisect(x, self.xs, self.ys)
[ "def", "Lookup", "(", "self", ",", "x", ")", ":", "return", "self", ".", "_Bisect", "(", "x", ",", "self", ".", "xs", ",", "self", ".", "ys", ")" ]
44.666667
0.014706
def _stop_ecs_services(awsclient, services, template, parameters, wait=True): """Helper to change desiredCount of ECS services to zero. By default it waits for this to complete. Docs here: http://docs.aws.amazon.com/cli/latest/reference/ecs/update-service.html :param awsclient: :param services: ...
[ "def", "_stop_ecs_services", "(", "awsclient", ",", "services", ",", "template", ",", "parameters", ",", "wait", "=", "True", ")", ":", "if", "len", "(", "services", ")", "==", "0", ":", "return", "client_ecs", "=", "awsclient", ".", "get_client", "(", "...
38.740741
0.001866
def import_from_string(value): """Copy of rest_framework.settings.import_from_string""" value = value.replace('-', '_') try: module_path, class_name = value.rsplit('.', 1) module = import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) ...
[ "def", "import_from_string", "(", "value", ")", ":", "value", "=", "value", ".", "replace", "(", "'-'", ",", "'_'", ")", "try", ":", "module_path", ",", "class_name", "=", "value", ".", "rsplit", "(", "'.'", ",", "1", ")", "module", "=", "import_module...
43.1
0.002273
def get_dense_lineups(df): """Returns a new DataFrame based on the one it is passed. Specifically, it adds five columns for each team (ten total), where each column has the ID of a player on the court during the play. This information is figured out sequentially from the game's substitution data in...
[ "def", "get_dense_lineups", "(", "df", ")", ":", "# TODO: add this precondition to documentation", "assert", "df", "[", "'boxscore_id'", "]", ".", "nunique", "(", ")", "==", "1", "def", "lineup_dict", "(", "aw_lineup", ",", "hm_lineup", ")", ":", "\"\"\"Returns a ...
43.438849
0.000162
def fill_clipboard(self, contents): """ Copy text into the clipboard Usage: C{clipboard.fill_clipboard(contents)} @param contents: string to be placed in the selection """ Gdk.threads_enter() if Gtk.get_major_version() >= 3: self.clip...
[ "def", "fill_clipboard", "(", "self", ",", "contents", ")", ":", "Gdk", ".", "threads_enter", "(", ")", "if", "Gtk", ".", "get_major_version", "(", ")", ">=", "3", ":", "self", ".", "clipBoard", ".", "set_text", "(", "contents", ",", "-", "1", ")", "...
30.214286
0.009174
def mask_and_flatten(self): """Return a vector of the masked data. Returns ------- np.ndarray, tuple of indices (np.ndarray), tuple of the mask shape """ self._check_for_mask() return self.get_data(smoothed=True, masked=True, safe_copy=False)[self.get_mask_indic...
[ "def", "mask_and_flatten", "(", "self", ")", ":", "self", ".", "_check_for_mask", "(", ")", "return", "self", ".", "get_data", "(", "smoothed", "=", "True", ",", "masked", "=", "True", ",", "safe_copy", "=", "False", ")", "[", "self", ".", "get_mask_indi...
33.909091
0.010444
def create_seq(character, action_metadata, direction, length=8, start=0): """Creates a sequence. Args: character: A character sprite tensor. action_metadata: An action metadata tuple. direction: An integer representing the direction, i.e., the row offset within each action group corresponding to ...
[ "def", "create_seq", "(", "character", ",", "action_metadata", ",", "direction", ",", "length", "=", "8", ",", "start", "=", "0", ")", ":", "sprite_start", "=", "(", "action_metadata", "[", "0", "]", "+", "direction", ")", "*", "FRAME_SIZE", "sprite_end", ...
40.323529
0.012108
def isentropic_work_compression(T1, k, Z=1, P1=None, P2=None, W=None, eta=None): r'''Calculation function for dealing with compressing or expanding a gas going through an isentropic, adiabatic process assuming constant Cp and Cv. The polytropic model is the same equation; just provide `n` instead of `k` ...
[ "def", "isentropic_work_compression", "(", "T1", ",", "k", ",", "Z", "=", "1", ",", "P1", "=", "None", ",", "P2", "=", "None", ",", "W", "=", "None", ",", "eta", "=", "None", ")", ":", "if", "W", "is", "None", "and", "(", "None", "not", "in", ...
35.609524
0.001821
def resize_move(self, title, xOrigin=-1, yOrigin=-1, width=-1, height=-1, matchClass=False): """ Resize and/or move the specified window Usage: C{window.close(title, xOrigin=-1, yOrigin=-1, width=-1, height=-1, matchClass=False)} Leaving and of the position/dimension values as ...
[ "def", "resize_move", "(", "self", ",", "title", ",", "xOrigin", "=", "-", "1", ",", "yOrigin", "=", "-", "1", ",", "width", "=", "-", "1", ",", "height", "=", "-", "1", ",", "matchClass", "=", "False", ")", ":", "mvArgs", "=", "[", "\"0\"", ",...
46.954545
0.008539