text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def size(self,*args): """ Set the size of the chart, args are width,height and can be tuple APIPARAM: chs """ if len(args) == 2: x,y = map(int,args) else: x,y = map(int,args[0]) self.check_size(x,y) self['chs'] = '%dx%d'%(x,y) ...
[ "def", "size", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "==", "2", ":", "x", ",", "y", "=", "map", "(", "int", ",", "args", ")", "else", ":", "x", ",", "y", "=", "map", "(", "int", ",", "args", "[", "0", "...
26.916667
13.75
def refresh_folder(self, update_parent_if_changed=False): """ Re-download folder data Inbox Folder will be unable to download its own data (no folder_id) :param bool update_parent_if_changed: updates self.parent with new parent Folder if changed :return: Refreshed or Not ...
[ "def", "refresh_folder", "(", "self", ",", "update_parent_if_changed", "=", "False", ")", ":", "folder_id", "=", "getattr", "(", "self", ",", "'folder_id'", ",", "None", ")", "if", "self", ".", "root", "or", "folder_id", "is", "None", ":", "return", "False...
37.896552
17.689655
def hil_state_send(self, time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc, force_mavlink1=False): ''' DEPRECATED PACKET! Suffers from missing airspeed fields and singularities due to Euler angles. Please use ...
[ "def", "hil_state_send", "(", "self", ",", "time_usec", ",", "roll", ",", "pitch", ",", "yaw", ",", "rollspeed", ",", "pitchspeed", ",", "yawspeed", ",", "lat", ",", "lon", ",", "alt", ",", "vx", ",", "vy", ",", "vz", ",", "xacc", ",", "yacc", ",",...
79.62963
48.666667
def setup(self, app): # noqa """Initialize the application.""" super().setup(app) # Setup Database self.database.initialize(connect(self.cfg.connection, **self.cfg.connection_params)) # Fix SQLite in-memory database if self.database.database == ':memory:': ...
[ "def", "setup", "(", "self", ",", "app", ")", ":", "# noqa", "super", "(", ")", ".", "setup", "(", "app", ")", "# Setup Database", "self", ".", "database", ".", "initialize", "(", "connect", "(", "self", ".", "cfg", ".", "connection", ",", "*", "*", ...
32.223881
18.701493
def remove_entry(self, entry = None): """This method can remove entries. The v1Entry-object entry is needed. """ if entry is None or type(entry) is not v1Entry: raise KPError("Need an entry.") elif entry in self.entries: entry.gr...
[ "def", "remove_entry", "(", "self", ",", "entry", "=", "None", ")", ":", "if", "entry", "is", "None", "or", "type", "(", "entry", ")", "is", "not", "v1Entry", ":", "raise", "KPError", "(", "\"Need an entry.\"", ")", "elif", "entry", "in", "self", ".", ...
31.125
12.3125
def alternating_least_squares(Ciu, factors, **kwargs): """ factorizes the matrix Cui using an implicit alternating least squares algorithm. Note: this method is deprecated, consider moving to the AlternatingLeastSquares class instead """ log.warning("This method is deprecated. Please use the Altern...
[ "def", "alternating_least_squares", "(", "Ciu", ",", "factors", ",", "*", "*", "kwargs", ")", ":", "log", ".", "warning", "(", "\"This method is deprecated. Please use the AlternatingLeastSquares\"", "\" class instead\"", ")", "model", "=", "AlternatingLeastSquares", "(",...
41.166667
19
def set_editor_ids_order(self, ordered_editor_ids): """ Order the root file items in the Outline Explorer following the provided list of editor ids. """ if self.ordered_editor_ids != ordered_editor_ids: self.ordered_editor_ids = ordered_editor_ids i...
[ "def", "set_editor_ids_order", "(", "self", ",", "ordered_editor_ids", ")", ":", "if", "self", ".", "ordered_editor_ids", "!=", "ordered_editor_ids", ":", "self", ".", "ordered_editor_ids", "=", "ordered_editor_ids", "if", "self", ".", "sort_files_alphabetically", "is...
44.444444
11.333333
def get_mass(self): '''Returns mass''' mass = parsers.get_mass(self.__chebi_id) if math.isnan(mass): mass = parsers.get_mass(self.get_parent_id()) if math.isnan(mass): for parent_or_child_id in self.__get_all_ids(): mass = parsers.get_mass(parent...
[ "def", "get_mass", "(", "self", ")", ":", "mass", "=", "parsers", ".", "get_mass", "(", "self", ".", "__chebi_id", ")", "if", "math", ".", "isnan", "(", "mass", ")", ":", "mass", "=", "parsers", ".", "get_mass", "(", "self", ".", "get_parent_id", "("...
27.2
21.2
def get_chat_members_count(self, *args, **kwargs): """See :func:`get_chat_members_count`""" return get_chat_members_count(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "get_chat_members_count", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "get_chat_members_count", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(",...
61
18.333333
def _eval(self, teaching): """ Returns the evaluation. """ # transform if someone called _get directly if isinstance(teaching, string_types): teaching = self._validate_teaching(None, teaching, namespaces=self._namespaces) return teaching(self._dataObject)
[ "def", "_eval", "(", "self", ",", "teaching", ")", ":", "# transform if someone called _get directly", "if", "isinstance", "(", "teaching", ",", "string_types", ")", ":", "teaching", "=", "self", ".", "_validate_teaching", "(", "None", ",", "teaching", ",", "nam...
34.222222
14.666667
def async_or_fail(self, **options): """ Attempt to call self.apply_async, but if that fails with an exception, we fake the task completion using the exception as the result. This allows us to seamlessly handle errors on task creation the same way we handle errors when a task runs...
[ "def", "async_or_fail", "(", "self", ",", "*", "*", "options", ")", ":", "args", "=", "options", ".", "pop", "(", "\"args\"", ",", "None", ")", "kwargs", "=", "options", ".", "pop", "(", "\"kwargs\"", ",", "None", ")", "possible_broker_errors", "=", "s...
48.428571
17.285714
def segmentation_image_simple1(): "Perfect" parameters = legion_parameters(); parameters.eps = 0.02; parameters.alpha = 0.005; parameters.betta = 0.1; parameters.gamma = 7.0; parameters.teta = 0.9; parameters.lamda = 0.1; parameters.teta_x = -0.5; parameters.teta_p = 7....
[ "def", "segmentation_image_simple1", "(", ")", ":", "parameters", "=", "legion_parameters", "(", ")", "parameters", ".", "eps", "=", "0.02", "parameters", ".", "alpha", "=", "0.005", "parameters", ".", "betta", "=", "0.1", "parameters", ".", "gamma", "=", "7...
30.05
16.15
def write_static_networks(gtfs, output_dir, fmt=None): """ Parameters ---------- gtfs: gtfspy.GTFS output_dir: (str, unicode) a path where to write fmt: None, optional defaulting to "edg" and writing results as ".edg" files If "csv" csv files are produced instead """...
[ "def", "write_static_networks", "(", "gtfs", ",", "output_dir", ",", "fmt", "=", "None", ")", ":", "if", "fmt", "is", "None", ":", "fmt", "=", "\"edg\"", "single_layer_networks", "=", "stop_to_stop_networks_by_type", "(", "gtfs", ")", "util", ".", "makedirs", ...
36.9
17.2
def update_url(self, url=None, regex=None): """ Accepts a fully-qualified url, or regex. Returns True if successful, False if not successful. """ if not url and not regex: raise ValueError("Neither a url or regex was provided to update_url.") headers = { ...
[ "def", "update_url", "(", "self", ",", "url", "=", "None", ",", "regex", "=", "None", ")", ":", "if", "not", "url", "and", "not", "regex", ":", "raise", "ValueError", "(", "\"Neither a url or regex was provided to update_url.\"", ")", "headers", "=", "{", "'...
30
19.130435
def get_version(self, version_id, expand=[]): """ Get a specific version of this layer """ target_url = self._client.get_url('VERSION', 'GET', 'single', {'layer_id': self.id, 'version_id': version_id}) return self._manager._get(target_url, expand=expand)
[ "def", "get_version", "(", "self", ",", "version_id", ",", "expand", "=", "[", "]", ")", ":", "target_url", "=", "self", ".", "_client", ".", "get_url", "(", "'VERSION'", ",", "'GET'", ",", "'single'", ",", "{", "'layer_id'", ":", "self", ".", "id", ...
48.166667
17.833333
def max_temperature(self, unit='kelvin'): """Returns a tuple containing the max value in the temperature series preceeded by its timestamp :param unit: the unit of measure for the temperature values. May be among: '*kelvin*' (default), '*celsius*' or '*fahrenheit*' ...
[ "def", "max_temperature", "(", "self", ",", "unit", "=", "'kelvin'", ")", ":", "if", "unit", "not", "in", "(", "'kelvin'", ",", "'celsius'", ",", "'fahrenheit'", ")", ":", "raise", "ValueError", "(", "\"Invalid value for parameter 'unit'\"", ")", "maximum", "=...
46.363636
18.045455
def check(self, feature): """Check that the feature has a fit/transform/fit_tranform interface""" assert hasattr(feature.transformer, 'fit') assert hasattr(feature.transformer, 'transform') assert hasattr(feature.transformer, 'fit_transform')
[ "def", "check", "(", "self", ",", "feature", ")", ":", "assert", "hasattr", "(", "feature", ".", "transformer", ",", "'fit'", ")", "assert", "hasattr", "(", "feature", ".", "transformer", ",", "'transform'", ")", "assert", "hasattr", "(", "feature", ".", ...
54
12.2
def GET_AUTH(self): """ GET request """ return self.template_helper.get_renderer().queue(*self.submission_manager.get_job_queue_snapshot(), datetime.fromtimestamp)
[ "def", "GET_AUTH", "(", "self", ")", ":", "return", "self", ".", "template_helper", ".", "get_renderer", "(", ")", ".", "queue", "(", "*", "self", ".", "submission_manager", ".", "get_job_queue_snapshot", "(", ")", ",", "datetime", ".", "fromtimestamp", ")" ...
59
37.333333
def remove_repo(self, repo, team): """Remove ``repo`` from ``team``. :param str repo: (required), form: 'user/repo' :param str team: (required) :returns: bool """ for t in self.iter_teams(): if team == t.name: return t.remove_repo(repo) ...
[ "def", "remove_repo", "(", "self", ",", "repo", ",", "team", ")", ":", "for", "t", "in", "self", ".", "iter_teams", "(", ")", ":", "if", "team", "==", "t", ".", "name", ":", "return", "t", ".", "remove_repo", "(", "repo", ")", "return", "False" ]
29.454545
10.909091
def random_tree(n_leaves): """ Randomly partition the nodes """ def _random_subtree(leaves): if len(leaves) == 1: return leaves[0] elif len(leaves) == 2: return (leaves[0], leaves[1]) else: split = npr.randint(1, len(leaves)-1) retu...
[ "def", "random_tree", "(", "n_leaves", ")", ":", "def", "_random_subtree", "(", "leaves", ")", ":", "if", "len", "(", "leaves", ")", "==", "1", ":", "return", "leaves", "[", "0", "]", "elif", "len", "(", "leaves", ")", "==", "2", ":", "return", "("...
29.6
11.466667
def delete_agile_board(self, board_id): """ Delete agile board by id :param board_id: :return: """ url = 'rest/agile/1.0/board/{}'.format(str(board_id)) return self.delete(url)
[ "def", "delete_agile_board", "(", "self", ",", "board_id", ")", ":", "url", "=", "'rest/agile/1.0/board/{}'", ".", "format", "(", "str", "(", "board_id", ")", ")", "return", "self", ".", "delete", "(", "url", ")" ]
28.125
9.875
def _get_cloud_zones(self, page_token=None): """Load all ManagedZones into the self._gcloud_zones dict which is mapped with the dns_name as key. :return: void """ gcloud_zones = self.gcloud_client.list_zones(page_token=page_token) for gcloud_zone in gcloud_zones: ...
[ "def", "_get_cloud_zones", "(", "self", ",", "page_token", "=", "None", ")", ":", "gcloud_zones", "=", "self", ".", "gcloud_client", ".", "list_zones", "(", "page_token", "=", "page_token", ")", "for", "gcloud_zone", "in", "gcloud_zones", ":", "self", ".", "...
36.461538
17.461538
def inspect(self, w): """ Get the value of a wirevector in the last simulation cycle. :param w: the name of the WireVector to inspect (passing in a WireVector instead of a name is deprecated) :return: value of w in the current step of simulation Will throw KeyError if w doe...
[ "def", "inspect", "(", "self", ",", "w", ")", ":", "wire", "=", "self", ".", "block", ".", "wirevector_by_name", ".", "get", "(", "w", ",", "w", ")", "return", "self", ".", "value", "[", "wire", "]" ]
39.909091
19.363636
def put_events(environment, start_response, headers): """ Store events in backends POST body should contain a JSON encoded version of: { namespace: namespace_name (optional), events: { stream_name1 : [event1, event2, ...], stream_name2 : [event1, event2, ...], ... } }...
[ "def", "put_events", "(", "environment", ",", "start_response", ",", "headers", ")", ":", "errors", "=", "[", "]", "events_to_insert", "=", "defaultdict", "(", "list", ")", "request_json", "=", "environment", "[", "'json'", "]", "namespace", "=", "request_json...
33.016393
20.196721
def plos_doi_to_xmlurl(doi_string): """ Attempts to resolve a PLoS DOI into a URL path to the XML file. """ #Create URL to request DOI resolution from http://dx.doi.org doi_url = 'http://dx.doi.org/{0}'.format(doi_string) log.debug('DOI URL: {0}'.format(doi_url)) #Open the page, follow the r...
[ "def", "plos_doi_to_xmlurl", "(", "doi_string", ")", ":", "#Create URL to request DOI resolution from http://dx.doi.org", "doi_url", "=", "'http://dx.doi.org/{0}'", ".", "format", "(", "doi_string", ")", "log", ".", "debug", "(", "'DOI URL: {0}'", ".", "format", "(", "d...
46.692308
17.692308
def use_gl(target='gl2'): """ Let Vispy use the target OpenGL ES 2.0 implementation Also see ``vispy.use()``. Parameters ---------- target : str The target GL backend to use. Available backends: * gl2 - Use ES 2.0 subset of desktop (i.e. normal) OpenGL * gl+ - Use the ...
[ "def", "use_gl", "(", "target", "=", "'gl2'", ")", ":", "target", "=", "target", "or", "'gl2'", "target", "=", "target", ".", "replace", "(", "'+'", ",", "'plus'", ")", "# Get options", "target", ",", "_", ",", "options", "=", "target", ".", "partition...
34.020408
20.22449
def get_power(self,callb=None): """Convenience method to request the power status from the device This method will check whether the value has already been retrieved from the device, if so, it will simply return it. If no, it will request the information from the device and request that...
[ "def", "get_power", "(", "self", ",", "callb", "=", "None", ")", ":", "if", "self", ".", "power_level", "is", "None", ":", "response", "=", "self", ".", "req_with_resp", "(", "GetPower", ",", "StatePower", ",", "callb", "=", "callb", ")", "return", "se...
46.764706
23.470588
def save(f, arr, vocab): """ Save word embedding file. Check :func:`word_embedding_loader.saver.glove.save` for the API. """ f.write(('%d %d' % (arr.shape[0], arr.shape[1])).encode('utf-8')) for word, idx in vocab: _write_line(f, arr[idx], word)
[ "def", "save", "(", "f", ",", "arr", ",", "vocab", ")", ":", "f", ".", "write", "(", "(", "'%d %d'", "%", "(", "arr", ".", "shape", "[", "0", "]", ",", "arr", ".", "shape", "[", "1", "]", ")", ")", ".", "encode", "(", "'utf-8'", ")", ")", ...
33.75
12.5
def load_data(self): """ Loads data from grib2 file objects or list of grib2 file objects. Handles specific grib2 variable names and grib2 message numbers. Returns: Array of data loaded from files in (time, y, x) dimensions, Units """ file_...
[ "def", "load_data", "(", "self", ")", ":", "file_objects", "=", "self", ".", "file_objects", "var", "=", "self", ".", "variable", "valid_date", "=", "self", ".", "valid_dates", "data", "=", "self", ".", "data", "unknown_names", "=", "self", ".", "unknown_n...
44.752941
22.470588
def get_modes(_id): """ Pull a water heater's modes from the API. """ url = MODES_URL % _id arequest = requests.get(url, headers=HEADERS) status_code = str(arequest.status_code) if status_code == '401': _LOGGER.error("Token expired.") retur...
[ "def", "get_modes", "(", "_id", ")", ":", "url", "=", "MODES_URL", "%", "_id", "arequest", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "HEADERS", ")", "status_code", "=", "str", "(", "arequest", ".", "status_code", ")", "if", "status_...
31.636364
8.909091
def _pick_statement(self, block_address, stmt_idx): """ Include a statement in the final slice. :param int block_address: Address of the basic block. :param int stmt_idx: Statement ID. """ # TODO: Support context-sensitivity # Sanity check if n...
[ "def", "_pick_statement", "(", "self", ",", "block_address", ",", "stmt_idx", ")", ":", "# TODO: Support context-sensitivity", "# Sanity check", "if", "not", "isinstance", "(", "block_address", ",", "int", ")", ":", "raise", "AngrBackwardSlicingError", "(", "\"Invalid...
35.941176
20.294118
def clean_html(data, full=True, parser=DEFAULT_PARSER): """ Cleans HTML from XSS vulnerabilities using html5lib If full is False, only the contents inside <body> will be returned (without the <body> tags). """ if full: dom_tree = parser.parse(data) else: dom_tree = parser.par...
[ "def", "clean_html", "(", "data", ",", "full", "=", "True", ",", "parser", "=", "DEFAULT_PARSER", ")", ":", "if", "full", ":", "dom_tree", "=", "parser", ".", "parse", "(", "data", ")", "else", ":", "dom_tree", "=", "parser", ".", "parseFragment", "(",...
33.444444
13.222222
def expand_uri(self, **kwargs): '''Returns the template uri expanded with the current arguments''' kwargs = dict([(k, v if v != 0 else '0') for k, v in kwargs.items()]) return uritemplate.expand(self.link.uri, kwargs)
[ "def", "expand_uri", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "dict", "(", "[", "(", "k", ",", "v", "if", "v", "!=", "0", "else", "'0'", ")", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "]", ")", "ret...
59.5
24
def parse(self, text, key=None): """ Parses a response. Args: text (str): Text to parse Kwargs: key (str): Key to look for, if any Returns: Parsed value Raises: ValueError """ try: data = json.loads(t...
[ "def", "parse", "(", "self", ",", "text", ",", "key", "=", "None", ")", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "text", ")", "except", "ValueError", "as", "e", ":", "raise", "ValueError", "(", "\"%s: Value: [%s]\"", "%", "(", "e", ...
23.56
20.8
def set_username(self, username = None): """This method is used to set the username. username must be a string. """ if username is None or type(username) is not str: raise KPError("Need a new image number") else: self.username = username ...
[ "def", "set_username", "(", "self", ",", "username", "=", "None", ")", ":", "if", "username", "is", "None", "or", "type", "(", "username", ")", "is", "not", "str", ":", "raise", "KPError", "(", "\"Need a new image number\"", ")", "else", ":", "self", "."...
30
16.923077
def inferObject(exp, objectId, objects, objectName): """ Run inference on the given object. objectName is the name of this object in the experiment. """ # Create sequence of random sensations for this object for one column. The # total number of sensations is equal to the number of points on the object. ...
[ "def", "inferObject", "(", "exp", ",", "objectId", ",", "objects", ",", "objectName", ")", ":", "# Create sequence of random sensations for this object for one column. The", "# total number of sensations is equal to the number of points on the object.", "# No point should be visited more...
30.384615
17.615385
def visit_BinOp(self, node): """ Combine operands ranges for given operator. >>> import gast as ast >>> from pythran import passmanager, backend >>> node = ast.parse(''' ... def foo(): ... a = 2 ... c = 3 ... d = a - c''') >>> pm = pas...
[ "def", "visit_BinOp", "(", "self", ",", "node", ")", ":", "res", "=", "combine", "(", "node", ".", "op", ",", "self", ".", "visit", "(", "node", ".", "left", ")", ",", "self", ".", "visit", "(", "node", ".", "right", ")", ")", "return", "self", ...
32.882353
13.705882
def _first_weekday(weekday, d): """ Given a weekday and a date, will increment the date until it's weekday matches that of the given weekday, then that date is returned. """ while weekday != d.weekday(): d += timedelta(days=1) return d
[ "def", "_first_weekday", "(", "weekday", ",", "d", ")", ":", "while", "weekday", "!=", "d", ".", "weekday", "(", ")", ":", "d", "+=", "timedelta", "(", "days", "=", "1", ")", "return", "d" ]
32.5
14.25
def single_run_arrays(spanning_cluster=True, **kwargs): r''' Generate statistics for a single run This is a stand-alone helper function to evolve a single sample state (realization) and return the cluster statistics. Parameters ---------- spanning_cluster : bool, optional Whether t...
[ "def", "single_run_arrays", "(", "spanning_cluster", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# initial iteration", "# we do not need a copy of the result dictionary since we copy the values", "# anyway", "kwargs", "[", "'copy_result'", "]", "=", "False", "ret", "...
29.685393
23.640449
def _read_geometry(surf_file): """Read a triangular format Freesurfer surface mesh. Parameters ---------- surf_file : str path to surface file Returns ------- coords : numpy.ndarray nvtx x 3 array of vertex (x, y, z) coordinates faces : numpy.ndarray nfaces x 3 ...
[ "def", "_read_geometry", "(", "surf_file", ")", ":", "with", "open", "(", "surf_file", ",", "'rb'", ")", "as", "f", ":", "filebytes", "=", "f", ".", "read", "(", ")", "assert", "filebytes", "[", ":", "3", "]", "==", "b'\\xff\\xff\\xfe'", "i0", "=", "...
26.35
19.475
def from_country(cls, country): """Retrieve the first datacenter id associated to a country.""" result = cls.list({'sort_by': 'id ASC'}) dc_countries = {} for dc in result: if dc['country'] not in dc_countries: dc_countries[dc['country']] = dc['id'] r...
[ "def", "from_country", "(", "cls", ",", "country", ")", ":", "result", "=", "cls", ".", "list", "(", "{", "'sort_by'", ":", "'id ASC'", "}", ")", "dc_countries", "=", "{", "}", "for", "dc", "in", "result", ":", "if", "dc", "[", "'country'", "]", "n...
38.111111
12.222222
def load_csv(path): """Load data from a CSV file. Args: path (str): A path to the CSV format file containing data. dense (boolean): An optional variable indicating if the return matrix should be dense. By default, it is false. Returns: Data matrix X and ta...
[ "def", "load_csv", "(", "path", ")", ":", "with", "open", "(", "path", ")", "as", "f", ":", "line", "=", "f", ".", "readline", "(", ")", ".", "strip", "(", ")", "X", "=", "np", ".", "loadtxt", "(", "path", ",", "delimiter", "=", "','", ",", "...
25.727273
23.454545
def _sampleHiddenStateTrajectory(self, obs, dtype=np.int32): """Sample a hidden state trajectory from the conditional distribution P(s | T, E, o) Parameters ---------- o_t : numpy.array with dimensions (T,) observation[n] is the nth observation dtype : numpy.dtype, o...
[ "def", "_sampleHiddenStateTrajectory", "(", "self", ",", "obs", ",", "dtype", "=", "np", ".", "int32", ")", ":", "# Determine observation trajectory length", "T", "=", "obs", ".", "shape", "[", "0", "]", "# Convenience access.", "A", "=", "self", ".", "model",...
35.512821
23.692308
def extended_kalman_filter(cls,p_state_dim, p_a, p_f_A, p_f_Q, p_h, p_f_H, p_f_R, Y, m_init=None, P_init=None,calc_log_likelihood=False): """ Extended Kalman Filter Input: ----------------- p_state_dim: integer p_a: if None - the function fro...
[ "def", "extended_kalman_filter", "(", "cls", ",", "p_state_dim", ",", "p_a", ",", "p_f_A", ",", "p_f_Q", ",", "p_h", ",", "p_f_H", ",", "p_f_R", ",", "Y", ",", "m_init", "=", "None", ",", "P_init", "=", "None", ",", "calc_log_likelihood", "=", "False", ...
37.042169
25.873494
def _toggle_autoescape(context, escape_on=True): ''' Internal method to toggle autoescaping on or off. This function needs access to the caller, so the calling method must be decorated with @supports_caller. ''' previous = is_autoescape(context) setattr(context.caller_stack, AUTOESCAPE_KEY, ...
[ "def", "_toggle_autoescape", "(", "context", ",", "escape_on", "=", "True", ")", ":", "previous", "=", "is_autoescape", "(", "context", ")", "setattr", "(", "context", ".", "caller_stack", ",", "AUTOESCAPE_KEY", ",", "escape_on", ")", "try", ":", "context", ...
36.5
20
def add_links(converted_text, html): """ Add the links to the bottom of the text """ soup = BeautifulSoup(html, 'html.parser') link_exceptions = [ 'footnote-reference', 'fn-backref', 'citation-reference' ] footnotes = {} citations = {} backrefs = {} lin...
[ "def", "add_links", "(", "converted_text", ",", "html", ")", ":", "soup", "=", "BeautifulSoup", "(", "html", ",", "'html.parser'", ")", "link_exceptions", "=", "[", "'footnote-reference'", ",", "'fn-backref'", ",", "'citation-reference'", "]", "footnotes", "=", ...
26.852459
15.967213
def confusion_matrix(self, data): """ Returns a confusion matrix based of H2O's default prediction threshold for a dataset. :param data: metric for which the confusion matrix will be calculated. """ return {model.model_id: model.confusion_matrix(data) for model in self.models}
[ "def", "confusion_matrix", "(", "self", ",", "data", ")", ":", "return", "{", "model", ".", "model_id", ":", "model", ".", "confusion_matrix", "(", "data", ")", "for", "model", "in", "self", ".", "models", "}" ]
44.571429
26.285714
def set_exception(self, exception): """Sets the result of the future as being the given exception. Only called internally. """ with self.__condition: self.__exception = exception self.__state = FINISHED self.__condition.notify_all() self._invok...
[ "def", "set_exception", "(", "self", ",", "exception", ")", ":", "with", "self", ".", "__condition", ":", "self", ".", "__exception", "=", "exception", "self", ".", "__state", "=", "FINISHED", "self", ".", "__condition", ".", "notify_all", "(", ")", "self"...
36.111111
4.222222
def calculate_size(name, index): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES return data_size
[ "def", "calculate_size", "(", "name", ",", "index", ")", ":", "data_size", "=", "0", "data_size", "+=", "calculate_size_str", "(", "name", ")", "data_size", "+=", "INT_SIZE_IN_BYTES", "return", "data_size" ]
31.666667
9.666667
def migrate_config_file( self, config_file_path, always_update=False, current_file_type=None, output_file_name=None, output_file_type=None, create=True, update_defaults=True, dump_kwargs=None, include_bootstrap=True, ): """Migra...
[ "def", "migrate_config_file", "(", "self", ",", "config_file_path", ",", "always_update", "=", "False", ",", "current_file_type", "=", "None", ",", "output_file_name", "=", "None", ",", "output_file_type", "=", "None", ",", "create", "=", "True", ",", "update_de...
37.295455
22.25
def set(self, key, value, expire=0, noreply=None): """ The memcached "set" command. Args: key: str, see class docs for details. value: str, see class docs for details. expire: optional int, number of seconds until the item is expired from the cach...
[ "def", "set", "(", "self", ",", "key", ",", "value", ",", "expire", "=", "0", ",", "noreply", "=", "None", ")", ":", "if", "noreply", "is", "None", ":", "noreply", "=", "self", ".", "default_noreply", "return", "self", ".", "_store_cmd", "(", "b'set'...
43.05
20.75
def write(self, p_str): """Write to stream. :param str p_str: string to print. """ for segment in RE_SPLIT.split(p_str): if not segment: # Empty string. p_str probably starts with colors so the first item is always ''. continue if ...
[ "def", "write", "(", "self", ",", "p_str", ")", ":", "for", "segment", "in", "RE_SPLIT", ".", "split", "(", "p_str", ")", ":", "if", "not", "segment", ":", "# Empty string. p_str probably starts with colors so the first item is always ''.", "continue", "if", "not", ...
43.588235
18.058824
def logs(self, container=None, pretty=None, previous=False, since_seconds=None, since_time=None, timestamps=False, tail_lines=None, limit_bytes=None): """ Produces the same result as calling kubectl logs pod/<pod-name>. Check parameters meaning at http://kuberne...
[ "def", "logs", "(", "self", ",", "container", "=", "None", ",", "pretty", "=", "None", ",", "previous", "=", "False", ",", "since_seconds", "=", "None", ",", "since_time", "=", "None", ",", "timestamps", "=", "False", ",", "tail_lines", "=", "None", ",...
39.052632
13.526316
def create_key(self, **params): """ Create an API Key for this Device via the `Create Key <https://m2x.att.com/developer/documentation/v2/keys#Create-Key>`_ endpoint. :param params: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. :return: Th...
[ "def", "create_key", "(", "self", ",", "*", "*", "params", ")", ":", "return", "Key", ".", "create", "(", "self", ".", "api", ",", "device", "=", "self", ".", "id", ",", "*", "*", "params", ")" ]
48.181818
29.181818
def save_report(self, file_path): """Write coveralls report to file.""" try: report = self.create_report() except coverage.CoverageException as e: log.error('Failure to gather coverage:', exc_info=e) else: with open(file_path, 'w') as report_file: ...
[ "def", "save_report", "(", "self", ",", "file_path", ")", ":", "try", ":", "report", "=", "self", ".", "create_report", "(", ")", "except", "coverage", ".", "CoverageException", "as", "e", ":", "log", ".", "error", "(", "'Failure to gather coverage:'", ",", ...
38.777778
12
def _get_operations(self, context): """Returns a list of operations that need to be performed to turn the cached source code into the one in the buffer.""" #Most of the time, the real-time update is going to fire with #incomplete statements that don't result in any changes being made ...
[ "def", "_get_operations", "(", "self", ",", "context", ")", ":", "#Most of the time, the real-time update is going to fire with", "#incomplete statements that don't result in any changes being made", "#to the module instances. The SequenceMatches caches hashes for the", "#second argument. Logi...
45.418605
22.674419
def encodePolymorphicNucleotide(polySeq) : """returns a single character encoding all nucletides of polySeq in a single character. PolySeq must have one of the following forms: ['A', 'T', 'G'], 'ATG', 'A/T/G'""" if type(polySeq) is types.StringType : if polySeq.find("/") < 0 : sseq = list(polySeq) else :...
[ "def", "encodePolymorphicNucleotide", "(", "polySeq", ")", ":", "if", "type", "(", "polySeq", ")", "is", "types", ".", "StringType", ":", "if", "polySeq", ".", "find", "(", "\"/\"", ")", "<", "0", ":", "sseq", "=", "list", "(", "polySeq", ")", "else", ...
21.076923
20.557692
def add_dicts(d1, d2): """ Merge two dicts of addable values """ if d1 is None: return d2 if d2 is None: return d1 keys = set(d1) keys.update(set(d2)) ret = {} for key in keys: v1 = d1.get(key) v2 = d2.get(key) if v1 is None: ret[key] = v2 ...
[ "def", "add_dicts", "(", "d1", ",", "d2", ")", ":", "if", "d1", "is", "None", ":", "return", "d2", "if", "d2", "is", "None", ":", "return", "d1", "keys", "=", "set", "(", "d1", ")", "keys", ".", "update", "(", "set", "(", "d2", ")", ")", "ret...
21.684211
18.578947
def _get_gradient_log_pdf(self): """ Method that finds gradient and its log at position """ sub_vec = self.variable_assignments - self.model.mean.flatten() grad = - np.dot(self.model.precision_matrix, sub_vec) log_pdf = 0.5 * np.dot(sub_vec, grad) return grad, lo...
[ "def", "_get_gradient_log_pdf", "(", "self", ")", ":", "sub_vec", "=", "self", ".", "variable_assignments", "-", "self", ".", "model", ".", "mean", ".", "flatten", "(", ")", "grad", "=", "-", "np", ".", "dot", "(", "self", ".", "model", ".", "precision...
35.222222
15
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the mode...
[ "def", "overlay_mask", "(", "self", ",", "image", ",", "predictions", ")", ":", "masks", "=", "predictions", ".", "get_field", "(", "\"mask\"", ")", ".", "numpy", "(", ")", "labels", "=", "predictions", ".", "get_field", "(", "\"labels\"", ")", "colors", ...
35.52
20.24
def parse_blocks(self, text): """Extract the code and non-code blocks from given markdown text. Returns a list of block dictionaries. Each dictionary has at least the keys 'type' and 'content', containing the type of the block ('markdown', 'code') and the contents of the block....
[ "def", "parse_blocks", "(", "self", ",", "text", ")", ":", "code_matches", "=", "[", "m", "for", "m", "in", "self", ".", "code_pattern", ".", "finditer", "(", "text", ")", "]", "# determine where the limits of the non code bits are", "# based on the code block edges...
38.641509
20.679245
def matches_pattern(self, other): """Return if the current message matches a message template. Compare the current message to a template message to test matches to a pattern. """ properties = self._message_properties() ismatch = False if isinstance(other, Message...
[ "def", "matches_pattern", "(", "self", ",", "other", ")", ":", "properties", "=", "self", ".", "_message_properties", "(", ")", "ismatch", "=", "False", "if", "isinstance", "(", "other", ",", "Message", ")", "and", "self", ".", "code", "==", "other", "."...
38
13.47619
def replace_acquaintance_with_swap_network( circuit: circuits.Circuit, qubit_order: Sequence[ops.Qid], acquaintance_size: Optional[int] = 0, swap_gate: ops.Gate = ops.SWAP ) -> bool: """ Replace every moment containing acquaintance gates (after rectification) with a g...
[ "def", "replace_acquaintance_with_swap_network", "(", "circuit", ":", "circuits", ".", "Circuit", ",", "qubit_order", ":", "Sequence", "[", "ops", ".", "Qid", "]", ",", "acquaintance_size", ":", "Optional", "[", "int", "]", "=", "0", ",", "swap_gate", ":", "...
42.021739
19.413043
def is_unitary(matrix: np.ndarray) -> bool: """ A helper function that checks if a matrix is unitary. :param matrix: a matrix to test unitarity of :return: true if and only if matrix is unitary """ rows, cols = matrix.shape if rows != cols: return False return np.allclose(np.eye...
[ "def", "is_unitary", "(", "matrix", ":", "np", ".", "ndarray", ")", "->", "bool", ":", "rows", ",", "cols", "=", "matrix", ".", "shape", "if", "rows", "!=", "cols", ":", "return", "False", "return", "np", ".", "allclose", "(", "np", ".", "eye", "("...
31.454545
14
def create_presenter(self, request, target_route): """ Create presenter from the given requests and target routes :param request: client request :param target_route: route to use :return: WWebPresenter """ presenter_name = target_route.presenter_name() if self.presenter_collection().has(presenter_name) i...
[ "def", "create_presenter", "(", "self", ",", "request", ",", "target_route", ")", ":", "presenter_name", "=", "target_route", ".", "presenter_name", "(", ")", "if", "self", ".", "presenter_collection", "(", ")", ".", "has", "(", "presenter_name", ")", "is", ...
45.583333
18
def mask(self, dims=None, base=None, fill='deeppink', stroke='black', background=None, cmap=None, cmap_stroke=None, value=None): """ Create a mask image with colored regions. Parameters ---------- dims : tuple, optional, default = None Dimensions of emb...
[ "def", "mask", "(", "self", ",", "dims", "=", "None", ",", "base", "=", "None", ",", "fill", "=", "'deeppink'", ",", "stroke", "=", "'black'", ",", "background", "=", "None", ",", "cmap", "=", "None", ",", "cmap_stroke", "=", "None", ",", "value", ...
39.065574
21
def gte(): ''' This function is called externally from the alternative Python interpreter from within _get_tops function. :param extra_mods: :param so_mods: :return: ''' extra = salt.utils.json.loads(sys.argv[1]) tops = get_tops(**extra) return salt.utils.json.dumps(tops, ensur...
[ "def", "gte", "(", ")", ":", "extra", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "sys", ".", "argv", "[", "1", "]", ")", "tops", "=", "get_tops", "(", "*", "*", "extra", ")", "return", "salt", ".", "utils", ".", "json", ".", "...
24.769231
24
def _bse_cli_list_basis_sets(args): '''Handles the list-basis-sets subcommand''' metadata = api.filter_basis_sets(args.substr, args.family, args.role, args.data_dir) if args.no_description: liststr = metadata.keys() else: liststr = format_columns([(k, v['description']) for k, v in metad...
[ "def", "_bse_cli_list_basis_sets", "(", "args", ")", ":", "metadata", "=", "api", ".", "filter_basis_sets", "(", "args", ".", "substr", ",", "args", ".", "family", ",", "args", ".", "role", ",", "args", ".", "data_dir", ")", "if", "args", ".", "no_descri...
35.5
24.9
def execute(self, input_data): ''' Okay this worker is going build graphs from PCAP Bro output logs ''' # Grab the Bro log handles from the input bro_logs = input_data['pcap_bro'] # Weird log if 'weird_log' in bro_logs: stream = self.workbench.stream_sample(bro_logs...
[ "def", "execute", "(", "self", ",", "input_data", ")", ":", "# Grab the Bro log handles from the input", "bro_logs", "=", "input_data", "[", "'pcap_bro'", "]", "# Weird log", "if", "'weird_log'", "in", "bro_logs", ":", "stream", "=", "self", ".", "workbench", ".",...
36.136364
26.681818
def outline(self, value): """ sets the outline """ if isinstance(value, SimpleLineSymbol): self._outline = value.asDictionary
[ "def", "outline", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "SimpleLineSymbol", ")", ":", "self", ".", "_outline", "=", "value", ".", "asDictionary" ]
37.5
7
def vpoint2point(vpoint): """Convert *vpoint* into a point in an N-dimensional Boolean space. The *vpoint* argument is a mapping from multi-dimensional arrays of variables to matching arrays of :math:`{0, 1}`. Elements from the values array will be converted to :math:`{0, 1}` using the `int` builti...
[ "def", "vpoint2point", "(", "vpoint", ")", ":", "point", "=", "dict", "(", ")", "for", "v", ",", "val", "in", "vpoint", ".", "items", "(", ")", ":", "point", ".", "update", "(", "_flatten", "(", "v", ",", "val", ")", ")", "return", "point" ]
35.837209
18.860465
def port_channels(self): """list[dict]: A list of dictionary items of port channels. Examples: >>> import pynos.device >>> switches = ['10.24.39.202'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ...
[ "def", "port_channels", "(", "self", ")", ":", "pc_urn", "=", "\"{urn:brocade.com:mgmt:brocade-lag}\"", "result", "=", "[", "]", "has_more", "=", "''", "last_aggregator_id", "=", "''", "while", "(", "has_more", "==", "''", ")", "or", "(", "has_more", "==", "...
53.944444
18.666667
def _parse_date_default_value(property_name, default_value_string): """Parse and return the default value for a date property.""" # OrientDB doesn't use ISO-8601 datetime format, so we have to parse it manually # and then turn it into a python datetime object. strptime() will raise an exception # if the...
[ "def", "_parse_date_default_value", "(", "property_name", ",", "default_value_string", ")", ":", "# OrientDB doesn't use ISO-8601 datetime format, so we have to parse it manually", "# and then turn it into a python datetime object. strptime() will raise an exception", "# if the provided value ca...
74.857143
31.285714
def numDisparities(self, value): """Set private ``_num_disp`` and reset ``_block_matcher``.""" if value > 0 and value % 16 == 0: self._num_disp = value else: raise InvalidNumDisparitiesError("numDisparities must be a " "positiv...
[ "def", "numDisparities", "(", "self", ",", "value", ")", ":", "if", "value", ">", "0", "and", "value", "%", "16", "==", "0", ":", "self", ".", "_num_disp", "=", "value", "else", ":", "raise", "InvalidNumDisparitiesError", "(", "\"numDisparities must be a \""...
46.888889
15.888889
def visit_Assign(self, node, **kwargs): """ Handles assignments within code. Variable assignments in Python are used to represent interface attributes in addition to basic variables. If an assignment appears to be an attribute, it gets labeled as such for Doxygen. If a variabl...
[ "def", "visit_Assign", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "lineNum", "=", "node", ".", "lineno", "-", "1", "# Assignments have one Doxygen-significant special case:", "# interface attributes.", "match", "=", "AstWalker", ".", "__attributeRE...
45.780488
16.609756
def _shift(tokens): """pop the next token, then peek the gid of the following""" after = tokens.peek(n=1, skip=_is_comment, drop=True) tok = tokens._buffer.popleft() return tok[0], tok[1], tok[2], after[0]
[ "def", "_shift", "(", "tokens", ")", ":", "after", "=", "tokens", ".", "peek", "(", "n", "=", "1", ",", "skip", "=", "_is_comment", ",", "drop", "=", "True", ")", "tok", "=", "tokens", ".", "_buffer", ".", "popleft", "(", ")", "return", "tok", "[...
43.4
9.4
def validate_bindings(bindings): """ Validate the bindings configuration. Raises: exceptions.ConfigurationException: If the configuration provided is of an invalid format. """ if not isinstance(bindings, (list, tuple)): raise exceptions.ConfigurationException( ...
[ "def", "validate_bindings", "(", "bindings", ")", ":", "if", "not", "isinstance", "(", "bindings", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "exceptions", ".", "ConfigurationException", "(", "\"bindings must be a list or tuple of dictionaries, but was a ...
34.5625
19.375
def markers(self, values): """Set the markers. Args: values (list): list of marker objects. Raises: ValueError: Markers must be a list of objects. """ if not isinstance(values, list): raise TypeError("Markers must be a list of...
[ "def", "markers", "(", "self", ",", "values", ")", ":", "if", "not", "isinstance", "(", "values", ",", "list", ")", ":", "raise", "TypeError", "(", "\"Markers must be a list of objects\"", ")", "self", ".", "options", "[", "\"markers\"", "]", "=", "values" ]
27.692308
18.307692
def _populate_unknown_statuses(set_tasks): """ Add the "upstream_*" and "not_run" statuses my mutating set_tasks. """ visited = set() for task in set_tasks["still_pending_not_ext"]: _depth_first_search(set_tasks, task, visited)
[ "def", "_populate_unknown_statuses", "(", "set_tasks", ")", ":", "visited", "=", "set", "(", ")", "for", "task", "in", "set_tasks", "[", "\"still_pending_not_ext\"", "]", ":", "_depth_first_search", "(", "set_tasks", ",", "task", ",", "visited", ")" ]
35.571429
11
def init_gl(self): """ Perform the magic incantations to create an OpenGL scene using pyglet. """ # default background color is white-ish background = [.99, .99, .99, 1.0] # if user passed a background color use it if 'background' in self.kwargs: ...
[ "def", "init_gl", "(", "self", ")", ":", "# default background color is white-ish", "background", "=", "[", ".99", ",", ".99", ",", ".99", ",", "1.0", "]", "# if user passed a background color use it", "if", "'background'", "in", "self", ".", "kwargs", ":", "try",...
36.32
10.48
def install(self, param, author=None, constraints=None, origin=''): """Install by url or name""" if isinstance(param, SkillEntry): skill = param else: skill = self.find_skill(param, author) entry = build_skill_entry(skill.name, origin, skill.is_beta) try: ...
[ "def", "install", "(", "self", ",", "param", ",", "author", "=", "None", ",", "constraints", "=", "None", ",", "origin", "=", "''", ")", ":", "if", "isinstance", "(", "param", ",", "SkillEntry", ")", ":", "skill", "=", "param", "else", ":", "skill", ...
36.16
12.08
def path_to_url(path): """ Convert a path to a file: URL. The path will be made absolute. """ path = os.path.normcase(os.path.abspath(path)) if _drive_re.match(path): path = path[0] + '|' + path[2:] url = urllib.quote(path) url = url.replace(os.path.sep, '/') url = url.lstrip('/...
[ "def", "path_to_url", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", "if", "_drive_re", ".", "match", "(", "path", ")", ":", "path", "=", "path", "[", "0", ...
30.909091
9.818182
def _process_download_descriptor(self, dd): # type: (Downloader, blobxfer.models.download.Descriptor) -> None """Process download descriptor :param Downloader self: this :param blobxfer.models.download.Descriptor dd: download descriptor """ # update progress bar s...
[ "def", "_process_download_descriptor", "(", "self", ",", "dd", ")", ":", "# type: (Downloader, blobxfer.models.download.Descriptor) -> None", "# update progress bar", "self", ".", "_update_progress_bar", "(", ")", "# get download offsets", "offsets", ",", "resume_bytes", "=", ...
43.644737
12.052632
def _do_main(self, commands): """ :type commands: list of VSCtlCommand """ self._reset() self._init_schema_helper() self._run_prerequisites(commands) idl_ = idl.Idl(self.remote, self.schema_helper) seqno = idl_.change_seqno while True: ...
[ "def", "_do_main", "(", "self", ",", "commands", ")", ":", "self", ".", "_reset", "(", ")", "self", ".", "_init_schema_helper", "(", ")", "self", ".", "_run_prerequisites", "(", "commands", ")", "idl_", "=", "idl", ".", "Idl", "(", "self", ".", "remote...
25.75
14.666667
def import_xml(self, xml_gzipped_file_path, taxids=None, silent=False): """Imports XML :param str xml_gzipped_file_path: path to XML file :param Optional[list[int]] taxids: NCBI taxonomy identifier :param bool silent: no output if True """ version = self.session.query(mo...
[ "def", "import_xml", "(", "self", ",", "xml_gzipped_file_path", ",", "taxids", "=", "None", ",", "silent", "=", "False", ")", ":", "version", "=", "self", ".", "session", ".", "query", "(", "models", ".", "Version", ")", ".", "filter", "(", "models", "...
33.387097
24.435484
def b_fit_score(self, x, y): """ Compute the RECI fit score Args: x (numpy.ndarray): Variable 1 y (numpy.ndarray): Variable 2 Returns: float: RECI fit score """ x = np.reshape(minmax_scale(x), (-1, 1)) y = np.reshape(minmax_scale(y),...
[ "def", "b_fit_score", "(", "self", ",", "x", ",", "y", ")", ":", "x", "=", "np", ".", "reshape", "(", "minmax_scale", "(", "x", ")", ",", "(", "-", "1", ",", "1", ")", ")", "y", "=", "np", ".", "reshape", "(", "minmax_scale", "(", "y", ")", ...
24.5
17.692308
def _build_meta(text: str, title: str) -> DocstringMeta: """Build docstring element. :param text: docstring element text :param title: title of section containing element :return: """ meta = _sections[title] if meta == "returns" and ":" not in text.split()[0]: return DocstringMeta(...
[ "def", "_build_meta", "(", "text", ":", "str", ",", "title", ":", "str", ")", "->", "DocstringMeta", ":", "meta", "=", "_sections", "[", "title", "]", "if", "meta", "==", "\"returns\"", "and", "\":\"", "not", "in", "text", ".", "split", "(", ")", "["...
29.966667
16.566667
def node2geoff(node_name, properties, encoder): """converts a NetworkX node into a Geoff string. Parameters ---------- node_name : str or int the ID of a NetworkX node properties : dict a dictionary of node attributes encoder : json.JSONEncoder an instance of a JSON enco...
[ "def", "node2geoff", "(", "node_name", ",", "properties", ",", "encoder", ")", ":", "if", "properties", ":", "return", "'({0} {1})'", ".", "format", "(", "node_name", ",", "encoder", ".", "encode", "(", "properties", ")", ")", "else", ":", "return", "'({0}...
26.227273
17.818182
def source_csv_to_pandas(path, table, read_csv_args=None): """ Parameters ---------- path: str path to directory or zipfile table: str name of table read_csv_args: string arguments passed to the read_csv function Returns ------- df: pandas:DataFrame """ ...
[ "def", "source_csv_to_pandas", "(", "path", ",", "table", ",", "read_csv_args", "=", "None", ")", ":", "if", "'.txt'", "not", "in", "table", ":", "table", "+=", "'.txt'", "if", "isinstance", "(", "path", ",", "dict", ")", ":", "data_obj", "=", "path", ...
22.5
17.928571
def apply_default_constraints(self): """Applies default secthresh & exclusion radius constraints """ try: self.apply_secthresh(pipeline_weaksec(self.koi)) except NoWeakSecondaryError: logging.warning('No secondary eclipse threshold set for {}'.format(self.koi)) ...
[ "def", "apply_default_constraints", "(", "self", ")", ":", "try", ":", "self", ".", "apply_secthresh", "(", "pipeline_weaksec", "(", "self", ".", "koi", ")", ")", "except", "NoWeakSecondaryError", ":", "logging", ".", "warning", "(", "'No secondary eclipse thresho...
45.625
14.875
def execute_script(self, sql_script=None, commands=None, split_algo='sql_split', prep_statements=False, dump_fails=True, execute_fails=True, ignored_commands=('DROP', 'UNLOCK', 'LOCK')): """Wrapper method for SQLScript class.""" ss = Execute(sql_script, split_algo, prep_statements...
[ "def", "execute_script", "(", "self", ",", "sql_script", "=", "None", ",", "commands", "=", "None", ",", "split_algo", "=", "'sql_split'", ",", "prep_statements", "=", "False", ",", "dump_fails", "=", "True", ",", "execute_fails", "=", "True", ",", "ignored_...
85.6
43.8
def warn(self, msg, *args, **kwargs): """Logs 'msg % args' with severity 'WARN'.""" if six.PY3: warnings.warn("The 'warn' method is deprecated, use 'warning' instead", DeprecationWarning, 2) self.log(logging.WARN, msg, *args, **kwargs)
[ "def", "warn", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "six", ".", "PY3", ":", "warnings", ".", "warn", "(", "\"The 'warn' method is deprecated, use 'warning' instead\"", ",", "DeprecationWarning", ",", "2", ")", ...
44.666667
12.5
def tan_rand(q, seed=9): """Find a random vector in the tangent space of the n sphere This function will find a random orthogonal vector to q. Parameters ---------- q (n+1,) array which is in the n-sphere Returns ------- qd (n+1,) array which is orthogonal to n-sphere ...
[ "def", "tan_rand", "(", "q", ",", "seed", "=", "9", ")", ":", "# probably need a check in case we get a parallel vector", "rs", "=", "np", ".", "random", ".", "RandomState", "(", "seed", ")", "rvec", "=", "rs", ".", "rand", "(", "q", ".", "shape", "[", "...
22.655172
22.068966
def read_xml(self): """ read metadata from xml and set all the found properties. :return: the root element of the xml :rtype: ElementTree.Element """ if self.xml_uri is None: root = self._read_xml_db() else: root = self._read_xml_file() ...
[ "def", "read_xml", "(", "self", ")", ":", "if", "self", ".", "xml_uri", "is", "None", ":", "root", "=", "self", ".", "_read_xml_db", "(", ")", "else", ":", "root", "=", "self", ".", "_read_xml_file", "(", ")", "if", "root", "is", "not", "None", ":"...
32.473684
14.368421
def do_upgrade(self): """Implement your upgrades here.""" sql = text('delete from upgrade where upgrade = :upgrade') for upgrade in self.legacy_upgrades: db.engine.execute(sql, upgrade=upgrade)
[ "def", "do_upgrade", "(", "self", ")", ":", "sql", "=", "text", "(", "'delete from upgrade where upgrade = :upgrade'", ")", "for", "upgrade", "in", "self", ".", "legacy_upgrades", ":", "db", ".", "engine", ".", "execute", "(", "sql", ",", "upgrade", "=", "up...
45
12
def make_downloader(url: str, path: str) -> Callable[[bool], str]: # noqa: D202 """Make a function that downloads the data for you, or uses a cached version at the given path. :param url: The URL of some data :param path: The path of the cached data, or where data is cached if it does not already exist ...
[ "def", "make_downloader", "(", "url", ":", "str", ",", "path", ":", "str", ")", "->", "Callable", "[", "[", "bool", "]", ",", "str", "]", ":", "# noqa: D202", "def", "download_data", "(", "force_download", ":", "bool", "=", "False", ")", "->", "str", ...
37.590909
23.136364
def isEmpty(cls, datatype=None): """Method to test if the general pasteboard is empty or not with respect to the type of object you want. Parameters: datatype (defaults to strings) Returns: Boolean True (empty) / False (has contents); Raises exception (passes any raised...
[ "def", "isEmpty", "(", "cls", ",", "datatype", "=", "None", ")", ":", "if", "not", "datatype", ":", "datatype", "=", "AppKit", ".", "NSString", "if", "not", "isinstance", "(", "datatype", ",", "types", ".", "ListType", ")", ":", "datatype", "=", "[", ...
41.40625
18.5
def migrate(name, target=''): ''' Migrate a VM from one host to another. This routine will just start the migration and display information on how to look up the progress. ''' client = salt.client.get_local_client(__opts__['conf_file']) data = query(quiet=True) origin_data = _find_vm(name, d...
[ "def", "migrate", "(", "name", ",", "target", "=", "''", ")", ":", "client", "=", "salt", ".", "client", ".", "get_local_client", "(", "__opts__", "[", "'conf_file'", "]", ")", "data", "=", "query", "(", "quiet", "=", "True", ")", "origin_data", "=", ...
47.485714
26.514286
def _copy_attr(self, module, varname, cls, attrname=None): """ Copies attribute from module object to self. Raises if object not of expected class Args: module: module object varname: variable name cls: expected class of variable attrname: attribu...
[ "def", "_copy_attr", "(", "self", ",", "module", ",", "varname", ",", "cls", ",", "attrname", "=", "None", ")", ":", "if", "not", "hasattr", "(", "module", ",", "varname", ")", ":", "raise", "RuntimeError", "(", "\"Variable '{}' not found\"", ".", "format"...
32.25
21.416667
def ticker_pitch(ax=None): '''Set the y-axis of the given axes to MIDI frequencies Parameters ---------- ax : matplotlib.pyplot.axes The axes handle to apply the ticker. By default, uses the current axes handle. ''' ax, _ = __get_axes(ax=ax) ax.yaxis.set_major_formatter(FMT...
[ "def", "ticker_pitch", "(", "ax", "=", "None", ")", ":", "ax", ",", "_", "=", "__get_axes", "(", "ax", "=", "ax", ")", "ax", ".", "yaxis", ".", "set_major_formatter", "(", "FMT_MIDI_HZ", ")" ]
26.5
19.666667