text
stringlengths
78
104k
score
float64
0
0.18
def add_map(self, event, handle, *args): """ Add a mapping like event -(arg0, arg1, arg2, ...)-> handle. """ item = self.base.setdefault(event, list()) item.append((handle, args))
0.009091
def list( self, **kwargs ): """ Get a list of all Accounts authorized for the provided token. Args: Returns: v20.response.Response containing the results from submitting the request """ request = Request( 'GET', ...
0.002172
def cdf(self, x_data): """ Cumulative distribution function. Note that chaospy only supports cumulative distribution functions for stochastically independent distributions. Args: x_data (numpy.ndarray): Location for the distribution function. Assumes...
0.002123
def _bash_comp_command(self, cmd, add_help=True): """Build a list of all options for a given command. Args: cmd (str): command name, set to None or '' for bare command. add_help (bool): add an help option. Returns: list of str: list of CLI options strings. ...
0.003617
def get_enabled_browsers(): """ Check the ADMINFILES_BROWSER_VIEWS setting and return a list of instantiated browser views that have the necessary dependencies/configuration to run. """ global _enabled_browsers_cache if _enabled_browsers_cache is not None: return _enabled_browsers_c...
0.001259
def get_offset_and_prefix(body, skip_assignments=False): """Returns the offset after which a statement can be inserted to the `body`. This offset is calculated to come after all imports, and maybe existing (possibly annotated) assignments if `skip_assignments` is True. Also returns the indentation pre...
0.002201
def put_object_acl(ACL=None, AccessControlPolicy=None, Bucket=None, GrantFullControl=None, GrantRead=None, GrantReadACP=None, GrantWrite=None, GrantWriteACP=None, Key=None, RequestPayer=None, VersionId=None): """ uses the acl subresource to set the access control list (ACL) permissions for an object that alread...
0.006806
def sign(self, h): """ Return a der-encoded signature for a hash h. Will throw a RuntimeError if this key is not a private key """ if not self.is_private(): raise RuntimeError("Key must be private to be able to sign") val = from_bytes_32(h) r, s = self...
0.005
def Nor(*xs, simplify=True): """Expression NOR (not OR) operator If *simplify* is ``True``, return a simplified expression. """ xs = [Expression.box(x).node for x in xs] y = exprnode.not_(exprnode.or_(*xs)) if simplify: y = y.simplify() return _expr(y)
0.00346
def toggle_wrap_mode(self, checked): """Toggle wrap mode""" self.shell.toggle_wrap_mode(checked) self.set_option('wrap', checked)
0.012821
def _send(self, event): """Generic function for sending commands to Alarm.com :param event: Event command to send to alarm.com """ _LOGGER.debug('Sending %s to Alarm.com', event) try: with async_timeout.timeout(10, loop=self._loop): response = yield ...
0.000847
def set_mlag_id(self, name, value=None, default=False, disable=False): """Configures the interface mlag value for the specified interface Args: name (str): The interface to configure. Valid values for the name arg include Port-Channel* value (str): The mlag iden...
0.002398
def process_corpus(self, corpus, output_path, frame_size=400, hop_size=160, sr=None): """ Process all utterances of the given corpus and save the processed features in a feature-container. The utterances are processed in **offline** mode so the full utterance in one go. Args: ...
0.008078
def writeBib(self, fname = None, maxStringLength = 1000, wosMode = False, reducedOutput = False, niceIDs = True): """Writes a bibTex entry to _fname_ for each `Record` in the collection. If the Record is of a journal article (PT J) the bibtext type is set to `'article'`, otherwise it is set to `'misc'`...
0.013665
def _rename(self, full_name): """Renames the tree node""" self._full_name = full_name if full_name: self._name = full_name.rsplit('.', 1)[-1]
0.011299
def create_audio(self, blogname, **kwargs): """ Create a audio post on a blog :param blogname: a string, the url of the blog you want to post to. :param state: a string, The state of the post. :param tags: a list of tags that you want applied to the post :param tweet: a ...
0.004115
def on_change(self, attr, old, new): """ Process change events adding timeout to process multiple concerted value change at once rather than firing off multiple plot updates. """ self._queue.append((attr, old, new)) if not self._active and self.plot.document: ...
0.004773
def sell_avg_holding_price(self): """ [float] 卖方向持仓均价 """ return 0 if self.sell_quantity == 0 else self._sell_holding_cost / self.sell_quantity / self.contract_multiplier
0.014851
def get_changed_files(include_staged=False): """ Returns a list of the files that changed in the Git repository. This is used to check if the files that are supposed to be upgraded have changed. If so, the upgrade will be prevented. """ process = subprocess.Popen(['git', 'status', '--porcelain'], stdou...
0.015965
def hashprefs(self): """ A ``list`` of preferred hash algorithms specified in this signature, if any. Otherwise, an empty ``list``. """ if 'PreferredHashAlgorithms' in self._signature.subpackets: return next(iter(self._signature.subpackets['h_PreferredHashAlgorithms'])).flags...
0.011834
def ensure_coordinator_ready(self): """Block until the coordinator for this group is known (and we have an active connection -- java client uses unsent queue). """ with self._client._lock, self._lock: while self.coordinator_unknown(): # Prior to 0.8.2 there w...
0.003441
def fire_trigger(request, trigger_id): """ start the handling of only ONE trigger :param request: request object :param trigger_id: the trigger ID to switch the status to True or False :type request: HttpRequest object :type trigger_id: int :return render :rty...
0.003003
def cal_k_bm3(p, k): """ calculate bulk modulus :param p: pressure :param k: [v0, k0, k0p] :return: bulk modulus at high pressure """ v = cal_v_bm3(p, k) return cal_k_bm3_from_v(v, k)
0.00463
def b58decode(v: str) -> bytes: '''Decode a Base58 encoded string''' origlen = len(v) v = v.lstrip(alphabet[0]) newlen = len(v) p, acc = 1, 0 for c in v[::-1]: acc += p * alphabet.index(c) p *= 58 result = [] while acc > 0: acc, mod = divmod(acc, 256) r...
0.002506
def schedule_downtime(scope, api_key=None, app_key=None, monitor_id=None, start=None, end=None, message=None, recurrence=None, timezone=None, ...
0.001231
def add_source(self, source_name, description=None): """Adds a row to table "source" if "name" does not exist. Returns (source_id, True) if a new row is created, (source_id, False) otherwise. """ # TODO: shoud be able to do this inside a transaction if not source_name:...
0.00534
def movement(self): """ Returns the movement of this aspect. The movement is the one of the active object, except if the active is separating but within less than 1 degree. """ mov = self.active.movement if self.orb < 1 and mov == const.SEPARATIVE: ...
0.013736
def _check_formula_terms(self, ds, coord): ''' Checks a dimensionless vertical coordinate contains valid formula_terms - formula_terms is a non-empty string - formula_terms matches regx - every variable defined in formula_terms exists :param netCDF4.Dataset ds: An open ...
0.003813
def _my_hash(arg_list): # type: (List[Any]) -> int """Simple helper hash function""" res = 0 for arg in arg_list: res = res * 31 + hash(arg) return res
0.005587
def iter_orgs(username, number=-1, etag=None): """List the organizations associated with ``username``. :param str username: (required), login of the user :param int number: (optional), number of orgs to return. Default: -1, return all of the issues :param str etag: (optional), ETag from a previ...
0.001916
def get_external_account(resource_root, name, view=None): """ Lookup an external account by name @param resource_root: The root Resource object. @param name: Account name @param view: View @return: An ApiExternalAccount object """ return call(resource_root.get, EXTERNAL_ACCOUNT_FETCH_PATH % ("acco...
0.012285
def limit(self, maximum): """ Return a new query, limited to a certain number of results. Unlike core reporting queries, you cannot specify a starting point for live queries, just the maximum results returned. ```python # first 50 query.limit(50) ``` ...
0.004357
def export(user, directory=None, warnings=True): """ Build a temporary directory with the visualization. Returns the local path where files have been written. Examples -------- >>> bandicoot.visualization.export(U) Successfully exported the visualization to /tmp/tmpsIyncS """ ...
0.000994
def sample(self, logits, argmax_sampling=False): """ Sample from a probability space of all actions """ if argmax_sampling: return torch.argmax(logits, dim=-1) else: u = torch.rand_like(logits) return torch.argmax(logits - torch.log(-torch.log(u)), dim=-1)
0.006329
def reassembly(self, info): """Reassembly procedure. Positional arguments: * info -- Info, info dict of packets to be reassembled """ BUFID = info.bufid # Buffer Identifier DSN = info.dsn # Data Sequence Number ACK = info.ack # Acknowledgement Num...
0.003422
def get_options(self): """ Get program options. """ super(ScriptBaseWithConfig, self).get_options() self.config_dir = os.path.abspath(os.path.expanduser(self.options.config_dir or os.environ.get('PYRO_CONFIG_DIR', None) or self.CONFIG_DIR_DEFAULT)) load_c...
0.007538
def write(self, filename, append=True): """Write the parameters to a file as a human-readable series of dicts. :type filename: str :param filename: File to write to :type append: bool :param append: Append to already existing file or over-write. """ header = ' '....
0.002415
def doctree_resolved(app, doctree, fromdocname): """ When the document, and all the links are fully resolved, we inject one raw html element for running the command for processing the wavedrom diagrams at the onload event. """ # Skip for non-html or if javascript is not inlined if not app.en...
0.001686
def set_version(self, version): """ Set the version number of the certificate. Note that the version value is zero-based, eg. a value of 0 is V1. :param version: The version number of the certificate. :type version: :py:class:`int` :return: ``None`` """ ...
0.004329
def _vertex_enumeration_gen(labelings_bits_tup, equations_tup, trans_recips): """ Main body of `vertex_enumeration_gen`. Parameters ---------- labelings_bits_tup : tuple(ndarray(np.uint64, ndim=1)) Tuple of ndarrays of integers representing labelings of the vertices of the best resp...
0.000714
def type(self): """ Retrieve the Type (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_type'): self._type = conf.lib.clang_getCursorType(self) return self._type
0.008333
def _intersection(A,B): """ A simple function to find an intersection between two arrays. @type A: List @param A: First List @type B: List @param B: Second List @rtype: List @return: List of Intersections """ intersection = [] for i in A: if i in B: ...
0.018568
def kwargs_to_variable_assignment(kwargs: dict, value_representation=repr, assignment_operator: str = ' = ', statement_separator: str = '\n', statement_per_line: bool = False) -> str: """ Convert a dictionary i...
0.001168
def catCSVs(folder, ouputFileName, removeDups = False) : """Concatenates all csv in 'folder' and wites the results in 'ouputFileName'. My not work on non Unix systems""" strCmd = r"""cat %s/*.csv > %s""" %(folder, ouputFileName) os.system(strCmd) if removeDups : removeDuplicates(ouputFileName, ouputFileName)
0.037975
def watch(self, path, func=None, delay=0, ignore=None): """Add a task to watcher. :param path: a filepath or directory path or glob pattern :param func: the function to be executed when file changed :param delay: Delay sending the reload message. Use 'forever' to n...
0.002911
def savenetcdf(dataarray, filename=None): """Save a dataarray to a NetCDF file. Args: dataarray (xarray.DataArray): Dataarray to be saved. filename (str): Filename (used as <filename>.nc). If not spacified, random 8-character name will be used. """ if filename is None: ...
0.001511
def _nest(self): """nests the roles (creates roles hierarchy)""" self._flatten() parent_roles = {} for roleid in self.flatten: role = copy.deepcopy(self.flatten[roleid]) # Display name is mandatory if 'display_name' not in role: raise ...
0.000704
def do_json_cat(self, params): """ \x1b[1mNAME\x1b[0m json_cat - Pretty prints a znode's JSON \x1b[1mSYNOPSIS\x1b[0m json_cat <path> [recursive] \x1b[1mOPTIONS\x1b[0m * recursive: recurse to all children (default: false) \x1b[1mEXAMPLES\x1b[0m > json_cat /configs/clusters ...
0.001502
def prettify_json(json_string): """Given a JSON string, it returns it as a safe formatted HTML""" try: data = json.loads(json_string) html = '<pre>' + json.dumps(data, sort_keys=True, indent=4) + '</pre>' except: html = json_string return mark_safe(html)
0.006711
def identity_gate(qubits: Union[int, Qubits]) -> Gate: """Returns the K-qubit identity gate""" _, qubits = qubits_count_tuple(qubits) return I(*qubits)
0.006135
def cli(env, identifier, details): """Invoices and all that mess""" manager = AccountManager(env.client) top_items = manager.get_billing_items(identifier) title = "Invoice %s" % identifier table = formatting.Table(["Item Id", "Category", "Description", "Single", "Mont...
0.001748
def replace_default_error_messages(): """ Replace Django's generic error messages with MTP-specific versions NB: avoid trailing full stops visually, they are added for screen readers in templates """ forms.Field.default_error_messages['required'] = _('This field is required') forms.CharField.def...
0.006198
def create(cls, name, multilink_members, multilink_method='rtt', retries=2, timeout=3600, comment=None): """ Create a new multilink configuration. Multilink requires at least one netlink for operation, although 2 or more are recommeneded. :param str name: name of ...
0.003618
def create_policy_version(policy_name, policy_document, set_as_default=None, region=None, key=None, keyid=None, profile=None): ''' Create a policy version. CLI Example: .. code-block:: bash salt myminios boto_iam.create_policy_version mypolicy '{"Version": "2012-10-17", "Stat...
0.003492
def iter_ensure_instance(iterable, types): """ Iterate over object and check each item type >>> iter_ensure_instance([1,2,3], [str]) Traceback (most recent call last): TypeError: >>> iter_ensure_instance([1,2,3], int) >>> iter_ensure_instance(1, int) Traceback (most recent call last): ...
0.006834
def append_hashx_signer(self, hashx, signer_weight, source=None): """Add a HashX signer to an account. Add a HashX signer to an account via a :class:`SetOptions <stellar_base.operation.SetOptions` operation. This is a helper function for :meth:`append_set_options_op`. :param ha...
0.002519
def patched_get_current(self, request=None): """ Monkey patched version of Django's SiteManager.get_current() function. Returns the current Site based on a given request or the SITE_ID in the project's settings. If a request is given attempts to match a site with domain matching request.get_host()....
0.00258
def get_histograms(self, request): """ Get histograms of requested query from log service. Unsuccessful opertaion will cause an LogException. :type request: GetHistogramsRequest :param request: the GetHistograms request parameters class. :return: GetHisto...
0.005425
def begin_segment(self, name=None, traceid=None, parent_id=None, sampling=None): """ Begin a segment on the current thread and return it. The recorder only keeps one segment at a time. Create the second one without closing existing one will overwrite it. :p...
0.00327
def support_autoupload_param_directory(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") support = ET.SubElement(config, "support", xmlns="urn:brocade.com:mgmt:brocade-ras") autoupload_param = ET.SubElement(support, "autoupload-param") directory = ...
0.005952
def model_counts_spectrum(self, name, logemin=None, logemax=None, summed=False, weighted=False): """Return the predicted number of model counts versus energy for a given source and energy range. If summed=True return the counts spectrum summed over all components o...
0.003094
def __add_coreference_chain_tiers(self, docgraph, body, min_chain_length=3): """ Parameters ---------- docgraph : DiscourseDocumentGraph the document graph from which the chains will be extracted body : etree._Element ...
0.001751
def define_udp(self, name, valid_type, valid_components=None, default=None): """ Pre-define a user-defined property. This is the equivalent to the following RDL: .. code-block:: none property <name> { type = <valid_type>; component = <valid_...
0.004704
def doubleclickrow(self, window_name, object_name, row_text): """ Double click row matching given text @param window_name: Window name to type in, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param object_name: Object name to type ...
0.003695
def skip_common_stack_elements(stacktrace, base_case): """Skips items that the target stacktrace shares with the base stacktrace.""" for i, (trace, base) in enumerate(zip(stacktrace, base_case)): if trace != base: return stacktrace[i:] return stacktrace[-1:]
0.018248
def create_sketch(self, name, description): """Create a new sketch with the specified name and description. Args: name (str): Title of sketch description (str): Description of sketch Returns: int: ID of created sketch """ resource_url = '{0:s}/sketches/'.format(self.api_base_url)...
0.001821
def _system_path(self, subdir, basename=''): ''' Gets the full path to the 'subdir/basename' file in the system binwalk directory. @subdir - Subdirectory inside the system binwalk directory. @basename - File name inside the subdirectory. Returns the full path to the 'subdir/b...
0.007246
def get_username(sciper): """ Return username of user """ attribute = 'uid' response = LDAP_search( pattern_search='(uniqueIdentifier={})'.format(sciper), attribute=attribute ) try: username = get_attribute(response, attribute) except Exception: raise Epfl...
0.004902
def changelist_view(self, request, extra_context=None, *args, **kwargs): """ Handle the changelist view, the django view for the model instances change list/actions page. """ if 'actions_column' not in self.list_display: self.list_display.append('actions_column') ...
0.003378
def slicing(args, length): """Internally used.""" if isinstance(args, tuple): for arg in args: yield from slicing_singlevalue(arg, length) else: yield from slicing_singlevalue(args, length)
0.004367
def clgrad(obj, exe, arg, delta=DELTA): """ Returns numerical gradient function of given class method with respect to a class attribute Input: obj, general object exe (str), name of object method arg (str), name of object atribute delta(float, optional), finite differenc...
0.002315
def getOutput(self): """ Returns the combined output of stdout and stderr """ output = self.stdout if self.stdout: output += '\r\n' output += self.stderr return output
0.008511
def pdb(self): """Generates a PDB string for the `PseudoMonomer`.""" pdb_str = write_pdb( [self], ' ' if not self.tags['chain_id'] else self.tags['chain_id']) return pdb_str
0.014354
def modify(self, management_address=None, username=None, password=None, connection_type=None): """ Modifies a remote system for remote replication. :param management_address: same as the one in `create` method. :param username: username for accessing the remote system. ...
0.004087
def is_child_of_objective(self, id_=None, objective_id=None): """Tests if an objective is a direct child of another. arg: id (osid.id.Id): an Id arg: objective_id (osid.id.Id): the Id of an objective return: (boolean) - true if the id is a child of objective_id, fa...
0.002347
def log(self, msg): """ log function Args: msg: the text message to be logged """ time = self.get_time() msg = "{:s}\t {:s}".format(time, msg) self.history.append(msg) self.history_model.insertRow(0, QtGui.QStandardItem(msg))
0.006579
def print_last(limit=None, file=None): """This is a shorthand for 'print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file)'.""" if not hasattr(sys, "last_type"): raise ValueError("no last exception") if file is None: file = sys.stderr print_exception(sys.last_...
0.002538
def list(self, before_id=None, since_id=None, **kwargs): """Return a page of direct messages. The messages come in reversed order (newest first). Note you can only provide _one_ of ``before_id``, ``since_id``. :param str before_id: message ID for paging backwards :param str sin...
0.003306
def fix_error_editor(self,filename,linenum,column,msg): """Open the editor at the given filename, linenumber, column and show an error message. This is used for correcting syntax errors. The current implementation only has special support for the VIM editor, and falls back on the 'editor' hook if VIM is...
0.010405
def rectify(self, slitlet2d, resampling, inverse=False): """Rectify slitlet using computed transformation. Parameters ---------- slitlet2d : numpy array Image containing the 2d slitlet image. resampling : int 1: nearest neighbour, 2: flux preserving inter...
0.001275
def deptree(self, field, oids, date=None, level=None, table=None): ''' Dependency tree builder. Recursively fetchs objects that are children of the initial set of parent object ids provided. :param field: Field that contains the 'parent of' data :param oids: Object oids to build...
0.001701
def get_distribution_names(self): """ Return all the distribution names known to this locator. """ result = set() for root, dirs, files in os.walk(self.base_dir): for fn in files: if self.should_include(fn, root): fn = os.path.join(...
0.002732
def readByte(self): """ Reads a byte value from the L{ReadData} stream object. @rtype: int @return: The byte value read from the L{ReadData} stream. """ byte = unpack('B' if not self.signed else 'b', self.readAt(self.offset, 1))[0] self.offset += 1 ...
0.012012
def get_mem_total(self): """Calculate the total memory in the current service unit.""" with open('/proc/meminfo') as meminfo_file: for line in meminfo_file: key, mem = line.split(':', 2) if key == 'MemTotal': mtot, modifier = mem.strip().sp...
0.005102
def visit_Call(self, node: parsing.Call) -> ast.expr: """Generates python code calling the function. fn(*args) """ return ast.Call( ast.Attribute( ast.Name('self', ast.Load), node.callObject.__name__, ast.Load()), [...
0.004843
def raw_reader(queue=None): """Returns a raw binary reader co-routine. Args: queue (Optional[BufferQueue]): The buffer read data for parsing, if ``None`` a new one will be created. Yields: IonEvent: parse events, will have an event type of ``INCOMPLETE`` if data is needed ...
0.007194
def __send_message_recv_reply(self, packed_message): """ Private method to send packed message and receive the reply message. :param packed_message: a binary string containing the entire message payload """ payload = io.BytesIO() try: with self._socket_lock: ...
0.003324
def _convolve3_old(data, h, dev=None): """convolves 3d data with kernel h on the GPU Device dev boundary conditions are clamping to edge. h is converted to float32 if dev == None the default one is used """ if dev is None: dev = get_device() if dev is None: raise ValueErro...
0.002786
def _create_disk( self, name, spec, template_repo=None, template_store=None, ): """ Creates a disc with the given name from the given repo or store Args: name (str): Name of the domain to create the disk for spec (dict): Specif...
0.001764
def handle(self, data, **kwargs): """Run marshalling for the specified mapper_class. Supports both .marshal and .many().marshal Kim interfaces. Handles errors raised during marshalling and automatically returns a HTTP error response. :param data: Data to be marshaled. :returns...
0.004228
def make_sequence(self): """Converts the response iterator in a list. By default this happens automatically if required. If `implicit_sequence_conversion` is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items. ...
0.002628
def add(self, pattern, function, method=None, type_cast=None): """Function for registering a path pattern. Args: pattern (str): Regex pattern to match a certain path. function (function): Function to associate with this path. method (str, optional): Usually used to d...
0.001986
def sparkline_value_color_map_apply_to(self, sparkline_value_color_map_apply_to): """Sets the sparkline_value_color_map_apply_to of this ChartSettings. For the single stat view, whether to apply dynamic color settings to the displayed TEXT or BACKGROUND # noqa: E501 :param sparkline_value_col...
0.004474
def parse_css(self, css): """ Parse a css style sheet into the CSS object. For the moment this will only work for very simple css documents. It works by using regular expression matching css syntax. This is not bullet proof. """ rulesets = self.ruleset_re.finda...
0.003731
def StartElement(self,name,attributes): 'SAX start element even handler' # Instantiate an Element object element = Element(name.encode(),attributes) # Push element onto the stack and make it a child of parent if len(self.nodeStack) > 0: parent = self.nodeStack[-1] parent.AddChild(element) else: ...
0.045699
def check_reference_label(y, ref_label): ''' :param list y: label :param ref_label: reference label ''' set_y = set(y) if ref_label not in set_y: raise ValueError('There is not reference label in dataset. ' "Reference label: '%s' " 'Label...
0.002786
def restore_from_snapshot(self, volume_id, snapshot_id): """Restores a specific volume from a snapshot :param integer volume_id: The id of the volume :param integer snapshot_id: The id of the restore point :return: Returns whether succesfully restored or not """ return ...
0.004577
def _is_numeric_data(self, data_type): """Private method for testing text data types.""" dt = DATA_TYPES[data_type] if dt['min'] and dt['max']: if type(self.data) is dt['type'] and dt['min'] < self.data < dt['max']: self.type = data_type.upper() self.l...
0.008065
def _children(self): """Yield all direct children of this object.""" if self.declarations: yield self.declarations if isinstance(self.condition, CodeExpression): yield self.condition if self.increment: yield self.increment for codeobj in self.b...
0.005525
def _permute_aux_specs(self): """Generate all permutations of the non-core specifications.""" # Convert to attr names that Calc is expecting. calc_aux_mapping = self._NAMES_SUITE_TO_CALC.copy() # Special case: manually add 'library' to mapping calc_aux_mapping[_OBJ_LIB_STR] = Non...
0.003367