text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def ttm(self, V, mode=None, transp=False, without=False): """ Tensor times matrix product Parameters ---------- V : M x N array_like or list of M_i x N_i array_likes Matrix or list of matrices for which the tensor times matrix products should be performed...
[ "def", "ttm", "(", "self", ",", "V", ",", "mode", "=", "None", ",", "transp", "=", "False", ",", "without", "=", "False", ")", ":", "if", "mode", "is", "None", ":", "mode", "=", "range", "(", "self", ".", "ndim", ")", "if", "isinstance", "(", "...
34.592593
0.001562
def pickFilepath( self ): """ Picks the image file to use for this icon path. """ filepath = QFileDialog.getOpenFileName( self, 'Select Image File', QDir.currentPath(), ...
[ "def", "pickFilepath", "(", "self", ")", ":", "filepath", "=", "QFileDialog", ".", "getOpenFileName", "(", "self", ",", "'Select Image File'", ",", "QDir", ".", "currentPath", "(", ")", ",", "self", ".", "fileTypes", "(", ")", ")", "if", "type", "(", "fi...
37.071429
0.016917
def create_tar(tar_filename, files, config_dir, config_files): ''' Create a tar file with a given set of files ''' with contextlib.closing(tarfile.open(tar_filename, 'w:gz', dereference=True)) as tar: for filename in files: if os.path.isfile(filename): tar.add(filename, arcname=os.path.basenam...
[ "def", "create_tar", "(", "tar_filename", ",", "files", ",", "config_dir", ",", "config_files", ")", ":", "with", "contextlib", ".", "closing", "(", "tarfile", ".", "open", "(", "tar_filename", ",", "'w:gz'", ",", "dereference", "=", "True", ")", ")", "as"...
38.454545
0.012687
def stop_times(self): """Return all stop_times for this agency.""" stop_times = set() for trip in self.trips(): stop_times |= trip.stop_times() return stop_times
[ "def", "stop_times", "(", "self", ")", ":", "stop_times", "=", "set", "(", ")", "for", "trip", "in", "self", ".", "trips", "(", ")", ":", "stop_times", "|=", "trip", ".", "stop_times", "(", ")", "return", "stop_times" ]
29.666667
0.010929
def _build_file_writer(cls, session: AppSession): '''Create the File Writer. Returns: FileWriter: An instance of :class:`.writer.BaseFileWriter`. ''' args = session.args if args.delete_after: return session.factory.new('FileWriter') # is a NullWriter ...
[ "def", "_build_file_writer", "(", "cls", ",", "session", ":", "AppSession", ")", ":", "args", "=", "session", ".", "args", "if", "args", ".", "delete_after", ":", "return", "session", ".", "factory", ".", "new", "(", "'FileWriter'", ")", "# is a NullWriter",...
34.342466
0.000775
def is_kdump_iommu_enabled(self): """ Does any kernel have 'intel_iommu=on' set? Returns: (bool): ``True`` when 'intel_iommu=on' is set, otherwise returns ``False`` """ for line in self._boot_entries: if line.cmdline and IOMMU in line.cmdline: ...
[ "def", "is_kdump_iommu_enabled", "(", "self", ")", ":", "for", "line", "in", "self", ".", "_boot_entries", ":", "if", "line", ".", "cmdline", "and", "IOMMU", "in", "line", ".", "cmdline", ":", "return", "True", "return", "False" ]
28.916667
0.00838
def p_term_mult_factor(self, args): ' term ::= term MULT_OP factor ' op = 'multiply' if args[1].attr == '*' else 'divide' return AST(op, [args[0], args[2]])
[ "def", "p_term_mult_factor", "(", "self", ",", "args", ")", ":", "op", "=", "'multiply'", "if", "args", "[", "1", "]", ".", "attr", "==", "'*'", "else", "'divide'", "return", "AST", "(", "op", ",", "[", "args", "[", "0", "]", ",", "args", "[", "2...
44.25
0.011111
def attendee_data(request, form, user_id=None): ''' Lists attendees for a given product/category selection along with profile data.''' status_display = { commerce.Cart.STATUS_ACTIVE: "Unpaid", commerce.Cart.STATUS_PAID: "Paid", commerce.Cart.STATUS_RELEASED: "Refunded", } o...
[ "def", "attendee_data", "(", "request", ",", "form", ",", "user_id", "=", "None", ")", ":", "status_display", "=", "{", "commerce", ".", "Cart", ".", "STATUS_ACTIVE", ":", "\"Unpaid\"", ",", "commerce", ".", "Cart", ".", "STATUS_PAID", ":", "\"Paid\"", ","...
33.460606
0.000704
def add_indented_commands(self, commands, *, heading, max_size=None): """Indents a list of commands after the specified heading. The formatting is added to the :attr:`paginator`. The default implementation is the command name indented by :attr:`indent` spaces, padded to ``max_size`` fo...
[ "def", "add_indented_commands", "(", "self", ",", "commands", ",", "*", ",", "heading", ",", "max_size", "=", "None", ")", ":", "if", "not", "commands", ":", "return", "self", ".", "paginator", ".", "add_line", "(", "heading", ")", "max_size", "=", "max_...
39.6
0.002113
def gMagnitudeError(G): """ Calculate the single-field-of-view-transit photometric standard error in the G band as a function of G. A 20% margin is included. Parameters ---------- G - Value(s) of G-band magnitude. Returns ------- The G band photometric standard error in units of magnitude. "...
[ "def", "gMagnitudeError", "(", "G", ")", ":", "z", "=", "calcZ", "(", "G", ")", "return", "1.0e-3", "*", "sqrt", "(", "0.04895", "*", "z", "*", "z", "+", "1.8633", "*", "z", "+", "0.0001985", ")", "*", "_scienceMargin" ]
23.117647
0.01467
def load_bernoulli_mnist_dataset(directory, split_name): """Returns Hugo Larochelle's binary static MNIST tf.data.Dataset.""" amat_file = download(directory, FILE_TEMPLATE.format(split=split_name)) dataset = tf.data.TextLineDataset(amat_file) str_to_arr = lambda string: np.array([c == b"1" for c in string.split...
[ "def", "load_bernoulli_mnist_dataset", "(", "directory", ",", "split_name", ")", ":", "amat_file", "=", "download", "(", "directory", ",", "FILE_TEMPLATE", ".", "format", "(", "split", "=", "split_name", ")", ")", "dataset", "=", "tf", ".", "data", ".", "Tex...
45.916667
0.014235
def handle_annotation_list(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle statements like ``DEFINE ANNOTATION X AS LIST {"Y","Z", ...}``. :raises: RedefinedAnnotationError """ annotation = tokens['name'] self.raise_for_redefined_annotation(line,...
[ "def", "handle_annotation_list", "(", "self", ",", "line", ":", "str", ",", "position", ":", "int", ",", "tokens", ":", "ParseResults", ")", "->", "ParseResults", ":", "annotation", "=", "tokens", "[", "'name'", "]", "self", ".", "raise_for_redefined_annotatio...
47.222222
0.009238
def find(C, node, path, namespaces=None, extensions=None, smart_strings=True, **args): """use Element.xpath() rather than Element.find() in order to normalize the interface""" xp = node.xpath( path, namespaces=namespaces or C.NS, extensions=extensions, ...
[ "def", "find", "(", "C", ",", "node", ",", "path", ",", "namespaces", "=", "None", ",", "extensions", "=", "None", ",", "smart_strings", "=", "True", ",", "*", "*", "args", ")", ":", "xp", "=", "node", ".", "xpath", "(", "path", ",", "namespaces", ...
38.454545
0.009238
def n_chunks(self, chunksize, stride=1, skip=0): """ how many chunks an iterator of this sourcde will output, starting (eg. after calling reset()) Parameters ---------- chunksize stride skip """ if chunksize != 0: chunksize = float(chunksize) ...
[ "def", "n_chunks", "(", "self", ",", "chunksize", ",", "stride", "=", "1", ",", "skip", "=", "0", ")", ":", "if", "chunksize", "!=", "0", ":", "chunksize", "=", "float", "(", "chunksize", ")", "chunks", "=", "int", "(", "sum", "(", "(", "ceil", "...
34
0.009542
def get_metrics(awsclient, name): """Print out cloudformation metrics for a lambda function. :param awsclient :param name: name of the lambda function :return: exit_code """ metrics = ['Duration', 'Errors', 'Invocations', 'Throttles'] client_cw = awsclient.get_client('cloudwatch') for m...
[ "def", "get_metrics", "(", "awsclient", ",", "name", ")", ":", "metrics", "=", "[", "'Duration'", ",", "'Errors'", ",", "'Invocations'", ",", "'Throttles'", "]", "client_cw", "=", "awsclient", ".", "get_client", "(", "'cloudwatch'", ")", "for", "metric", "in...
32.59375
0.001862
def _matches_patterns(path, patterns): """Given a list of patterns, returns a if a path matches any pattern.""" for glob in patterns: try: if PurePath(path).match(glob): return True except TypeError: pass return False
[ "def", "_matches_patterns", "(", "path", ",", "patterns", ")", ":", "for", "glob", "in", "patterns", ":", "try", ":", "if", "PurePath", "(", "path", ")", ".", "match", "(", "glob", ")", ":", "return", "True", "except", "TypeError", ":", "pass", "return...
34.333333
0.009464
def required_opts(opt, parser, opt_list, required_by=None): """Check that all the opts are defined Parameters ---------- opt : object Result of option parsing parser : object OptionParser instance. opt_list : list of strings required_by : string, optional the option ...
[ "def", "required_opts", "(", "opt", ",", "parser", ",", "opt_list", ",", "required_by", "=", "None", ")", ":", "for", "name", "in", "opt_list", ":", "attr", "=", "name", "[", "2", ":", "]", ".", "replace", "(", "'-'", ",", "'_'", ")", "if", "not", ...
33.35
0.001458
def split(ol,value,**kwargs): ''' ol = ['a',1,'a',2,'a',3,'a',4,'a'] split(ol,'a') split(ol,'a',whiches=[0]) split(ol,'a',whiches=[1]) split(ol,'a',whiches=[2]) split(ol,'a',whiches=[0,2]) ol = [1,'a',2,'a',3,'a',4] split(ol,'a') split('x=bcdse...
[ "def", "split", "(", "ol", ",", "value", ",", "*", "*", "kwargs", ")", ":", "if", "(", "'whiches'", "in", "kwargs", ")", ":", "whiches", "=", "kwargs", "[", "'whiches'", "]", "else", ":", "whiches", "=", "None", "indexes", "=", "indexes_all", "(", ...
25.272727
0.011547
def start(self, timeout=None): """Start callbacks""" self._running = True if timeout is None: timeout = self.calculate_next_run() self.io_loop.add_timeout(timeout, self._run)
[ "def", "start", "(", "self", ",", "timeout", "=", "None", ")", ":", "self", ".", "_running", "=", "True", "if", "timeout", "is", "None", ":", "timeout", "=", "self", ".", "calculate_next_run", "(", ")", "self", ".", "io_loop", ".", "add_timeout", "(", ...
26.625
0.009091
def create_logger(app): """Creates a logger for the given application. This logger works similar to a regular Python logger but changes the effective logging level based on the application's debug flag. Furthermore this function also removes all attached handlers in case there was a logger with th...
[ "def", "create_logger", "(", "app", ")", ":", "Logger", "=", "getLoggerClass", "(", ")", "class", "DebugLogger", "(", "Logger", ")", ":", "def", "getEffectiveLevel", "(", "x", ")", ":", "if", "x", ".", "level", "==", "0", "and", "app", ".", "debug", ...
35.793103
0.000938
def coherence(stream_in, stations=['all'], clip=False): """ Determine the average network coherence of a given template or detection. You will want your stream to contain only signal as noise will reduce the coherence (assuming it is incoherent random noise). :type stream_in: obspy.core.stream.Str...
[ "def", "coherence", "(", "stream_in", ",", "stations", "=", "[", "'all'", "]", ",", "clip", "=", "False", ")", ":", "stream", "=", "stream_in", ".", "copy", "(", ")", "# Copy the data before we remove stations", "# First check that all channels in stream have data of ...
44.444444
0.000408
def read(self, **keys): """ read data from this HDU By default, all data are read. send columns= and rows= to select subsets of the data. Table data are read into a recarray; use read_column() to get a single column as an ordinary array. You can alternatively use slice...
[ "def", "read", "(", "self", ",", "*", "*", "keys", ")", ":", "columns", "=", "keys", ".", "get", "(", "'columns'", ",", "None", ")", "rows", "=", "keys", ".", "get", "(", "'rows'", ",", "None", ")", "if", "columns", "is", "not", "None", ":", "i...
34.444444
0.001255
def interconnect_all(self): """Propagate dependencies for provided instances""" for dep in topologically_sorted(self._provides): if hasattr(dep, '__injections__') and not hasattr(dep, '__injections_source__'): self.inject(dep)
[ "def", "interconnect_all", "(", "self", ")", ":", "for", "dep", "in", "topologically_sorted", "(", "self", ".", "_provides", ")", ":", "if", "hasattr", "(", "dep", ",", "'__injections__'", ")", "and", "not", "hasattr", "(", "dep", ",", "'__injections_source_...
53.2
0.011111
def force_directed(self,defaultEdgeWeight=None,defaultNodeMass=None,\ defaultSpringCoefficient=None,defaultSpringLength=None,EdgeAttribute=None,\ isDeterministic=None,maxWeightCutoff=None,minWeightCutoff=None,network=None,\ NodeAttribute=None,nodeList=None,numIterations=None,singlePartition=None,\ Type=None,ver...
[ "def", "force_directed", "(", "self", ",", "defaultEdgeWeight", "=", "None", ",", "defaultNodeMass", "=", "None", ",", "defaultSpringCoefficient", "=", "None", ",", "defaultSpringLength", "=", "None", ",", "EdgeAttribute", "=", "None", ",", "isDeterministic", "=",...
58.403509
0.034564
def check_submission(self, submission_string, submission_id): """ Function DocString """ if self.question_upload_type == STRING: return self.question_answer_string.lower().replace(' ', '') == submission_string.lower().replace(' ', '') else: raise Excep...
[ "def", "check_submission", "(", "self", ",", "submission_string", ",", "submission_id", ")", ":", "if", "self", ".", "question_upload_type", "==", "STRING", ":", "return", "self", ".", "question_answer_string", ".", "lower", "(", ")", ".", "replace", "(", "' '...
43.25
0.008499
def get_real_related(self, id_equip): """ Find reals related with equipment :param id_equip: Identifier of equipment :return: Following dictionary: :: {'vips': [{'port_real': < port_real >, 'server_pool_member_id': < server_pool_member_id >, ...
[ "def", "get_real_related", "(", "self", ",", "id_equip", ")", ":", "url", "=", "'equipamento/get_real_related/'", "+", "str", "(", "id_equip", ")", "+", "'/'", "code", ",", "xml", "=", "self", ".", "submit", "(", "None", ",", "'GET'", ",", "url", ")", ...
32.448276
0.002064
def _get_named_graph(context): """ Returns the named graph for this context. """ if context is None: return None return models.NamedGraph.objects.get_or_create(identifier=context.identifier)[0]
[ "def", "_get_named_graph", "(", "context", ")", ":", "if", "context", "is", "None", ":", "return", "None", "return", "models", ".", "NamedGraph", ".", "objects", ".", "get_or_create", "(", "identifier", "=", "context", ".", "identifier", ")", "[", "0", "]"...
26.875
0.009009
def parse_schema_files(files): """ Parse a list of SQL files and return a dictionary of valid schema files where each key is a valid schema file and the corresponding value is a tuple containing the source and the target schema. """ f_dict = {} for f in files: root, ext = os.path.spl...
[ "def", "parse_schema_files", "(", "files", ")", ":", "f_dict", "=", "{", "}", "for", "f", "in", "files", ":", "root", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "f", ")", "if", "ext", "!=", "\".sql\"", ":", "continue", "vto", ",", ...
33.75
0.001802
def reference_to_greatcircle(reference_frame, greatcircle_frame): """Convert a reference coordinate to a great circle frame.""" # Define rotation matrices along the position angle vector, and # relative to the origin. pole = greatcircle_frame.pole.transform_to(coord.ICRS) ra0 = greatcircle_frame.ra...
[ "def", "reference_to_greatcircle", "(", "reference_frame", ",", "greatcircle_frame", ")", ":", "# Define rotation matrices along the position angle vector, and", "# relative to the origin.", "pole", "=", "greatcircle_frame", ".", "pole", ".", "transform_to", "(", "coord", ".", ...
36.297297
0.002175
def get_kde_scatter(self, xax="area_um", yax="deform", positions=None, kde_type="histogram", kde_kwargs={}, xscale="linear", yscale="linear"): """Evaluate the kernel density estimate for scatter plots Parameters ---------- xax: str ...
[ "def", "get_kde_scatter", "(", "self", ",", "xax", "=", "\"area_um\"", ",", "yax", "=", "\"deform\"", ",", "positions", "=", "None", ",", "kde_type", "=", "\"histogram\"", ",", "kde_kwargs", "=", "{", "}", ",", "xscale", "=", "\"linear\"", ",", "yscale", ...
34.836066
0.001831
def _on_enter(self, event): """Creates a delayed callback for the :obj:`<Enter>` event.""" self._id = self.master.after(int(self._timeout * 1000), func=self.show)
[ "def", "_on_enter", "(", "self", ",", "event", ")", ":", "self", ".", "_id", "=", "self", ".", "master", ".", "after", "(", "int", "(", "self", ".", "_timeout", "*", "1000", ")", ",", "func", "=", "self", ".", "show", ")" ]
58.666667
0.011236
def servers_update_addresses(request, servers, all_tenants=False): """Retrieve servers networking information from Neutron if enabled. Should be used when up to date networking information is required, and Nova's networking info caching mechanism is not fast enough. """ # NOTE(e0ne): we don'...
[ "def", "servers_update_addresses", "(", "request", ",", "servers", ",", "all_tenants", "=", "False", ")", ":", "# NOTE(e0ne): we don't need to call neutron if we have no instances", "if", "not", "servers", ":", "return", "# Get all (filtered for relevant servers) information from...
37.378788
0.000395
def pixels_from_coordinates(lat, lon, max_y, max_x): """ Return the 2 matrix with lat and lon of each pixel. Keyword arguments: lat -- A latitude matrix lon -- A longitude matrix max_y -- The max vertical pixels amount of an orthorectified image. max_x -- The max horizontal pixels amount of...
[ "def", "pixels_from_coordinates", "(", "lat", ",", "lon", ",", "max_y", ",", "max_x", ")", ":", "# The degrees by pixel of the orthorectified image.", "x_ratio", ",", "y_ratio", "=", "max_x", "/", "360.", ",", "max_y", "/", "180.", "x", ",", "y", "=", "np", ...
35.5625
0.001712
def put(contract_name, abi): ''' save the contract's ABI :param contract_name: string - name of the contract :param abi: the contract's abi JSON file :return: None, None if saved okay None, error is an error ''' if not Catalog.path: ...
[ "def", "put", "(", "contract_name", ",", "abi", ")", ":", "if", "not", "Catalog", ".", "path", ":", "return", "None", ",", "\"path to catalog must be set before saving to it\"", "if", "not", "contract_name", ":", "return", "None", ",", "\"contract name must be provi...
32.2
0.002413
def log_cef(name, severity=logging.INFO, env=None, username='none', signature=None, **kwargs): """ Wraps cef logging function so we don't need to pass in the config dictionary every time. See bug 707060. ``env`` can be either a request object or just the request.META dictionary. """ ...
[ "def", "log_cef", "(", "name", ",", "severity", "=", "logging", ".", "INFO", ",", "env", "=", "None", ",", "username", "=", "'none'", ",", "signature", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cef_logger", "=", "commonware", ".", "log", ".", ...
36.538462
0.000684
def create_branch(profile, name, branch_off): """Create a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. name ...
[ "def", "create_branch", "(", "profile", ",", "name", ",", "branch_off", ")", ":", "branch_off_sha", "=", "get_branch_sha", "(", "profile", ",", "branch_off", ")", "ref", "=", "\"heads/\"", "+", "name", "data", "=", "refs", ".", "create_ref", "(", "profile", ...
26.875
0.001497
def needs_remesh(self): """ whether the star needs to be re-meshed (for any reason) """ # TODO: may be able to get away with removing the features check and just doing for pulsations, etc? # TODO: what about dpdt, deccdt, dincldt, etc? return len(self.features) > 0 or sel...
[ "def", "needs_remesh", "(", "self", ")", ":", "# TODO: may be able to get away with removing the features check and just doing for pulsations, etc?", "# TODO: what about dpdt, deccdt, dincldt, etc?", "return", "len", "(", "self", ".", "features", ")", ">", "0", "or", "self", "....
55
0.01023
def info_file(self): """Grab sources from .info file and store filename """ sources = SBoGrep(self.prgnam).source().split() for source in sources: self.sbo_sources.append(source.split("/")[-1])
[ "def", "info_file", "(", "self", ")", ":", "sources", "=", "SBoGrep", "(", "self", ".", "prgnam", ")", ".", "source", "(", ")", ".", "split", "(", ")", "for", "source", "in", "sources", ":", "self", ".", "sbo_sources", ".", "append", "(", "source", ...
38.666667
0.008439
def autolight(scene): """ Generate a list of lights for a scene that looks decent. Parameters -------------- scene : trimesh.Scene Scene with geometry Returns -------------- lights : [Light] List of light objects transforms : (len(lights), 4, 4) float Transformati...
[ "def", "autolight", "(", "scene", ")", ":", "# create two default point lights", "lights", "=", "[", "PointLight", "(", ")", ",", "PointLight", "(", ")", "]", "# create two translation matrices for bounds corners", "transforms", "=", "[", "transformations", ".", "tran...
24.12
0.001595
def request(self, filter=None, stream_name=None, start_time=None, stop_time=None): """Creates a subscription for notifications from the server. *filter* specifies the subset of notifications to receive (by default all notificaitons are received) :seealso: :ref:`filter_params` ...
[ "def", "request", "(", "self", ",", "filter", "=", "None", ",", "stream_name", "=", "None", ",", "start_time", "=", "None", ",", "stop_time", "=", "None", ")", ":", "node", "=", "new_ele_ns", "(", "\"create-subscription\"", ",", "NETCONF_NOTIFICATION_NS", ")...
41.421053
0.002483
def move_to_origin(components): """ Components are positioned relative to their container. Use this method to position the bottom-left corner of the components at the origin. """ for component in components: if isinstance(component, Ellipse): component.x_origin = componen...
[ "def", "move_to_origin", "(", "components", ")", ":", "for", "component", "in", "components", ":", "if", "isinstance", "(", "component", ",", "Ellipse", ")", ":", "component", ".", "x_origin", "=", "component", ".", "e_width", "component", ".", "y_origin", "...
38.5
0.012673
def create_vm(access_token, subscription_id, resource_group, vm_name, vm_size, publisher, offer, sku, version, nic_id, location, storage_type='Standard_LRS', osdisk_name=None, username='azure', password=None, public_key=None): '''Create a new Azure virtual machine. Args: acc...
[ "def", "create_vm", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "vm_name", ",", "vm_size", ",", "publisher", ",", "offer", ",", "sku", ",", "version", ",", "nic_id", ",", "location", ",", "storage_type", "=", "'Standard_LRS'", ",",...
48.791045
0.001799
def rmse_and_unc(values_array, true_values): r"""Calculate the root meet squared error and its numerical uncertainty. With a reasonably large number of values in values_list the uncertainty on sq_errors should be approximately normal (from the central limit theorem). Uncertainties are calculated vi...
[ "def", "rmse_and_unc", "(", "values_array", ",", "true_values", ")", ":", "assert", "true_values", ".", "shape", "==", "(", "values_array", ".", "shape", "[", "1", "]", ",", ")", "errors", "=", "values_array", "-", "true_values", "[", "np", ".", "newaxis",...
38.382353
0.000747
async def create_guild(self, name, region=None, icon=None): """|coro| Creates a :class:`.Guild`. Bot accounts in more than 10 guilds are not allowed to create guilds. Parameters ---------- name: :class:`str` The name of the guild. region: :class:`Vo...
[ "async", "def", "create_guild", "(", "self", ",", "name", ",", "region", "=", "None", ",", "icon", "=", "None", ")", ":", "if", "icon", "is", "not", "None", ":", "icon", "=", "utils", ".", "_bytes_to_base64_data", "(", "icon", ")", "if", "region", "i...
30.365854
0.002335
def show_pricing(kwargs=None, call=None): ''' Show pricing for a particular profile. This is only an estimate, based on unofficial pricing sources. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt-cloud -f show_pricing my-linode-config profile=my-linode-profile '...
[ "def", "show_pricing", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "raise", "SaltCloudException", "(", "'The show_instance action must be called with -f or --function.'", ")", "profile", "=", "__opts__", "["...
30
0.001502
def cholesky(A, sparse=True, verbose=True): """ Choose the best possible cholesky factorizor. if possible, import the Scikit-Sparse sparse Cholesky method. Permutes the output L to ensure A = L.H . L otherwise defaults to numpy's non-sparse version Parameters ---------- A : array-like...
[ "def", "cholesky", "(", "A", ",", "sparse", "=", "True", ",", "verbose", "=", "True", ")", ":", "if", "SKSPIMPORT", ":", "A", "=", "sp", ".", "sparse", ".", "csc_matrix", "(", "A", ")", "try", ":", "F", "=", "spcholesky", "(", "A", ")", "# permut...
29.586207
0.001692
def intelligently_find_filenames(line, TeX=False, ext=False, commas_okay=False): """Intelligently find filenames. Find the filename in the line. We don't support all filenames! Just eps and ps for now. :param: line (string): the line we want to get a filename out of ...
[ "def", "intelligently_find_filenames", "(", "line", ",", "TeX", "=", "False", ",", "ext", "=", "False", ",", "commas_okay", "=", "False", ")", ":", "files_included", "=", "[", "'ERROR'", "]", "if", "commas_okay", ":", "valid_for_filename", "=", "'\\\\s*[A-Za-z...
36.15625
0.000841
def swap_yaml_string(file_path, swaps): """ Swap a string in a yaml file without touching the existing formatting. """ original_file = file_to_string(file_path) new_file = original_file changed = False for item in swaps: match = re.compile(r'(?<={0}: )(["\']?)(.*)\1'.format(item[0])...
[ "def", "swap_yaml_string", "(", "file_path", ",", "swaps", ")", ":", "original_file", "=", "file_to_string", "(", "file_path", ")", "new_file", "=", "original_file", "changed", "=", "False", "for", "item", "in", "swaps", ":", "match", "=", "re", ".", "compil...
26.35
0.001832
def _get_attr_by_tag(obj, tag, attr_name): """Get attribute from an object via a string tag. Parameters ---------- obj : object from which to get the attribute attr_name : str Unmodified name of the attribute to be found. The actual attribute that is returned may be modified be 'ta...
[ "def", "_get_attr_by_tag", "(", "obj", ",", "tag", ",", "attr_name", ")", ":", "attr_name", "=", "_TAG_ATTR_MODIFIERS", "[", "tag", "]", "+", "attr_name", "return", "getattr", "(", "obj", ",", "attr_name", ")" ]
32.052632
0.001595
def build_paths(self, end_entity_cert): """ Builds a list of ValidationPath objects from a certificate in the operating system trust store to the end-entity certificate :param end_entity_cert: A byte string of a DER or PEM-encoded X.509 certificate, or an instanc...
[ "def", "build_paths", "(", "self", ",", "end_entity_cert", ")", ":", "if", "not", "isinstance", "(", "end_entity_cert", ",", "byte_cls", ")", "and", "not", "isinstance", "(", "end_entity_cert", ",", "x509", ".", "Certificate", ")", ":", "raise", "TypeError", ...
36.666667
0.00166
def get_identity(context, prefix=None, identity_func=None, user=None): """ Get the identity of a logged in user from a template context. The `prefix` argument is used to provide different identities to different analytics services. The `identity_func` argument is a function that returns the identi...
[ "def", "get_identity", "(", "context", ",", "prefix", "=", "None", ",", "identity_func", "=", "None", ",", "user", "=", "None", ")", ":", "if", "prefix", "is", "not", "None", ":", "try", ":", "return", "context", "[", "'%s_identity'", "%", "prefix", "]...
34.1
0.000951
def visibleCount(self): """ Returns the number of visible items in this list. :return <int> """ return sum(int(not self.item(i).isHidden()) for i in range(self.count()))
[ "def", "visibleCount", "(", "self", ")", ":", "return", "sum", "(", "int", "(", "not", "self", ".", "item", "(", "i", ")", ".", "isHidden", "(", ")", ")", "for", "i", "in", "range", "(", "self", ".", "count", "(", ")", ")", ")" ]
31.714286
0.017544
def delete_stack(name=None, poll=0, timeout=60, profile=None): ''' Delete a stack (heat stack-delete) name Name of the stack poll Poll and report events until stack complete timeout Stack creation timeout in minute profile Profile to use CLI Examples: ...
[ "def", "delete_stack", "(", "name", "=", "None", ",", "poll", "=", "0", ",", "timeout", "=", "60", ",", "profile", "=", "None", ")", ":", "h_client", "=", "_auth", "(", "profile", ")", "ret", "=", "{", "'result'", ":", "True", ",", "'comment'", ":"...
27.75
0.002175
def public(self): """True if the Slot is public.""" return bool(lib.EnvSlotPublicP(self._env, self._cls, self._name))
[ "def", "public", "(", "self", ")", ":", "return", "bool", "(", "lib", ".", "EnvSlotPublicP", "(", "self", ".", "_env", ",", "self", ".", "_cls", ",", "self", ".", "_name", ")", ")" ]
43.666667
0.015038
def _all_dims(x, default_dims=None): """Returns a list of dims in x or default_dims if the rank is unknown.""" if x.get_shape().ndims is not None: return list(xrange(x.get_shape().ndims)) else: return default_dims
[ "def", "_all_dims", "(", "x", ",", "default_dims", "=", "None", ")", ":", "if", "x", ".", "get_shape", "(", ")", ".", "ndims", "is", "not", "None", ":", "return", "list", "(", "xrange", "(", "x", ".", "get_shape", "(", ")", ".", "ndims", ")", ")"...
37
0.017621
def get_app_hostname(): """Return hostname of a running Endpoints service. Returns hostname of an running Endpoints API. It can be 1) "localhost:PORT" if running on development server, or 2) "app_id.appspot.com" if running on external app engine prod, or "app_id.googleplex.com" if running as Google first-par...
[ "def", "get_app_hostname", "(", ")", ":", "if", "not", "is_running_on_app_engine", "(", ")", "or", "is_running_on_localhost", "(", ")", ":", "return", "None", "app_id", "=", "app_identity", ".", "get_application_id", "(", ")", "prefix", "=", "get_hostname_prefix",...
30
0.011136
def quantile_1D(data, weights, quantile): """ Compute the weighted quantile of a 1D numpy array. Parameters ---------- data : ndarray Input array (one dimension). weights : ndarray Array with the weights of the same size of `data`. quantile : float Quantile to comput...
[ "def", "quantile_1D", "(", "data", ",", "weights", ",", "quantile", ")", ":", "# Check the data", "if", "not", "isinstance", "(", "data", ",", "np", ".", "matrix", ")", ":", "data", "=", "np", ".", "asarray", "(", "data", ")", "if", "not", "isinstance"...
33.045455
0.001336
def write_field_report(odb, path, label, argiope_class, variable, instance, output_position, step = -1, frame = -1, sortItem='Node Label'): """ Writes a field report and rewrites it in a cleaner format. """ stepKeys = get_steps(odb) step = xrange(len(stepKeys))[step] frame = xrange(g...
[ "def", "write_field_report", "(", "odb", ",", "path", ",", "label", ",", "argiope_class", ",", "variable", ",", "instance", ",", "output_position", ",", "step", "=", "-", "1", ",", "frame", "=", "-", "1", ",", "sortItem", "=", "'Node Label'", ")", ":", ...
34.711864
0.036562
def arrange_all(self): """ Arrange the components of the node using Graphviz. """ # FIXME: Circular reference avoidance. import godot.dot_data_parser import godot.graph graph = godot.graph.Graph( ID="g", directed=True ) self.conn = "->" graph.edges.append...
[ "def", "arrange_all", "(", "self", ")", ":", "# FIXME: Circular reference avoidance.", "import", "godot", ".", "dot_data_parser", "import", "godot", ".", "graph", "graph", "=", "godot", ".", "graph", ".", "Graph", "(", "ID", "=", "\"g\"", ",", "directed", "=",...
31.956522
0.014531
def html_temp_launch(html): """given text, make it a temporary HTML file and launch it.""" fname = tempfile.gettempdir()+"/swhlab/temp.html" with open(fname,'w') as f: f.write(html) webbrowser.open(fname)
[ "def", "html_temp_launch", "(", "html", ")", ":", "fname", "=", "tempfile", ".", "gettempdir", "(", ")", "+", "\"/swhlab/temp.html\"", "with", "open", "(", "fname", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "html", ")", "webbrowser", "."...
37.166667
0.008772
def get_sitetree(self, alias): """Gets site tree items from the given site tree. Caches result to dictionary. Returns (tree alias, tree items) tuple. :param str|unicode alias: :rtype: tuple """ cache_ = self.cache get_cache_entry = cache_.get_entry ...
[ "def", "get_sitetree", "(", "self", ",", "alias", ")", ":", "cache_", "=", "self", ".", "cache", "get_cache_entry", "=", "cache_", ".", "get_entry", "set_cache_entry", "=", "cache_", ".", "set_entry", "caching_required", "=", "False", "if", "not", "self", "....
35.682353
0.001604
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ COEFFS = self.COEFFS[imt] R = self._compute_term_r(COEFFS, ru...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "COEFFS", "=", "self", ".", "COEFFS", "[", "imt", "]", "R", "=", "self", ".", "_compute_term_r", "(", "COEFFS", ",", "rup", ...
29.965517
0.00223
def emit_children(self, node): """Emit all the children of a node.""" return "".join([self.emit_node(child) for child in node.children])
[ "def", "emit_children", "(", "self", ",", "node", ")", ":", "return", "\"\"", ".", "join", "(", "[", "self", ".", "emit_node", "(", "child", ")", "for", "child", "in", "node", ".", "children", "]", ")" ]
50
0.013158
def __parse_world( world, radius=None, species_list=None, max_count=None, predicator=None): """ Private function to parse world. Return infomation about particles (name, coordinates and particle size) for each species. """ from ecell4_base.core import Species if species_list is...
[ "def", "__parse_world", "(", "world", ",", "radius", "=", "None", ",", "species_list", "=", "None", ",", "max_count", "=", "None", ",", "predicator", "=", "None", ")", ":", "from", "ecell4_base", ".", "core", "import", "Species", "if", "species_list", "is"...
33.211538
0.000562
def subscription_path(cls, project, incident, subscription): """Return a fully-qualified subscription string.""" return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}/subscriptions/{subscription}", project=project, incident=incident, ...
[ "def", "subscription_path", "(", "cls", ",", "project", ",", "incident", ",", "subscription", ")", ":", "return", "google", ".", "api_core", ".", "path_template", ".", "expand", "(", "\"projects/{project}/incidents/{incident}/subscriptions/{subscription}\"", ",", "proje...
44.875
0.008197
def _keep_analyses( analyses, keep_forms, target_forms ): ''' Filters the given list of *analyses* by morphological forms: deletes analyses that are listed in *target_forms*, but not in *keep_forms*. ''' to_delete = [] for aid, analysis in enumerate(analyses): delete = False ...
[ "def", "_keep_analyses", "(", "analyses", ",", "keep_forms", ",", "target_forms", ")", ":", "to_delete", "=", "[", "]", "for", "aid", ",", "analysis", "in", "enumerate", "(", "analyses", ")", ":", "delete", "=", "False", "for", "target", "in", "target_form...
37.5625
0.017857
def new_tracer(self, io_loop=None): """ Create a new Jaeger Tracer based on the passed `jaeger_client.Config`. Does not set `opentracing.tracer` global variable. """ channel = self._create_local_agent_channel(io_loop=io_loop) sampler = self.sampler if not sampler:...
[ "def", "new_tracer", "(", "self", ",", "io_loop", "=", "None", ")", ":", "channel", "=", "self", ".", "_create_local_agent_channel", "(", "io_loop", "=", "io_loop", ")", "sampler", "=", "self", ".", "sampler", "if", "not", "sampler", ":", "sampler", "=", ...
36.891304
0.001148
def digit(uni_char, default_value=None): """Returns the digit value assigned to the Unicode character uni_char as integer. If no such value is defined, default is returned, or, if not given, ValueError is raised.""" uni_char = unicod(uni_char) # Force to Unicode. if default_value is not None: ...
[ "def", "digit", "(", "uni_char", ",", "default_value", "=", "None", ")", ":", "uni_char", "=", "unicod", "(", "uni_char", ")", "# Force to Unicode.", "if", "default_value", "is", "not", "None", ":", "return", "unicodedata", ".", "digit", "(", "uni_char", ","...
46.333333
0.002353
def __run(self): """ The main loop """ already_cleaned = False try: while not self._done_event.is_set(): try: # Wait for an action (blocking) task = self._queue.get(True, self._timeout) if tas...
[ "def", "__run", "(", "self", ")", ":", "already_cleaned", "=", "False", "try", ":", "while", "not", "self", ".", "_done_event", ".", "is_set", "(", ")", ":", "try", ":", "# Wait for an action (blocking)", "task", "=", "self", ".", "_queue", ".", "get", "...
39.5
0.001123
def geocode( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, boundary_rect=None, country_bias=None, ): """ Return a location point by address. :param str query: The address, query or structured query to geocode...
[ "def", "geocode", "(", "self", ",", "query", ",", "exactly_one", "=", "True", ",", "timeout", "=", "DEFAULT_SENTINEL", ",", "boundary_rect", "=", "None", ",", "country_bias", "=", "None", ",", ")", ":", "params", "=", "{", "'text'", ":", "self", ".", "...
38.68
0.002353
def p_namedblock(self, p): 'namedblock : BEGIN COLON ID namedblock_statements END' p[0] = Block(p[4], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_namedblock", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Block", "(", "p", "[", "4", "]", ",", "p", "[", "3", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ",",...
44.25
0.011111
def get_all_without_ethernet(self, start=0, count=-1, filter='', sort=''): """ Gets a paginated collection of logical downlinks without ethernet. The collection is based on optional sorting and filtering and is constrained by start and count parameters. Args: start: ...
[ "def", "get_all_without_ethernet", "(", "self", ",", "start", "=", "0", ",", "count", "=", "-", "1", ",", "filter", "=", "''", ",", "sort", "=", "''", ")", ":", "without_ethernet_client", "=", "ResourceClient", "(", "self", ".", "_connection", ",", "\"/r...
51.538462
0.008059
def _load_cert_chain(self, cert_url, x509_backend=default_backend()): # type: (str, X509Backend) -> Certificate """Loads the certificate chain from the URL. This method loads the certificate chain from the certificate cache. If there is a cache miss, the certificate chain is loa...
[ "def", "_load_cert_chain", "(", "self", ",", "cert_url", ",", "x509_backend", "=", "default_backend", "(", ")", ")", ":", "# type: (str, X509Backend) -> Certificate", "try", ":", "if", "cert_url", "in", "self", ".", "_cert_cache", ":", "return", "self", ".", "_c...
46.054054
0.001724
def _check_stream(stream): '''Check that the stream is a file''' if not isinstance(stream, type(_sys.stderr)): raise TypeError("The stream given ({}) is not a file object.".format(stream))
[ "def", "_check_stream", "(", "stream", ")", ":", "if", "not", "isinstance", "(", "stream", ",", "type", "(", "_sys", ".", "stderr", ")", ")", ":", "raise", "TypeError", "(", "\"The stream given ({}) is not a file object.\"", ".", "format", "(", "stream", ")", ...
50.25
0.009804
def pauli_constraints(X, Y, Z): """Return a set of constraints that define Pauli spin operators. :param X: List of Pauli X operator on sites. :type X: list of :class:`sympy.physics.quantum.operator.HermitianOperator`. :param Y: List of Pauli Y operator on sites. :type Y: list of :class:`sympy.phys...
[ "def", "pauli_constraints", "(", "X", ",", "Y", ",", "Z", ")", ":", "substitutions", "=", "{", "}", "n_vars", "=", "len", "(", "X", ")", "for", "i", "in", "range", "(", "n_vars", ")", ":", "# They square to the identity", "substitutions", "[", "X", "["...
42.25
0.000578
def _format_value(value): """Returns `value` in a format parseable by `parse_value`, or `None`. Simply put, This function ensures that when it returns a string value, the following will hold: parse_value(_format_value(value)) == value Args: value: The value to format. Returns: A string repre...
[ "def", "_format_value", "(", "value", ")", ":", "literal", "=", "repr", "(", "value", ")", "try", ":", "if", "parse_value", "(", "literal", ")", "==", "value", ":", "return", "literal", "except", "SyntaxError", ":", "pass", "return", "None" ]
23.454545
0.013035
def get_default_location(self): """Return the default location. """ res = [] for location in self.distdefault: res.extend(self.get_location(location)) return res
[ "def", "get_default_location", "(", "self", ")", ":", "res", "=", "[", "]", "for", "location", "in", "self", ".", "distdefault", ":", "res", ".", "extend", "(", "self", ".", "get_location", "(", "location", ")", ")", "return", "res" ]
29.571429
0.00939
def to_dense(self): """Convert sparse Dataset to dense matrix.""" if hasattr(self._X_train, 'todense'): self._X_train = self._X_train.todense() self._X_test = self._X_test.todense()
[ "def", "to_dense", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "_X_train", ",", "'todense'", ")", ":", "self", ".", "_X_train", "=", "self", ".", "_X_train", ".", "todense", "(", ")", "self", ".", "_X_test", "=", "self", ".", "_X_test",...
43.4
0.00905
def enforce_versioning(force=False): """Install versioning on the db.""" connect_str, repo_url = get_version_data() LOG.warning("Your database uses an unversioned benchbuild schema.") if not force and not ui.ask( "Should I enforce version control on your schema?"): LOG.error("User de...
[ "def", "enforce_versioning", "(", "force", "=", "False", ")", ":", "connect_str", ",", "repo_url", "=", "get_version_data", "(", ")", "LOG", ".", "warning", "(", "\"Your database uses an unversioned benchbuild schema.\"", ")", "if", "not", "force", "and", "not", "...
46.909091
0.001901
def do_refresh(self, line): "refresh {table_name}" table = self.get_table(line) table.refresh(True) self.pprint(self.conn.describe_table(table.name))
[ "def", "do_refresh", "(", "self", ",", "line", ")", ":", "table", "=", "self", ".", "get_table", "(", "line", ")", "table", ".", "refresh", "(", "True", ")", "self", ".", "pprint", "(", "self", ".", "conn", ".", "describe_table", "(", "table", ".", ...
35.4
0.01105
def cena_tau(imt, mag, params): """ Returns the inter-event standard deviation, tau, for the CENA case """ if imt.name == "PGV": C = params["PGV"] else: C = params["SA"] if mag > 6.5: return C["tau3"] elif (mag > 5.5) and (mag <= 6.5): return ITPL(mag, C["tau3...
[ "def", "cena_tau", "(", "imt", ",", "mag", ",", "params", ")", ":", "if", "imt", ".", "name", "==", "\"PGV\"", ":", "C", "=", "params", "[", "\"PGV\"", "]", "else", ":", "C", "=", "params", "[", "\"SA\"", "]", "if", "mag", ">", "6.5", ":", "ret...
28.75
0.002105
def record_diff(old, new): """Return a JSON-compatible structure capable turn the `new` record back into the `old` record. The parameters must be structures compatible with json.dumps *or* strings compatible with json.loads. Note that by design, `old == record_patch(new, record_diff(old, new))`""" o...
[ "def", "record_diff", "(", "old", ",", "new", ")", ":", "old", ",", "new", "=", "_norm_json_params", "(", "old", ",", "new", ")", "return", "json_delta", ".", "diff", "(", "new", ",", "old", ",", "verbose", "=", "False", ")" ]
57.571429
0.002445
def _deadline_until(cls, closure, action_msg, timeout=FAIL_WAIT_SEC, wait_interval=WAIT_INTERVAL_SEC, info_interval=INFO_INTERVAL_SEC): """Execute a function/closure repeatedly until a True condition or timeout is met. :param func closure: the function/closure to execute (should not block...
[ "def", "_deadline_until", "(", "cls", ",", "closure", ",", "action_msg", ",", "timeout", "=", "FAIL_WAIT_SEC", ",", "wait_interval", "=", "WAIT_INTERVAL_SEC", ",", "info_interval", "=", "INFO_INTERVAL_SEC", ")", ":", "now", "=", "time", ".", "time", "(", ")", ...
52.25
0.01057
def apply_filter_list(func, obj): """Apply `func` to list or tuple `obj` element-wise and directly otherwise.""" if isinstance(obj, (list, tuple)): return [func(item) for item in obj] return func(obj)
[ "def", "apply_filter_list", "(", "func", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "func", "(", "item", ")", "for", "item", "in", "obj", "]", "return", "func", "(", "obj", ...
43.2
0.009091
def filter_trim(self, start=1, end=1, filt=True): """ Remove points from the start and end of filter regions. Parameters ---------- start, end : int The number of points to remove from the start and end of the specified filter. filt : vali...
[ "def", "filter_trim", "(", "self", ",", "start", "=", "1", ",", "end", "=", "1", ",", "filt", "=", "True", ")", ":", "params", "=", "locals", "(", ")", "del", "(", "params", "[", "'self'", "]", ")", "f", "=", "self", ".", "filt", ".", "grab_fil...
34.043478
0.01118
def outputindexbytemplate(project, user, outputtemplate): """Retrieve sorted index for the specified input template""" index = [] #pylint: disable=redefined-outer-name prefix = Project.path(project, user) + 'output/' for linkf, f in globsymlinks(prefix + '.*.OUTPUTTEMPLATE.' + outputtemp...
[ "def", "outputindexbytemplate", "(", "project", ",", "user", ",", "outputtemplate", ")", ":", "index", "=", "[", "]", "#pylint: disable=redefined-outer-name", "prefix", "=", "Project", ".", "path", "(", "project", ",", "user", ")", "+", "'output/'", "for", "li...
54.181818
0.016502
def calc_percentile_interval(bootstrap_replicates, conf_percentage): """ Calculate bootstrap confidence intervals based on raw percentiles of the bootstrap distribution of samples. Parameters ---------- bootstrap_replicates : 2D ndarray. Each row should correspond to a different bootstr...
[ "def", "calc_percentile_interval", "(", "bootstrap_replicates", ",", "conf_percentage", ")", ":", "# Check validity of arguments", "check_conf_percentage_validity", "(", "conf_percentage", ")", "ensure_samples_is_ndim_ndarray", "(", "bootstrap_replicates", ",", "ndim", "=", "2"...
48.609375
0.000315
def _combine_ranges(ranges): """ This function takes a list of row-ranges (as returned by `_parse_row`) ordered by rows, and produces a list of distinct rectangular ranges within this grid. Within this function we define a 2d-range as a rectangular set of cells such that: - there are no e...
[ "def", "_combine_ranges", "(", "ranges", ")", ":", "ranges2d", "=", "[", "]", "for", "irow", ",", "rowranges", "in", "enumerate", "(", "ranges", ")", ":", "ja", "=", "0", "jb", "=", "0", "while", "jb", "<", "len", "(", "rowranges", ")", ":", "bcol0...
35.520833
0.000571
def main(): """Parse the command-line arguments and run the bot.""" parser = argparse.ArgumentParser(description = 'XMPP echo bot', parents = [XMPPSettings.get_arg_parser()]) parser.add_argument('--debug', action = 'store_const', dest = 'log_level'...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'XMPP echo bot'", ",", "parents", "=", "[", "XMPPSettings", ".", "get_arg_parser", "(", ")", "]", ")", "parser", ".", "add_argument", "(", "'--debug'", ...
50.16129
0.027118
def check_types(func): """ Check if annotated function arguments are of the correct type """ call = PythonCall(func) @wraps(func) def decorator(*args, **kwargs): parameters = call.bind(args, kwargs) for arg_name, expected_type in func.__annotations__.items(): if not ...
[ "def", "check_types", "(", "func", ")", ":", "call", "=", "PythonCall", "(", "func", ")", "@", "wraps", "(", "func", ")", "def", "decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "parameters", "=", "call", ".", "bind", "(", "args", ...
34.6
0.001876
def lowest_cost_action(ic, dc, sc, im, dm, sm, cost): """Given the following values, choose the action (insertion, deletion, or substitution), that results in the lowest cost (ties are broken using the 'match' score). This is used within the dynamic programming algorithm. * ic - insertion cost * ...
[ "def", "lowest_cost_action", "(", "ic", ",", "dc", ",", "sc", ",", "im", ",", "dm", ",", "sm", ",", "cost", ")", ":", "best_action", "=", "None", "best_match_count", "=", "-", "1", "min_cost", "=", "min", "(", "ic", ",", "dc", ",", "sc", ")", "if...
29.424242
0.000997
def reduce_terms(term_doc_matrix, scores, num_term_to_keep=None): ''' Parameters ---------- term_doc_matrix: TermDocMatrix or descendant scores: array-like Same length as number of terms in TermDocMatrix. num_term_to_keep: int, default=4000. Should be> 0. Number of terms to keep. Will keep between num...
[ "def", "reduce_terms", "(", "term_doc_matrix", ",", "scores", ",", "num_term_to_keep", "=", "None", ")", ":", "terms_to_show", "=", "AutoTermSelector", ".", "get_selected_terms", "(", "term_doc_matrix", ",", "scores", ",", "num_term_to_keep", ")", "return", "term_do...
37.055556
0.02924
def machineCurrents(self, Xg, U): """ Based on MachineCurrents.m from MatDyn by Stijn Cole, developed at Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/ electa/teaching/matdyn/} for more information. @param Xg: Generator state variables. @param U: Generator vo...
[ "def", "machineCurrents", "(", "self", ",", "Xg", ",", "U", ")", ":", "generators", "=", "self", ".", "dyn_generators", "# Initialise.", "ng", "=", "len", "(", "generators", ")", "Id", "=", "zeros", "(", "ng", ")", "Iq", "=", "zeros", "(", "ng", ")",...
29.660377
0.002463
def t_INCLUDE(self, t): 'include' # # Now eat up the next two tokens which must be # 1 - the name of the include file, and # 2 - a terminating semicolon # # Then push the current lexer onto the stack, create a new one from # the include file, and push it o...
[ "def", "t_INCLUDE", "(", "self", ",", "t", ")", ":", "#", "# Now eat up the next two tokens which must be", "# 1 - the name of the include file, and", "# 2 - a terminating semicolon", "#", "# Then push the current lexer onto the stack, create a new one from", "# the include file, and pus...
38.46875
0.001585
def pypsa_id(self): #TODO: docstring """ Description """ return '_'.join(['MV', str( self.grid.grid_district.lv_load_area.mv_grid_district.mv_grid.\ id_db), 'tru', str(self.id_db)])
[ "def", "pypsa_id", "(", "self", ")", ":", "#TODO: docstring", "return", "'_'", ".", "join", "(", "[", "'MV'", ",", "str", "(", "self", ".", "grid", ".", "grid_district", ".", "lv_load_area", ".", "mv_grid_district", ".", "mv_grid", ".", "id_db", ")", ","...
34.142857
0.028571
def start(self, max_messages=math.inf, commit_offsets=True): """Start processing Kafka messages and executing jobs. :param max_messages: Maximum number of Kafka messages to process before stopping. If not set, worker runs until interrupted. :type max_messages: int :param com...
[ "def", "start", "(", "self", ",", "max_messages", "=", "math", ".", "inf", ",", "commit_offsets", "=", "True", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Starting {} ...'", ".", "format", "(", "self", ")", ")", "self", ".", "_consumer", ".",...
33.638889
0.001605
def _id_map(minion_id, dns_name): ''' Maintain a relationship between a minion and a dns name ''' bank = 'digicert/minions' cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR) dns_names = cache.fetch(bank, minion_id) if not isinstance(dns_names, list): dns_names = [] if dns_na...
[ "def", "_id_map", "(", "minion_id", ",", "dns_name", ")", ":", "bank", "=", "'digicert/minions'", "cache", "=", "salt", ".", "cache", ".", "Cache", "(", "__opts__", ",", "syspaths", ".", "CACHE_DIR", ")", "dns_names", "=", "cache", ".", "fetch", "(", "ba...
34
0.002387
def find_lib_path(): """Find the path to LightGBM library files. Returns ------- lib_path: list of strings List of all found library paths to LightGBM. """ if os.environ.get('LIGHTGBM_BUILD_DOC', False): # we don't need lib_lightgbm while building docs return [] curr...
[ "def", "find_lib_path", "(", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'LIGHTGBM_BUILD_DOC'", ",", "False", ")", ":", "# we don't need lib_lightgbm while building docs", "return", "[", "]", "curr_path", "=", "os", ".", "path", ".", "dirname", "("...
44.612903
0.001415
def getTemplate(self, copied_from, template_name=None, template_folder=None, keep=False, encoding="UTF-8"): """Get template from some to-be-copied :class:`rtcclient.workitem.Workitem` The resulting XML document is returned as a :class:`string`, but if `template_name`...
[ "def", "getTemplate", "(", "self", ",", "copied_from", ",", "template_name", "=", "None", ",", "template_folder", "=", "None", ",", "keep", "=", "False", ",", "encoding", "=", "\"UTF-8\"", ")", ":", "try", ":", "if", "isinstance", "(", "copied_from", ",", ...
42.328859
0.000775
def push_framer(self, *args, **kwargs): """ Called by the client protocol to temporarily switch to a new send framer, receive framer, or both. Can be called multiple times. Each call to ``push_framer()`` must be paired with a call to ``pop_framer()``, which restores to the prev...
[ "def", "push_framer", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# First, interpret the arguments", "elem", "=", "self", ".", "_interpret_framer", "(", "args", ",", "kwargs", ")", "# Append the element to the framer stack", "self", ".", "...
47.83871
0.001322