text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def encode(message, encoding_type='default', letter_sep=' ' * 3, strip=True): """Converts a string of message into morse Two types of marks are there. One is short mark, dot(.) or "dit" and other is long mark, dash(-) or "dah". After every dit or dah, there is a one dot duration or one unit log gap. ...
[ "def", "encode", "(", "message", ",", "encoding_type", "=", "'default'", ",", "letter_sep", "=", "' '", "*", "3", ",", "strip", "=", "True", ")", ":", "if", "strip", ":", "message", "=", "message", ".", "strip", "(", ")", "# No trailing or leading spaces",...
31.914894
0.001294
def format(self): """PixelFormat: The raw format of the texture. The actual format may differ, but pixel transfers will use this format. """ fmt = ffi.new('Uint32 *') check_int_err(lib.SDL_QueryTexture(self._ptr, fmt, ffi.NULL, ffi.NULL, ffi.NULL)) return ...
[ "def", "format", "(", "self", ")", ":", "fmt", "=", "ffi", ".", "new", "(", "'Uint32 *'", ")", "check_int_err", "(", "lib", ".", "SDL_QueryTexture", "(", "self", ".", "_ptr", ",", "fmt", ",", "ffi", ".", "NULL", ",", "ffi", ".", "NULL", ",", "ffi",...
47.571429
0.011799
def name_with_version(self): """ Get user-friendly representation of the route. :return: Route name with version suffix. The version suffix is omitted for version 1. """ if self.version == 1: return self.name else: return '{}:{}'.format(self.name,...
[ "def", "name_with_version", "(", "self", ")", ":", "if", "self", ".", "version", "==", "1", ":", "return", "self", ".", "name", "else", ":", "return", "'{}:{}'", ".", "format", "(", "self", ".", "name", ",", "self", ".", "version", ")" ]
32.5
0.008982
def to_pg_scheme(self, container=None, positions=None): """Convert the configuration to a pygimli measurement scheme Parameters ---------- container: reda.containers.ERT.ERT an ERT data container (we take the electrode positions from here) positions = None R...
[ "def", "to_pg_scheme", "(", "self", ",", "container", "=", "None", ",", "positions", "=", "None", ")", ":", "if", "container", "is", "None", "and", "positions", "is", "None", ":", "raise", "Exception", "(", "'electrode positions are required for BERT export'", "...
31.863636
0.000923
def cli(ctx, board, serial_port, ftdi_id, sram, project_dir, verbose, verbose_yosys, verbose_arachne): """Upload the bitstream to the FPGA.""" drivers = Drivers() drivers.pre_upload() # Run scons exit_code = SCons(project_dir).upload({ 'board': board, 'verbose': { ...
[ "def", "cli", "(", "ctx", ",", "board", ",", "serial_port", ",", "ftdi_id", ",", "sram", ",", "project_dir", ",", "verbose", ",", "verbose_yosys", ",", "verbose_arachne", ")", ":", "drivers", "=", "Drivers", "(", ")", "drivers", ".", "pre_upload", "(", "...
28.882353
0.001972
def get_wind_components(speed, wdir): r"""Calculate the U, V wind vector components from the speed and direction. Parameters ---------- speed : array_like The wind speed (magnitude) wdir : array_like The wind direction, specified as the direction from which the wind is blowi...
[ "def", "get_wind_components", "(", "speed", ",", "wdir", ")", ":", "u", "=", "-", "speed", "*", "np", ".", "sin", "(", "wdir", ")", "v", "=", "-", "speed", "*", "np", ".", "cos", "(", "wdir", ")", "return", "u", ",", "v" ]
27
0.001704
def init_service_processes(self): """ Prepare processes defined in the **settings.SERVICE_PROCESSES**. Return :class:`list` of the :class:`ProcessWrapper` instances. """ processes = [] for process_struct in getattr( self.context.config.settings, 'SERVICE_...
[ "def", "init_service_processes", "(", "self", ")", ":", "processes", "=", "[", "]", "for", "process_struct", "in", "getattr", "(", "self", ".", "context", ".", "config", ".", "settings", ",", "'SERVICE_PROCESSES'", ",", "(", ")", ")", ":", "process_cls", "...
34.608696
0.002445
def get_reduced(self, column_reductions): """This function gets called by ColumnFunction._apply(). After a ColumnFunction has been passed to Aggregator's constructor, the ColumnFunction can use this function to request the populated, aggregated columns that correspond to its ColumnReductions. ...
[ "def", "get_reduced", "(", "self", ",", "column_reductions", ")", ":", "for", "cr", "in", "column_reductions", ":", "if", "cr", "not", "in", "self", ".", "column_reductions", ":", "raise", "ValueError", "(", "\"Column reduction %r is not known to this Aggregator!\"", ...
47.666667
0.009602
def radio(self, radio): ''' Get songs belong to a specific genre. :param radio: genre to listen to :rtype: a :class:`Radio` object Genres: This list is incomplete because there isn't an English translation for some genres. Please look at the sources for...
[ "def", "radio", "(", "self", ",", "radio", ")", ":", "artists", "=", "self", ".", "connection", ".", "request", "(", "'getArtistsForTagRadio'", ",", "{", "'tagID'", ":", "radio", "}", ",", "self", ".", "connection", ".", "header", "(", "'getArtistsForTagRa...
64.032258
0.000496
def _generate(self): """Parses a file or directory of files into a set of ``Document`` objects.""" doc_count = 0 for fp in self.all_files: for doc in self._get_docs_for_path(fp): yield doc doc_count += 1 if doc_count >= self.max_docs: ...
[ "def", "_generate", "(", "self", ")", ":", "doc_count", "=", "0", "for", "fp", "in", "self", ".", "all_files", ":", "for", "doc", "in", "self", ".", "_get_docs_for_path", "(", "fp", ")", ":", "yield", "doc", "doc_count", "+=", "1", "if", "doc_count", ...
37.444444
0.008696
def extract_subsection(im, shape): r""" Extracts the middle section of a image Parameters ---------- im : ND-array Image from which to extract the subsection shape : array_like Can either specify the size of the extracted section or the fractional size of the image to e...
[ "def", "extract_subsection", "(", "im", ",", "shape", ")", ":", "# Check if shape was given as a fraction", "shape", "=", "sp", ".", "array", "(", "shape", ")", "if", "shape", "[", "0", "]", "<", "1", ":", "shape", "=", "sp", ".", "array", "(", "im", "...
26.361702
0.000778
def to_example_dict(encoder, inputs, mask, outputs): """Convert single h5 record to an example dict.""" # Inputs bases = [] input_ids = [] last_idx = -1 for row in np.argwhere(inputs): idx, base_id = row idx, base_id = int(idx), int(base_id) assert idx > last_idx # if not, means 2 True values i...
[ "def", "to_example_dict", "(", "encoder", ",", "inputs", ",", "mask", ",", "outputs", ")", ":", "# Inputs", "bases", "=", "[", "]", "input_ids", "=", "[", "]", "last_idx", "=", "-", "1", "for", "row", "in", "np", ".", "argwhere", "(", "inputs", ")", ...
33.969697
0.019081
def _interpret_as_minutes(sval, mdict): """ Times like "1:22" are ambiguous; do they represent minutes and seconds or hours and minutes? By default, timeparse assumes the latter. Call this function after parsing out a dictionary to change that assumption. >>> import pprint >>> pprint.ppri...
[ "def", "_interpret_as_minutes", "(", "sval", ",", "mdict", ")", ":", "if", "(", "sval", ".", "count", "(", "':'", ")", "==", "1", "and", "'.'", "not", "in", "sval", "and", "(", "(", "'hours'", "not", "in", "mdict", ")", "or", "(", "mdict", "[", "...
40.73913
0.016684
def add_jinja2_ext(pelican): """Add Webassets to Jinja2 extensions in Pelican settings.""" if 'JINJA_ENVIRONMENT' in pelican.settings: # pelican 3.7+ pelican.settings['JINJA_ENVIRONMENT']['extensions'].append(AssetsExtension) else: pelican.settings['JINJA_EXTENSIONS'].append(AssetsExtension...
[ "def", "add_jinja2_ext", "(", "pelican", ")", ":", "if", "'JINJA_ENVIRONMENT'", "in", "pelican", ".", "settings", ":", "# pelican 3.7+", "pelican", ".", "settings", "[", "'JINJA_ENVIRONMENT'", "]", "[", "'extensions'", "]", ".", "append", "(", "AssetsExtension", ...
45
0.009346
def make_hash(keys, **kwargs): """ Creates a perfect hash function from the given keys. For a description of the keyword arguments see :py:func:`hash_parameters`. >>> l = (0, 3, 4, 7 ,10, 13, 15, 18, 19, 21, 22, 24, 26, 29, 30, 34) >>> hf = make_hash(l) >>> hf(19) 1 >>> hash_parameters(...
[ "def", "make_hash", "(", "keys", ",", "*", "*", "kwargs", ")", ":", "params", "=", "hash_parameters", "(", "keys", ",", "*", "*", "kwargs", ")", "t", "=", "params", ".", "t", "r", "=", "params", ".", "r", "offset", "=", "params", ".", "offset", "...
26.689655
0.001247
async def update_price_info(self): """Update price info async.""" query = gql( """ { viewer { home(id: "%s") { currentSubscription { priceInfo { current { energy tax ...
[ "async", "def", "update_price_info", "(", "self", ")", ":", "query", "=", "gql", "(", "\"\"\"\n {\n viewer {\n home(id: \"%s\") {\n currentSubscription {\n priceInfo {\n current {\n energy\n ...
30.907407
0.001161
def CEN_misclassification_calc( table, TOP, P, i, j, subject_class, modified=False): """ Calculate misclassification probability of classifying. :param table: input matrix :type table : dict :param TOP: test outcome positive :type TOP : in...
[ "def", "CEN_misclassification_calc", "(", "table", ",", "TOP", ",", "P", ",", "i", ",", "j", ",", "subject_class", ",", "modified", "=", "False", ")", ":", "try", ":", "result", "=", "TOP", "+", "P", "if", "modified", ":", "result", "-=", "table", "[...
26.771429
0.00103
def SNR(img1, img2=None, bg=None, noise_level_function=None, constant_noise_level=False, imgs_to_be_averaged=False): ''' Returns a signal-to-noise-map uses algorithm as described in BEDRICH 2016 JPV (not jet published) :param constant_noise_level: True, to assume noise t...
[ "def", "SNR", "(", "img1", ",", "img2", "=", "None", ",", "bg", "=", "None", ",", "noise_level_function", "=", "None", ",", "constant_noise_level", "=", "False", ",", "imgs_to_be_averaged", "=", "False", ")", ":", "# dark current subtraction:\r", "img1", "=", ...
32.322034
0.000509
def init_app(self, app, config_group="flask_keystone"): """ Iniitialize the Flask_Keystone module in an application factory. :param app: `flask.Flask` application to which to connect. :type app: `flask.Flask` :param str config_group: :class:`oslo_config.cfg.OptGroup` to which ...
[ "def", "init_app", "(", "self", ",", "app", ",", "config_group", "=", "\"flask_keystone\"", ")", ":", "cfg", ".", "CONF", ".", "register_opts", "(", "RAX_OPTS", ",", "group", "=", "config_group", ")", "self", ".", "logger", "=", "logging", ".", "getLogger"...
43.736842
0.001177
def mr_dim_ind(self): """Get the correct index of the MR dimension in the cube slice.""" mr_dim_ind = self._cube.mr_dim_ind if self._cube.ndim == 3: if isinstance(mr_dim_ind, int): if mr_dim_ind == 0: # If only the 0th dimension of a 3D is an MR, t...
[ "def", "mr_dim_ind", "(", "self", ")", ":", "mr_dim_ind", "=", "self", ".", "_cube", ".", "mr_dim_ind", "if", "self", ".", "_cube", ".", "ndim", "==", "3", ":", "if", "isinstance", "(", "mr_dim_ind", ",", "int", ")", ":", "if", "mr_dim_ind", "==", "0...
54.695652
0.001563
def Security_handleCertificateError(self, eventId, action): """ Function path: Security.handleCertificateError Domain: Security Method name: handleCertificateError Parameters: Required arguments: 'eventId' (type: integer) -> The ID of the event. 'action' (type: CertificateErrorAction) -> T...
[ "def", "Security_handleCertificateError", "(", "self", ",", "eventId", ",", "action", ")", ":", "assert", "isinstance", "(", "eventId", ",", "(", "int", ",", ")", ")", ",", "\"Argument 'eventId' must be of type '['int']'. Received type: '%s'\"", "%", "type", "(", "e...
36.35
0.041555
def ensure_data_exists(self, request, data, error_message=None): """ Ensure that the wrapped API client's response brings us valid data. If not, raise an error and log it. """ if not data: error_message = ( error_message or "Unable to fetch API response from e...
[ "def", "ensure_data_exists", "(", "self", ",", "request", ",", "data", ",", "error_message", "=", "None", ")", ":", "if", "not", "data", ":", "error_message", "=", "(", "error_message", "or", "\"Unable to fetch API response from endpoint '{}'.\"", ".", "format", "...
45.3
0.008658
def run_git_log(git_dir=None, git_since=None): '''run_git_log([git_dir]) -> File Run `git log --numstat --pretty=raw` on the specified git repository and return its stdout as a pseudo-File.''' import subprocess if git_dir: command = [ 'git', '--git-dir=' + git_dir, ...
[ "def", "run_git_log", "(", "git_dir", "=", "None", ",", "git_since", "=", "None", ")", ":", "import", "subprocess", "if", "git_dir", ":", "command", "=", "[", "'git'", ",", "'--git-dir='", "+", "git_dir", ",", "'log'", ",", "'--numstat'", ",", "'--pretty=r...
29.153846
0.001277
def _get_installed(self): """Gets a list of the file paths to repo settings files that are being monitored by the CI server. """ from utility import get_json #This is a little tricky because the data file doesn't just have a list #of installed servers. It also manages the...
[ "def", "_get_installed", "(", "self", ")", ":", "from", "utility", "import", "get_json", "#This is a little tricky because the data file doesn't just have a list", "#of installed servers. It also manages the script's database that tracks", "#the user's interactions with it.", "fulldata", ...
41.538462
0.01087
def execute(self, peer_jid, command_name): """ Start execution of a command with a peer. :param peer_jid: JID of the peer to start the command at. :type peer_jid: :class:`~aioxmpp.JID` :param command_name: Node name of the command to execute. :type command_name: :class:`...
[ "def", "execute", "(", "self", ",", "peer_jid", ",", "command_name", ")", ":", "session", "=", "ClientSession", "(", "self", ".", "client", ".", "stream", ",", "peer_jid", ",", "command_name", ",", ")", "yield", "from", "session", ".", "start", "(", ")",...
33
0.002356
def set_version(self, version='0.0.0', save=True): """Set configuration (not application!) version""" self.set(self.DEFAULT_SECTION_NAME, 'version', version, save=save)
[ "def", "set_version", "(", "self", ",", "version", "=", "'0.0.0'", ",", "save", "=", "True", ")", ":", "self", ".", "set", "(", "self", ".", "DEFAULT_SECTION_NAME", ",", "'version'", ",", "version", ",", "save", "=", "save", ")" ]
61.333333
0.010753
def _make_type_comment(args_info, return_type): # type: (ArgTypes, InternalType) -> str """Generate a type comment of form '(arg, ...) -> ret'.""" if not args_info.pos_args: args_string = '' else: args_string = ', '.join([repr(t) for t in args_info.pos_args]) if args_info.varargs: ...
[ "def", "_make_type_comment", "(", "args_info", ",", "return_type", ")", ":", "# type: (ArgTypes, InternalType) -> str", "if", "not", "args_info", ".", "pos_args", ":", "args_string", "=", "''", "else", ":", "args_string", "=", "', '", ".", "join", "(", "[", "rep...
37.866667
0.001718
def mean_rotor_in_chordal_metric(R, t=None): """Return rotor that is closest to all R in the least-squares sense This can be done (quasi-)analytically because of the simplicity of the chordal metric function. The only approximation is the simple 2nd-order discrete formula for the definite integral of ...
[ "def", "mean_rotor_in_chordal_metric", "(", "R", ",", "t", "=", "None", ")", ":", "if", "not", "t", ":", "return", "np", ".", "quaternion", "(", "*", "(", "np", ".", "sum", "(", "as_float_array", "(", "R", ")", ")", ")", ")", ".", "normalized", "("...
40.894737
0.001258
def _getMetrics(self): """ Protected function that can be overridden by subclasses. Its main purpose is to allow the the OPFDummyModelRunner to override this with deterministic values Returns: All the metrics being computed for this model """ metric = None if self.metrics is not None: ...
[ "def", "_getMetrics", "(", "self", ")", ":", "metric", "=", "None", "if", "self", ".", "metrics", "is", "not", "None", ":", "metric", "=", "self", ".", "metrics", "(", "self", ".", "_currentRecordIndex", "+", "1", ")", "elif", "self", ".", "metricValue...
35.1875
0.012111
def shuffled_indices_batch_iterator(self, batch_size, shuffle_rng): """ Create an iterator that generates randomly shuffled mini-batches of sample indices. The batches will have `batch_size` elements. The generated mini-batches indices take the form of 1D NumPy integer arrays. ...
[ "def", "shuffled_indices_batch_iterator", "(", "self", ",", "batch_size", ",", "shuffle_rng", ")", ":", "while", "True", ":", "yield", "shuffle_rng", ".", "choice", "(", "len", "(", "self", ".", "weights", ")", ",", "size", "=", "(", "batch_size", ",", ")"...
33.708333
0.002404
def abs_error(predictions, labels, weights_fn=None): """Computes mean(abs(preds-target)).""" del weights_fn # Unused targets = tf.squeeze(labels, axis=[2, 3]) batch_abs_error = tf.abs(predictions - targets) den = tf.ones(tf.shape(batch_abs_error), dtype=tf.float32) return (batch_abs_error, den)
[ "def", "abs_error", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "del", "weights_fn", "# Unused", "targets", "=", "tf", ".", "squeeze", "(", "labels", ",", "axis", "=", "[", "2", ",", "3", "]", ")", "batch_abs_error", "=...
43.142857
0.022727
def git_str(self): """ If the distribution is not installed via git, return an empty string. If the distribution is installed via git and pip recognizes the git source, return the pip requirement string specifying the git URL and commit, with an '*' appended if :py:attr:`~.git_i...
[ "def", "git_str", "(", "self", ")", ":", "dirty", "=", "'*'", "if", "self", ".", "_git_is_dirty", "else", "''", "if", "'git'", "in", "self", ".", "_pip_requirement", ":", "return", "self", ".", "_pip_requirement", "+", "dirty", "if", "self", ".", "_git_c...
40.961538
0.001835
def mode_run_common_obs(args, extra_args): """Observing mode processing mode of numina.""" # Loading observation result if exists loaded_obs = [] sessions = [] if args.session: for obfile in args.obsresult: _logger.info("session file from %r", obfile) with open(obfi...
[ "def", "mode_run_common_obs", "(", "args", ",", "extra_args", ")", ":", "# Loading observation result if exists", "loaded_obs", "=", "[", "]", "sessions", "=", "[", "]", "if", "args", ".", "session", ":", "for", "obfile", "in", "args", ".", "obsresult", ":", ...
38.192982
0.002089
def _format_batch_statuses(statuses, batch_ids, tracker): """Takes a statuses dict and formats it for transmission with Protobuf and ZMQ. Args: statuses (dict of int): Dict with batch ids as the key, status as value batch_ids (list of str): The batch ids in their original order trac...
[ "def", "_format_batch_statuses", "(", "statuses", ",", "batch_ids", ",", "tracker", ")", ":", "proto_statuses", "=", "[", "]", "for", "batch_id", "in", "batch_ids", ":", "if", "statuses", "[", "batch_id", "]", "==", "client_batch_submit_pb2", ".", "ClientBatchSt...
35.866667
0.000905
def main(): """Function to remove temperature effect from field data """ options = handle_options() # read in observed and synthetic data elecs, d_obs = readin_volt(options.d_obs) elecs, d_est = readin_volt(options.d_est) elecs, d_estTC = readin_volt(options.d_estTC) # calculate correct...
[ "def", "main", "(", ")", ":", "options", "=", "handle_options", "(", ")", "# read in observed and synthetic data", "elecs", ",", "d_obs", "=", "readin_volt", "(", "options", ".", "d_obs", ")", "elecs", ",", "d_est", "=", "readin_volt", "(", "options", ".", "...
30
0.001701
def get_all_events(self, source_identifier=None, source_type=None, start_time=None, end_time=None, max_records=None, marker=None): """ Get information about events related to your DBInstances, DBSecurityGroups and DBParameterGroups. :type so...
[ "def", "get_all_events", "(", "self", ",", "source_identifier", "=", "None", ",", "source_type", "=", "None", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ",", "max_records", "=", "None", ",", "marker", "=", "None", ")", ":", "params", "...
44.517857
0.001962
def set_tracks(self, name, vrid, tracks, run=True): """Configure the track property of the vrrp Notes: set_tracks takes a list of tracked objects which are to be set on the virtual router. An empty list will remove any existing tracked objects from the vrrp. A list c...
[ "def", "set_tracks", "(", "self", ",", "name", ",", "vrid", ",", "tracks", ",", "run", "=", "True", ")", ":", "cmds", "=", "[", "]", "# Get the current set of tracks defined for the vrrp", "curr_tracks", "=", "[", "]", "vrrps", "=", "self", ".", "get", "("...
38.563758
0.000339
def samples_by_indices_nomapping(self, indices): """ Gather a batch of samples by indices *without* applying any index mapping. Parameters ---------- indices: list of either 1D-array of ints or slice A list of index arrays or slices; one for each data source ...
[ "def", "samples_by_indices_nomapping", "(", "self", ",", "indices", ")", ":", "if", "not", "self", ".", "_random_access", ":", "raise", "TypeError", "(", "'samples_by_indices_nomapping method not '", "'supported as one or more of the underlying '", "'data sources does not suppo...
41.214286
0.001693
def default_unit_label(axis, unit): """Set default label for an axis from a `~astropy.units.Unit` If the axis already has a label, this function does nothing. Parameters ---------- axis : `~matplotlib.axis.Axis` the axis to manipulate unit : `~astropy.units.Unit` the unit to u...
[ "def", "default_unit_label", "(", "axis", ",", "unit", ")", ":", "if", "not", "axis", ".", "isDefault_label", ":", "return", "label", "=", "axis", ".", "set_label_text", "(", "unit", ".", "to_string", "(", "'latex_inline_dimensional'", ")", ")", "axis", ".",...
26.826087
0.001565
def sinter(self, *other_sets): """Performs an intersection between Sets. Returns a set of common members. Uses Redis.sinter. """ return self.db.sinter([self.key] + [s.key for s in other_sets])
[ "def", "sinter", "(", "self", ",", "*", "other_sets", ")", ":", "return", "self", ".", "db", ".", "sinter", "(", "[", "self", ".", "key", "]", "+", "[", "s", ".", "key", "for", "s", "in", "other_sets", "]", ")" ]
36.666667
0.008889
def yield_module_imports_nodes(root, checks=import_nodes()): """ Yield all nodes that provide an import """ if not isinstance(root, asttypes.Node): raise TypeError('provided root must be a node') for child in yield_function(root, deep_filter): for f, condition in checks: ...
[ "def", "yield_module_imports_nodes", "(", "root", ",", "checks", "=", "import_nodes", "(", ")", ")", ":", "if", "not", "isinstance", "(", "root", ",", "asttypes", ".", "Node", ")", ":", "raise", "TypeError", "(", "'provided root must be a node'", ")", "for", ...
30.214286
0.002294
def delete_product_set( self, location, product_set_id, project_id=None, retry=None, timeout=None, metadata=None ): """ For the documentation see: :class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductSetDeleteOperator` """ client = self.get_conn() ...
[ "def", "delete_product_set", "(", "self", ",", "location", ",", "product_set_id", ",", "project_id", "=", "None", ",", "retry", "=", "None", ",", "timeout", "=", "None", ",", "metadata", "=", "None", ")", ":", "client", "=", "self", ".", "get_conn", "(",...
51.416667
0.009554
def EventsNotificationsDelete(self, event_notification_id): """ Delete an event-notification from CommonSense. @param event_notification_id (int) - Id of the event-notification to delete. @return (bool) - Boolean indicating whether EventsNotifi...
[ "def", "EventsNotificationsDelete", "(", "self", ",", "event_notification_id", ")", ":", "if", "self", ".", "__SenseApiCall__", "(", "'/events/notifications/{0}.json'", ".", "format", "(", "event_notification_id", ")", ",", "'DELETE'", ")", ":", "return", "True", "e...
44.538462
0.011844
def _merge_a_into_b(self, a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ from easydict import EasyDict as edict if type(a) is not edict: return for k, v in a.items(): ...
[ "def", "_merge_a_into_b", "(", "self", ",", "a", ",", "b", ")", ":", "from", "easydict", "import", "EasyDict", "as", "edict", "if", "type", "(", "a", ")", "is", "not", "edict", ":", "return", "for", "k", ",", "v", "in", "a", ".", "items", "(", ")...
36.878788
0.002402
def find_essential_reactions(model, threshold=None, processes=None): """Return a set of essential reactions. A reaction is considered essential if restricting its flux to zero causes the objective, e.g., the growth rate, to also be zero, below the threshold, or infeasible. Parameters --------...
[ "def", "find_essential_reactions", "(", "model", ",", "threshold", "=", "None", ",", "processes", "=", "None", ")", ":", "if", "threshold", "is", "None", ":", "threshold", "=", "model", ".", "slim_optimize", "(", "error_value", "=", "None", ")", "*", "1E-0...
38.6875
0.000788
def _handle_authn_response(self, context, internal_response, idp): """ See super class satosa.frontends.base.FrontendModule :type context: satosa.context.Context :type internal_response: satosa.internal.InternalData :type idp: saml.server.Server :param context: The curr...
[ "def", "_handle_authn_response", "(", "self", ",", "context", ",", "internal_response", ",", "idp", ")", ":", "request_state", "=", "self", ".", "load_state", "(", "context", ".", "state", ")", "resp_args", "=", "request_state", "[", "\"resp_args\"", "]", "sp_...
40.114035
0.001494
def default(self, obj): """Encode more types.""" if isinstance(obj, UUID): return obj.hex elif isinstance(obj, datetime.datetime): return obj.isoformat() return super().default(obj)
[ "def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "UUID", ")", ":", "return", "obj", ".", "hex", "elif", "isinstance", "(", "obj", ",", "datetime", ".", "datetime", ")", ":", "return", "obj", ".", "isoformat", ...
28.875
0.008403
def pull(self, images, file_name=None, save=True, **kwargs): '''pull an image from a singularity registry Parameters ========== images: refers to the uri given by the user to pull in the format <collection>/<namespace>. You should have an API that is able to retrieve a container based on pars...
[ "def", "pull", "(", "self", ",", "images", ",", "file_name", "=", "None", ",", "save", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# Here we take an entire list or a single image by ensuring we have a list", "# This makes the client flexible to command line or internal...
39.855422
0.00826
def _incoming(self, packet): """ Callback for data received from the copter. """ if len(packet.data) < 1: logger.warning('Localization packet received with incorrect' + 'length (length is {})'.format(len(packet.data))) return pk...
[ "def", "_incoming", "(", "self", ",", "packet", ")", ":", "if", "len", "(", "packet", ".", "data", ")", "<", "1", ":", "logger", ".", "warning", "(", "'Localization packet received with incorrect'", "+", "'length (length is {})'", ".", "format", "(", "len", ...
37.178571
0.001873
def handle_data(self, data): """ Djeffify data between tags """ if data.strip(): data = djeffify_string(data) self.djhtml += data
[ "def", "handle_data", "(", "self", ",", "data", ")", ":", "if", "data", ".", "strip", "(", ")", ":", "data", "=", "djeffify_string", "(", "data", ")", "self", ".", "djhtml", "+=", "data" ]
25
0.01105
def restrict_to_polygon(feed: "Feed", polygon: Polygon) -> "Feed": """ Build a new feed by restricting this one to only the trips that have at least one stop intersecting the given Shapely polygon, then restricting stops, routes, stop times, etc. to those associated with that subset of trips. Re...
[ "def", "restrict_to_polygon", "(", "feed", ":", "\"Feed\"", ",", "polygon", ":", "Polygon", ")", "->", "\"Feed\"", ":", "# Initialize the new feed as the old feed.", "# Restrict its DataFrames below.", "feed", "=", "feed", ".", "copy", "(", ")", "# Get IDs of stops with...
31.309524
0.000369
def getOperation(self, ps, address): '''Returns a method of class. address -- ws-address ''' action = address.getAction() opName = self.getOperationName(ps, action) return getattr(self, opName)
[ "def", "getOperation", "(", "self", ",", "ps", ",", "address", ")", ":", "action", "=", "address", ".", "getAction", "(", ")", "opName", "=", "self", ".", "getOperationName", "(", "ps", ",", "action", ")", "return", "getattr", "(", "self", ",", "opName...
33.714286
0.012397
def prepare_encoder(inputs, hparams, attention_type="local_1d"): """Prepare encoder for images.""" x = prepare_image(inputs, hparams, name="enc_channels") # Add position signals. x = add_pos_signals(x, hparams, "enc_pos") x_shape = common_layers.shape_list(x) if attention_type == "local_1d": x = tf.resh...
[ "def", "prepare_encoder", "(", "inputs", ",", "hparams", ",", "attention_type", "=", "\"local_1d\"", ")", ":", "x", "=", "prepare_image", "(", "inputs", ",", "hparams", ",", "name", "=", "\"enc_channels\"", ")", "# Add position signals.", "x", "=", "add_pos_sign...
44.083333
0.016667
def copy_file(self, path, prefixed_path, source_storage): """ Attempt to copy ``path`` with storage """ # Skip this file if it was already copied earlier if prefixed_path in self.copied_files: return self.log("Skipping '%s' (already copied earlier)" % path) # ...
[ "def", "copy_file", "(", "self", ",", "path", ",", "prefixed_path", ",", "source_storage", ")", ":", "# Skip this file if it was already copied earlier", "if", "prefixed_path", "in", "self", ".", "copied_files", ":", "return", "self", ".", "log", "(", "\"Skipping '%...
44.65
0.002193
def force_orthotropic(self): r"""Force an orthotropic laminate The terms `A_{13}`, `A_{23}`, `A_{31}`, `A_{32}`, `B_{13}`, `B_{23}`, `B_{31}`, `B_{32}`, `D_{13}`, `D_{23}`, `D_{31}`, `D_{32}` are set to zero to force an orthotropic laminate. """ if self....
[ "def", "force_orthotropic", "(", "self", ")", ":", "if", "self", ".", "offset", "!=", "0.", ":", "raise", "RuntimeError", "(", "'Laminates with offset cannot be forced orthotropic!'", ")", "self", ".", "A", "[", "0", ",", "2", "]", "=", "0.", "self", ".", ...
26.776119
0.017742
def update_ticket(self, tid, tickets=None): """If the customer should be granted an electronic ticket as a result of a successful payment, the merchant may (at any time) PUT ticket information to this endpoint. There is an ordered list of tickets; the merchant may PUT several times to up...
[ "def", "update_ticket", "(", "self", ",", "tid", ",", "tickets", "=", "None", ")", ":", "arguments", "=", "{", "'tickets'", ":", "tickets", "}", "return", "self", ".", "do_req", "(", "'PUT'", ",", "self", ".", "merchant_api_base_url", "+", "'/payment_reque...
48.52381
0.001925
def term_count_buckets(self): """ Returns: dict: A dictionary that maps occurrence counts to the terms that appear that many times in the text. """ buckets = {} for term, count in self.term_counts().items(): if count in buckets: buckets[count...
[ "def", "term_count_buckets", "(", "self", ")", ":", "buckets", "=", "{", "}", "for", "term", ",", "count", "in", "self", ".", "term_counts", "(", ")", ".", "items", "(", ")", ":", "if", "count", "in", "buckets", ":", "buckets", "[", "count", "]", "...
27.642857
0.01
def _get_instance(self, klasses): """ internal method that gets every instance of the klasses out of the internal plugin state. """ return [x for x in self.plugins if isinstance(x, klasses)]
[ "def", "_get_instance", "(", "self", ",", "klasses", ")", ":", "return", "[", "x", "for", "x", "in", "self", ".", "plugins", "if", "isinstance", "(", "x", ",", "klasses", ")", "]" ]
37.5
0.008696
def _inject_closure_values_fix_closures(c, injected, **kwargs): """ Recursively fix closures Python bytecode for a closure looks like:: LOAD_CLOSURE var1 BUILD_TUPLE <n_of_vars_closed_over> LOAD_CONST <code_object_containing_closure> MAKE_CLOSURE or this in 3.6...
[ "def", "_inject_closure_values_fix_closures", "(", "c", ",", "injected", ",", "*", "*", "kwargs", ")", ":", "code", "=", "c", ".", "code", "orig_len", "=", "len", "(", "code", ")", "for", "iback", ",", "(", "opcode", ",", "value", ")", "in", "enumerate...
31.695652
0.001331
def get_varied_cfg_lbls(cfg_list, default_cfg=None, mainkey='_cfgname', checkname=False): r""" Args: cfg_list (list): default_cfg (None): (default = None) checkname (bool): if True removes names if they are all the same. Returns: list: cfglbl_list ...
[ "def", "get_varied_cfg_lbls", "(", "cfg_list", ",", "default_cfg", "=", "None", ",", "mainkey", "=", "'_cfgname'", ",", "checkname", "=", "False", ")", ":", "import", "utool", "as", "ut", "try", ":", "cfgname_list", "=", "[", "cfg", "[", "mainkey", "]", ...
37.3
0.000653
def prepare_to_run(self): """ Prepare the model for execution. """ self.clock.reset() for e in self.entities: e.prepare_to_run(self.clock, self.period_count)
[ "def", "prepare_to_run", "(", "self", ")", ":", "self", ".", "clock", ".", "reset", "(", ")", "for", "e", "in", "self", ".", "entities", ":", "e", ".", "prepare_to_run", "(", "self", ".", "clock", ",", "self", ".", "period_count", ")" ]
25.375
0.009524
def model_to_select_list(model_class, filter_dict=None, q_filter=None): """ 只选择 id 和 name,用来做列表选择 :param model_class: :param filter_dict: :param q_filter: :return: """ if filter_dict is None: filter_dict = {} if q_filter is not None: filter_list = [q_filter] else...
[ "def", "model_to_select_list", "(", "model_class", ",", "filter_dict", "=", "None", ",", "q_filter", "=", "None", ")", ":", "if", "filter_dict", "is", "None", ":", "filter_dict", "=", "{", "}", "if", "q_filter", "is", "not", "None", ":", "filter_list", "="...
22.7
0.002114
def create_account_group(self, account_id, body, **kwargs): # noqa: E501 """Create a new group. # noqa: E501 An endpoint for creating a new group. **Example usage:** `curl -X POST https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/policy-groups -d '{\"name\": \"MyGroup1\"}' -H 'content-typ...
[ "def", "create_account_group", "(", "self", ",", "account_id", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return",...
58
0.001542
def line(self, plunge, bearing, *args, **kwargs): """ Plot points representing linear features on the axes. Additional arguments and keyword arguments are passed on to `plot`. Parameters ---------- plunge, bearing : number or sequence of numbers The plunge an...
[ "def", "line", "(", "self", ",", "plunge", ",", "bearing", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lon", ",", "lat", "=", "stereonet_math", ".", "line", "(", "plunge", ",", "bearing", ")", "args", ",", "kwargs", "=", "self", ".", "_...
38.954545
0.002278
def extract(context, data): """Extract a compressed file""" with context.http.rehash(data) as result: file_path = result.file_path content_type = result.content_type extract_dir = random_filename(context.work_path) if content_type in ZIP_MIME_TYPES: extracted_files = ...
[ "def", "extract", "(", "context", ",", "data", ")", ":", "with", "context", ".", "http", ".", "rehash", "(", "data", ")", "as", "result", ":", "file_path", "=", "result", ".", "file_path", "content_type", "=", "result", ".", "content_type", "extract_dir", ...
44.8
0.000874
def AgregarRetencion(self, codigo_concepto, detalle_aclaratorio, base_calculo, alicuota, nro_certificado_retencion=None, fecha_certificado_retencion=None, importe_certificado_retencion=None, ...
[ "def", "AgregarRetencion", "(", "self", ",", "codigo_concepto", ",", "detalle_aclaratorio", ",", "base_calculo", ",", "alicuota", ",", "nro_certificado_retencion", "=", "None", ",", "fecha_certificado_retencion", "=", "None", ",", "importe_certificado_retencion", "=", "...
62.230769
0.010347
def get_model(name, **kwargs): """Returns a pre-defined model by name Parameters ---------- name : str Name of the model. pretrained : bool Whether to load the pretrained weights for model. classes : int Number of classes for the output layer. ctx : Context, default ...
[ "def", "get_model", "(", "name", ",", "*", "*", "kwargs", ")", ":", "models", "=", "{", "'resnet18_v1'", ":", "resnet18_v1", ",", "'resnet34_v1'", ":", "resnet34_v1", ",", "'resnet50_v1'", ":", "resnet50_v1", ",", "'resnet101_v1'", ":", "resnet101_v1", ",", ...
34.854839
0.0009
def start( loop: abstract_loop = None, interval: float = 0.5, hook: hook_type = None) -> asyncio.Task: """ Start the reloader. Create the task which is watching loaded modules and manually added files via ``watch()`` and reloading the process in case of modification. Att...
[ "def", "start", "(", "loop", ":", "abstract_loop", "=", "None", ",", "interval", ":", "float", "=", "0.5", ",", "hook", ":", "hook_type", "=", "None", ")", "->", "asyncio", ".", "Task", ":", "if", "loop", "is", "None", ":", "loop", "=", "asyncio", ...
24.823529
0.00114
def select(self, fcn, *args, **kwds): """ Return arrays from an hdf5 file that satisfy the given function Parameters ---------- fcn : a function A function that accepts the same number of argument as keys given and returns a boolean array of the same length. ...
[ "def", "select", "(", "self", ",", "fcn", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "# get references to each array", "refs", "=", "{", "}", "data", "=", "{", "}", "for", "arg", "in", "args", ":", "refs", "[", "arg", "]", "=", "self", "[...
33.246575
0.002401
def fprocess(infilep,outfilep): """ Scans an input file for LA equations between double square brackets, e.g. [[ M3_mymatrix = M3_anothermatrix^-1 ]], and replaces the expression with a comment containing the equation followed by nested function calls that implement the equation as C code. A trailin...
[ "def", "fprocess", "(", "infilep", ",", "outfilep", ")", ":", "pattern", "=", "r'\\[\\[\\s*(.*?)\\s*\\]\\]'", "eqn", "=", "re", ".", "compile", "(", "pattern", ",", "re", ".", "DOTALL", ")", "s", "=", "infilep", ".", "read", "(", ")", "def", "parser", ...
40.73913
0.017727
def predict(self, inputs: np.ndarray) -> np.ndarray: """Run on multiple inputs""" return self.sess.run(self.out_var, {self.inp_var: inputs})
[ "def", "predict", "(", "self", ",", "inputs", ":", "np", ".", "ndarray", ")", "->", "np", ".", "ndarray", ":", "return", "self", ".", "sess", ".", "run", "(", "self", ".", "out_var", ",", "{", "self", ".", "inp_var", ":", "inputs", "}", ")" ]
51.333333
0.012821
def _calldata_fields(fields, exclude_fields, format_ids): """Utility function to determine which calldata (i.e., FORMAT) fields to extract.""" if fields is None: # no fields specified by user # default to all standard fields plus all FORMAT fields in VCF header fields = config.STANDA...
[ "def", "_calldata_fields", "(", "fields", ",", "exclude_fields", ",", "format_ids", ")", ":", "if", "fields", "is", "None", ":", "# no fields specified by user", "# default to all standard fields plus all FORMAT fields in VCF header", "fields", "=", "config", ".", "STANDARD...
44.52381
0.001047
def find_fxpeaks(sp, times_sigma_threshold, minimum_threshold, nwinwidth_initial, nwinwidth_refined, npix_avoid_border, nbrightlines, sigma_gaussian_filtering, minimum_gaussian_filteri...
[ "def", "find_fxpeaks", "(", "sp", ",", "times_sigma_threshold", ",", "minimum_threshold", ",", "nwinwidth_initial", ",", "nwinwidth_refined", ",", "npix_avoid_border", ",", "nbrightlines", ",", "sigma_gaussian_filtering", ",", "minimum_gaussian_filtering", ",", "plottitle",...
38.540698
0.000147
def delete_external_link(self, id, **kwargs): # noqa: E501 """Delete a specific external link # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_external_...
[ "def", "delete_external_link", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "delete_...
42.095238
0.002212
def get_object_cat1(con, token, cat, kwargs): """ Constructs the "GET" URL. The functions is used by the get_object method First Category of "GET" URL construction. Again calling it first category because more complex functions maybe added later. """ req_str = "/"+kwarg...
[ "def", "get_object_cat1", "(", "con", ",", "token", ",", "cat", ",", "kwargs", ")", ":", "req_str", "=", "\"/\"", "+", "kwargs", "[", "'id'", "]", "+", "\"?\"", "#/id?", "req_str", "+=", "\"access_token=\"", "+", "token", "#/id?@acces_token=......", "del", ...
45.166667
0.020777
def request_check(client, exception, *msg_parms, **kwargs): """Make blocking request to client and raise exception if reply is not ok. Parameters ---------- client : DeviceClient instance exception: Exception class to raise *msg_parms : Message parameters sent to the Message.request() call ...
[ "def", "request_check", "(", "client", ",", "exception", ",", "*", "msg_parms", ",", "*", "*", "kwargs", ")", ":", "timeout", "=", "kwargs", ".", "get", "(", "'timeout'", ",", "None", ")", "req_msg", "=", "Message", ".", "request", "(", "*", "msg_parms...
34.85
0.000698
def merge(mer_inputs=MER_INPUTS, mer_output=MER_OUTPUT): """ merge the phrase files into one file :param mer_inputs: the phrase files :param mer_output: the output file :return: None """ dirname = os.path.dirname(__file__) output_file = os.path.join(dirname, DICT_DIRECTORY, mer_output) ...
[ "def", "merge", "(", "mer_inputs", "=", "MER_INPUTS", ",", "mer_output", "=", "MER_OUTPUT", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "output_file", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "DIC...
33.684211
0.00152
def p_block(self, p): """block : LBRACE source_elements RBRACE""" p[0] = self.asttypes.Block(p[2]) p[0].setpos(p)
[ "def", "p_block", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "self", ".", "asttypes", ".", "Block", "(", "p", "[", "2", "]", ")", "p", "[", "0", "]", ".", "setpos", "(", "p", ")" ]
33.5
0.014599
def read_header(cls, headers_path, block_height, allow_none=False): """ Get a block header at a particular height from disk. Return the header if found Return None if not. """ if os.path.exists(headers_path): header_parser = BlockHeaderSerializer() ...
[ "def", "read_header", "(", "cls", ",", "headers_path", ",", "block_height", ",", "allow_none", "=", "False", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "headers_path", ")", ":", "header_parser", "=", "BlockHeaderSerializer", "(", ")", "sb", "="...
34.740741
0.014523
def perform_smooth(x_values, y_values, span=None, smoother_cls=None): """ Convenience function to run the basic smoother. Parameters ---------- x_values : iterable List of x value observations y_ values : iterable list of y value observations span : float, optional F...
[ "def", "perform_smooth", "(", "x_values", ",", "y_values", ",", "span", "=", "None", ",", "smoother_cls", "=", "None", ")", ":", "if", "smoother_cls", "is", "None", ":", "smoother_cls", "=", "DEFAULT_BASIC_SMOOTHER", "smoother", "=", "smoother_cls", "(", ")", ...
27.666667
0.001294
def get_instance(self, payload): """ Build an instance of LastMonthInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.last_month.LastMonthInstance :rtype: twilio.rest.api.v2010.account.usage.record.last_month.LastMon...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "LastMonthInstance", "(", "self", ".", "_version", ",", "payload", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ")" ]
43.5
0.011261
def time(name=None): """ Creates the grammar for a Time or Duration (T) field, accepting only numbers in a certain pattern. :param name: name for the field :return: grammar for the date field """ if name is None: name = 'Time Field' # Basic field # This regex allows values...
[ "def", "time", "(", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'Time Field'", "# Basic field", "# This regex allows values from 000000 to 235959", "field", "=", "pp", ".", "Regex", "(", "'(0[0-9]|1[0-9]|2[0-3])[0-5][0-9][0-5][0-9]'",...
23.444444
0.001517
def get_plc_datetime(self): """ Get date and time from PLC. :return: date and time as datetime """ type_ = c_int32 buffer = (type_ * 9)() result = self.library.Cli_GetPlcDateTime(self.pointer, byref(buffer)) check_error(result, context="client") ...
[ "def", "get_plc_datetime", "(", "self", ")", ":", "type_", "=", "c_int32", "buffer", "=", "(", "type_", "*", "9", ")", "(", ")", "result", "=", "self", ".", "library", ".", "Cli_GetPlcDateTime", "(", "self", ".", "pointer", ",", "byref", "(", "buffer",...
27.473684
0.025926
def get_outputs (self): """Add the generated config file to the list of outputs.""" outs = super(MyInstallLib, self).get_outputs() conf_output = self.get_conf_output() outs.append(conf_output) if self.compile: outs.extend(self._bytecode_filenames([conf_output])) ...
[ "def", "get_outputs", "(", "self", ")", ":", "outs", "=", "super", "(", "MyInstallLib", ",", "self", ")", ".", "get_outputs", "(", ")", "conf_output", "=", "self", ".", "get_conf_output", "(", ")", "outs", ".", "append", "(", "conf_output", ")", "if", ...
40.875
0.008982
def fix2real(uval, conv): """ Convert a 32 bit unsigned int register into the value it represents in its Fixed arithmetic form. @param uval: the numeric unsigned value in simulink representation @param conv: conv structure with conversion specs as generated by I{get_conv} @return: the real number re...
[ "def", "fix2real", "(", "uval", ",", "conv", ")", ":", "res", "=", "0", "int_val", "=", "(", "(", "uval", "&", "conv", "[", "\"int_mask\"", "]", ")", ">>", "conv", "[", "\"bin_point\"", "]", ")", "dec_val", "=", "conv", "[", "\"dec_step\"", "]", "*...
48.25
0.008895
def calc_image_merge_clip(p1, p2, dst, q1, q2): """ p1 (x1, y1, z1) and p2 (x2, y2, z2) define the extent of the (non-scaled) data shown. The image, defined by region q1, q2 is to be placed at dst in the image (destination may be outside of the actual data array). Refines the modified points (q1',...
[ "def", "calc_image_merge_clip", "(", "p1", ",", "p2", ",", "dst", ",", "q1", ",", "q2", ")", ":", "x1", ",", "y1", "=", "p1", "[", ":", "2", "]", "x2", ",", "y2", "=", "p2", "[", ":", "2", "]", "dst_x", ",", "dst_y", "=", "dst", "[", ":", ...
24.645161
0.000629
async def encode_jwt(self, identity: SessionIdentity) -> str: """ 将identity编码为JWT """ assert identity payload = { "sub": identity.identity, "user_id": identity.user_id, "exp": int(time.time() + self._max_age) # seconds from 1970-1-1 UTC } ...
[ "async", "def", "encode_jwt", "(", "self", ",", "identity", ":", "SessionIdentity", ")", "->", "str", ":", "assert", "identity", "payload", "=", "{", "\"sub\"", ":", "identity", ".", "identity", ",", "\"user_id\"", ":", "identity", ".", "user_id", ",", "\"...
27.5
0.011719
def download(s3_conn, out_filename, s3_path): """Downloads the given s3_path Args: s3_conn (boto.s3.connection) a boto s3 connection out_filename (str) local filename to save the file s3_path (str) the source path on s3 """ bucket_name, prefix = split_s3_path(s3_path) bucket...
[ "def", "download", "(", "s3_conn", ",", "out_filename", ",", "s3_path", ")", ":", "bucket_name", ",", "prefix", "=", "split_s3_path", "(", "s3_path", ")", "bucket", "=", "s3_conn", ".", "get_bucket", "(", "bucket_name", ")", "key", "=", "boto", ".", "s3", ...
34.4375
0.001767
def parse_csv_file(url, res): """Parse given URL and write res with {scheme -> description}""" response = requests.get(url, stream=True) reader = csv.reader(response.iter_lines()) first_row = True for row in reader: if first_row: # skip first row first_row = False ...
[ "def", "parse_csv_file", "(", "url", ",", "res", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "reader", "=", "csv", ".", "reader", "(", "response", ".", "iter_lines", "(", ")", ")", "first_row", "=",...
34.666667
0.002342
def _process_task_instances(self, dag, queue, session=None): """ This method schedules the tasks for a single DAG by looking at the active DAG runs and adding task instances that should run to the queue. """ # update the state of the previously active dag runs da...
[ "def", "_process_task_instances", "(", "self", ",", "dag", ",", "queue", ",", "session", "=", "None", ")", ":", "# update the state of the previously active dag runs", "dag_runs", "=", "DagRun", ".", "find", "(", "dag_id", "=", "dag", ".", "dag_id", ",", "state"...
42.448276
0.002382
def _process_environments(self): """ There's only about 30 environments in which the phenotypes are recorded. There are no externally accessible identifiers for environments, so we make anonymous nodes for now. Some of the environments are comprised of >1 of the other env...
[ "def", "_process_environments", "(", "self", ")", ":", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else", ":", "graph", "=", "self", ".", "graph", "raw", "=", "'/'", ".", "join", "(", "(", "self", ".", "rawdir", ",",...
40.857143
0.000759
def get_record(self, param, must=[APIKEY, START_TIME, END_TIME]): '''查短信发送记录 参数名 类型 是否必须 描述 示例 apikey String 是 用户唯一标识 9b11127a9701975c734b8aee81ee3526 mobile String 否 需要查询的手机号 15205201314 start_time String 是 短信发送开始时间 2013-08-11 00:00:00 end_time String 是 短信发送结束时间...
[ "def", "get_record", "(", "self", ",", "param", ",", "must", "=", "[", "APIKEY", ",", "START_TIME", ",", "END_TIME", "]", ")", ":", "r", "=", "self", ".", "verify_param", "(", "param", ",", "must", ")", "if", "not", "r", ".", "is_succ", "(", ")", ...
36.571429
0.008883
def sim_hamming(src, tar, diff_lens=True): """Return the normalized Hamming similarity of two strings. This is a wrapper for :py:meth:`Hamming.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison diff_lens : bool ...
[ "def", "sim_hamming", "(", "src", ",", "tar", ",", "diff_lens", "=", "True", ")", ":", "return", "Hamming", "(", ")", ".", "sim", "(", "src", ",", "tar", ",", "diff_lens", ")" ]
28.194444
0.000952
def plot_bit_for_bit(case, var_name, model_data, bench_data, diff_data): """ Create a bit for bit plot """ plot_title = "" plot_name = case + "_" + var_name + ".png" plot_path = os.path.join(os.path.join(livvkit.output_dir, "verification", "imgs")) functions.mkdir_p(plot_path) m_ndim = np.ndim(m...
[ "def", "plot_bit_for_bit", "(", "case", ",", "var_name", ",", "model_data", ",", "bench_data", ",", "diff_data", ")", ":", "plot_title", "=", "\"\"", "plot_name", "=", "case", "+", "\"_\"", "+", "var_name", "+", "\".png\"", "plot_path", "=", "os", ".", "pa...
34
0.002269
def flush(self): """ Force commit changes to the file and stdout """ if not self.nostdout: self.stdout.flush() if self.file is not None: self.file.flush()
[ "def", "flush", "(", "self", ")", ":", "if", "not", "self", ".", "nostdout", ":", "self", ".", "stdout", ".", "flush", "(", ")", "if", "self", ".", "file", "is", "not", "None", ":", "self", ".", "file", ".", "flush", "(", ")" ]
32.833333
0.009901
def convertDate(self, date, prefix="", weekday=False): """Convert a datetime object representing into a human-ready string that can be read, spoken aloud, etc. In effect, runs both convertDay and convertTime on the input, merging the results. Args: date (datetime.date): A da...
[ "def", "convertDate", "(", "self", ",", "date", ",", "prefix", "=", "\"\"", ",", "weekday", "=", "False", ")", ":", "dayString", "=", "self", ".", "convertDay", "(", "date", ",", "prefix", "=", "prefix", ",", "weekday", "=", "weekday", ")", "timeString...
48.857143
0.001912
def get_bind_data(zone_id, profile): ''' Export Zone to the BIND compatible format. :param zone_id: Zone to export. :type zone_id: ``str`` :param profile: The profile key :type profile: ``str`` :return: Zone data in BIND compatible format. :rtype: ``str`` CLI Example: .. c...
[ "def", "get_bind_data", "(", "zone_id", ",", "profile", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "zone", "=", "conn", ".", "get_zone", "(", "zone_id", ")", "return", "conn", ".", "export_zone_to_bind_format", "(", "zone", ...
23.454545
0.001862
def parse_keystring(conn, key_string): """ A utility function to turn strings like 'Mod1+Mod4+a' into a pair corresponding to its modifiers and keycode. :param key_string: String starting with zero or more modifiers followed by exactly one key press. Avail...
[ "def", "parse_keystring", "(", "conn", ",", "key_string", ")", ":", "# FIXME this code is temporary hack, requires better abstraction", "from", "PyQt5", ".", "QtGui", "import", "QKeySequence", "from", "PyQt5", ".", "QtCore", "import", "Qt", "from", ".", "qt_keycodes", ...
33.711864
0.000489
def info(self): """ Property for accessing :class:`InfoManager` instance, which is used to general server info. :rtype: yagocd.resources.info.InfoManager """ if self._info_manager is None: self._info_manager = InfoManager(session=self._session) return self._i...
[ "def", "info", "(", "self", ")", ":", "if", "self", ".", "_info_manager", "is", "None", ":", "self", ".", "_info_manager", "=", "InfoManager", "(", "session", "=", "self", ".", "_session", ")", "return", "self", ".", "_info_manager" ]
35.888889
0.009063
def caller_name(skip=2, include_lineno=False): ''' Get a name of a caller in the format module.class.method `skip` specifies how many levels of stack to skip while getting caller name. skip=1 means "who calls me", skip=2 "who calls my caller" etc. An empty string is returned if skipped levels exce...
[ "def", "caller_name", "(", "skip", "=", "2", ",", "include_lineno", "=", "False", ")", ":", "stack", "=", "inspect", ".", "stack", "(", ")", "start", "=", "0", "+", "skip", "if", "len", "(", "stack", ")", "<", "start", "+", "1", ":", "return", "'...
35.928571
0.00129