text
stringlengths
78
104k
score
float64
0
0.18
def schemas(self): """ Get a listing of all non-system schemas (prefixed with 'pg_') that exist in the database. """ sql = """SELECT schema_name FROM information_schema.schemata ORDER BY schema_name""" schemas = self.query(sql).fetchall() return [...
0.00551
def human_audible(self): """ Returns an estimate of whether this AudioSegment is mostly human audible or not. This is done by taking an FFT of the segment and checking if the SPL of the segment falls below the function `f(x) = 40.11453 - 0.01683697x + 1.406211e-6x^2 - 2.371512e-11x^3`, ...
0.008904
def labels(self, *labelvalues, **labelkwargs): """Return the child for the given labelset. All metrics can have labels, allowing grouping of related time series. Taking a counter as an example: from prometheus_client import Counter c = Counter('my_requests_total', 'HTT...
0.004833
def get_permissions(self, user_id): """Fetches the permissions object from the graph.""" response = self.request( "{0}/{1}/permissions".format(self.version, user_id), {} )["data"] return {x["permission"] for x in response if x["status"] == "granted"}
0.006803
def create_png(cls_name, meth_name, graph, dir_name='graphs2'): """ Creates a PNG from a given :class:`~androguard.decompiler.dad.graph.Graph`. :param str cls_name: name of the class :param str meth_name: name of the method :param androguard.decompiler.dad.graph.Graph graph: :param str dir_name...
0.002004
def wait_for_edge(self, pin, edge): """Wait for an edge. Pin should be type IN. Edge must be RISING, FALLING or BOTH. """ self.rpi_gpio.wait_for_edge(pin, self._edge_mapping[edge])
0.009302
def read_documentation(self, fid): """Read documentation from an acclaim skeleton file stream.""" lin = self.read_line(fid) while lin[0] != ':': self.documentation.append(lin) lin = self.read_line(fid) return lin
0.007435
def multiple_replace(dict, text): """ Replace in 'text' all occurences of any key in the given dictionary by its corresponding value. Returns the new string.""" # Function by Xavier Defrang, originally found at: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 # Create a regular ex...
0.00177
def move_prev(lines=1, file=sys.stdout): """ Move the cursor to the beginning of the line, a number of lines up. Default: 1 Esc[<lines>F """ move.prev(lines).write(file=file)
0.004926
def UploadSignedConfigBlob(content, aff4_path, client_context=None, limit=None, token=None): """Upload a signed blob into the datastore. Args: content: File content to upload. aff4_path: aff4 path to...
0.008053
def install(name=None, refresh=False, pkgs=None, **kwargs): r''' Install the passed package(s) on the system using winrepo Args: name (str): The name of a single package, or a comma-separated list of packages to install. (no spaces after the commas) refresh (bool):...
0.001122
def _marshaled_dispatch(self, data, dispatch_method = None, path = None): """Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards com...
0.005576
def get_collection(self, id_or_uri, filter=''): """ Retrieves a collection of resources. Use this function when the 'start' and 'count' parameters are not allowed in the GET call. Otherwise, use get_all instead. Optional filtering criteria may be specified. Args: ...
0.00454
def setup(self, app): """ Make sure that other installed plugins don't affect the same keyword argument and check if metadata is available.""" for other in app.plugins: if not isinstance(other, AuthPlugin): continue if other.keyword == self.keyword: ...
0.003824
def pet_get(self, **kwargs): """ pet.get wrapper. Returns a record dict for the requested pet. :rtype: dict :returns: The pet's record dict. """ root = self._do_api_call("pet.get", kwargs) return self._parse_pet_record(root.find("pet"))
0.006803
def share_with_link(self, share_type='view', share_scope='anonymous'): """ Creates or returns a link you can share with others :param str share_type: 'view' to allow only view access, 'edit' to allow editions, and 'embed' to allow the DriveItem to be embedded :param str share_...
0.001944
def ensembl_to_kegg(organism,kegg_db): """ Looks up KEGG mappings of KEGG ids to ensembl ids :param organism: an organisms as listed in organismsKEGG() :param kegg_db: a matching KEGG db as reported in databasesKEGG :returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'. """ print("KEG...
0.019584
def select_action(self, q_values): """Return the selected action # Arguments q_values (np.ndarray): List of the estimations of Q for each action # Returns Selection action """ # We can't use BGE during testing, since we don't have access to the #...
0.003053
def body(self): """get the contents of the script""" if not hasattr(self, '_body'): self._body = inspect.getsource(self.module) return self._body
0.01105
def imap_unordered(self, jobs, timeout=0.5): """A iterator over a set of jobs. :param jobs: the items to pass through our function :param timeout: timeout between polling queues Results are yielded as soon as they are available in the output queue (up to the discretisation prov...
0.002823
def clean_chars(value): "Hack to remove non-ASCII data. Should convert to Unicode: code page 437?" value = value.replace('\xb9', ' ') value = value.replace('\xf8', ' ') value = value.replace('\xab', ' ') value = value.replace('\xa7', ' ') value = value.replace('\xa8', ' ') value = value.repl...
0.002551
def encoder_config(self, pin_a, pin_b, cb=None): """ This command enables the rotary encoder (2 pin + ground) and will enable encoder reporting. NOTE: This command is not currently part of standard arduino firmata, but is provided for legacy support of CodeShield on an Arduino U...
0.00695
def save(self, *args, **kwargs): """ call synchronizer "after_external_layer_saved" method for any additional operation that must be executed after save """ after_save = kwargs.pop('after_save', True) super(LayerExternal, self).save(*args, **kwargs) # call after_e...
0.002894
def _choice_stmt(self, stmt: Statement, sctx: SchemaContext) -> None: """Handle choice statement.""" self._handle_child(ChoiceNode(), stmt, sctx)
0.012422
def get(self, resource, **params): """ Generic TeleSign REST API GET handler. :param resource: The partial resource URI to perform the request against, as a string. :param params: Body params to perform the GET request with, as a dictionary. :return: The RestClient Response obje...
0.00978
def anchor(self, value): """ Setter for **self.__anchor** attribute. :param value: Attribute value. :type value: int """ if value is not None: assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("anchor", value) assert v...
0.008547
def cmd(self, *args, **kwargs): """ Execute tmux command and return output. Returns ------- :class:`common.tmux_cmd` Notes ----- .. versionchanged:: 0.8 Renamed from ``.tmux`` to ``.cmd``. """ args = list(args) if se...
0.002283
def _detect_or_validate(self, val): ''' Detect the version used from the row content, or validate against the version if given. ''' if isinstance(val, list) \ or isinstance(val, dict) \ or isinstance(val, SortableDict) \ or isinstan...
0.004796
def get_what_txt(self): """ Overrides the base behaviour defined in ValidationError in order to add details about the class field. :return: """ return 'field [{field}] for class [{clazz}]'.format(field=self.get_variable_str(), ...
0.013055
def compute_savings_list(self, graph): """Compute Clarke and Wright savings list A saving list is a matrix containing the saving amount S between i and j S is calculated by S = d(0,i) + d(0,j) - d(i,j) (CLARKE; WRIGHT, 1964) Args ---- graph: :networkx:`NetworkX...
0.006506
def login(self) -> bool: """Return True if log in request succeeds""" user_check = isinstance(self.username, str) and len(self.username) > 0 pass_check = isinstance(self.password, str) and len(self.password) > 0 if user_check and pass_check: response, _ = helpers.call_api( ...
0.001925
def normalized(self): """Return a normalized version of the histogram where the values sum to one. """ total = self.total() result = Histogram() for value, count in iteritems(self): try: result[value] = count / float(total) except ...
0.00409
def set_configuration(self, ip_address, network_mask, from_ip_address, to_ip_address): """configures the server in ip_address of type str server IP address in network_mask of type str server network mask in from_ip_address of type str server From IP...
0.008117
def set(self, value): """This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter""" if self.validate(value): #print "Parameter " + self.id + " ...
0.012411
def reflection_matrix(point, normal): """Return matrix to mirror at plane defined by point and normal vector. >>> v0 = np.random.random(4) - 0.5 >>> v0[3] = 1. >>> v1 = np.random.random(3) - 0.5 >>> R = reflection_matrix(v0, v1) >>> np.allclose(2, np.trace(R)) True >>> np.allclose(v0, n...
0.001502
def _ipython_display_(self): """Display Jupyter Notebook widget""" from IPython.display import display self.build_widget() display(self.widget())
0.011236
def treebeard_js(): """ Template tag to print out the proper <script/> tag to include a custom .js """ path = get_static_url() js_file = urljoin(path, 'treebeard/treebeard-admin.js') jquery_ui = urljoin(path, 'treebeard/jquery-ui-1.8.5.custom.min.js') # Jquery UI is needed to call disableSe...
0.002315
def macho_dependencies_list(target_path, header_magic=None): """ Generates a list of libraries the given Mach-O file depends on. In that list a single library is represented by its "install path": for some libraries it would be a full file path, and for others it would be a relative path (sometimes with dyld templ...
0.027344
def _get_session_for_table(self, base_session): """ Only present session for modeling when doses were dropped if it's succesful; otherwise show the original modeling session. """ if base_session.recommended_model is None and base_session.doses_dropped > 0: return base...
0.010471
def ishex(obj): """ Test if the argument is a string representing a valid hexadecimal digit. :param obj: Object :type obj: any :rtype: boolean """ return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits)
0.007843
def update(name, connection_uri="", id_file="", o=[], config=None): """ Enhanced version of the edit command featuring multiple edits using regular expressions to match entries """ storm_ = get_storm_instance(config) settings = {} if id_file != "": settings['identityfile'] = id_fil...
0.002805
def generate_page_title(self, data_slug): """Generates remainder of page title specific to data_slug (tag).""" tag = Tag.objects.filter(slug=data_slug) return tag[0].word
0.010309
def pull_repo(repo_name): """Pull from origin for repo_name.""" repo = ClonedRepo.objects.get(pk=repo_name) repo.pull()
0.007634
def shape(self) -> Tuple[int, ...]: """Shape of histogram's data. Returns ------- One-element tuple with the number of bins along each axis. """ return tuple(bins.bin_count for bins in self._binnings)
0.008032
def find(self, title): """Return the first worksheet with the given title. Args: title(str): title/name of the worksheet to return Returns: WorkSheet: contained worksheet object Raises: KeyError: if the spreadsheet has no no worksheet with the given `...
0.006667
def get_tree(self, request, tree_id, item_id=None): """Fetches Tree for current or given TreeItem.""" if tree_id is None: tree_id = self.get_object(request, item_id).tree_id self.tree = MODEL_TREE_CLASS._default_manager.get(pk=tree_id) self.tree.verbose_name_plural = self.tre...
0.004902
def depth_file_for_rgb_file(rgb_filename, rgb_file_list, depth_file_list): """Returns the *closest* depth file from an RGB filename""" (root, filename) = os.path.split(rgb_filename) rgb_timestamps = np.array(Kinect.timestamps_from_file_list(rgb_file_list)) depth_timestamps = np.array(Kin...
0.006745
def post(self): """Dump current profiler statistics into a file.""" filename = self.get_argument('filename', 'dump.prof') CProfileWrapper.profiler.dump_stats(filename) self.finish()
0.00939
def _create_PmtInf_node(self): """ Method to create the blank payment information nodes as a dict. """ ED = dict() # ED is element dict ED['PmtInfNode'] = ET.Element("PmtInf") ED['PmtInfIdNode'] = ET.Element("PmtInfId") ED['PmtMtdNode'] = ET.Element("PmtMtd") ...
0.001147
def permute(self, qubits: Qubits) -> 'Density': """Return a copy of this state with qubit labels permuted""" vec = self.vec.permute(qubits) return Density(vec.tensor, vec.qubits, self._memory)
0.009259
def _register_default_option(nsobj, opt): """ Register default ConfigOption value if it doesn't exist. If does exist, update the description if needed """ item = ConfigItem.get(nsobj.namespace_prefix, opt.name) if not item: logger.info('Adding {} ({}) = {} to {}'.format( opt.name, ...
0.003293
def _current_color(self, which=0): """Returns a color for the queue. Parameters ---------- which : int (optional, default: ``0``) Specifies the type of color to return. Returns ------- color : list Returns a RGBA color that is represented...
0.001049
def make_tree(self): """ Generates the merkle tree. """ self.tree['is_ready'] = False leaf_count = len(self.tree['leaves']) if leaf_count > 0: # skip this whole process if there are no leaves added to the tree self._unshift(self.tree['levels'], sel...
0.005929
def _get_music_services_data_xml(soco=None): """Fetch the music services data xml from a Sonos device. Args: soco (SoCo): a SoCo instance to query. If none is specified, a random device will be used. Defaults to `None`. Returns: str: a string containing the ...
0.002692
def deploy(self, id_networkv6): """Deploy network in equipments and set column 'active = 1' in tables redeipv6 ] :param id_networkv6: ID for NetworkIPv6 :return: Equipments configuration output """ data = dict() uri = 'api/networkv6/%s/equipments/' % id_networkv6 ...
0.007916
def _parse_banners(self): """Parses the global config and returns the value for both motd and login banners. Returns: dict: The configure value for modtd and login banners. If the banner is not set it will return a value of None for that key. T...
0.00464
def _collect_uncolored_outputs(unspent_outputs, amount): """ Returns a list of uncolored outputs for the specified amount. :param list[SpendableOutput] unspent_outputs: The list of available outputs. :param int amount: The amount to collect. :return: A list of outputs, and the t...
0.004043
def describe(self, fields=None, **kwargs): """ :param fields: dict where the keys are field names that should be returned, and values should be set to True (by default, all fields are returned) :type fields: dict :returns: Description of the analysis :rtyp...
0.004601
def private_ip(self): """ Private ip_address """ ip = None for eth in self.networks['v4']: if eth['type'] == 'private': ip = eth['ip_address'] break if ip is None: raise ValueError("No private IP found") retu...
0.006154
def actions(self): """Gets the list of allowed actions :rtype: list[str] """ r = self.session.query(models.Action).all() return [x.type_name for x in r]
0.010363
async def listTasks(self, *args, **kwargs): """ List Tasks List the tasks immediately under a given namespace. This endpoint lists up to 1000 tasks. If more tasks are present, a `continuationToken` will be returned, which can be given in the next request. For th...
0.005563
def make_decoder(base_depth, activation, input_size, output_shape): """Creates the decoder function. Args: base_depth: Layer base depth in decoder net. activation: Activation function in hidden layers. input_size: The flattened latent input shape as an int. output_shape: The output image shape as a...
0.004456
def _get_user_groups(self, user): ''' Get user groups. :param user: :return: ''' return [g.gr_name for g in grp.getgrall() if user in g.gr_mem] + [grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name]
0.011538
def PopupNonBlocking(*args, button_type=POPUP_BUTTONS_OK, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=True, icon=DEFAULT_WINDOW_ICON, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep...
0.005747
def remove(self, processor_identity): """Removes all of the Processors for a particular transaction processor zeromq identity. Args: processor_identity (str): The zeromq identity of the transaction processor. """ with self._condition: proc...
0.001564
def hash(self): "signatures are non deterministic" if self.sender is None: raise MissingSignatureError() class HashSerializable(rlp.Serializable): fields = [(field, sedes) for field, sedes in self.fields if field not in ('v', 'r', 's')] + [('_sender...
0.004843
def sparse_cross_entropy(input_, labels, name=PROVIDED, loss_weight=None, per_example_weights=None): """Calculates the Cross Entropy of input_ vs labels. Args: input_: A rank 2 `Tensor` or a Pretty Tensor holdin...
0.005085
def validate(input_schema=None, output_schema=None, input_example=None, output_example=None, validator_cls=None, format_checker=None, on_empty_404=False, use_defaults=False): """Parameterized decorator for schema validation :type validator_cls: IValidator cla...
0.000196
def read_from_buffer(cls, buf, identifier_str=None): """Load the context from a buffer.""" try: return cls._read_from_buffer(buf, identifier_str) except Exception as e: cls._load_error(e, identifier_str)
0.007968
def get_process_log(self, pid=None, start=0, limit=1000): ''' get_process_log(self, pid=None, start=0, limit=1000 Get process logs :Parameters: * *pid* (`string`) -- Identifier of an existing process * *pid* (`string`) -- start index to retrieve logs from * *pid...
0.006359
def cart_clear(self, CartId=None, HMAC=None, **kwargs): """CartClear. Removes all items from cart :param CartId: Id of cart :param HMAC: HMAC of cart. Do not use url encoded :return: An :class:`~.AmazonCart`. """ if not CartId or not HMAC: raise CartException(...
0.003425
def _check_groups(s, groups): """Ensures that all particles are included in exactly 1 group""" ans = [] for g in groups: ans.extend(g) if np.unique(ans).size != np.size(ans): return False elif np.unique(ans).size != s.obj_get_positions().shape[0]: return False else: ...
0.002584
def authenticate_heat_admin(self, keystone): """Authenticates the admin user with heat.""" self.log.debug('Authenticating heat admin...') ep = keystone.service_catalog.url_for(service_type='orchestration', interface='publicURL') if keystone.s...
0.004032
def contains_all(set1, set2, warn): """ Checks if all elements from set2 are in set1. :param set1: a set of values :param set2: a set of values :param warn: the error message that should be thrown when the sets are not containd :return: returns true if all values of set2 are in set1 ...
0.004695
def body_as_str(self, encoding='UTF-8'): """ The body of the event data as a string if the data is of a compatible type. :param encoding: The encoding to use for decoding message data. Default is 'UTF-8' :rtype: str or unicode """ data = self.body ...
0.005764
def BHI(self, params): """ BHI label Branch to the instruction at label if the C flag is set and the Z flag is not set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BHI label def BHI_func():...
0.00655
def download(self, uuid, output_format='gzip'): """ Download pre-prepared data by UUID :type uuid: str :param uuid: Data UUID :type output_format: str :param output_format: Output format of the data, either "gzip" or "text" :rtype: str :return: The down...
0.004724
def service_define(self, service, ty): """ Add a service variable of type ``ty`` to this model :param str service: variable name :param type ty: variable type :return: None """ assert service not in self._data assert service not in self._algebs + self._s...
0.005
def signals(): """Show all signal types.""" signalbus = current_app.extensions['signalbus'] for signal_model in signalbus.get_signal_models(): click.echo(signal_model.__name__)
0.005076
def create_from_array(self, blockname, array, Nfile=None, memorylimit=1024 * 1024 * 256): """ create a block from array like objects The operation is well defined only if array is at most 2d. Parameters ---------- array : array_like, array shall h...
0.002791
def to_lst(self): """Cycle all items and puts them in a list :return: list representation """ out = [] node = self.head while node is not None: out.append(node.val) node = node.next_node return out
0.007143
def get(self): """API endpoint to get the related blocks for a transaction. Return: A ``list`` of ``block_id``s that contain the given transaction. The list may be filtered when provided a status query parameter: "valid", "invalid", "undecided". """ p...
0.002946
def check_filepath(self, path, filename): """ Check and return the final filepath to settings Args: path (str): Directory path where to search for settings file. filename (str): Filename to use to search for settings file. Raises: boussole.exceptions...
0.002442
def proxy_upload(self, path, filename, content_type=None, content_encoding=None, cb=None, num_cb=None): """ This is the main function that uploads. We assume the bucket and key (== path) exists. What we do here is simple. Calculate the headers we will need, (e.g. md5...
0.005215
def delete_saml_provider(name, region=None, key=None, keyid=None, profile=None): ''' Delete SAML provider CLI Example: .. code-block:: bash salt myminion boto_iam.delete_saml_provider my_saml_provider_name ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ...
0.003382
def list_vdirs(site, app=_DEFAULT_APP): ''' Get all configured IIS virtual directories for the specified site, or for the combination of site and application. Args: site (str): The IIS site name. app (str): The IIS application. Returns: dict: A dictionary of the virtual dir...
0.000875
def get_signature(self, content): """Get signature from inspect reply content""" data = content.get('data', {}) text = data.get('text/plain', '') if text: text = ANSI_OR_SPECIAL_PATTERN.sub('', text) self._control.current_prompt_pos = self._prompt_pos ...
0.002368
def delete_key(self, key_id): """ :: DELETE /:login/keys/:key :param key_id: identifier for an individual key record for the account :type key_id: :py:class:`basestring` Deletes an SSH key from the server identified by `key_id`. """ ...
0.01171
def run_fusion_caller(job, star_bam, univ_options, fusion_options): """ This module will run a fusion caller on DNA bams. This module will be implemented in the future. This module corresponds to node 10 on the tree """ job.fileStore.logToMaster('Running FUSION on %s' % univ_options['patient']...
0.002193
def get_abs_url(self, rel_url): """ Create an absolute url from a relative one. >>> url_formatter = URLFormatter("example.com", 80) >>> url_formatter.get_abs_url("kml_master.kml") 'http://example.com:80/kml_master.kml' """ rel_url = rel_url.lstrip("/") re...
0.007595
def stsci(hdulist): """For STScI GEIS files, need to do extra steps.""" instrument = hdulist[0].header.get('INSTRUME', '') # Update extension header keywords if instrument in ("WFPC2", "FOC"): rootname = hdulist[0].header.get('ROOTNAME', '') filetype = hdulist[0].header.get('FILETYPE',...
0.004069
def qual_name(self) -> QualName: """Return the receiver's qualified name.""" p, s, loc = self._key.partition(":") return (loc, p) if s else (p, self.namespace)
0.010929
def get_ruleset_dirs(): """ Get the directory with ruleset files First directory to check: ./rulesets Second directory to check: $HOME/.local/share/colin/rulesets Third directory to check: /usr/local/share/colin/rulesets :return: str """ ruleset_dirs = [] cwd_rulesets = os.path.j...
0.003127
def magnification(self, x, y, kwargs, diff=diff): """ computes the magnification :return: potential """ f_xx, f_xy, f_yx, f_yy = self.hessian(x, y, kwargs, diff=diff) det_A = (1 - f_xx) * (1 - f_yy) - f_xy*f_yx return 1/det_A
0.007117
def checkAndCreateClasses(self, classes): """ Function checkAndCreateClasses Check and add puppet class @param classes: The classes ids list @return RETURN: boolean """ actual_classes = self['puppetclasses'].keys() for i in classes: if i not in actual...
0.004228
def write(self, face, data, viewport=None, *, alignment=1) -> None: ''' Update the content of the texture. Args: face (int): The face to update. data (bytes): The pixel data. viewport (tuple): The viewport. Keyword Args: ...
0.003891
def scrub_py2_sys_modules(): """ Removes any Python 2 standard library modules from ``sys.modules`` that would interfere with Py3-style imports using import hooks. Examples are modules with the same names (like urllib or email). (Note that currently import hooks are disabled for modules like these ...
0.002439
def slice_sequence(sequence, length, pad_last=False, pad_val=C.PAD_TOKEN, overlap=0): """Slice a flat sequence of tokens into sequences tokens, with each inner sequence's length equal to the specified `length`, taking into account the requested sequence overlap. Parameters ---------- sequence :...
0.004701
def _set_log_format(color, include_caller): """ Set log format :param color: Log message is colored :param include_caller: At the end, put a [caller:line-of-code], e.g. [script:123] :return: string of log format """ level_name = '* %(levelname)1s' time = '%(asctime)s,%(msecs)03d' mes...
0.004494
def get_cfws(value): """CFWS = (1*([FWS] comment) [FWS]) / FWS """ cfws = CFWSList() while value and value[0] in CFWS_LEADER: if value[0] in WSP: token, value = get_fws(value) else: token, value = get_comment(value) cfws.append(token) return cfws, val...
0.003106