Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
385,800
def tree_multiresolution(G, Nlevel, reduction_method=, compute_full_eigen=False, root=None): r if not root: if hasattr(G, ): root = G.root else: root = 1 Gs = [G] if compute_full_eigen: Gs[0].compute_fourier_basis() subsamp...
r"""Compute a multiresolution of trees Parameters ---------- G : Graph Graph structure of a tree. Nlevel : Number of times to downsample and coarsen the tree root : int The index of the root of the tree. (default = 1) reduction_method : str The graph reduction method (de...
385,801
def _convert_or_shorten_month(cls, data): short_month = { "jan": [str(1), "01", "Jan", "January"], "feb": [str(2), "02", "Feb", "February"], "mar": [str(3), "03", "Mar", "March"], "apr": [str(4), "04", "Apr", "April"], "may": [str(5)...
Convert a given month into our unified format. :param data: The month to convert or shorten. :type data: str :return: The unified month name. :rtype: str
385,802
def rect(self): CheckParent(self) val = _fitz.Link_rect(self) val = Rect(val) return val
rect(self) -> PyObject *
385,803
def gausspars(fwhm, nsigma=1.5, ratio=1, theta=0.): xsigma = fwhm / FWHM2SIG ysigma = ratio * xsigma f = nsigma**2/2. theta = np.deg2rad(theta) cost = np.cos(theta) sint = np.sin(theta) if ratio == 0: if theta == 0 or theta == 180: a = 1/xsigma**2 ...
height - the amplitude of the gaussian x0, y0, - center of the gaussian fwhm - full width at half maximum of the observation nsigma - cut the gaussian at nsigma ratio = ratio of xsigma/ysigma theta - angle of position angle of the major axis measured counter-clockwise fro...
385,804
def add_to_emails(self, *emails): assert all(isinstance(element, (str, unicode)) for element in emails), emails post_parameters = emails headers, data = self._requester.requestJsonAndCheck( "POST", "/user/emails", input=post_parameters )
:calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_ :param email: string :rtype: None
385,805
def list_datasets(self, get_global_public): appending = "" if get_global_public: appending = "public" url = self.url() + "/resource/{}dataset/".format(appending) req = self.remote_utils.get_url(url) if req.status_code is not 200: raise RemoteData...
Lists datasets in resources. Setting 'get_global_public' to 'True' will retrieve all public datasets in cloud. 'False' will get user's public datasets. Arguments: get_global_public (bool): True if user wants all public datasets in cloud. False i...
385,806
def run(cl_args, compo_type): cluster, role, env = cl_args[], cl_args[], cl_args[] topology = cl_args[] spouts_only, bolts_only = cl_args[], cl_args[] try: components = tracker_access.get_logical_plan(cluster, env, topology, role) topo_info = tracker_access.get_topology_info(cluster, env, topology, r...
run command
385,807
def find_items(self, q, shape=ID_ONLY, depth=SHALLOW, additional_fields=None, order_fields=None, calendar_view=None, page_size=None, max_items=None, offset=0): if shape not in SHAPE_CHOICES: raise ValueError(" %s must be one of %s" % (shape, SHAPE_CHOICES)) if dep...
Private method to call the FindItem service :param q: a Q instance containing any restrictions :param shape: controls whether to return (id, chanegkey) tuples or Item objects. If additional_fields is non-null, we always return Item objects. :param depth: controls the whether to r...
385,808
def _to_operator(rep, data, input_dim, output_dim): if rep == : return data if rep == : return _stinespring_to_operator(data, input_dim, output_dim) if rep != : data = _to_kraus(rep, data, input_dim, output_dim) return _kraus_to_operator(data, input_dim, output_dim)
Transform a QuantumChannel to the Operator representation.
385,809
def get_redirect_url(self, **kwargs): params = { : self.get_request_token().key, } return % (self.auth_url, urllib.urlencode(params))
Return the authorization/authentication URL signed with the request token.
385,810
def get_ref_free_exc_info(): "Free traceback from references to locals() in each frame to avoid circular reference leading to gc.collect() unable to reclaim memory" type, val, tb = sys.exc_info() traceback.clear_frames(tb) return (type, val, tb)
Free traceback from references to locals() in each frame to avoid circular reference leading to gc.collect() unable to reclaim memory
385,811
def read(filename,**kwargs): base,ext = os.path.splitext(filename) if ext in (,): return fitsio.read(filename,**kwargs) elif ext in (): return np.load(filename,**kwargs) elif ext in (): return np.recfromcsv(filename,**kwargs) elif ext in (,): return np.g...
Read a generic input file into a recarray. Accepted file formats: [.fits,.fz,.npy,.csv,.txt,.dat] Parameters: filename : input file name kwargs : keyword arguments for the reader Returns: recarray : data array
385,812
def update_editor ( self ): object = self.value canvas = self.factory.canvas if canvas is not None: for nodes_name in canvas.node_children: node_children = getattr(object, nodes_name) self._add_nodes(node_children) for ed...
Updates the editor when the object trait changes externally to the editor.
385,813
def __solve_overlaps(self, start_time, end_time): if end_time is None or start_time is None: return query = conflicts = self.fetchall(query, (start_time, end_time, start_time, end_time, ...
finds facts that happen in given interval and shifts them to make room for new fact
385,814
def _involuted_reverse(self): def inv_is_top(si): return (si.stride == 1 and self._lower_bound == StridedInterval._modular_add(self._upper_bound, 1, self.bits) ) o = self.copy() o._reversed = not o._reversed if o.bits == 8: ...
This method reverses the StridedInterval object for real. Do expect loss of precision for most cases! :return: A new reversed StridedInterval instance
385,815
def get_link_page_text(link_page): text = for i, link in enumerate(link_page): capped_link_text = (link[] if len(link[]) <= 20 else link[][:19] + ) text += .format(i, capped_link_text, link[]) return text
Construct the dialog box to display a list of links to the user.
385,816
def delete(self): if not self.id: return if not self._loaded: self.reload() return self.http_delete(self.id, etag=self.etag)
Deletes the object. Returns without doing anything if the object is new.
385,817
def pretty_format(message): skip = { TIMESTAMP_FIELD, TASK_UUID_FIELD, TASK_LEVEL_FIELD, MESSAGE_TYPE_FIELD, ACTION_TYPE_FIELD, ACTION_STATUS_FIELD} def add_field(previous, key, value): value = unicode(pprint.pformat(value, width=40)).replace( "\\n", "\n ").replace("\\t...
Convert a message dictionary into a human-readable string. @param message: Message to parse, as dictionary. @return: Unicode string.
385,818
def delitem_via_sibseqs(ol,*sibseqs): abc pathlist = list(sibseqs) this = ol for i in range(0,pathlist.__len__()-1): key = pathlist[i] this = this.__getitem__(key) this.__delitem__(pathlist[-1]) return(ol)
from elist.elist import * y = ['a',['b',["bb"]],'c'] y[1][1] delitem_via_sibseqs(y,1,1) y
385,819
def set_task_object(self, task_id, task_progress_object): self.set_task(task_id=task_id, total=task_progress_object.total, prefix=task_progress_object.prefix, suffix=task_progress_object.su...
Defines a new progress bar with the given information using a TaskProgress object. :param task_id: Unique identifier for this progress bar. Will erase if already existing. :param task_progress_object: TaskProgress object holding the progress bar information.
385,820
def flush(self): content = self._buffer.getvalue() self._buffer = StringIO() if content: self._client.send_message(self._target, content, mtype="chat")
Sends buffered data to the target
385,821
def TEST(): w = World(, [0, 0.0, 0.9, 0.0]) print(w) p = Person(, {:0.0, :0.9,:0.9, :0.0}) print(p) h = Happiness(p,w) h.add_factor(HappinessFactors(, , 0.1, 0.3)) h.add_factor(HappinessFactors(, , 0.3, 0.9)) h.add_factor(HappinessFactors(, , 0.1, 0.9)) h.add_factor(Happin...
Modules for testing happiness of 'persons' in 'worlds' based on simplistic preferences. Just a toy - dont take seriously ----- WORLD SUMMARY for : Mars ----- population = 0 tax_rate = 0.0 tradition = 0.9 equity = 0.0 Preferences for Rover tax_min = 0....
385,822
def base26(x, _alphabet=string.ascii_uppercase): result = [] while x: x, digit = divmod(x, 26) if not digit: x -= 1 digit = 26 result.append(_alphabet[digit - 1]) return .join(result[::-1])
Return positive ``int`` ``x`` as string in bijective base26 notation. >>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]] ['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB'] >>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 * 26**1 + 13 * 26**0 'SPAM' >>> base26(256) 'IV'
385,823
def get_consensus_hashes(block_heights, hostport=None, proxy=None): assert proxy or hostport, if proxy is None: proxy = connect_hostport(hostport) consensus_hashes_schema = { : , : { : { : , : { : { ...
Get consensus hashes for a list of blocks NOTE: returns {block_height (int): consensus_hash (str)} (coerces the key to an int) Returns {'error': ...} on error
385,824
def add(self, dist): if self.can_add(dist) and dist.has_version(): dists = self._distmap.setdefault(dist.key, []) if dist not in dists: dists.append(dist) dists.sort(key=operator.attrgetter(), reverse=True)
Add `dist` if we ``can_add()`` it and it has not already been added
385,825
def _CollectTypeChecks(function, parent_type_check_dict, stack_location, self_name): type_check_dict = dict(parent_type_check_dict) type_check_dict.update(_ParseDocstring(function)) for key, value in type_check_dict.items(): if isinstance(value, str): type_check_dict[key] = ...
Collect all type checks for this function.
385,826
def add_unique_template_variables(self, options): options.update(dict( colorProperty=self.color_property, colorStops=self.color_stops, colorType=self.color_function_type, radiusType=self.radius_function_type, defaultColor=self.color_default, ...
Update map template variables specific to graduated circle visual
385,827
def answers(self, other): if other.__class__ == self.__class__: return (other.service + 0x40) == self.service or \ (self.service == 0x7f and self.request_service_id == other.service) return False
DEV: true if self is an answer from other
385,828
def init_module(self, run_object): self.profile = self.profile_module self._run_object, _, self._run_args = run_object.partition() self._object_name = % self._run_object self._globs = { : self._run_object, : , : None, } progra...
Initializes profiler with a module.
385,829
def convert_types(cls, value): if isinstance(value, decimal.Decimal): return float(value) else: return value
Takes a value from MSSQL, and converts it to a value that's safe for JSON/Google Cloud Storage/BigQuery.
385,830
def query(querystr, connection=None, **connectkwargs): if connection is None: connection = connect(**connectkwargs) cursor = connection.cursor() cursor.execute(querystr) return cursor.fetchall()
Execute a query of the given SQL database
385,831
def _preprocess_values(self, Y): Y_prep = Y.copy() Y1 = Y[Y.flatten()==1].size Y2 = Y[Y.flatten()==0].size assert Y1 + Y2 == Y.size, Y_prep[Y.flatten() == 0] = -1 return Y_prep
Check if the values of the observations correspond to the values assumed by the likelihood function. ..Note:: Binary classification algorithm works better with classes {-1, 1}
385,832
def segments(self): seg_list = self._event.chat_message.message_content.segment return [ChatMessageSegment.deserialize(seg) for seg in seg_list]
List of :class:`ChatMessageSegment` in message (:class:`list`).
385,833
def get_safe_return_to(request, return_to): if return_to and is_safe_url(url=return_to, host=request.get_host()) and return_to != request.build_absolute_uri(): return return_to
Ensure the user-originating redirection url is safe, i.e. within same scheme://domain:port
385,834
def reduce(fname, reduction_factor): if fname.endswith(): with open(fname) as f: line = f.readline() if csv.Sniffer().has_header(line): header = line all_lines = f.readlines() else: header = None f.see...
Produce a submodel from `fname` by sampling the nodes randomly. Supports source models, site models and exposure models. As a special case, it is also able to reduce .csv files by sampling the lines. This is a debugging utility to reduce large computations to small ones.
385,835
def encode_sequence(content, error=None, version=None, mode=None, mask=None, encoding=None, eci=False, boost_error=True, symbol_count=None): def one_item_segments(chunk, mode): segs = Segments() segs.add_segment(make_segment(chunk, mode=mode, enc...
\ EXPERIMENTAL: Creates a sequence of QR Codes in Structured Append mode. :return: Iterable of named tuples, see :py:func:`encode` for details.
385,836
def _do_api_call(self, method, data): data.update({ "key": self.api_key, status_code = root.find("header/status/code").text exc_class = _get_exception_class_from_status_code(status_code) if exc_class: ...
Convenience method to carry out a standard API call against the Petfinder API. :param basestring method: The API method name to call. :param dict data: Key/value parameters to send to the API method. This varies based on the method. :raises: A number of :py:exc:`petfinder.ex...
385,837
def patch(module, external=(), internal=()): external = tuple(external) internal = tuple(internal) def decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): master_mock = mock.MagicMock() def get_mock(name): ...
Temporarily monkey-patch dependencies which can be external to, or internal to the supplied module. :param module: Module object :param external: External dependencies to patch (full paths as strings) :param internal: Internal dependencies to patch (short names as strings) :return:
385,838
def activate_left(self, token): watchers.MATCHER.debug( "Node <%s> activated left with token %r", self, token) return self._activate_left(token.copy())
Make a copy of the received token and call `_activate_left`.
385,839
def str_rfind(x, sub, start=0, end=None): return _to_string_sequence(x).find(sub, start, 0 if end is None else end, end is None, False)
Returns the highest indices in each string in a column, where the provided substring is fully contained between within a sample. If the substring is not found, -1 is returned. :param str sub: A substring to be found in the samples :param int start: :param int end: :returns: an expression containing...
385,840
def _generate_splits(self, m, r): new_rects = [] if r.left > m.left: new_rects.append(Rectangle(m.left, m.bottom, r.left-m.left, m.height)) if r.right < m.right: new_rects.append(Rectangle(r.right, m.bottom, m.right-r.right, m.height)) if r.top <...
When a rectangle is placed inside a maximal rectangle, it stops being one and up to 4 new maximal rectangles may appear depending on the placement. _generate_splits calculates them. Arguments: m (Rectangle): max_rect rectangle r (Rectangle): rectangle placed Ret...
385,841
def get_page_labels(self, page_id, prefix=None, start=None, limit=None): url = .format(id=page_id) params = {} if prefix: params[] = prefix if start is not None: params[] = int(start) if limit is not None: params[] = int(limit) ...
Returns the list of labels on a piece of Content. :param page_id: A string containing the id of the labels content container. :param prefix: OPTIONAL: The prefixes to filter the labels with {@see Label.Prefix}. Default: None. :param start: OPTIONAL: The start poin...
385,842
def extractHolidayWeekendSchedules(self): result = namedtuple("result", ["Weekend", "Holiday"]) result.Weekend = self.m_hldy["Weekend_Schd"][MeterData.StringValue] result.Holiday = self.m_hldy["Holiday_Schd"][MeterData.StringValue] return result
extract holiday and weekend :class:`~ekmmeters.Schedule` from meter object buffer. Returns: tuple: Holiday and weekend :class:`~ekmmeters.Schedule` values, as strings. ======= ====================================== Holiday :class:`~ekmmeters.Schedule` as string ...
385,843
def expose_ancestors_or_children(self, member, collection, lang=None): x = { "id": member.id, "label": str(member.get_label(lang)), "model": str(member.model), "type": str(member.type), "size": member.size, "semantic": self.semanti...
Build an ancestor or descendant dict view based on selected information :param member: Current Member to build for :param collection: Collection from which we retrieved it :param lang: Language to express data in :return:
385,844
def create_service_from_endpoint(endpoint, service_type, title=None, abstract=None, catalog=None): from models import Service if Service.objects.filter(url=endpoint, catalog=catalog).count() == 0: request = requests.get(endpoint) if request.status_code == 200: LOGGER.de...
Create a service from an endpoint if it does not already exists.
385,845
def getKeyword(filename, keyword, default=None, handle=None): if filename.find() < 0: filename += _fname, _extn = parseFilename(filename) if not handle: _fimg = openImage(_fname) else: if isinstance(handle, fits.HDUList): _fimg ...
General, write-safe method for returning a keyword value from the header of a IRAF recognized image. Returns the value as a string.
385,846
def generate_join_docs_list(self, left_collection_list, right_collection_list): joined_docs = [] if (len(left_collection_list) != 0) and (len(right_collection_list) != 0): for left_doc in left_collection_list: for right_doc in right_collection_list: ...
Helper function for merge_join_docs :param left_collection_list: Left Collection to be joined :type left_collection_list: MongoCollection :param right_collection_list: Right Collection to be joined :type right_collection_list: MongoCollection :return joine...
385,847
def _nextSequence(cls, name=None): if not name: name = cls._sqlSequence if not name: curs = cls.cursor() curs.execute("SELECT nextval()" % name) value = curs.fetchone()[0] curs.close() return value
Return a new sequence number for insertion in self._sqlTable. Note that if your sequences are not named tablename_primarykey_seq (ie. for table 'blapp' with primary key 'john_id', sequence name blapp_john_id_seq) you must give the full sequence name as an optional argument to _nextSe...
385,848
def get_project(self) -> str: with IHCController._mutex: if self._project is None: if self.client.get_state() != IHCSTATE_READY: ready = self.client.wait_for_state_change(IHCSTATE_READY, 10) ...
Get the ihc project and make sure controller is ready before
385,849
def new(cls, nsptagname, val): elm = OxmlElement(nsptagname) elm.val = val return elm
Return a new ``CT_String`` element with tagname *nsptagname* and ``val`` attribute set to *val*.
385,850
def send(self, smtp=None, **kw): smtp_options = {} smtp_options.update(self.config.smtp_options) if smtp: smtp_options.update(smtp) return super(Message, self).send(smtp=smtp_options, **kw)
Sends message. :param smtp: When set, parameters from this dictionary overwrite options from config. See `emails.Message.send` for more information. :param kwargs: Parameters for `emails.Message.send` :return: Response objects from emails backend. For def...
385,851
def switch_delete_record_for_userid(self, userid): with get_network_conn() as conn: conn.execute("DELETE FROM switch WHERE userid=?", (userid,)) LOG.debug("Switch record for user %s is removed from " "switch table" % userid)
Remove userid switch record from switch table.
385,852
def repack(self, to_width, *, msb_first, start=0, start_bit=0, length=None): to_width = operator.index(to_width) if not isinstance(msb_first, bool): raise TypeError() available = self.repack_data_available( to_width, start=start, start_bit=star...
Extracts a part of a BinArray's data and converts it to a BinArray of a different width. For the purposes of this conversion, words in this BinArray are joined side-by-side, starting from a given start index (defaulting to 0), skipping ``start_bit`` first bits of the first word, then th...
385,853
def _escape(self, msg): escaped = for c in msg: escaped += c if c == : escaped += return escaped
Escapes double quotes by adding another double quote as per the Scratch protocol. Expects a string without its delimiting quotes. Returns a new escaped string.
385,854
def timezone(self, tz): self.data[].update( timezone=tz, time_show_zone=True)
Set timezone on the audit records. Timezone can be in formats: 'US/Eastern', 'PST', 'Europe/Helsinki' See SMC Log Viewer settings for more examples. :param str tz: timezone, i.e. CST
385,855
def send(self, to, from_, body, dm=False): tweet = .format(to, body) if from_ not in self.accounts: raise AccountNotFoundError() if len(tweet) > 140: raise TweetTooLongError() self.auth.set_access_token(*self.accounts.get(from_)) api = tweepy.AP...
Send BODY as an @message from FROM to TO If we don't have the access tokens for FROM, raise AccountNotFoundError. If the tweet resulting from '@{0} {1}'.format(TO, BODY) is > 140 chars raise TweetTooLongError. If we want to send this message as a DM, do so. Arguments: ...
385,856
def domain_block(self, domain=None): params = self.__generate_params(locals()) self.__api_request(, , params)
Add a block for all statuses originating from the specified domain for the logged-in user.
385,857
def validate_text(value): possible_transform = [, , ] validate_transform = ValidateInStrings(, possible_transform, True) tests = [validate_float, validate_float, validate_str, validate_transform, dict] if isinstance(value, six.string_types): ...
Validate a text formatoption Parameters ---------- value: see :attr:`psyplot.plotter.labelplotter.text` Raises ------ ValueError
385,858
def interpolate_gridded_scalar(self, x, y, c, order=1, pad=1, offset=0):
Interpolate gridded scalar C to points x,y. Parameters ---------- x, y : array-like Points at which to interpolate c : array-like The scalar, assumed to be defined on the grid. order : int Order of interpolation pad : int ...
385,859
def add_auth_attribute(attr, value, actor=False): if attr in (, , , , , ): raise AttributeError("Attribute name %s is reserved by current_auth" % attr) ca = current_auth._get_current_object()
Helper function for login managers. Adds authorization attributes to :obj:`current_auth` for the duration of the request. :param str attr: Name of the attribute :param value: Value of the attribute :param bool actor: Whether this attribute is an actor (user or client app accessing own data) ...
385,860
def compliance_report(self, validation_file=None, validation_source=None): return validate.compliance_report( self, validation_file=validation_file, validation_source=validation_source )
Return a compliance report. Verify that the device complies with the given validation file and writes a compliance report file. See https://napalm.readthedocs.io/en/latest/validate/index.html. :param validation_file: Path to the file containing compliance definition. Default is None. :...
385,861
def mouseMoveEvent(self, e): super(PyInteractiveConsole, self).mouseMoveEvent(e) cursor = self.cursorForPosition(e.pos()) assert isinstance(cursor, QtGui.QTextCursor) p = cursor.positionInBlock() usd = cursor.block().userData() if usd and usd.start_pos_in_block <...
Extends mouseMoveEvent to display a pointing hand cursor when the mouse cursor is over a file location
385,862
def apply(self, coordinates): transform = self.get_transformation(coordinates) result = MolecularDistortion(self.affected_atoms, transform) result.apply(coordinates) return result
Generate, apply and return a random manipulation
385,863
def set_monitor(module): def monitor(name, tensor, track_data=True, track_grad=True): module.monitored_vars[name] = { :tensor, :track_data, :track_grad, } module.monitor = monitor
Defines the monitor method on the module.
385,864
def cmsearch_from_file(cm_file_path, seqs, moltype, cutoff=0.0, params=None): seqs = SequenceCollection(seqs,MolType=moltype).degap() int_map, int_keys = seqs.getIntMap() int_map = SequenceCollection(int_map,MolType=moltype) app = Cmsearch(InputHandler=,WorkingDir=,\ params=...
Uses cmbuild to build a CM file, then cmsearch to find homologs. - cm_file_path: path to the file created by cmbuild, containing aligned sequences. This will be used to search sequences in seqs. - seqs: SequenceCollection object or something that can be used to construct one, co...
385,865
def wipe_container(self): if self.test_run: print("Wipe would delete {0} objects.".format(len(self.container.object_count))) else: if not self.quiet or self.verbosity > 1: print("Deleting {0} objects...".format(len(self.container.object_count))) ...
Completely wipes out the contents of the container.
385,866
def updateMktDepthL2(self, id, position, marketMaker, operation, side, price, size): return _swigibpy.EWrapper_updateMktDepthL2(self, id, position, marketMaker, operation, side, price, size)
updateMktDepthL2(EWrapper self, TickerId id, int position, IBString marketMaker, int operation, int side, double price, int size)
385,867
def forwards(self, orm): "Write your forwards methods here." User = orm[user_orm_label] try: user = User.objects.all()[0] for article in orm.Article.objects.all(): article.author = user article.save() except IndexError:...
Write your forwards methods here.
385,868
def set_limit(self, param): limit = int(param) if -2000 <= limit <= 6000: self.device.temperature_limit = limit / 10.0 return ""
Models "Limit Command" functionality of device. Sets the target temperate to be reached. :param param: Target temperature in C, multiplied by 10, as a string. Can be negative. :return: Empty string.
385,869
def set_stepdown_window(self, start, end, enabled=True, scheduled=True, weekly=True): if not start < end: raise TypeError() week_delta = datetime.timedelta(days=7) if not ((end - start) <= week_delta): raise TypeError() url = self._ser...
Set the stepdown window for this instance. Date times are assumed to be UTC, so use UTC date times. :param datetime.datetime start: The datetime which the stepdown window is to open. :param datetime.datetime end: The datetime which the stepdown window is to close. :param bool enabled: ...
385,870
def add_store(name, store, saltenv=): ret = {: name, : True, : , : {}} cert_file = __salt__[](name, saltenv) if cert_file is False: ret[] = False ret[] += else: cert_serial = __salt__[](cert_file) serials = __salt__[](store) ...
Store a certificate to the given store name The certificate to store, this can use local paths or salt:// paths store The store to add the certificate to saltenv The salt environment to use, this is ignored if a local path is specified
385,871
def add_format(self, mimetype, format, requires_context=False): self.formats[mimetype] = format if not requires_context: self.ctxless_mimetypes.append(mimetype) self.all_mimetypes.append(mimetype)
Registers a new format to be used in a graph's serialize call If you've installed an rdflib serializer plugin, use this to add it to the content negotiation system Set requires_context=True if this format requires a context-aware graph
385,872
def urlopen(self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw): if headers is None: headers = sel...
Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such ...
385,873
def create_permissions_from_tuples(model, codename_tpls): if codename_tpls: model_cls = django_apps.get_model(model) content_type = ContentType.objects.get_for_model(model_cls) for codename_tpl in codename_tpls: app_label, codename, name = get_from_codename_tuple( ...
Creates custom permissions on model "model".
385,874
def auth(self): self.send(nsq.auth(self.auth_secret)) frame, data = self.read_response() if frame == nsq.FRAME_TYPE_ERROR: raise data try: response = json.loads(data.decode()) except ValueError: self.close_stream() raise ...
Send authorization secret to nsqd.
385,875
def __replace_adjective(sentence, counts): if sentence is not None: while sentence.find() != -1: sentence = sentence.replace(, str(__get_adjective(counts)), 1) if sentence.find() == -1: return sentence return s...
Lets find and replace all instances of #ADJECTIVE :param _sentence: :param counts:
385,876
def _maybe_trim_strings(self, array, **keys): trim_strings = keys.get(, False) if self.trim_strings or trim_strings: _trim_strings(array)
if requested, trim trailing white space from all string fields in the input array
385,877
def update_next_block(self): last = self.mem[-1] if last.inst not in (, , ) or last.condition_flag is not None: return if last.inst == : if self.next is not None: self.next.delete_from(self) self.delete_goes(self.next) ...
If the last instruction of this block is a JP, JR or RET (with no conditions) then the next and goes_to sets just contains a single block
385,878
async def fetchmany(self, size: int = None) -> Iterable[sqlite3.Row]: args = () if size is not None: args = (size,) return await self._execute(self._cursor.fetchmany, *args)
Fetch up to `cursor.arraysize` number of rows.
385,879
def load_dataset(data_name): if data_name == or data_name == : train_dataset, output_size = _load_file(data_name) vocab, max_len = _build_vocab(data_name, train_dataset, []) train_dataset, train_data_lengths = _preprocess_dataset(train_dataset, vocab, max_len) return vocab, max...
Load sentiment dataset.
385,880
def natural_ipv4_netmask(ip, fmt=): bits = _ipv4_to_bits(ip) if bits.startswith(): mask = elif bits.startswith(): mask = else: mask = if fmt == : return cidr_to_ipv4_netmask(mask) else: return + mask
Returns the "natural" mask of an IPv4 address
385,881
def _record(self): return struct.pack(self.FMT, 1, self.platform_id, 0, self.id_string, self.checksum, 0x55, 0xaa)
An internal method to generate a string representing this El Torito Validation Entry. Parameters: None. Returns: String representing this El Torito Validation Entry.
385,882
def compare_tags(self, tags): all_tags = [] for task in self._tasks: all_tags.extend(task.tags) all_tags_set = set(all_tags) tags_set = set(tags) matched_tags = all_tags_set & tags_set unmatched_tags = all_tags_set - tags_set ...
given a list of tags that the user has specified, return two lists: matched_tags: tags were found within the current play and match those given by the user unmatched_tags: tags that were found within the current play but do not match any provided by the ...
385,883
def get_inline_instances(self, request, *args, **kwargs): inlines = super(PlaceholderEditorAdmin, self).get_inline_instances(request, *args, **kwargs) extra_inline_instances = [] inlinetypes = self.get_extra_inlines() for InlineType in inlinetypes: inline_instance =...
Create the inlines for the admin, including the placeholder and contentitem inlines.
385,884
def _plot_colorbar(mappable, fig, subplot_spec, max_cbar_height=4): width, height = fig.get_size_inches() if height > max_cbar_height: axs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=subplot_spec, height_ratios=[height - m...
Plots a vertical color bar based on mappable. The height of the colorbar is min(figure-height, max_cmap_height) Parameters ---------- mappable : The image to which the colorbar applies. fig ; The figure object subplot_spec : the gridspec subplot. Eg. axs[1,2] max_cbar_height : `float` ...
385,885
def add_transaction_clause(self, clause): if not isinstance(clause, TransactionClause): raise StatementException() clause.set_context_id(self.context_counter) self.context_counter += clause.get_context_size() self.transactions.append(clause)
Adds a iff clause to this statement :param clause: The clause that will be added to the iff statement :type clause: TransactionClause
385,886
def create_parser() -> FileAwareParser: parser = FileAwareParser(description="Clear data from FHIR observation fact table", prog="removefacts", use_defaults=False) parser.add_argument("-ss", "--sourcesystem", metavar="SOURCE SYSTEM CODE", help="Sourcesystem code") parser.ad...
Create a command line parser :return: parser
385,887
def write_extra_data(self, stream: WriteStream) -> None: if self.params: stream.align(8) if self._params_offset_writer: self._params_offset_writer.write_current_offset(stream) else: self._params_offset = stream.tell() self....
Writes the param container and string pointer arrays. Unlike other write_extra_data functions, this can be called before write().
385,888
def resolve_imports(self, imports, import_depth, parser=None): if imports and import_depth: for i in list(self.imports): try: if os.path.exists(i) or i.startswith((, )): self.merge(Ontology(i, import_depth=import_depth-1, parser=p...
Import required ontologies.
385,889
def MGMT_ED_SCAN(self, sAddr, xCommissionerSessionId, listChannelMask, xCount, xPeriod, xScanDuration): print % self.port channelMask = channelMask = + self.__convertLongToString(self.__convertChannelMask(listChannelMask)) try: cmd = % (channelMask, xCount, xPeri...
send MGMT_ED_SCAN message to a given destinaition. Args: sAddr: IPv6 destination address for this message xCommissionerSessionId: commissioner session id listChannelMask: a channel array to indicate which channels to be scaned xCount: number of IEEE 802.15.4 ED S...
385,890
def create_job(db, datadir): calc_id = get_calc_id(db, datadir) + 1 job = dict(id=calc_id, is_running=1, description=, user_name=, calculation_mode=, ds_calc_dir=os.path.join( % (datadir, calc_id))) return db(, job.keys(), job.values()).lastrowid
Create job for the given user, return it. :param db: a :class:`openquake.server.dbapi.Db` instance :param datadir: Data directory of the user who owns/started this job. :returns: the job ID
385,891
def devices(self): context = Context() existing_devices = context.list_devices(subsystem="hidraw") future_devices = self._get_future_devices(context) for hidraw_device in itertools.chain(existing_devices, future_devices): hid_device = hidraw_device.parent ...
Wait for new DS4 devices to appear.
385,892
def cut_mechanisms(self): for mechanism in utils.powerset(self.node_indices, nonempty=True): micro_mechanism = self.macro2micro(mechanism) if self.cut.splits_mechanism(micro_mechanism): yield mechanism
The mechanisms of this system that are currently cut. Note that although ``cut_indices`` returns micro indices, this returns macro mechanisms. Yields: tuple[int]
385,893
def resource_filename(package_or_requirement, resource_name): if pkg_resources.resource_exists(package_or_requirement, resource_name): return pkg_resources.resource_filename(package_or_requirement, resource_name) path = _search_in_share_folders(package_or_requirement, resource_name) if path: ...
Similar to pkg_resources.resource_filename but if the resource it not found via pkg_resources it also looks in a predefined list of paths in order to find the resource :param package_or_requirement: the module in which the resource resides :param resource_name: the name of the resource :return: the pat...
385,894
def build_model(self): if self.model_config[]: return self.build_red() elif self.model_config[]: return self.buidl_hred() else: raise Error("Unrecognized model type ".format(self.model_config[]))
Find out the type of model configured and dispatch the request to the appropriate method
385,895
def check_config(conf): if in conf and not isinstance(conf[], string_types): raise TypeError(TAG + ": `fmode` must be a string") if in conf and not isinstance(conf[], string_types): raise TypeError(TAG + ": `dmode` must be a string") if in conf: if not isinstance(conf[], in...
Type and boundary check
385,896
def Authenticate(self, app_id, challenge, registered_keys): client_data = model.ClientData(model.ClientData.TYP_AUTHENTICATION, challenge, self.origin) app_param = self.InternalSHA256(app_id) challenge_param = self.InternalSHA256(client_data.GetJson()) num_invalid...
Authenticates app_id with the security key. Executes the U2F authentication/signature flow with the security key. Args: app_id: The app_id to register the security key against. challenge: Server challenge passed to the security key as a bytes object. registered_keys: List of keys already reg...
385,897
def exists(self, uri): try: urllib.request.urlopen(uri) return True except urllib.error.HTTPError: return False
Method returns true is the entity exists in the Repository, false, otherwise Args: uri(str): Entity URI Returns: bool
385,898
def get_parent_families(self, family_id): if self._catalog_session is not None: return self._catalog_session.get_parent_catalogs(catalog_id=family_id) return FamilyLookupSession( self._proxy, self._runtime).get_families_by_ids( ...
Gets the parent families of the given ``id``. arg: family_id (osid.id.Id): the ``Id`` of the ``Family`` to query return: (osid.relationship.FamilyList) - the parent families of the ``id`` raise: NotFound - a ``Family`` identified by ``Id is`` not ...
385,899
def is_valid(edtf_candidate): if ( isLevel0(edtf_candidate) or isLevel1(edtf_candidate) or isLevel2(edtf_candidate) ): if in edtf_candidate: return is_valid_interval(edtf_candidate) else: return True else: return False
isValid takes a candidate date and returns if it is valid or not