Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
7,700
def _use_gl(objs): from ..models.plots import Plot return _any(objs, lambda obj: isinstance(obj, Plot) and obj.output_backend == "webgl")
Whether a collection of Bokeh objects contains a plot requesting WebGL Args: objs (seq[Model or Document]) : Returns: bool
7,701
def _on_remove_library(self, *event): self.view[].grab_focus() if react_to_event(self.view, self.view[], event): path = self.view["library_tree_view"].get_cursor()[0] if path is not None: library_name = self.library_list_store[int(path[0])][0] ...
Callback method handling the removal of an existing library
7,702
def add_element(self, elt): if not isinstance(elt, Element): raise TypeError("argument should be a subclass of Element") self.elements[elt.get_name()] = elt return elt
Helper to add a element to the current section. The Element name will be used as an identifier.
7,703
def proxy_label_for(label: str) -> str: label_java = _VertexLabel(label).unwrap() proxy_label_java = k.jvm_view().SequenceBuilder.proxyLabelFor(label_java) return proxy_label_java.getQualifiedName()
>>> Sequence.proxy_label_for("foo") 'proxy_for.foo'
7,704
def best_policy(mdp, U): pi = {} for s in mdp.states: pi[s] = argmax(mdp.actions(s), lambda a:expected_utility(a, s, U, mdp)) return pi
Given an MDP and a utility function U, determine the best policy, as a mapping from state to action. (Equation 17.4)
7,705
def get_push_pop_stack(): push = copy.deepcopy(PUSH_STACK) pop = copy.deepcopy(POP_STACK) anno.setanno(push, , pop) anno.setanno(push, , True) anno.setanno(pop, , push) op_id = _generate_op_id() return push, pop, op_id
Create pop and push nodes for substacks that are linked. Returns: A push and pop node which have `push_func` and `pop_func` annotations respectively, identifying them as such. They also have a `pop` and `push` annotation respectively, which links the push node to the pop node and vice ver...
7,706
def _dry_message_received(self, msg): for callback in self._dry_wet_callbacks: callback(LeakSensorState.DRY) self._update_subscribers(0x11)
Report a dry state.
7,707
def _take_values(self, item: Node) -> DictBasicType: values = super()._take_values(item) values[] = None return values
Takes snapshot of the object and replaces _parent property value on None to avoid infitinite recursion in GPflow tree traversing. :param item: GPflow node object. :return: dictionary snapshot of the node object.
7,708
def admin_log(instances, msg: str, who: User=None, **kw): from django.contrib.admin.models import LogEntry, CHANGE from django.contrib.admin.options import get_content_type_for_model from django.utils.encoding import force_text if not who: username = settings.DJANGO_SYSTEM_USER if ha...
Logs an entry to admin logs of model(s). :param instances: Model instance or list of instances :param msg: Message to log :param who: Who did the change :param kw: Optional key-value attributes to append to message :return: None
7,709
def zlist(self, name_start, name_end, limit=10): limit = get_positive_integer(, limit) return self.execute_command(, name_start, name_end, limit)
Return a list of the top ``limit`` zset's name between ``name_start`` and ``name_end`` in ascending order .. note:: The range is (``name_start``, ``name_end``]. The ``name_start`` isn't in the range, but ``name_end`` is. :param string name_start: The lower bound(not included) of zse...
7,710
def apply_pre_filters(instance, html): for post_func in appsettings.PRE_FILTER_FUNCTIONS: html = post_func(instance, html) return html
Perform optimizations in the HTML source code. :type instance: fluent_contents.models.ContentItem :raise ValidationError: when one of the filters detects a problem.
7,711
def visit_importfrom(self, node): if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node): return name_parts = node.modname.split(".") try: module = node.do_import_module(name_parts[0]) except astroid.Astroid...
check modules attribute accesses
7,712
def p_recent(self, kind, cur_p=, with_catalog=True, with_date=True): if cur_p == : current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MPost.total_num...
List posts that recent edited, partially.
7,713
def update_user(self, user_id, **kwargs): body = self._formdata(kwargs, FastlyUser.FIELDS) content = self._fetch("/user/%s" % user_id, method="PUT", body=body) return FastlyUser(self, content)
Update a user.
7,714
def is_child_of(self, node): return node.get_children().filter(pk=self.pk).exists()
:returns: ``True`` if the node is a child of another node given as an argument, else, returns ``False`` :param node: The node that will be checked as a parent
7,715
def patch_namespaced_stateful_set_scale(self, name, namespace, body, **kwargs): kwargs[] = True if kwargs.get(): return self.patch_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs) else: (data) = self.patch_namespaced_stateful_set_...
patch_namespaced_stateful_set_scale # noqa: E501 partially update scale of the specified StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_stateful_set_sc...
7,716
def read_multi(flatten, cls, source, *args, **kwargs): verbose = kwargs.pop(, False) try: files = file_list(source) except ValueError: files = [source] path = None else: path = files[0] if files else None return fobj, exc.getExceptio...
Read sources into a `cls` with multiprocessing This method should be called by `cls.read` and uses the `nproc` keyword to enable and handle pool-based multiprocessing of multiple source files, using `flatten` to combine the chunked data into a single object of the correct type. Parameters ----...
7,717
async def delete_chat_photo(self, chat_id: typing.Union[base.Integer, base.String]) -> base.Boolean: payload = generate_payload(**locals()) result = await self.request(api.Methods.DELETE_CHAT_PHOTO, payload) return result
Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ sett...
7,718
def compare(ver1, ver2): v1, v2 = parse(ver1), parse(ver2) return _compare_by_keys(v1, v2)
Compare two versions :param ver1: version string 1 :param ver2: version string 2 :return: The return value is negative if ver1 < ver2, zero if ver1 == ver2 and strictly positive if ver1 > ver2 :rtype: int >>> import semver >>> semver.compare("1.0.0", "2.0.0") -1 >>> semver...
7,719
def alphavsks(self,autozoom=True,**kwargs): pylab.plot(self._alpha_values, self._xmin_kstest, ) pylab.errorbar(self._alpha, self._ks, xerr=self._alphaerr, fmt=) ax=pylab.gca() if autozoom: ax.set_ylim(0.8*(self._ks),3*(self._ks)) ax.set_xlim((self._alph...
Plot alpha versus the ks value for derived alpha. This plot can be used as a diagnostic of whether you have derived the 'best' fit: if there are multiple local minima, your data set may be well suited to a broken powerlaw or a different function.
7,720
def edit(self, entity, id, payload, sync=True): url = urljoin(self.host, entity.value + ) url = urljoin(url, id + ) params = {: str(sync).lower()} url = Utils.add_url_parameters(url, params) r = requests.put(url, auth=self.auth, data=json.dumps(payload), ...
Edit a document.
7,721
def merge_commit(commit): "Fetches the latest code and merges up the specified commit." with cd(env.path): run() if in commit: branch, commit = commit.split() run(.format(branch)) run(.format(commit))
Fetches the latest code and merges up the specified commit.
7,722
def calcRapRperi(self,*args,**kwargs): if isinstance(self._pot,list): thispot= [p.toPlanar() for p in self._pot if not isinstance(p,planarPotential)] thispot.extend([p for p in self._pot if isinstance(p,planarPotential)]) elif not isinstance(self._pot,planarPote...
NAME: calcRapRperi PURPOSE: calculate the apocenter and pericenter radii INPUT: Either: a) R,vR,vT,z,vz b) Orbit instance: initial condition used if that's it, orbit(t) if there is a time given as well OUTPUT: ...
7,723
def subclass(cls, t): t.doc = None t.terms = [] t.__class__ = SectionTerm return t
Change a term into a Section Term
7,724
def save(self): self.cells = list(self.renumber()) if not self.cells[-1].endswith(): self.cells[-1] += with open(self.filename, ) as file_open: file_open.write(.join(self.cells))
Format and save cells.
7,725
def _add_embedding_config(file_path, data_dir, has_metadata=False, label_img_shape=None): with open(os.path.join(file_path, ), ) as f: s = s += .format(data_dir) s += .format(os.path.join(data_dir, )) if has_metadata: s += .format(os.path.join(data_dir, )) i...
Creates a config file used by the embedding projector. Adapted from the TensorFlow function `visualize_embeddings()` at https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/tensorboard/plugins/projector/__init__.py
7,726
def fixtags(self, text): text = _guillemetLeftPat.sub(ur, text) text = _guillemetRightPat.sub(ur, text) return text
Clean up special characters, only run once, next-to-last before doBlockLevels
7,727
def _to_ascii(s): from six import text_type, binary_type if isinstance(s, text_type): ascii_ = s.encode(, ) elif isinstance(s, binary_type): ascii_ = s.decode().encode(, ) else: raise Exception(.format(type(s))) return ascii_
Converts given string to ascii ignoring non ascii. Args: s (text or binary): Returns: str:
7,728
def generic_visit(self, node): if node.__class__.__name__ == : if node.ctx.__class__ == ast.Load and node.id not in self.names: self.names.append(node.id) ast.NodeVisitor.generic_visit(self, node)
TODO: docstring in public method.
7,729
def findAnyBracketBackward(self, block, column): depth = {: 1, : 1, : 1 } for foundBlock, foundColumn, char in self.iterateCharsBackwardFrom(block, column): if self._qpart.isCode(foundBlock.blockNumber(), foundColumn): ...
Search for a needle and return (block, column) Raise ValueError, if not found NOTE this methods ignores strings and comments
7,730
def _helpful_failure(method): @wraps(method) def wrapper(self, val): try: return method(self, val) except: exc_cls, inst, tb = sys.exc_info() if hasattr(inst, ): _, expr, _, inner_val = Q.__debug_info__ Q.__debug_info__ =...
Decorator for eval_ that prints a helpful error message if an exception is generated in a Q expression
7,731
def get_version(): "Returns a PEP 386-compliant version number from VERSION." assert len(VERSION) == 5 assert VERSION[3] in (, , , ) parts = 2 if VERSION[2] == 0 else 3 main = .join(str(x) for x in VERSION[:parts]) sub = if VERSION[3] != : mapping = {: , : , :...
Returns a PEP 386-compliant version number from VERSION.
7,732
def debug(self, value): self._debug = value if self._debug: logging.getLogger().setLevel(logging.DEBUG)
Turn on debug logging if necessary. :param value: Value of debug flag
7,733
def translate(self, body, params=None): if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument .") return self.transport.perform_request( "POST", "/_sql/translate", params=params, body=body )
`<Translate SQL into Elasticsearch queries>`_ :arg body: Specify the query in the `query` element.
7,734
def wait(self): "wait for a message, respecting timeout" data=self.getcon().recv(256) if not data: raise PubsubDisco if self.reset: self.reset=False raise PubsubDisco self.buf+=data msg,self.buf=complete_message(self.buf) return msg
wait for a message, respecting timeout
7,735
def generate(cls, curve=ec.SECP256R1(), progress_func=None, bits=None): if bits is not None: curve = cls._ECDSA_CURVES.get_by_key_length(bits) if curve is None: raise ValueError("Unsupported key length: {:d}".format(bits)) curve = curve.curve_class() ...
Generate a new private ECDSA key. This factory function can be used to generate a new host key or authentication key. :param progress_func: Not used for this type of key. :returns: A new private key (`.ECDSAKey`) object
7,736
def replay_position(position, result): assert position.n == len(position.recent), "Position history is incomplete" pos = Position(komi=position.komi) for player_move in position.recent: color, next_move = player_move yield PositionWithContext(pos, next_move, result) pos = pos.pl...
Wrapper for a go.Position which replays its history. Assumes an empty start position! (i.e. no handicap, and history must be exhaustive.) Result must be passed in, since a resign cannot be inferred from position history alone. for position_w_context in replay_position(position): print(position...
7,737
def _iop(self, operation, other, *allowed): f = self._field if self._combining: return reduce(self._combining, (q._iop(operation, other, *allowed) for q in f)) if __debug__ and _complex_safety_check(f, {operation} | set(allowed)): raise NotImplementedError("{self!r} does not allow ...
An iterative operation operating on multiple values. Consumes iterators to construct a concrete list at time of execution.
7,738
def MergeAttributeContainers( self, callback=None, maximum_number_of_containers=0): if maximum_number_of_containers < 0: raise ValueError() if not self._cursor: self._Open() self._ReadStorageMetadata() self._container_types = self._GetContainerTypes() number_of_container...
Reads attribute containers from a task storage file into the writer. Args: callback (function[StorageWriter, AttributeContainer]): function to call after each attribute container is deserialized. maximum_number_of_containers (Optional[int]): maximum number of containers to merge, wh...
7,739
def parseWord(word): mapping = {: True, : True, : False, : False} _, key, value = word.split(, 2) try: value = int(value) except ValueError: value = mapping.get(value, value) return (key, value)
Split given attribute word to key, value pair. Values are casted to python equivalents. :param word: API word. :returns: Key, value pair.
7,740
def set_output_fields(self, output_fields): if isinstance(output_fields, dict) or isinstance(output_fields, list): self.output_fields = output_fields elif isinstance(output_fields, basestring): self.output_field = output_fields else: raise ValueError(...
Defines where to put the dictionary output of the extractor in the doc, but renames the fields of the extracted output for the document or just filters the keys
7,741
def get_random(self): Statement = self.get_model() statement = Statement.objects.order_by().first() if statement is None: raise self.EmptyDatabaseException() return statement
Returns a random statement from the database
7,742
def get_prtfmt_list(self, flds, add_nl=True): fmts = [] for fld in flds: if fld[:2] == : fmts.append(.format(FLD=fld)) elif fld in self.default_fld2fmt: fmts.append(self.default_fld2fmt[fld]) else: raise Excepti...
Get print format, given fields.
7,743
def _request_bulk(self, urls: List[str]) -> List: if not urls: raise Exception("No results were found") session: FuturesSession = FuturesSession(max_workers=len(urls)) self.log.info("Bulk requesting: %d" % len(urls)) futures = [session.get(u, headers=gen_headers(), t...
Batch the requests going out.
7,744
def remove(self, removeItems=False): if not self.prepareToRemove(): return False items = self.items() if self._scene._layers: new_layer = self._scene._layers[0] else: new_layer = None ...
Removes this layer from the scene. If the removeItems flag is set to \ True, then all the items on this layer will be removed as well. \ Otherwise, they will be transferred to another layer from the scene. :param removeItems | <bool> :return <bool>
7,745
def update_house(self, complex: str, id: str, **kwargs): self.check_house(complex, id) self.put(.format( developer=self.developer, complex=complex, id=id, ), data=kwargs)
Update the existing house
7,746
def default(self, obj): countrowsEd JonesPete JonesWendy WilliamsMary ContraryFred Smith if hasattr(obj, ) and six.callable(obj.__json__): return obj.__json__() elif isinstance(obj, (date, datetime)): return str(obj) elif isinstance(obj, Decimal): ...
Converts an object and returns a ``JSON``-friendly structure. :param obj: object or structure to be converted into a ``JSON``-ifiable structure Considers the following special cases in order: * object has a callable __json__() attribute defined returns the resu...
7,747
def _solNa2SO4(T, mH2SO4, mNaCl): if T < 523.15 or T > 623.15 or mH2SO4 < 0 or mH2SO4 > 0.75 or \ mNaCl < 0 or mNaCl > 2.25: raise NotImplementedError("Incoming out of bound") A00 = -0.8085987*T+81.4613752+0.10537803*T*log(T) A10 = 3.4636364*T-281.63322-0.46779874*T*log(T) ...
Equation for the solubility of sodium sulfate in aqueous mixtures of sodium chloride and sulfuric acid Parameters ---------- T : float Temperature, [K] mH2SO4 : float Molality of sufuric acid, [mol/kg(water)] mNaCl : float Molality of sodium chloride, [mol/kg(water)] ...
7,748
def refresh(self, leave_clean=False): remote, merge = self._get_upstream() self._check_call([, , remote, merge], raise_type=Scm.RemoteException) try: self._check_call([, ], raise_type=Scm.LocalException) except Scm.LocalException as e: if leave_clean: logger.debug() try:...
Attempt to pull-with-rebase from upstream. This is implemented as fetch-plus-rebase so that we can distinguish between errors in the fetch stage (likely network errors) and errors in the rebase stage (conflicts). If leave_clean is true, then in the event of a rebase failure, the branch will be ro...
7,749
def operation_recorder_enabled(self, value): for recorder in self._operation_recorders: if value: recorder.enable() else: recorder.disable()
Setter method; for a description see the getter method.
7,750
def get_item(env, name, default=None): for key in name.split(): if isinstance(env, dict) and key in env: env = env[key] elif isinstance(env, types.ModuleType) and key in env.__dict__: env = env.__dict__[key] else: return default return env
Get an item from a dictionary, handling nested lookups with dotted notation. Args: env: the environment (dictionary) to use to look up the name. name: the name to look up, in dotted notation. default: the value to return if the name if not found. Returns: The result of looking up the name, if foun...
7,751
def set_position(self, position): if position > self._duration(): return position_ns = position * _NANOSEC_MULT self._manager[ATTR_POSITION] = position self._player.seek_simple(_FORMAT_TIME, Gst.SeekFlags.FLUSH, position_ns)
Set media position.
7,752
def compute_Wp(self, Epmin=None, Epmax=None): if Epmin is None and Epmax is None: Wp = self.Wp else: if Epmax is None: Epmax = self.Epmax if Epmin is None: Epmin = self.Epmin log10Epmin = np.log10(Epmin.to("GeV").v...
Total energy in protons between energies Epmin and Epmax Parameters ---------- Epmin : :class:`~astropy.units.Quantity` float, optional Minimum proton energy for energy content calculation. Epmax : :class:`~astropy.units.Quantity` float, optional Maximum proton ...
7,753
def filter(args): p = OptionParser(filter.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) frgfile, idsfile = args assert frgfile.endswith(".frg") fp = open(idsfile) allowed = set(x.strip() for x in fp) logging.debug("A total of {0}...
%prog filter frgfile idsfile Removes the reads from frgfile that are indicated as duplicates in the clstrfile (generated by CD-HIT-454). `idsfile` includes a set of names to include in the filtered frgfile. See apps.cdhit.ids().
7,754
def pick(self, *props): result = Parameters() for prop in props: if self.contains_key(prop): result.put(prop, self.get(prop)) return result
Picks select parameters from this Parameters and returns them as a new Parameters object. :param props: keys to be picked and copied over to new Parameters. :return: a new Parameters object.
7,755
def check(self, topic, value): datatype_key = topic.meta.get(, ) self._datatypes[datatype_key].check(topic, value) validate_dt = topic.meta.get(, None) if validate_dt: self._datatypes[validate_dt].check(topic, value)
Checking the value if it fits into the given specification
7,756
def run_iterations(cls, the_callable, iterations=1, label=None, schedule=, userdata = None, run_immediately=False, delay_until=None): task = task_with_callable(the_callable, label=label, schedule=schedule, userdata=userdata) task.iterations = iterations if delay_until is not None: ...
Class method to run a callable with a specified number of iterations
7,757
def exportable(self): if in self._signature.subpackets: return bool(next(iter(self._signature.subpackets[]))) return True
``False`` if this signature is marked as being not exportable. Otherwise, ``True``.
7,758
def deploy(self, initial_instance_count, instance_type, accelerator_type=None, endpoint_name=None, use_compiled_model=False, update_endpoint=False, **kwargs): self._ensure_latest_training_job() endpoint_name = endpoint_name or self.latest_training_job.name self.deploy_ins...
Deploy the trained model to an Amazon SageMaker endpoint and return a ``sagemaker.RealTimePredictor`` object. More information: http://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-training.html Args: initial_instance_count (int): Minimum number of EC2 instances to deploy to...
7,759
def _apply_advanced_config(config_spec, advanced_config, vm_extra_config=None): log.trace( , advanced_config) if isinstance(advanced_config, str): raise salt.exceptions.ArgumentValueError( advanced_configs\ ) for key, value in six.iteritems(advanced_config)...
Sets configuration parameters for the vm config_spec vm.ConfigSpec object advanced_config config key value pairs vm_extra_config Virtual machine vm_ref.config.extraConfig object
7,760
def render_image(self, rgbobj, dst_x, dst_y): pos = (0, 0) arr = self.viewer.getwin_array(order=self.rgb_order, alpha=1.0, dtype=np.uint8) self.gl_set_image(arr, pos)
Render the image represented by (rgbobj) at dst_x, dst_y in the pixel space.
7,761
def is_containerized() -> bool: try: cginfo = Path().read_text() if in cginfo or in cginfo: return True except IOError: return False
Check if I am running inside a Linux container.
7,762
def format_row(self, row): assert all(isinstance(x, VTMLBuffer) for x in row) raw = (fn(x) for x, fn in zip(row, self.formatters)) for line in itertools.zip_longest(*raw): line = list(line) for i, col in enumerate(line): if col is None: ...
Apply overflow, justification and padding to a row. Returns lines (plural) of rendered text for the row.
7,763
def get_connections(self): path = Client.urls[] conns = self._call(path, ) return conns
:returns: list of dicts, or an empty list if there are no connections.
7,764
def to_dict(self): return dict( variants=self.variants, distinct=self.distinct, sort_key=self.sort_key, sources=self.sources, source_to_metadata_dict=self.source_to_metadata_dict)
Since Collection.to_dict() returns a state dictionary with an 'elements' field we have to rename it to 'variants'.
7,765
def character_set(instance): char_re = re.compile(r) for key, obj in instance[].items(): if ( in obj and obj[] == and in obj): if enums.char_sets(): if obj[] not in enums.char_sets(): yield JSONError("The property of object " ...
Ensure certain properties of cyber observable objects come from the IANA Character Set list.
7,766
def _replace(self, feature, cursor): try: cursor.execute( constants._UPDATE, list(feature.astuple()) + [feature.id]) except sqlite3.ProgrammingError: cursor.execute( constants._INSERT, list(feature.astuple(s...
Insert a feature into the database.
7,767
def doQuery(self, url, method=, getParmeters=None, postParameters=None, files=None, extraHeaders={}, session={}): headers = {} if not postParameters: postParameters = {} for key, value in extraHeaders.iteritems(): if isinstance(value, bas...
Send a request to the server and return the result
7,768
def add_dnc( self, obj_id, channel=, reason=MANUAL, channel_id=None, comments= ): data = { : reason, : channel_id, : comments } response = self._client.session.post( .format( ...
Adds Do Not Contact :param obj_id: int :param channel: str :param reason: str :param channel_id: int :param comments: str :return: dict|str
7,769
def get_prinz_pot(nstep, x0=0., nskip=1, dt=0.01, kT=10.0, mass=1.0, damping=1.0): r pw = PrinzModel(dt, kT, mass=mass, damping=damping) return pw.sample(x0, nstep, nskip=nskip)
r"""wrapper for the Prinz model generator
7,770
def fetch_table_names(self, include_system_table=False): self.check_connection() return self.schema_extractor.fetch_table_names(include_system_table)
:return: List of table names in the database. :rtype: list :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Sample Code: .. code:: python from simplesql...
7,771
def recv(self, bufsiz, flags=None): buf = _no_zero_allocator("char[]", bufsiz) if flags is not None and flags & socket.MSG_PEEK: result = _lib.SSL_peek(self._ssl, buf, bufsiz) else: result = _lib.SSL_read(self._ssl, buf, bufsiz) self._raise_ssl_error(self...
Receive data on the connection. :param bufsiz: The maximum number of bytes to read :param flags: (optional) The only supported flag is ``MSG_PEEK``, all other flags are ignored. :return: The string read from the Connection
7,772
def p_const_expression_stringliteral(self, p): p[0] = StringConst(p[1], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
const_expression : stringliteral
7,773
def eventFilter(self, watchedObject, event): if self.comboBox.isEditable() and event.type() == QtCore.QEvent.KeyPress: key = event.key() if key in (Qt.Key_Delete, Qt.Key_Backspace): if (watchedObject == self._comboboxListView or (watchedObject...
Deletes an item from an editable combobox when the delete or backspace key is pressed in the list of items, or when ctrl-delete or ctrl-back space is pressed in the line-edit. When the combobox is not editable the filter does nothing.
7,774
def insert(self, key, obj, future_expiration_minutes=15): expiration_time = self._calculate_expiration(future_expiration_minutes) self._CACHE[key] = (expiration_time, obj) return True
Insert item into cache. :param key: key to look up in cache. :type key: ``object`` :param obj: item to store in cache. :type obj: varies :param future_expiration_minutes: number of minutes item is valid :type param: ``int`` :returns: True :rtype: ``boo...
7,775
def present(name, vname=None, vdata=None, vtype=, use_32bit_registry=False, win_owner=None, win_perms=None, win_deny_perms=None, win_inheritance=True, win_perms_reset=False): rd like to create beneath the Key...
r''' Ensure a registry key or value is present. Args: name (str): A string value representing the full path of the key to include the HIVE, Key, and all Subkeys. For example: ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` Valid hive values include: ...
7,776
def generate_scalar_constant(output_name, tensor_name, scalar): t = onnx.helper.make_tensor(tensor_name, data_type=TensorProto.FLOAT, dims=[1], vals=[scalar]) c = onnx.helper.make_node("Constant", [], ...
Convert a scalar value to a Constant buffer. This is mainly used for xxScalar operators.
7,777
def binaryEntropy(x): entropy = - x*x.log2() - (1-x)*(1-x).log2() entropy[x*(1 - x) == 0] = 0 return entropy, entropy.sum()
Calculate entropy for a list of binary random variables :param x: (torch tensor) the probability of the variable to be 1. :return: entropy: (torch tensor) entropy, sum(entropy)
7,778
def copy(self, dest, symlinks=False): if isinstance(dest, Directory): dest = dest.get_name() shutil.copytree(self.dirname, dest)
Copy to destination directory recursively. If symlinks is true, symbolic links in the source tree are represented as symbolic links in the new tree, but the metadata of the original links is NOT copied; if false or omitted, the contents and metadata of the linked files are copied to the ...
7,779
def _l2rgb(self, mode): self._check_modes(("L", "LA")) self.channels.append(self.channels[0].copy()) self.channels.append(self.channels[0].copy()) if self.fill_value is not None: self.fill_value = self.fill_value[:1] * 3 + self.fill_value[1:] if self.mode == ...
Convert from L (black and white) to RGB.
7,780
def filtany(entities, **kw): ret = set() for k,v in kw.items(): for entity in entities: if getattr(entity, k)() == v: ret.add(entity) return ret
Filter a set of entities based on method return. Use keyword arguments. Example: filtmeth(entities, id='123') filtmeth(entities, name='bart') Multiple filters are 'OR'.
7,781
def objwalk(obj, path=(), memo=None): if len( path ) > MAX_DEPTH + 1: yield path, obj if memo is None: memo = set() iterator = None if isinstance(obj, Mapping): iterator = iteritems elif isinstance(obj, (Sequence, Set)) and not isinstance(obj, string_types): ite...
Walks an arbitrary python pbject. :param mixed obj: Any python object :param tuple path: A tuple of the set attributes representing the path to the value :param set memo: The list of attributes traversed thus far :rtype <tuple<tuple>, <mixed>>: The path to the value on the object, the value.
7,782
def nb_r_deriv(r, data_row): n = len(data_row) d = sum(digamma(data_row + r)) - n*digamma(r) + n*np.log(r/(r+np.mean(data_row))) return d
Derivative of log-likelihood wrt r (formula from wikipedia) Args: r (float): the R paramemter in the NB distribution data_row (array): 1d array of length cells
7,783
def delete_webhook(self, ): result = self.do("deleteWebhook", ) if self.return_python_objects: logger.debug("Trying to parse {data}".format(data=repr(result))) try: return from_array_list(bool, result, list_level=0, is_builtin=True) e...
Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters. https://core.telegram.org/bots/api#deletewebhook Returns: :return: Returns True on success :rtype: bool
7,784
def generate_report( self, components, output_folder=None, iface=None, ordered_layers_uri=None, legend_layers_uri=None, use_template_extent=False): if not iface: iface = iface_object ...
Generate Impact Report independently by the Impact Function. :param components: Report components to be generated. :type components: list :param output_folder: The output folder. :type output_folder: str :param iface: A QGIS App interface :type iface: QgsInterface ...
7,785
def literal_eval(node_or_string): _safe_names = { : None, : True, : False, : dict, : list, : sorted } if isinstance(node_or_string, basestring): node_or_string = parse(node_or_string, mode=) if isinstance(node_or_string, ast.Expr...
Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
7,786
def _apply_odf_properties(df, headers, model): df.headers = headers df.model = model
Attach properties to the Dataframe to carry along ODF metadata :param df: The dataframe to be modified :param headers: The ODF header lines :param model: The ODF model type
7,787
def get_times_from_utterance(utterance: str, char_offset_to_token_index: Dict[int, int], indices_of_approximate_words: Set[int]) -> Dict[str, List[int]]: pm_linking_dict = _time_regex_match(r, utterance, ...
Given an utterance, we get the numbers that correspond to times and convert them to values that may appear in the query. For example: convert ``7pm`` to ``1900``.
7,788
def changiling(self, infile): gf = infile[31:] baby, fetch = (self.word_toaster() for _ in range(2)) gf = [g.replace(baby, fetch) for g in gf] return infile[:31] + gf
Changiling: 任意のバイト文字を 他の任意のバイト文字に置き換える
7,789
def patch_project(self, owner, id, **kwargs): kwargs[] = True if kwargs.get(): return self.patch_project_with_http_info(owner, id, **kwargs) else: (data) = self.patch_project_with_http_info(owner, id, **kwargs) return data
Update a project Update an existing project. Note that only elements, files or linked datasets included in the request will be updated. All omitted elements, files or linked datasets will remain untouched. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP requ...
7,790
def findScopedPar(theDict, scope, name): if len(scope): theDict = theDict[scope] return theDict, theDict[name]
Find the given par. Return tuple: (its own (sub-)dict, its value).
7,791
def trace(self, name, chain=-1): trace = copy.copy(self._traces[name]) trace._chain = chain return trace
Return the trace of a tallyable object stored in the database. :Parameters: name : string The name of the tallyable object. chain : int The trace index. Setting `chain=i` will return the trace created by the ith call to `sample`.
7,792
def get_line(thing): try: return inspect.getsourcelines(thing)[1] except TypeError: return inspect.getsourcelines(thing.fget)[1] except Exception as e: raise e
Get the line number for something. Parameters ---------- thing : function, class, module Returns ------- int Line number in the source file
7,793
def _process(self, project, build_system, job_priorities): jobs = [] cache_key = .format(project, build_system) ref_data_names_map = cache.get(cache_key) if not ref_data_names_map: ref_data_names_map = self._build_ref_data_names(pr...
Return list of ref_data_name for job_priorities
7,794
def vote_count(self): return Vote.objects.filter( content_type=ContentType.objects.get_for_model(self), object_id=self.id ).aggregate(Sum())[] or 0
Returns the total number of votes cast for this poll options.
7,795
def get_symbol_train(network, num_classes, from_layers, num_filters, strides, pads, sizes, ratios, normalizations=-1, steps=[], min_filter=128, nms_thresh=0.5, force_suppress=False, nms_topk=400, **kwargs): label = mx.sym.Variable() body = import_module(network).ge...
Build network symbol for training SSD Parameters ---------- network : str base network symbol name num_classes : int number of object classes not including background from_layers : list of str feature extraction layers, use '' for add extra layers For example: ...
7,796
def average_patterson_f3(acc, aca, acb, blen, normed=True): T, B = patterson_f3(acc, aca, acb) if normed: f3 = np.nansum(T) / np.nansum(B) else: f3 = np.nanmean(T) if normed: T_bsum = moving_statistic(T, statistic=np.nansum, size=blen) ...
Estimate F3(C; A, B) and standard error using the block-jackknife. Parameters ---------- acc : array_like, int, shape (n_variants, 2) Allele counts for the test population (C). aca : array_like, int, shape (n_variants, 2) Allele counts for the first source population (A). acb : arra...
7,797
def plot_entropy(self, tmin, tmax, ntemp, ylim=None, **kwargs): temperatures = np.linspace(tmin, tmax, ntemp) if self.structure: ylabel = r"$S$ (J/K/mol)" else: ylabel = r"$S$ (J/K/mol-c)" fig = self._plot_thermo(self.dos.entropy, temperatures, ylabel=y...
Plots the vibrational entrpy in a temperature range. Args: tmin: minimum temperature tmax: maximum temperature ntemp: number of steps ylim: tuple specifying the y-axis limits. kwargs: kwargs passed to the matplotlib function 'plot'. Returns: ...
7,798
def nl_send_iovec(sk, msg, iov, _): hdr = msghdr(msg_name=sk.s_peer, msg_iov=iov) dst = nlmsg_get_dst(msg) if dst.nl_family == socket.AF_NETLINK: hdr.msg_name = dst creds = nlmsg_get_creds(msg) if creds: raise NotImplementedError return nl_sendmsg(sk, msg, hdr...
Transmit Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L342 This function is identical to nl_send(). This function triggers the `NL_CB_MSG_OUT` callback. Positional arguments: sk -- Netlink socket (nl_sock class instance). msg -- Netlink message (nl_msg class in...
7,799
def bucket_exists(self, bucket_name): is_valid_bucket_name(bucket_name) try: self._url_open(, bucket_name=bucket_name) except NoSuchBucket: return False except ResponseError: raise return True
Check if the bucket exists and if the user has access to it. :param bucket_name: To test the existence and user access. :return: True on success.