text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def gui(): """Main function""" global SCREEN_SIZE # ####### # setup all objects # ####### os.environ['SDL_VIDEO_CENTERED'] = '1' screen = new_widow() pygame.display.set_caption('Client swag') pygame.event.set_allowed([QUIT, KEYDOWN, MOUSEBUTTONDOWN]) clock = pygame.time.Clock(...
[ "def", "gui", "(", ")", ":", "global", "SCREEN_SIZE", "# #######", "# setup all objects", "# #######", "os", ".", "environ", "[", "'SDL_VIDEO_CENTERED'", "]", "=", "'1'", "screen", "=", "new_widow", "(", ")", "pygame", ".", "display", ".", "set_caption", "(", ...
28.7
0.001837
def get_price_as_of(self, stock: Commodity, on_date: datetime): """ Gets the latest price on or before the given date. """ # return self.get_price_as_of_query(stock, on_date).first() prices = PriceDbApplication() prices.get_prices_on(on_date.date().isoformat(), stock.namespace, stock.mne...
[ "def", "get_price_as_of", "(", "self", ",", "stock", ":", "Commodity", ",", "on_date", ":", "datetime", ")", ":", "# return self.get_price_as_of_query(stock, on_date).first()", "prices", "=", "PriceDbApplication", "(", ")", "prices", ".", "get_prices_on", "(", "on_dat...
64.4
0.009202
def send_patch_document(self, event): """ Sends a PATCH-DOC message, returning a Future that's completed when it's written out. """ msg = self.protocol.create('PATCH-DOC', [event]) return self._socket.send_message(msg)
[ "def", "send_patch_document", "(", "self", ",", "event", ")", ":", "msg", "=", "self", ".", "protocol", ".", "create", "(", "'PATCH-DOC'", ",", "[", "event", "]", ")", "return", "self", ".", "_socket", ".", "send_message", "(", "msg", ")" ]
59.75
0.012397
def setup_arguments(arguments): ''' Prepares argumnents output by docopt. ''' # Ensure parallel/port are numbers for key in ('--parallel', '--port', '--fail-percent'): if arguments[key]: try: arguments[key] = int(arguments[key]) except ValueError: ...
[ "def", "setup_arguments", "(", "arguments", ")", ":", "# Ensure parallel/port are numbers", "for", "key", "in", "(", "'--parallel'", ",", "'--port'", ",", "'--fail-percent'", ")", ":", "if", "arguments", "[", "key", "]", ":", "try", ":", "arguments", "[", "key...
31.142857
0.001482
def is_color_supported(): "Find out if your terminal environment supports color." # shinx.util.console if not hasattr(sys.stdout, 'isatty'): return False if not sys.stdout.isatty() and 'TERMINAL-COLOR' not in os.environ: return False if sys.platform == 'win32': # pragma: no cover ...
[ "def", "is_color_supported", "(", ")", ":", "# shinx.util.console", "if", "not", "hasattr", "(", "sys", ".", "stdout", ",", "'isatty'", ")", ":", "return", "False", "if", "not", "sys", ".", "stdout", ".", "isatty", "(", ")", "and", "'TERMINAL-COLOR'", "not...
27.590909
0.001592
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data["properties"] address_pools = [] for content in properties.get("loadBalancerBackendAddressPools", []): resource = Resource.from_raw_data(content) address_p...
[ "def", "process_raw_data", "(", "cls", ",", "raw_data", ")", ":", "properties", "=", "raw_data", "[", "\"properties\"", "]", "address_pools", "=", "[", "]", "for", "content", "in", "properties", ".", "get", "(", "\"loadBalancerBackendAddressPools\"", ",", "[", ...
41.375
0.001476
def _serialize(self, include_run_logs=False, strict_json=False): """ Serialize a representation of this Task to a Python dict. """ result = {'command': self.command, 'name': self.name, 'started_at': self.started_at, 'completed_at': self.completed_at...
[ "def", "_serialize", "(", "self", ",", "include_run_logs", "=", "False", ",", "strict_json", "=", "False", ")", ":", "result", "=", "{", "'command'", ":", "self", ".", "command", ",", "'name'", ":", "self", ".", "name", ",", "'started_at'", ":", "self", ...
41.956522
0.002026
def max_fmeasure(fg_vals, bg_vals): """ Computes the maximum F-measure. Parameters ---------- fg_vals : array_like The list of values for the positive set. bg_vals : array_like The list of values for the negative set. Returns ------- f : float Maximum f...
[ "def", "max_fmeasure", "(", "fg_vals", ",", "bg_vals", ")", ":", "x", ",", "y", "=", "roc_values", "(", "fg_vals", ",", "bg_vals", ")", "x", ",", "y", "=", "x", "[", "1", ":", "]", ",", "y", "[", "1", ":", "]", "# don't include origin", "p", "=",...
21.83871
0.008487
def from_ip(cls, ip): """Retrieve ip id associated to an ip.""" ips = dict([(ip_['ip'], ip_['id']) for ip_ in cls.list({'items_per_page': 500})]) return ips.get(ip)
[ "def", "from_ip", "(", "cls", ",", "ip", ")", ":", "ips", "=", "dict", "(", "[", "(", "ip_", "[", "'ip'", "]", ",", "ip_", "[", "'id'", "]", ")", "for", "ip_", "in", "cls", ".", "list", "(", "{", "'items_per_page'", ":", "500", "}", ")", "]",...
40.8
0.009615
def gpu_source_extraction(in1, tolerance, store_on_gpu, neg_comp): """ The following function determines connectivity within a given wavelet decomposition. These connected and labelled structures are thresholded to within some tolerance of the maximum coefficient at the scale. This determines whether on...
[ "def", "gpu_source_extraction", "(", "in1", ",", "tolerance", ",", "store_on_gpu", ",", "neg_comp", ")", ":", "# The following are pycuda kernels which are executed on the gpu. Specifically, these both perform thresholding", "# operations. The gpu is much faster at this on large arrays due...
46.066667
0.013852
def retrieve(self, request, project, pk=None): """ GET method implementation for detail view Return a single job with log_references and artifact names and links to the artifact blobs. """ try: job = Job.objects.select_related( *self._default_...
[ "def", "retrieve", "(", "self", ",", "request", ",", "project", ",", "pk", "=", "None", ")", ":", "try", ":", "job", "=", "Job", ".", "objects", ".", "select_related", "(", "*", "self", ".", "_default_select_related", "+", "[", "'taskcluster_metadata'", ...
37.153846
0.002017
def execute(self, cmd, *args, **kwargs): """ Execute the SQL command and return the data rows as tuples """ self.cursor.execute(cmd, *args, **kwargs)
[ "def", "execute", "(", "self", ",", "cmd", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "cursor", ".", "execute", "(", "cmd", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
42.5
0.011561
def get_columns_of_table(self, table=None): """Return the list of columns for a particular table by querying the SQL for the complete list of column names.""" # Check the table exists # if table is None: table = self.main_table if not table in self.tables: return [] # A P...
[ "def", "get_columns_of_table", "(", "self", ",", "table", "=", "None", ")", ":", "# Check the table exists #", "if", "table", "is", "None", ":", "table", "=", "self", ".", "main_table", "if", "not", "table", "in", "self", ".", "tables", ":", "return", "[",...
50.545455
0.008834
def conjugate_gradient(op, x, rhs, niter, callback=None): """Optimized implementation of CG for self-adjoint operators. This method solves the inverse problem (of the first kind):: A(x) = y for a linear and self-adjoint `Operator` ``A``. It uses a minimum amount of memory copies by applying ...
[ "def", "conjugate_gradient", "(", "op", ",", "x", ",", "rhs", ",", "niter", ",", "callback", "=", "None", ")", ":", "# TODO: add a book reference", "# TODO: update doc", "if", "op", ".", "domain", "!=", "op", ".", "range", ":", "raise", "ValueError", "(", ...
30.050633
0.000408
def publish(self, message, key=None, **kws): """Put a message in the queue and updates any coroutine wating with fetch. *works as a coroutine operation*""" return PSPut(self, message, key, **kws)
[ "def", "publish", "(", "self", ",", "message", ",", "key", "=", "None", ",", "*", "*", "kws", ")", ":", "return", "PSPut", "(", "self", ",", "message", ",", "key", ",", "*", "*", "kws", ")" ]
54.75
0.009009
def run(self): ''' Spin up the multiprocess event returner ''' salt.utils.process.appendproctitle(self.__class__.__name__) self.event = get_event('master', opts=self.opts, listen=True) events = self.event.iter_events(full=True) self.event.fire_event({}, 'salt/even...
[ "def", "run", "(", "self", ")", ":", "salt", ".", "utils", ".", "process", ".", "appendproctitle", "(", "self", ".", "__class__", ".", "__name__", ")", "self", ".", "event", "=", "get_event", "(", "'master'", ",", "opts", "=", "self", ".", "opts", ",...
39.571429
0.00235
def resolve_sam_resource_id_refs(self, input, supported_resource_id_refs): """ Some SAM resources have their logical ids mutated from the original id that the customer writes in the template. This method recursively walks the tree and updates these logical ids from the old value to the n...
[ "def", "resolve_sam_resource_id_refs", "(", "self", ",", "input", ",", "supported_resource_id_refs", ")", ":", "return", "self", ".", "_traverse", "(", "input", ",", "supported_resource_id_refs", ",", "self", ".", "_try_resolve_sam_resource_id_refs", ")" ]
62.5
0.008596
def set_token(self, value): """ Set Token """ if value and value.find('Token token=') == 0: token = value[12:] else: token = value self.token = token
[ "def", "set_token", "(", "self", ",", "value", ")", ":", "if", "value", "and", "value", ".", "find", "(", "'Token token='", ")", "==", "0", ":", "token", "=", "value", "[", "12", ":", "]", "else", ":", "token", "=", "value", "self", ".", "token", ...
24.875
0.009709
def deeplearning(interactive=True, echo=True, testing=False): """Deep Learning model demo.""" def demo_body(go): """ Demo of H2O's Deep Learning model. This demo uploads a dataset to h2o, parses it, and shows a description. Then it divides the dataset into training and test set...
[ "def", "deeplearning", "(", "interactive", "=", "True", ",", "echo", "=", "True", ",", "testing", "=", "False", ")", ":", "def", "demo_body", "(", "go", ")", ":", "\"\"\"\n Demo of H2O's Deep Learning model.\n\n This demo uploads a dataset to h2o, parses it,...
33.178571
0.002091
def _compress_for_distribute(max_vol, plan, **kwargs): """ Combines as many dispenses as can fit within the maximum volume """ source = None new_source = None a_vol = 0 temp_dispenses = [] new_transfer_plan = [] disposal_vol = kwargs.get('disposal_vol', 0) max_vol = max_vol - dis...
[ "def", "_compress_for_distribute", "(", "max_vol", ",", "plan", ",", "*", "*", "kwargs", ")", ":", "source", "=", "None", "new_source", "=", "None", "a_vol", "=", "0", "temp_dispenses", "=", "[", "]", "new_transfer_plan", "=", "[", "]", "disposal_vol", "="...
29.688889
0.000725
def detect_stream_mode(stream): ''' detect_stream_mode - Detect the mode on a given stream @param stream <object> - A stream object If "mode" is present, that will be used. @return <type> - "Bytes" type or "str" type ''' # If "Mode" is present, pull from that i...
[ "def", "detect_stream_mode", "(", "stream", ")", ":", "# If \"Mode\" is present, pull from that", "if", "hasattr", "(", "stream", ",", "'mode'", ")", ":", "if", "'b'", "in", "stream", ".", "mode", ":", "return", "bytes", "elif", "'t'", "in", "stream", ".", "...
26.548387
0.002345
def help_center_vote_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/votes#delete-vote" api_path = "/api/v2/help_center/votes/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
[ "def", "help_center_vote_delete", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/help_center/votes/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "("...
57.8
0.010239
def create_bootstrap_dataframe(orig_df, obs_id_col, resampled_obs_ids_1d, groupby_dict, boot_id_col="bootstrap_id"): """ Will create the altered dataframe of data needed to estimate a choi...
[ "def", "create_bootstrap_dataframe", "(", "orig_df", ",", "obs_id_col", ",", "resampled_obs_ids_1d", ",", "groupby_dict", ",", "boot_id_col", "=", "\"bootstrap_id\"", ")", ":", "# Check the validity of the passed arguments.", "check_column_existence", "(", "obs_id_col", ",", ...
41.916667
0.000389
def stack(recs, fields=None): """Stack common fields in multiple record arrays (concatenate them). Parameters ---------- recs : list List of NumPy record arrays fields : list of strings, optional (default=None) The list of fields to include in the stacked array. If None, then ...
[ "def", "stack", "(", "recs", ",", "fields", "=", "None", ")", ":", "if", "fields", "is", "None", ":", "fields", "=", "list", "(", "set", ".", "intersection", "(", "*", "[", "set", "(", "rec", ".", "dtype", ".", "names", ")", "for", "rec", "in", ...
32.041667
0.001263
def _getpath(self, path): "A wrapper of JFS.getObject(), with some tweaks that make sense in a file system." if is_blacklisted(path): raise JottaFuseError('Blacklisted file, refusing to retrieve it') return self.client.getObject(path)
[ "def", "_getpath", "(", "self", ",", "path", ")", ":", "if", "is_blacklisted", "(", "path", ")", ":", "raise", "JottaFuseError", "(", "'Blacklisted file, refusing to retrieve it'", ")", "return", "self", ".", "client", ".", "getObject", "(", "path", ")" ]
44.333333
0.01107
def POST_query(self, req_hook, req_args): ''' Generic POST query method ''' # HTTP POST queries require keyManagerTokens and sessionTokens headers = {'Content-Type': 'application/json', 'sessionToken': self.__session__, 'keyManagerToken': self.__keymngr__} ...
[ "def", "POST_query", "(", "self", ",", "req_hook", ",", "req_args", ")", ":", "# HTTP POST queries require keyManagerTokens and sessionTokens", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", ",", "'sessionToken'", ":", "self", ".", "__session__", ",",...
46.521739
0.001832
def swap_deployment(self, service_name, production, source_deployment): ''' Initiates a virtual IP swap between the staging and production deployment environments for a service. If the service is currently running in the staging environment, it will be swapped to the production e...
[ "def", "swap_deployment", "(", "self", ",", "service_name", ",", "production", ",", "source_deployment", ")", ":", "_validate_not_none", "(", "'service_name'", ",", "service_name", ")", "_validate_not_none", "(", "'production'", ",", "production", ")", "_validate_not_...
48.409091
0.001842
def on_train_begin(self, **kwargs): "check if loss is reduction" if hasattr(self.loss_func, "reduction") and (self.loss_func.reduction != "sum"): warn("For better gradients consider 'reduction=sum'")
[ "def", "on_train_begin", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ".", "loss_func", ",", "\"reduction\"", ")", "and", "(", "self", ".", "loss_func", ".", "reduction", "!=", "\"sum\"", ")", ":", "warn", "(", "\"For b...
56.25
0.02193
def dimensions(self): """ Returns dimensions as (x, y) tuple. """ return (self.xmax - self.xmin, self.ymax - self.ymin)
[ "def", "dimensions", "(", "self", ")", ":", "return", "(", "self", ".", "xmax", "-", "self", ".", "xmin", ",", "self", ".", "ymax", "-", "self", ".", "ymin", ")" ]
29.4
0.013245
def putcellslice(self, columnname, rownr, value, blc, trc, inc=[]): """Put into a slice of a table cell holding an array. The columnname and (0-relative) rownr indicate the table cell. Unlike putcell only a single row can be given. The slice to put is defined by the blc, trc, and optio...
[ "def", "putcellslice", "(", "self", ",", "columnname", ",", "rownr", ",", "value", ",", "blc", ",", "trc", ",", "inc", "=", "[", "]", ")", ":", "self", ".", "_putcellslice", "(", "columnname", ",", "rownr", ",", "value", ",", "blc", ",", "trc", ","...
46.473684
0.00222
def map_stack(array3D, z_function): """Return 3D array where each z-slice has had the function applied to it. :param array3D: 3D numpy.array :param z_function: function to be mapped to each z-slice """ _, _, zdim = array3D.shape return np.dstack([z_function(array3D[:,:,z]) for z in range(zdim)]...
[ "def", "map_stack", "(", "array3D", ",", "z_function", ")", ":", "_", ",", "_", ",", "zdim", "=", "array3D", ".", "shape", "return", "np", ".", "dstack", "(", "[", "z_function", "(", "array3D", "[", ":", ",", ":", ",", "z", "]", ")", "for", "z", ...
39.25
0.009346
def _determine_impact_coordtransform(self,deltaAngleTrackImpact, nTrackChunksImpact, timpact,impact_angle): """Function that sets up the transformation between (x,v) and (O,theta)""" # Integrate the progenitor backward to ...
[ "def", "_determine_impact_coordtransform", "(", "self", ",", "deltaAngleTrackImpact", ",", "nTrackChunksImpact", ",", "timpact", ",", "impact_angle", ")", ":", "# Integrate the progenitor backward to the time of impact", "self", ".", "_gap_progenitor_setup", "(", ")", "# Sign...
67.404762
0.020538
def detect_other_protocol(server_handshake_bytes): """ Looks at the server handshake bytes to try and detect a different protocol :param server_handshake_bytes: A byte string of the handshake data received from the server :return: None, or a unicode string of "ftp", "http", "imap", "po...
[ "def", "detect_other_protocol", "(", "server_handshake_bytes", ")", ":", "if", "server_handshake_bytes", "[", "0", ":", "5", "]", "==", "b'HTTP/'", ":", "return", "'HTTP'", "if", "server_handshake_bytes", "[", "0", ":", "4", "]", "==", "b'220 '", ":", "if", ...
27.833333
0.002315
def handle_netusb(self, message): """Handles 'netusb' in message""" # _LOGGER.debug("message: {}".format(message)) needs_update = 0 if self._yamaha: if 'play_info_updated' in message: play_info = self.get_play_info() # _LOGGER.debug(play_info)...
[ "def", "handle_netusb", "(", "self", ",", "message", ")", ":", "# _LOGGER.debug(\"message: {}\".format(message))", "needs_update", "=", "0", "if", "self", ".", "_yamaha", ":", "if", "'play_info_updated'", "in", "message", ":", "play_info", "=", "self", ".", "get_p...
40.764706
0.001409
def remove_summaries(): """Remove summaries from the default graph.""" g = tf.get_default_graph() key = tf.GraphKeys.SUMMARIES log_debug("Remove summaries %s" % str(g.get_collection(key))) del g.get_collection_ref(key)[:] assert not g.get_collection(key)
[ "def", "remove_summaries", "(", ")", ":", "g", "=", "tf", ".", "get_default_graph", "(", ")", "key", "=", "tf", ".", "GraphKeys", ".", "SUMMARIES", "log_debug", "(", "\"Remove summaries %s\"", "%", "str", "(", "g", ".", "get_collection", "(", "key", ")", ...
37.142857
0.026316
def astra_cpu_back_projector(proj_data, geometry, reco_space, out=None): """Run an ASTRA back-projection on the given data using the CPU. Parameters ---------- proj_data : `DiscreteLpElement` Projection data to which the back-projector is applied geometry : `Geometry` Geometry defin...
[ "def", "astra_cpu_back_projector", "(", "proj_data", ",", "geometry", ",", "reco_space", ",", "out", "=", "None", ")", ":", "if", "not", "isinstance", "(", "proj_data", ",", "DiscreteLpElement", ")", ":", "raise", "TypeError", "(", "'projection data {!r} is not a ...
40.505376
0.000259
def create_case(self, name, email, subject, description, businessImpact, priority, phone): """ Send a case creation to SalesForces to create a ticket. @param name of the person creating the case. @param email of the person creating the case. @param subject of the cas...
[ "def", "create_case", "(", "self", ",", "name", ",", "email", ",", "subject", ",", "description", ",", "businessImpact", ",", "priority", ",", "phone", ")", ":", "if", "not", "(", "'@'", "in", "parseaddr", "(", "email", ")", "[", "1", "]", ")", ":", ...
41.290909
0.00129
def remove_constants(source): '''Replaces Strings and Regexp literals in the source code with identifiers and *removes comments*. Identifier is of the format: PyJsStringConst(String const number)_ - for Strings PyJsRegExpConst(RegExp const number)_ - for RegExps Returns dict which rela...
[ "def", "remove_constants", "(", "source", ")", ":", "source", "=", "' '", "+", "source", "+", "'\\n'", "comments", "=", "[", "]", "inside_comment", ",", "single_comment", "=", "False", ",", "False", "inside_single", ",", "inside_double", "=", "False", ",", ...
40.583893
0.00113
def fix(x, digs): """Format x as [-]ddd.ddd with 'digs' digits after the point and at least one digit before. If digs <= 0, the point is suppressed.""" if type(x) != type(''): x = repr(x) try: sign, intpart, fraction, expo = extract(x) except NotANumber: return x intpart, fra...
[ "def", "fix", "(", "x", ",", "digs", ")", ":", "if", "type", "(", "x", ")", "!=", "type", "(", "''", ")", ":", "x", "=", "repr", "(", "x", ")", "try", ":", "sign", ",", "intpart", ",", "fraction", ",", "expo", "=", "extract", "(", "x", ")",...
39.4
0.01157
def _adjust_cell_attributes(self, insertion_point, no_to_insert, axis, tab=None, cell_attrs=None): """Adjusts cell attributes on insertion/deletion Parameters ---------- insertion_point: Integer \tPont on axis, before which insertion takes place ...
[ "def", "_adjust_cell_attributes", "(", "self", ",", "insertion_point", ",", "no_to_insert", ",", "axis", ",", "tab", "=", "None", ",", "cell_attrs", "=", "None", ")", ":", "def", "replace_cell_attributes_table", "(", "index", ",", "new_table", ")", ":", "\"\"\...
35.876289
0.000839
def _fixup_record_bitfields_type(self, s): """Fix the bitfield packing issue for python ctypes, by changing the bitfield type, and respecting compiler alignement rules. This method should be called AFTER padding to have a perfect continuous layout. There is one very special cas...
[ "def", "_fixup_record_bitfields_type", "(", "self", ",", "s", ")", ":", "# phase 1, make bitfield, relying upon padding.", "bitfields", "=", "[", "]", "bitfield_members", "=", "[", "]", "current_bits", "=", "0", "for", "m", "in", "s", ".", "members", ":", "if", ...
41.590476
0.001342
def populate_translation_fields(sender, kwargs): """ When models are created or loaded from fixtures, replicates values provided for translatable fields to some / all empty translation fields, according to the current population mode. Population is performed only on keys (field names) present in kw...
[ "def", "populate_translation_fields", "(", "sender", ",", "kwargs", ")", ":", "populate", "=", "mt_settings", ".", "AUTO_POPULATE", "if", "not", "populate", ":", "return", "if", "populate", "is", "True", ":", "# What was meant by ``True`` is now called ``all``.", "pop...
45.833333
0.00178
def create_record_task(self, frame_parameters: dict=None, channels_enabled: typing.List[bool]=None) -> RecordTask: """Create a record task for this hardware source. .. versionadded:: 1.0 :param frame_parameters: The frame parameters for the record. Pass None for defaults. :type frame_p...
[ "def", "create_record_task", "(", "self", ",", "frame_parameters", ":", "dict", "=", "None", ",", "channels_enabled", ":", "typing", ".", "List", "[", "bool", "]", "=", "None", ")", "->", "RecordTask", ":", "return", "RecordTask", "(", "self", ".", "__hard...
47.647059
0.012107
def xmlrpc_reschedule(self): """ Reschedule all running tasks. """ if not len(self.scheduled_tasks) == 0: self.reschedule = list(self.scheduled_tasks.items()) self.scheduled_tasks = {} return True
[ "def", "xmlrpc_reschedule", "(", "self", ")", ":", "if", "not", "len", "(", "self", ".", "scheduled_tasks", ")", "==", "0", ":", "self", ".", "reschedule", "=", "list", "(", "self", ".", "scheduled_tasks", ".", "items", "(", ")", ")", "self", ".", "s...
31.75
0.011494
def _extended_lookup( datastore_api, project, key_pbs, missing=None, deferred=None, eventual=False, transaction_id=None, ): """Repeat lookup until all keys found (unless stop requested). Helper function for :meth:`Client.get_multi`. :type datastore_api: :class:`google.c...
[ "def", "_extended_lookup", "(", "datastore_api", ",", "project", ",", "key_pbs", ",", "missing", "=", "None", ",", "deferred", "=", "None", ",", "eventual", "=", "False", ",", "transaction_id", "=", "None", ",", ")", ":", "if", "missing", "is", "not", "N...
33.409639
0.00035
def unpack_sver_response_version(packet): """For internal use. Unpack the version-related parts of an sver (aka CMD_VERSION) response. Parameters ---------- packet : :py:class:`~rig.machine_control.packets.SCPPacket` The packet recieved in response to the version command. Returns -...
[ "def", "unpack_sver_response_version", "(", "packet", ")", ":", "software_name", "=", "packet", ".", "data", ".", "decode", "(", "\"utf-8\"", ")", "legacy_version_field", "=", "packet", ".", "arg2", ">>", "16", "if", "legacy_version_field", "!=", "0xFFFF", ":", ...
35.27907
0.000641
def time(ctx, hours, minutes, seconds): """ Defines a time value """ return _time(conversions.to_integer(hours, ctx), conversions.to_integer(minutes, ctx), conversions.to_integer(seconds, ctx))
[ "def", "time", "(", "ctx", ",", "hours", ",", "minutes", ",", "seconds", ")", ":", "return", "_time", "(", "conversions", ".", "to_integer", "(", "hours", ",", "ctx", ")", ",", "conversions", ".", "to_integer", "(", "minutes", ",", "ctx", ")", ",", "...
41
0.009569
def revoke_all(self, paths: Union[str, Iterable[str]], recursive: bool=False): """ See `AccessControlMapper.revoke_all`. :param paths: see `AccessControlMapper.revoke_all` :param access_controls: see `AccessControlMapper.revoke_all` :param recursive: whether the access control li...
[ "def", "revoke_all", "(", "self", ",", "paths", ":", "Union", "[", "str", ",", "Iterable", "[", "str", "]", "]", ",", "recursive", ":", "bool", "=", "False", ")", ":" ]
55
0.015345
def refresh_config(self): ''' __NB__ This *must* be called from a *different* thread than the GUI/Gtk thread. ''' from gi.repository import Clutter, Gst, GstVideo, ClutterGst from path_helpers import path from .warp import bounding_box_from_allocation if self.con...
[ "def", "refresh_config", "(", "self", ")", ":", "from", "gi", ".", "repository", "import", "Clutter", ",", "Gst", ",", "GstVideo", ",", "ClutterGst", "from", "path_helpers", "import", "path", "from", ".", "warp", "import", "bounding_box_from_allocation", "if", ...
52.404762
0.001338
def decode(encoded, eol=NL): """Decode a quoted-printable string. Lines are separated with eol, which defaults to \\n. """ if not encoded: return encoded # BAW: see comment in encode() above. Again, we're building up the # decoded string with string concatenation, which could be done m...
[ "def", "decode", "(", "encoded", ",", "eol", "=", "NL", ")", ":", "if", "not", "encoded", ":", "return", "encoded", "# BAW: see comment in encode() above. Again, we're building up the", "# decoded string with string concatenation, which could be done much more", "# efficiently."...
29.8
0.000722
def ParseMessagesRow(self, parser_mediator, query, row, **unused_kwargs): """Parses an Messages row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that created the row. row (sqlite3.R...
[ "def", "ParseMessagesRow", "(", "self", ",", "parser_mediator", ",", "query", ",", "row", ",", "*", "*", "unused_kwargs", ")", ":", "query_hash", "=", "hash", "(", "query", ")", "event_data", "=", "HangoutsMessageData", "(", ")", "event_data", ".", "sender",...
41.884615
0.000898
def _is_primitive(thing): """Determine if the value is a primitive""" primitive = (int, str, bool, float) return isinstance(thing, primitive)
[ "def", "_is_primitive", "(", "thing", ")", ":", "primitive", "=", "(", "int", ",", "str", ",", "bool", ",", "float", ")", "return", "isinstance", "(", "thing", ",", "primitive", ")" ]
40.5
0.012121
def validate(self, value, attribute_filter=None, minified=False): """ :param value: serializable input to validate :type value: dict | None :param attribute_filter: :type: prestans.parser.AttributeFilter | None :param minified: whether or not the input is minified ...
[ "def", "validate", "(", "self", ",", "value", ",", "attribute_filter", "=", "None", ",", "minified", "=", "False", ")", ":", "if", "self", ".", "_required", "and", "(", "value", "is", "None", "or", "not", "isinstance", "(", "value", ",", "dict", ")", ...
35.948718
0.001736
def get_tuple_version(name, default=DEFAULT_TUPLE_NOT_FOUND, allow_ambiguous=True): """ Get tuple version from installed package information for easy handling. It will return :attr:`default` value when the named package is not installed. Parameters -...
[ "def", "get_tuple_version", "(", "name", ",", "default", "=", "DEFAULT_TUPLE_NOT_FOUND", ",", "allow_ambiguous", "=", "True", ")", ":", "def", "_prefer_int", "(", "x", ")", ":", "try", ":", "return", "int", "(", "x", ")", "except", "ValueError", ":", "retu...
27.509804
0.000688
def on_touch_move(self, touch): """If a card is being dragged, move other cards out of the way to show where the dragged card will go if you drop it. """ if ( 'card' not in touch.ud or 'layout' not in touch.ud or touch.ud['layout'] != self...
[ "def", "on_touch_move", "(", "self", ",", "touch", ")", ":", "if", "(", "'card'", "not", "in", "touch", ".", "ud", "or", "'layout'", "not", "in", "touch", ".", "ud", "or", "touch", ".", "ud", "[", "'layout'", "]", "!=", "self", ")", ":", "return", ...
42.185714
0.000662
def accept_hotp(key, response, counter, format='dec6', hash=hashlib.sha1, drift=3, backward_drift=0): ''' Validate a HOTP value inside a window of [counter-backward_drift:counter+forward_drift] :param key: the shared secret :type key: hexadecimal string of ...
[ "def", "accept_hotp", "(", "key", ",", "response", ",", "counter", ",", "format", "=", "'dec6'", ",", "hash", "=", "hashlib", ".", "sha1", ",", "drift", "=", "3", ",", "backward_drift", "=", "0", ")", ":", "for", "i", "in", "range", "(", "-", "back...
37
0.00162
def patch_namespaced_replica_set(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_replica_set # noqa: E501 partially update the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, ple...
[ "def", "patch_namespaced_replica_set", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")...
61.56
0.00128
def get_string_relative(strings: Sequence[str], prefix1: str, delta: int, prefix2: str, ignoreleadingcolon: bool = False, stripwhitespace: bool = True) -> Optional[str]: """ Finds a line (stri...
[ "def", "get_string_relative", "(", "strings", ":", "Sequence", "[", "str", "]", ",", "prefix1", ":", "str", ",", "delta", ":", "int", ",", "prefix2", ":", "str", ",", "ignoreleadingcolon", ":", "bool", "=", "False", ",", "stripwhitespace", ":", "bool", "...
36.357143
0.000638
def epub_zip(outdirect): """ Zips up the input file directory into an EPUB file. """ def recursive_zip(zipf, directory, folder=None): if folder is None: folder = '' for item in os.listdir(directory): if os.path.isfile(os.path.join(directory, item)): ...
[ "def", "epub_zip", "(", "outdirect", ")", ":", "def", "recursive_zip", "(", "zipf", ",", "directory", ",", "folder", "=", "None", ")", ":", "if", "folder", "is", "None", ":", "folder", "=", "''", "for", "item", "in", "os", ".", "listdir", "(", "direc...
35.517241
0.000945
def jsonHook(encoded): """Custom JSON decoder that allows construction of a new ``Smi`` instance from a decoded JSON object. :param encoded: a JSON decoded object literal (a dict) :returns: "encoded" or one of the these objects: :class:`Smi`, :class:`MzmlScan`, :class:`Mzml...
[ "def", "jsonHook", "(", "encoded", ")", ":", "if", "'__Smi__'", "in", "encoded", ":", "return", "Smi", ".", "_fromJSON", "(", "encoded", "[", "'__Smi__'", "]", ")", "elif", "'__MzmlScan__'", "in", "encoded", ":", "return", "MzmlScan", ".", "_fromJSON", "("...
42.421053
0.002427
def clean_address(address): """ Cleans a single email address. :param address: String (email address) :return: String (clean email address) """ if isinstance(address, header.Header): return clean_address(address.encode('ascii')) elif isinstance(address, str): address = addre...
[ "def", "clean_address", "(", "address", ")", ":", "if", "isinstance", "(", "address", ",", "header", ".", "Header", ")", ":", "return", "clean_address", "(", "address", ".", "encode", "(", "'ascii'", ")", ")", "elif", "isinstance", "(", "address", ",", "...
32.731707
0.001447
def distArrayFactory(BaseClass): """ Returns a distributed array class that derives from BaseClass @param BaseClass base class, e.g. numpy.ndarray or numpy.ma.masked_array @return dist array class """ class DistArrayAny(BaseClass): """ Distributed array. Each process owns data a...
[ "def", "distArrayFactory", "(", "BaseClass", ")", ":", "class", "DistArrayAny", "(", "BaseClass", ")", ":", "\"\"\"\n Distributed array. Each process owns data and can expose a subset\n of the data to other processes. These are known as windows. Any\n number of windows c...
32.278351
0.00062
def getSlaveStatus(self): """Returns status of replication slaves. @return: Dictionary of status items. """ info_dict = {} if self.checkVersion('9.1'): cols = ['procpid', 'usename', 'application_name', 'client_addr', 'client_port...
[ "def", "getSlaveStatus", "(", "self", ")", ":", "info_dict", "=", "{", "}", "if", "self", ".", "checkVersion", "(", "'9.1'", ")", ":", "cols", "=", "[", "'procpid'", ",", "'usename'", ",", "'application_name'", ",", "'client_addr'", ",", "'client_port'", "...
38.666667
0.010817
def generate_index(fn, cols=None, names=None, sep=" "): """Build a index for the given file. Args: fn (str): the name of the file. cols (list): a list containing column to keep (as int). names (list): the name corresponding to the column to keep (as str). sep (str): the field se...
[ "def", "generate_index", "(", "fn", ",", "cols", "=", "None", ",", "names", "=", "None", ",", "sep", "=", "\" \"", ")", ":", "# Some assertions", "assert", "cols", "is", "not", "None", ",", "\"'cols' was not set\"", "assert", "names", "is", "not", "None", ...
29.882353
0.000953
def leftcontext(self, size, placeholder=None, scope=None): """Returns the left context for an element, as a list. This method crosses sentence/paragraph boundaries by default, which can be restricted by setting scope""" if size == 0: return [] #for efficiency context = [] e = self ...
[ "def", "leftcontext", "(", "self", ",", "size", ",", "placeholder", "=", "None", ",", "scope", "=", "None", ")", ":", "if", "size", "==", "0", ":", "return", "[", "]", "#for efficiency", "context", "=", "[", "]", "e", "=", "self", "while", "len", "...
32.666667
0.013223
def selected(self, interrupt=False): """This object has been selected.""" self.ao2.output(self.get_title(), interrupt=interrupt)
[ "def", "selected", "(", "self", ",", "interrupt", "=", "False", ")", ":", "self", ".", "ao2", ".", "output", "(", "self", ".", "get_title", "(", ")", ",", "interrupt", "=", "interrupt", ")" ]
47.333333
0.013889
def hide_navbar_items(portal): """Hide root items in navigation """ logger.info("*** Hide Navigation Items ***") # Get the list of object ids for portal object_ids = portal.objectIds() object_ids = filter(lambda id: id in object_ids, NAV_BAR_ITEMS_TO_HIDE) for object_id in object_ids: ...
[ "def", "hide_navbar_items", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"*** Hide Navigation Items ***\"", ")", "# Get the list of object ids for portal", "object_ids", "=", "portal", ".", "objectIds", "(", ")", "object_ids", "=", "filter", "(", "lambda", ...
33.5
0.002421
def main(): """Main function for :command:`fabulous-text`.""" import optparse parser = optparse.OptionParser() parser.add_option( "-l", "--list", dest="list", action="store_true", default=False, help=("List available fonts")) parser.add_option( "-S", "--skew", dest="skew", ty...
[ "def", "main", "(", ")", ":", "import", "optparse", "parser", "=", "optparse", ".", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "\"-l\"", ",", "\"--list\"", ",", "dest", "=", "\"list\"", ",", "action", "=", "\"store_true\"", ",", "default",...
46.604167
0.000876
def cli(env, volume_id, replicant_id, immediate): """Failover a block volume to the given replicant volume.""" block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failover_to_replicant( volume_id, replicant_id, immediate ) if su...
[ "def", "cli", "(", "env", ",", "volume_id", ",", "replicant_id", ",", "immediate", ")", ":", "block_storage_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "success", "=", "block_storage_manager", ".", "failover_to_replicant...
32.285714
0.002151
def check_validity(self): """ Raise an error if any invalid attribute found. Raises ------ TypeError If an attribute has an invalid type. ValueError If an attribute has an invalid value (of the correct type). """ # tracks ...
[ "def", "check_validity", "(", "self", ")", ":", "# tracks", "for", "track", "in", "self", ".", "tracks", ":", "if", "not", "isinstance", "(", "track", ",", "Track", ")", ":", "raise", "TypeError", "(", "\"`tracks` must be a list of \"", "\"`pypianoroll.Track` in...
42.159091
0.001054
def _updateEndpoints(self,*args,**kwargs): """ Updates all endpoints except the one from which this slot was called. Note: this method is probably not complete threadsafe. Maybe a lock is needed when setter self.ignoreEvents """ sender = self.sender() if not self.ignore...
[ "def", "_updateEndpoints", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "sender", "=", "self", ".", "sender", "(", ")", "if", "not", "self", ".", "ignoreEvents", ":", "self", ".", "ignoreEvents", "=", "True", "for", "binding", "i...
33.52381
0.01105
def formatargspec(args, varargs=None, varkw=None, defaults=None, formatarg=str, formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), join=joinseq): """Format...
[ "def", "formatargspec", "(", "args", ",", "varargs", "=", "None", ",", "varkw", "=", "None", ",", "defaults", "=", "None", ",", "formatarg", "=", "str", ",", "formatvarargs", "=", "lambda", "name", ":", "'*'", "+", "name", ",", "formatvarkw", "=", "lam...
44.48
0.00088
def sign_json(self, keys=None, headers=None, flatten=False): """ Produce JWS using the JWS JSON Serialization :param keys: list of keys to use for signing the JWS :param headers: list of tuples (protected headers, unprotected headers) for each signature :return: A si...
[ "def", "sign_json", "(", "self", ",", "keys", "=", "None", ",", "headers", "=", "None", ",", "flatten", "=", "False", ")", ":", "def", "create_signature", "(", "protected", ",", "unprotected", ")", ":", "protected_headers", "=", "protected", "or", "{", "...
38.928571
0.001193
def remove_end_NaN(self, data, var=None): """ Remove end NaN. CHECK: Note issue with multi-column df. Parameters ---------- data : pd.DataFrame() Input dataframe. var : list(str) List that specifies specific columns of data...
[ "def", "remove_end_NaN", "(", "self", ",", "data", ",", "var", "=", "None", ")", ":", "# Limit to one or some variables", "if", "var", ":", "end_ok_data", "=", "data", "[", "var", "]", ".", "last_valid_index", "(", ")", "else", ":", "end_ok_data", "=", "da...
25.222222
0.008487
def unique_username_validator(form, field): """ Ensure that Username is unique. This validator may NOT be customized.""" user_manager = current_app.user_manager if not user_manager.db_manager.username_is_available(field.data): raise ValidationError(_('This Username is already in use. Please try ano...
[ "def", "unique_username_validator", "(", "form", ",", "field", ")", ":", "user_manager", "=", "current_app", ".", "user_manager", "if", "not", "user_manager", ".", "db_manager", ".", "username_is_available", "(", "field", ".", "data", ")", ":", "raise", "Validat...
65.6
0.012048
def mass_3d(self, r, rho0, gamma): """ mass enclosed a 3d sphere or radius r :param r: :param a: :param s: :return: """ mass_3d = 4 * np.pi * rho0 /(-gamma + 3) * r ** (-gamma + 3) return mass_3d
[ "def", "mass_3d", "(", "self", ",", "r", ",", "rho0", ",", "gamma", ")", ":", "mass_3d", "=", "4", "*", "np", ".", "pi", "*", "rho0", "/", "(", "-", "gamma", "+", "3", ")", "*", "r", "**", "(", "-", "gamma", "+", "3", ")", "return", "mass_3...
25.8
0.011236
def hash_args(*args, **kwargs): """Define a unique string for any set of representable args.""" arg_string = '_'.join([str(arg) for arg in args]) kwarg_string = '_'.join([str(key) + '=' + str(value) for key, value in iteritems(kwargs)]) combined = ':'.join([arg_string, kwarg...
[ "def", "hash_args", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "arg_string", "=", "'_'", ".", "join", "(", "[", "str", "(", "arg", ")", "for", "arg", "in", "args", "]", ")", "kwarg_string", "=", "'_'", ".", "join", "(", "[", "str", "(...
40.1
0.002439
def Run(self, unused_arg): """Run the kill.""" # Send a message back to the service to say that we are about to shutdown. reply = rdf_flows.GrrStatus(status=rdf_flows.GrrStatus.ReturnedStatus.OK) # Queue up the response message, jump the queue. self.SendReply(reply, message_type=rdf_flows.GrrMessage...
[ "def", "Run", "(", "self", ",", "unused_arg", ")", ":", "# Send a message back to the service to say that we are about to shutdown.", "reply", "=", "rdf_flows", ".", "GrrStatus", "(", "status", "=", "rdf_flows", ".", "GrrStatus", ".", "ReturnedStatus", ".", "OK", ")",...
37.384615
0.002008
def draw(self,cov,num_reals=1,names=None): """ draw random realizations from a multivariate Gaussian distribution Parameters ---------- cov: pyemu.Cov covariance structure to draw from num_reals: int number of realizations to generate ...
[ "def", "draw", "(", "self", ",", "cov", ",", "num_reals", "=", "1", ",", "names", "=", "None", ")", ":", "real_names", "=", "np", ".", "arange", "(", "num_reals", ",", "dtype", "=", "np", ".", "int64", ")", "# make sure everything is cool WRT ordering", ...
35.521739
0.013103
def run_step(context): """Remove specified keys from context. Args: Context is a dictionary or dictionary-like. context['contextClear'] must exist. It's a dictionary. Will iterate context['contextClear'] and remove those keys from context. For example, say input context is:...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'contextClear'", ",", "caller", "=", "__name__", ")", "for", "k", "in", "context", "[", "'contextClear'", ...
28
0.001015
def mesh(self,xyzs): """ Evaluate basis function on a mesh of points *xyz*. """ return sum(c*p.mesh(xyzs) for c,p in self)
[ "def", "mesh", "(", "self", ",", "xyzs", ")", ":", "return", "sum", "(", "c", "*", "p", ".", "mesh", "(", "xyzs", ")", "for", "c", ",", "p", "in", "self", ")" ]
30
0.025974
def uri_split_tree(uri): """ Return (scheme, (user, passwd, host, port), path, ((k1, v1), (k2, v2), ...), fragment) using basic_urisplit(), then split_authority() and split_query() on the result. >>> uri_split_tree( ... 'http://%42%20+blabla:lol@%77ww.foobar.org/%7Exilun/' + ...
[ "def", "uri_split_tree", "(", "uri", ")", ":", "scheme", ",", "authority", ",", "path", ",", "query", ",", "fragment", "=", "basic_urisplit", "(", "uri", ")", "if", "authority", ":", "authority", "=", "split_authority", "(", "authority", ")", "if", "query"...
44.285714
0.002105
def _reset(self): """Clear the cache.""" self.log.info("Clearing the cache, resetting event offsets") self.raw_header = None self.event_offsets = [] self.index = 0
[ "def", "_reset", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"Clearing the cache, resetting event offsets\"", ")", "self", ".", "raw_header", "=", "None", "self", ".", "event_offsets", "=", "[", "]", "self", ".", "index", "=", "0" ]
33
0.009852
def path_to_vertexlist(path, group=None, colors=None, **kwargs): """ Convert a Path3D object to arguments for an indexed vertex list constructor. Parameters ------------- path : trimesh.path.Path3D object Mesh to be rendered group : str Rendering group for the vertex list R...
[ "def", "path_to_vertexlist", "(", "path", ",", "group", "=", "None", ",", "colors", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# avoid cache check inside tight loop", "vertices", "=", "path", ".", "vertices", "# get (n, 2, (2|3)) lines", "lines", "=", "np"...
28.025
0.000862
def register_calendar_type(self, name, calendar_type, force=False): """ Registers a calendar by type. This is useful for registering a new calendar to be lazily instantiated at some future point in time. Parameters ---------- name: str The key with w...
[ "def", "register_calendar_type", "(", "self", ",", "name", ",", "calendar_type", ",", "force", "=", "False", ")", ":", "if", "force", ":", "self", ".", "deregister_calendar", "(", "name", ")", "if", "self", ".", "has_calendar", "(", "name", ")", ":", "ra...
32.233333
0.002008
def merge(cls, *args, **kwargs): """Create a new Ent from one or more existing Ents. Keys in the later Ent objects will overwrite the keys of the previous Ents. Later keys of different type than in earlier Ents will be bravely ignored. The following keyword arguments are recogn...
[ "def", "merge", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "newkeys", "=", "bool", "(", "kwargs", ".", "get", "(", "'newkeys'", ",", "False", ")", ")", "ignore", "=", "kwargs", ".", "get", "(", "'ignore'", ",", "list", "(", ...
35.5
0.001246
def add_atom(self, key, atom): """Set an atom. Existing atom will be overwritten.""" self.graph.add_node(key, atom=atom)
[ "def", "add_atom", "(", "self", ",", "key", ",", "atom", ")", ":", "self", ".", "graph", ".", "add_node", "(", "key", ",", "atom", "=", "atom", ")" ]
44.666667
0.014706
def calculo(self): """Calculate procedure""" T = self.kwargs["T"] rho = self.kwargs["rho"] P = self.kwargs["P"] # Composition alternate definition if self._composition == "A": A = self.kwargs["A"] elif self._composition == "xa": xa = self....
[ "def", "calculo", "(", "self", ")", ":", "T", "=", "self", ".", "kwargs", "[", "\"T\"", "]", "rho", "=", "self", ".", "kwargs", "[", "\"rho\"", "]", "P", "=", "self", ".", "kwargs", "[", "\"P\"", "]", "# Composition alternate definition", "if", "self",...
30.016393
0.001058
def verifySignature(self, msg): """ Validate the signature of the request Note: Batch is whitelisted because the inner messages are checked :param msg: a message requiring signature verification :return: None; raises an exception if the signature is not valid """ ...
[ "def", "verifySignature", "(", "self", ",", "msg", ")", ":", "if", "isinstance", "(", "msg", ",", "self", ".", "authnWhitelist", ")", ":", "return", "if", "isinstance", "(", "msg", ",", "Propagate", ")", ":", "typ", "=", "'propagate'", "req", "=", "Txn...
33.96875
0.001789
def run_rnaseq_variant_calling(data): """ run RNA-seq variant calling, variation file is stored in `vrn_file` in the datadict """ variantcaller = dd.get_variantcaller(data) if isinstance(variantcaller, list) and len(variantcaller) > 1: logger.error("Only one variantcaller can be run for ...
[ "def", "run_rnaseq_variant_calling", "(", "data", ")", ":", "variantcaller", "=", "dd", ".", "get_variantcaller", "(", "data", ")", "if", "isinstance", "(", "variantcaller", ",", "list", ")", "and", "len", "(", "variantcaller", ")", ">", "1", ":", "logger", ...
41.25
0.001185
def add_object(self, name, content, headers=None, replace=True): """ Adds a new content object to the Distribution. The content for the object will be copied to a new Key in the S3 Bucket and the permissions will be set appropriately for the type of Distribution. :type ...
[ "def", "add_object", "(", "self", ",", "name", ",", "content", ",", "headers", "=", "None", ",", "replace", "=", "True", ")", ":", "if", "self", ".", "config", ".", "origin", ".", "origin_access_identity", ":", "policy", "=", "'private'", "else", ":", ...
38.75
0.001574
def check(codeString, filename, reporter=None): """ Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. @type filename: C{st...
[ "def", "check", "(", "codeString", ",", "filename", ",", "reporter", "=", "None", ")", ":", "if", "reporter", "is", "None", ":", "reporter", "=", "modReporter", ".", "_makeDefaultReporter", "(", ")", "# First, compile into an AST and handle syntax errors.", "try", ...
36.152542
0.000456
def split(self, indices): """ Splits logical networks according to given indices Parameters ---------- indices : list 1-D array of sorted integers, the entries indicate where the array is split Returns ------- list List of :class:...
[ "def", "split", "(", "self", ",", "indices", ")", ":", "return", "[", "LogicalNetworkList", "(", "self", ".", "hg", ",", "part", ")", "for", "part", "in", "np", ".", "split", "(", "self", ".", "__matrix", ",", "indices", ")", "]" ]
33.055556
0.009804
def wait(self): """Wait until there are no more inprogress transfers This will not stop when failures are encountered and not propogate any of these errors from failed transfers, but it can be interrupted with a KeyboardInterrupt. """ try: transfer_coordinato...
[ "def", "wait", "(", "self", ")", ":", "try", ":", "transfer_coordinator", "=", "None", "for", "transfer_coordinator", "in", "self", ".", "tracked_transfer_coordinators", ":", "transfer_coordinator", ".", "result", "(", ")", "except", "KeyboardInterrupt", ":", "log...
42.259259
0.001714
def main(xmpp_server, xmpp_port, peer_name, node_name, app_id, xmpp_jid=None, xmpp_password=None): """ Runs the framework :param xmpp_server: Address of the XMPP server :param xmpp_port: Port of the XMPP server :param peer_name: Name of the peer :param node_name: Name (also, UID) of th...
[ "def", "main", "(", "xmpp_server", ",", "xmpp_port", ",", "peer_name", ",", "node_name", ",", "app_id", ",", "xmpp_jid", "=", "None", ",", "xmpp_password", "=", "None", ")", ":", "# Create the framework", "framework", "=", "pelix", ".", "framework", ".", "cr...
33.767857
0.000514
def show_cloudwatch_logs(self, count=10, grp_name=None): """ Show ``count`` latest CloudWatch Logs entries for our lambda function. :param count: number of log entries to show :type count: int """ if grp_name is None: grp_name = '/aws/lambda/%s' % self.config...
[ "def", "show_cloudwatch_logs", "(", "self", ",", "count", "=", "10", ",", "grp_name", "=", "None", ")", ":", "if", "grp_name", "is", "None", ":", "grp_name", "=", "'/aws/lambda/%s'", "%", "self", ".", "config", ".", "func_name", "logger", ".", "debug", "...
40.111111
0.001803
def load_next(mod, altmod, name, buf): """ mod, name, buf = load_next(mod, altmod, name, buf) altmod is either None or same as mod """ if len(name) == 0: # completely empty module name should only happen in # 'from . import' (or '__import__("")') return mod, None, buf ...
[ "def", "load_next", "(", "mod", ",", "altmod", ",", "name", ",", "buf", ")", ":", "if", "len", "(", "name", ")", "==", "0", ":", "# completely empty module name should only happen in", "# 'from . import' (or '__import__(\"\")')", "return", "mod", ",", "None", ",",...
23.567568
0.001101
def _init_item_marks(item_marks): """Initialize the makred item dict.""" if isinstance(item_marks, dict): return item_marks if item_marks: return {item_id:'>' for item_id in item_marks}
[ "def", "_init_item_marks", "(", "item_marks", ")", ":", "if", "isinstance", "(", "item_marks", ",", "dict", ")", ":", "return", "item_marks", "if", "item_marks", ":", "return", "{", "item_id", ":", "'>'", "for", "item_id", "in", "item_marks", "}" ]
38
0.012876
def get_file(self, *args, **kwargs): """See :func:`get_file`""" return get_file(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "get_file", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "get_file", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(", ")" ]
47
0.013986
def calculate_stats(data_list, stats_to_calculate=['mean', 'std'], percentiles_to_calculate=[]): """ Calculate statistics for given data. :param list data_list: List of floats :param list stats_to_calculate: List of strings with statistics to calculate. Supported stats are defined in constant stats_to_numpy_me...
[ "def", "calculate_stats", "(", "data_list", ",", "stats_to_calculate", "=", "[", "'mean'", ",", "'std'", "]", ",", "percentiles_to_calculate", "=", "[", "]", ")", ":", "stats_to_numpy_method_map", "=", "{", "'mean'", ":", "numpy", ".", "mean", ",", "'avg'", ...
43.151515
0.013049