Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
374,700
def needle(self, serie): serie_node = self.svg.serie(serie) for i, theta in enumerate(serie.values): if theta is None: continue def point(x, y): return % self.view((x, y)) val = self._format(serie, i) metadata = ...
Draw a needle for each value
374,701
def _maybe_validate_shape_override(self, override_shape, base_is_scalar, validate_args, name): if override_shape is None: override_shape = [] override_shape = tf.convert_to_tensor( value=override_shape, dtype=tf.int32, name=name) if not dtype_util.is...
Helper to __init__ which ensures override batch/event_shape are valid.
374,702
def login_exists(login, domain=, **kwargs): LOGIN if domain: login = .format(domain, login) try: return len(tsql_query(query="SELECT name FROM sys.syslogins WHERE name=".format(login), **kwargs)) == 1 except Exception as e: return .format(e)
Find if a login exists in the MS SQL server. domain, if provided, will be prepended to login CLI Example: .. code-block:: bash salt minion mssql.login_exists 'LOGIN'
374,703
def report(self, name, **kwargs): group_obj = Report(name, **kwargs) return self._group(group_obj)
Add Report data to Batch object. Args: name (str): The name for this Group. file_name (str): The name for the attached file for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. file_content (str;method, kwargs): The file content...
374,704
def collect(coro, index, results, preserve_order=False, return_exceptions=False): result = yield from safe_run(coro, return_exceptions=return_exceptions) if preserve_order: results[index] = result else: results.append(result)
Collect is used internally to execute coroutines and collect the returned value. This function is intended to be used internally.
374,705
def getRootJobs(self): roots = set() visited = set() def getRoots(job): if job not in visited: visited.add(job) if len(job._directPredecessors) > 0: list(map(lambda p : getRoots(p), job._directPredecessors)) ...
:return: The roots of the connected component of jobs that contains this job. \ A root is a job with no predecessors. :rtype : set of toil.job.Job instances
374,706
def splitter(div, *args): retstr = "" if type(div) is int: div = theArray()[div] if len(args) == 1: return args[0] for s in args: retstr += s retstr += "\n" retstr += div retstr += "\n" return retstr
Split text with dividers easily. :return: newly made value :rtype: str :param div: the divider
374,707
def actions(obj, **kwargs): if in kwargs: kwargs[] = kwargs[].split() actions = obj.get_actions(**kwargs) if isinstance(actions, dict): actions = actions.values() buttons = "".join("%s" % action.render() for action in actions) return % buttons
Return actions available for an object
374,708
def url_report(self, scan_url, apikey): url = self.base_url + "url/report" params = {"apikey": apikey, : scan_url} rate_limit_clear = self.rate_limit() if rate_limit_clear: response = requests.post(url, params=params, headers=self.headers) if response.sta...
Send URLS for list of past malicous associations
374,709
def log_formatter(request=None): if request: format_str = ( ) else: format_str = try: hostname = socket.gethostname() except socket.gaierror: hostname = try: ip = socket.gethostbyname(hostname) except ...
Log formatter used in our syslog :param request: a request object :returns: logging.Formatter
374,710
def get_forces(self, a=None): if a is None: a = self.a forces = np.zeros([len(a), 3], dtype=float) if self.mask is None: forces[self.mask] = self.force else: forces[:] = self.force return forces
Calculate atomic forces.
374,711
def read(self, source_path): self._metadata = {} with pelican_open(source_path) as text: content = creole2html(text, macros={: self._parse_header_macro, : self._parse_code_macro}) return content, self._metadata
Parse content and metadata of creole files
374,712
def get_lookups(cls): class_lookups = [parent.__dict__.get(, {}) for parent in inspect.getmro(cls)] return cls.merge_dicts(class_lookups)
Fetch all Lookups
374,713
def set(self, section, option, value): if not value: value = if self.is_secure_option(section, option): self.set_secure(section, option, value) else: ConfigParser.set(self, section, option, value)
Set an option value. Knows how to set options properly marked as secure.
374,714
def eklef(fname): fname = stypes.stringToCharP(fname) handle = ctypes.c_int() libspice.eklef_c(fname, ctypes.byref(handle)) return handle.value
Load an EK file, making it accessible to the EK readers. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/eklef_c.html :param fname: Name of EK file to load. :type fname: str :return: File handle of loaded EK file. :rtype: int
374,715
def add_property(self, prop): if _debug: Object._debug("add_property %r", prop) self._properties = _copy(self._properties) self._properties[prop.identifier] = prop self._values[prop.identifier] = prop.default
Add a property to an object. The property is an instance of a Property or one of its derived classes. Adding a property disconnects it from the collection of properties common to all of the objects of its class.
374,716
def fullversion(): * cmd = out = __salt__[](cmd).splitlines() comps = out[0].split() version_num = comps[2] comps = out[1].split() return {: version_num, : comps[3:]}
Shows installed version of dnsmasq and compile options. CLI Example: .. code-block:: bash salt '*' dnsmasq.fullversion
374,717
def get_devicelist(home_hub_ip=): url = .format(home_hub_ip) try: response = requests.get(url, timeout=5) except requests.exceptions.Timeout: _LOGGER.exception("Connection to the router timed out") return if response.status_code == 200: return parse_devicelist(resp...
Retrieve data from BT Home Hub 5 and return parsed result.
374,718
def display_google_book(id, page=None, width=700, height=500, **kwargs): if isinstance(page, int): url = .format(id=id, page=page) else: url = .format(id=id, page=page) display_iframe_url(url, width=width, height=height, **kwargs)
Display an embedded version of a Google book. :param id: the id of the google book to display. :type id: string :param page: the start page for the book. :type id: string or int.
374,719
def var(self, ddof=1, *args, **kwargs): nv.validate_groupby_func(, args, kwargs) if ddof == 1: try: return self._cython_agg_general(, **kwargs) except Exception: f = lambda x: x.var(ddof=ddof, **kwargs) with _group_selectio...
Compute variance of groups, excluding missing values. For multiple groupings, the result index will be a MultiIndex. Parameters ---------- ddof : integer, default 1 degrees of freedom
374,720
def set_alternative(self, experiment_name, alternative): experiment = experiment_manager.get_experiment(experiment_name) if experiment: self._set_enrollment(experiment, alternative)
Explicitly set the alternative the user is enrolled in for the specified experiment. This allows you to change a user between alternatives. The user and goal counts for the new alternative will be increment, but those for the old one will not be decremented. The user will be enrolled in the exp...
374,721
def extend(self, builder): for extension in self._extensions: getattr(self, % extension)(builder) builder.on_delete(self._on_delete)
Extend the query builder with the needed functions. :param builder: The query builder :type builder: eloquent.orm.builder.Builder
374,722
def attrlist(self): keymap = self.config.get() if keymap: return [s.encode() for s in keymap.values()] else: return None
Transform the KEY_MAP paramiter into an attrlist for ldap filters
374,723
def clean_slug(self): self.instance._old_slug = self.instance.slug new_slug = self.cleaned_data[] if not isinstance(self.instance, Link) and new_slug != "/": new_slug = clean_slashes(self.cleaned_data[]) return new_slug
Save the old slug to be used later in PageAdmin.save_model() to make the slug change propagate down the page tree, and clean leading and trailing slashes which are added on elsewhere.
374,724
def print_file_results(file_result): print_results_header(file_result.filepath, file_result.is_valid) for object_result in file_result.object_results: if object_result.warnings: print_warning_results(object_result, 1) if object_result.errors: print_schema_results(ob...
Print the results of validating a file. Args: file_result: A FileValidationResults instance.
374,725
def parse_endpoint_name(self, endpoint): parts = [x for x in endpoint.split() if x] endpoint = parts[0] if len(parts) == 1: path = else: path = .join(parts[1:]) return endpoint, path
split an endpoint name by colon, as the user can provide an endpoint name separated from a path: Parameters ========== endpoint 12345:/path/on/remote
374,726
def get(self): self.log.debug() if not self.append: self.append = "" if not self.readability: pdfPath = self._print_original_webpage() else: pdfPath = self._print_parsed_webpage() tag( log=self.log, ...
*get the PDF* **Return:** - ``pdfPath`` -- the path to the generated PDF
374,727
def get_crimes_no_location(self, force, date=None, category=None): if not isinstance(force, Force): force = Force(self, id=force) if isinstance(category, CrimeCategory): category = category.id kwargs = { : force.id, : category or , ...
Get crimes with no location for a force. Uses the crimes-no-location_ API call. .. _crimes-no-location: https://data.police.uk/docs/method/crimes-no-location/ :rtype: list :param force: The force to get no-location crimes for. :type force: str or Force :para...
374,728
def deployment_label(self): label = dict() label[] = self.info label[] = self.rest_api_name label[] = os.path.basename(self._swagger_file) label[] = self.md5_filehash return label
this property returns the deployment label dictionary (mainly used by stage description)
374,729
def transitDurationCircular(P, R_s, R_p, a, i): r if i is nan: i = 90 * aq.deg i = i.rescale(aq.rad) k = R_p / R_s b = (a * cos(i)) / R_s duration = (P / pi) * arcsin(((R_s * sqrt((1 + k) ** 2 - b ** 2)) / (a * sin(i))).simplified) ...
r"""Estimation of the primary transit time. Assumes a circular orbit. .. math:: T_\text{dur} = \frac{P}{\pi}\sin^{-1} \left[\frac{R_\star}{a}\frac{\sqrt{(1+k)^2 + b^2}}{\sin{a}} \right] Where :math:`T_\text{dur}` transit duration, P orbital period, :math:`R_\star` radius of the star, a is ...
374,730
def add_bookmark(self, new_bookmark, *, max_retries=3): with (yield from self._lock): bookmarks = yield from self._get_bookmarks() try: modified_bookmarks = list(bookmarks) if new_bookmark not in bookmarks: modified_bookmarks....
Add a bookmark and check whether it was successfully added to the bookmark list. Already existant bookmarks are not added twice. :param new_bookmark: the bookmark to add :type new_bookmark: an instance of :class:`~bookmark_xso.Bookmark` :param max_retries: the number of retries if setti...
374,731
def join(self, column_label, other, other_label=None): if self.num_rows == 0 or other.num_rows == 0: return None if not other_label: other_label = column_label self_rows = self.index_by(column_label) other_rows = other.index_by(other_label) ...
Creates a new table with the columns of self and other, containing rows for all values of a column that appear in both tables. Args: ``column_label`` (``str``): label of column in self that is used to join rows of ``other``. ``other``: Table object to join with...
374,732
def udom83(text: str) -> str: if not text or not isinstance(text, str): return "" text = _RE_1.sub("ัน\\1", text) text = _RE_2.sub("ั\\1", text) text = _RE_3.sub("ัน\\1", text) text = _RE_4.sub("ัน", text) text = _RE_5.sub("\\1", text) text = _RE_6.sub("\\1ย", text) text =...
Udom83 - It's a Thai soundex rule. :param str text: Thai word :return: Udom83 soundex
374,733
def update(self): self.filename = self.parent.info.dataset.filename self.chan = self.parent.info.dataset.header[] for chan in self.chan: self.idx_chan.addItem(chan)
Get info from dataset before opening dialog.
374,734
def get_plugin_folders(): folders = [] defaultfolder = normpath("~/.linkchecker/plugins") if not os.path.exists(defaultfolder) and not Portable: try: make_userdir(defaultfolder) except Exception as errmsg: msg = _("could not create plugin directory %(dirname)r: %...
Get linkchecker plugin folders. Default is ~/.linkchecker/plugins/.
374,735
def to_gds(self, multiplier): name = self.ref_cell.name if len(name) % 2 != 0: name = name + data = struct.pack(, 4, 0x0A00, 4 + len(name), 0x1206) + name.encode() if (self.rotation is not None) or (self.magnification is ...
Convert this object to a GDSII element. Parameters ---------- multiplier : number A number that multiplies all dimensions written in the GDSII element. Returns ------- out : string The GDSII binary string that represents this object.
374,736
def get_cgroup_container_metadata(): if not os.path.exists(CGROUP_PATH): return {} with open(CGROUP_PATH) as f: return parse_cgroups(f) or {}
Reads docker/kubernetes metadata (container id, pod id) from /proc/self/cgroup The result is a nested dictionary with the detected IDs, e.g. { "container": {"id": "2227daf62df6694645fee5df53c1f91271546a9560e8600a525690ae252b7f63"}, "pod": {"uid": "90d81341_92de_11e7_8cf2_507b9d4141...
374,737
def main(): try: args = get_args() if in args and in args: _construct_cfgs_from_json(args) else: construct_cfgs(**args) except Exception as Error: print(str(Error)) print("Exiting cleanly...") exit_cleanly() exit_cleanly(error_nu...
main The entrypoint function. This function should also handle any runtime errors and exceptions in a cleanly fashon.
374,738
def setup(options): if not options.misc.debug: requests.packages.urllib3.disable_warnings( requests.packages.urllib3.exceptions.InsecureRequestWarning )
Initialize debug/logging in third party libraries correctly. Args: options (:class:`nyawc.Options`): The options to use for the current crawling runtime.
374,739
def parse_limit(limit_def): lower, upper = get_limits(limit_def) reaction = limit_def.get() return reaction, lower, upper
Parse a structured flux limit definition as obtained from a YAML file Returns a tuple of reaction, lower and upper bound.
374,740
def replace_discount_coupon_by_id(cls, discount_coupon_id, discount_coupon, **kwargs): kwargs[] = True if kwargs.get(): return cls._replace_discount_coupon_by_id_with_http_info(discount_coupon_id, discount_coupon, **kwargs) else: (data) = cls._replace_discount_co...
Replace DiscountCoupon Replace all attributes of DiscountCoupon This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_discount_coupon_by_id(discount_coupon_id, discount_coupon, async=True) >...
374,741
def _set_fields(self, fields): super(_BaseHNVModel, self)._set_fields(fields) if not self.resource_ref: endpoint = self._endpoint.format( resource_id=self.resource_id, parent_id=self.parent_id, grandparent_id=self.grandparent_id) self.reso...
Set or update the fields value.
374,742
def read_dir(input_dir,input_ext,func): import os for dirpath, dnames, fnames in os.walk(input_dir): for fname in fnames: if not dirpath.endswith(os.sep): dirpath = dirpath + os.sep if fname.endswith(input_ext): func(read_file(dirpath + fname)...
reads all files with extension input_ext in a directory input_dir and apply function func to their contents
374,743
def invoked_with(self): command_name = self._command_impl.name ctx = self.context if ctx is None or ctx.command is None or ctx.command.qualified_name != command_name: return command_name return ctx.invoked_with
Similar to :attr:`Context.invoked_with` except properly handles the case where :meth:`Context.send_help` is used. If the help command was used regularly then this returns the :attr:`Context.invoked_with` attribute. Otherwise, if it the help command was called using :meth:`Context.send_h...
374,744
def purge_network(network_id, purge_data,**kwargs): user_id = kwargs.get() try: net_i = db.DBSession.query(Network).filter(Network.id == network_id).one() except NoResultFound: raise ResourceNotFoundError("Network %s not found"%(network_id)) log.info("Deleting network %s, id=%s", n...
Remove a network from DB completely Use purge_data to try to delete the data associated with only this network. If no other resources link to this data, it will be deleted.
374,745
def virtualchain_set_opfields( op, **fields ): for f in fields.keys(): if f not in indexer.RESERVED_KEYS: log.warning("Unsupported virtualchain field " % f) for f in fields.keys(): if f in indexer.RESERVED_KEYS: op[f] = fields[f] return op
Pass along virtualchain-reserved fields to a virtualchain operation. This layer of indirection is meant to help with future compatibility, so virtualchain implementations do not try to set operation fields directly.
374,746
def one_step(self, current_state, previous_kernel_results): with tf.compat.v1.name_scope( name=mcmc_util.make_name(self.name, , ), values=[self._seed_stream, current_state, previous_kernel_results.log_likelihood]): with tf.compat.v1.name_scope(): [ ...
Runs one iteration of the Elliptical Slice Sampler. Args: current_state: `Tensor` or Python `list` of `Tensor`s representing the current state(s) of the Markov chain(s). The first `r` dimensions index independent chains, `r = tf.rank(log_likelihood_fn(*normal_sampler_fn()))`. pr...
374,747
async def fetch_wallet_search_next_records(wallet_handle: int, wallet_search_handle: int, count: int) -> str: logger = logging.getLogger(__name__) logger.debug("fetch_wallet_search_next_records: >>> wallet_handle: %r, wa...
Fetch next records for wallet search. :param wallet_handle: wallet handler (created by open_wallet). :param wallet_search_handle: wallet wallet handle (created by open_wallet_search) :param count: Count of records to fetch :return: wallet records json: { totalCount: <str>, // present only i...
374,748
def _plot_transform_pairs(fCI, r, k, axes, tit): r plt.sca(axes[0]) plt.title( + tit + ) for f in fCI: if f.name == : lhs = f.lhs(k) plt.loglog(k, np.abs(lhs[0]), lw=2, label=) plt.loglog(k, np.abs(lhs[1]), lw=2, label=) else: plt.log...
r"""Plot the input transform pairs.
374,749
def folderitem(self, obj, item, index): item = super(AnalysesView, self).folderitem(obj, item, index) item_obj = api.get_object(obj) uid = item["uid"] slot = self.get_item_slot(uid) item["Pos"] = slot str_position = ...
Applies new properties to the item (analysis) that is currently being rendered as a row in the list. :param obj: analysis to be rendered as a row in the list :param item: dict representation of the analysis, suitable for the list :param index: current position of the item within the lis...
374,750
def _get_state(self): result = yield from self._execute("showvminfo", [self._vmname, "--machinereadable"]) for info in result.splitlines(): if in info: name, value = info.split(, 1) if name == "VMState": return value.strip() ...
Returns the VM state (e.g. running, paused etc.) :returns: state (string)
374,751
def get_ip_interface_output_interface_if_state(self, **kwargs): config = ET.Element("config") get_ip_interface = ET.Element("get_ip_interface") config = get_ip_interface output = ET.SubElement(get_ip_interface, "output") interface = ET.SubElement(output, "interface") ...
Auto Generated Code
374,752
def errmsg(self, message, opts={}): if != self.debugger.settings[]: message = colorize(, message) pass return(self.intf[-1].errmsg(message))
Convenience short-hand for self.intf[-1].errmsg
374,753
def start(self): self.log.debug() self.browser.open(self.url) self.system_check()
Start the installation wizard
374,754
def attach(cls, name, vhost, remote_name): paas_access = cls.get() if not paas_access: paas_info = cls.info(name) paas_access = \ % (paas_info[], paas_info[]) remote_url = % (paas_access, vhost) ret = cls.execute( % (remote_...
Attach an instance's vhost to a remote from the local repository.
374,755
def handle_401(self, response, repo, **kwargs): if response.status_code != requests.codes.unauthorized: return response auth_info = response.headers.get(, ) if not in auth_info.lower(): return response self._token_cache[repo] = self._get_token(auth_in...
Fetch Bearer token and retry.
374,756
def create_mixin(self): _builder = self class CustomModelMixin(object): @cached_property def _content_type(self): return ContentType.objects.get_for_model(self) @classmethod def get_model_custom_fields(cls): ...
This will create the custom Model Mixin to attach to your custom field enabled model. :return:
374,757
def create_model(self, base_model_id, forced_glossary=None, parallel_corpus=None, name=None, **kwargs): if base_model_id is None: raise ValueError() headers = {} if in...
Create model. Uploads Translation Memory eXchange (TMX) files to customize a translation model. You can either customize a model with a forced glossary or with a corpus that contains parallel sentences. To create a model that is customized with a parallel corpus <b>and</b> a forced glos...
374,758
def reply_inform(self, inform, orig_req): assert (inform.mtype == Message.INFORM) assert (inform.name == orig_req.name) inform.mid = orig_req.mid return self._send_message(inform)
Send an inform as part of the reply to an earlier request. Parameters ---------- inform : Message object The inform message to send. orig_req : Message object The request message being replied to. The inform message's id is overridden with the id from...
374,759
def getAxisNames(self): s = {} for l, x in self.items(): s.update(dict.fromkeys([k for k, v in l], None)) return set(s.keys())
Collect a set of axis names from all deltas.
374,760
def drag(self, NewPt): X = 0 Y = 1 Z = 2 W = 3 self.m_EnVec = self._mapToSphere(NewPt) Perp = Vector3fCross(self.m_StVec, self.m_EnVec) NewRot = Quat4fT() if Vector3fLength(Perp) > Epsilon: ...
drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec
374,761
def channel_interpolate(layer1, n_channel1, layer2, n_channel2): def inner(T): batch_n = T(layer1).get_shape().as_list()[0] arr1 = T(layer1)[..., n_channel1] arr2 = T(layer2)[..., n_channel2] weights = (np.arange(batch_n)/float(batch_n-1)) S = 0 for n in range(batch_n): S += (1-weight...
Interpolate between layer1, n_channel1 and layer2, n_channel2. Optimize for a convex combination of layer1, n_channel1 and layer2, n_channel2, transitioning across the batch. Args: layer1: layer to optimize 100% at batch=0. n_channel1: neuron index to optimize 100% at batch=0. layer2: layer to optim...
374,762
def unique(values): values = _ensure_arraylike(values) if is_extension_array_dtype(values): return values.unique() original = values htable, _, values, dtype, ndtype = _get_hashtable_algo(values) table = htable(len(values)) uniques = table.unique(values) uniques = _...
Hash table-based unique. Uniques are returned in order of appearance. This does NOT sort. Significantly faster than numpy.unique. Includes NA values. Parameters ---------- values : 1d array-like Returns ------- numpy.ndarray or ExtensionArray The return can be: * Ind...
374,763
def set_home_position_send(self, target_system, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach_z, force_mavlink1=False): return self.send(self.set_home_position_encode(target_system, latitude, longitude, altitude, x, y, z, q, approach_x, approach_y, approach...
The position the system will return to and land on. The position is set automatically by the system during the takeoff in case it was not explicitely set by the operator before or after. The global and local positions encode the position in the respective ...
374,764
def save_xml(self, doc, element): super(Preceding, self).save_xml(doc, element) pre_element = doc.createElementNS(RTS_NS, RTS_NS_S + ) if self.timeout: pre_element.setAttributeNS(RTS_NS, RTS_NS_S + , str(self.timeout)) if self.sending_timing: ...
Save this preceding condition into an xml.dom.Element object.
374,765
def get_serializer(instance, plugin=None, model=None, *args, **kwargs): serializer_class = get_serializer_class(plugin=plugin, model=model) if not in kwargs: kwargs[] = True return serializer_class(instance, *args, **kwargs)
:param instance: model instance or queryset :param plugin: plugin instance that is used to get serializer for :param model: plugin model we build serializer for :param kwargs: kwargs like many and other :return:
374,766
def _FracInt(x,y,z,a,b,c,tau,n): denom = np.sqrt((a + tau)*(b + tau)*(c + tau)) return (1. - x**2/(a + tau) - y**2/(b + tau) - z**2/(c + tau))**n / denom
Returns 1 x^2 y^2 z^2 -------------------------- (1 - ------- - ------- - -------)^n sqrt(tau+a)(tau+b)(tau+c)) tau+a tau+b tau+c
374,767
def vlan_dot1q_tag_native(self, **kwargs): config = ET.Element("config") vlan = ET.SubElement(config, "vlan", xmlns="urn:brocade.com:mgmt:brocade-vlan") dot1q = ET.SubElement(vlan, "dot1q") tag = ET.SubElement(dot1q, "tag") native = ET.SubElement(tag, "native") ...
Auto Generated Code
374,768
def add_object(self, obj): self.objects[obj.id] = obj self.all_objects[obj.id] = obj child_stack = list(obj.children) while child_stack: child = child_stack.pop() self.all_objects[child.id] = child child_stack.extend(getattr(child, "children",...
Add object to local and app environment storage :param obj: Instance of a AutoAPI object
374,769
def tree(self, path, max_depth, full_path=False, include_stat=False): for child_level_stat in self.do_tree(path, max_depth, 0, full_path, include_stat): yield child_level_stat
DFS generator which starts from a given path and goes up to a max depth. :param path: path from which the DFS will start :param max_depth: max depth of DFS (0 means no limit) :param full_path: should the full path of the child node be returned :param include_stat: return the child Znode...
374,770
def query(self, query): self.logger.info( % (self, query)) return super(LoggingDatastore, self).query(query)
Returns an iterable of objects matching criteria expressed in `query`. LoggingDatastore logs the access.
374,771
def order_by(self, field_name=None): assert self.query.can_filter(), "Cannot reorder a query once a slice has been taken." clone = self._clone() clone.query.clear_ordering() if field_name is not None: clone.query.add_ordering(field_name) return clone
Returns a new QuerySet instance with the ordering changed.
374,772
def dispatch_hook(cls, s=None, *_args, **_kwds): if s is None: return config.conf.raw_layer fb = orb(s[0]) if fb & 0x80 != 0: return HPackIndexedHdr if fb & 0x40 != 0: return HPackLitHdrFldWithIncrIndexing if fb & 0x20 != 0: ...
dispatch_hook returns the subclass of HPackHeaders that must be used to dissect the string.
374,773
def send_msg(self, msg): if not self.is_active: self.logger.debug( , msg) return elif not self.send_q: self.logger.debug( , msg) return elif self.zserv_ver != msg.version: self.logger.debug( ...
Sends Zebra message. :param msg: Instance of py:class: `ryu.lib.packet.zebra.ZebraMessage`. :return: Serialized msg if succeeded, otherwise None.
374,774
def calibration_total_count(self): if self.selected_calibration_index == 2: return self.tone_calibrator.count() else: return self.bs_calibrator.count()
The number of stimuli presentations (including reps) for the current calibration selected :returns: int -- number of presentations
374,775
def _get_binop_contexts(context, left, right): for arg in (right, left): new_context = context.clone() new_context.callcontext = contextmod.CallContext(args=[arg]) new_context.boundnode = None yield new_context
Get contexts for binary operations. This will return two inference contexts, the first one for x.__op__(y), the other one for y.__rop__(x), where only the arguments are inversed.
374,776
def barrier_layer_thickness(SA, CT): import gsw sigma_theta = gsw.sigma0(SA, CT) mask = mixed_layer_depth(CT) mld = np.where(mask)[0][-1] sig_surface = sigma_theta[0] sig_bottom_mld = gsw.sigma0(SA[0], CT[mld]) d_sig_t = sig_surface - sig_bottom_mld d_sig = sigma_theta - sig_bottom...
Compute the thickness of water separating the mixed surface layer from the thermocline. A more precise definition would be the difference between mixed layer depth (MLD) calculated from temperature minus the mixed layer depth calculated using density.
374,777
def ltrim(self, name, start, end): with self.pipe as pipe: return pipe.ltrim(self.redis_key(name), start, end)
Trim the list from start to end. :param name: str the name of the redis key :param start: :param end: :return: Future()
374,778
def predict_cumulative_hazard(self, X): n, _ = X.shape cols = _get_index(X) if isinstance(X, pd.DataFrame): order = self.cumulative_hazards_.columns order = order.drop("_intercept") if self.fit_intercept else order X_ = X[order].values else: ...
Returns the hazard rates for the individuals Parameters ---------- X: a (n,d) covariate numpy array or DataFrame. If a DataFrame, columns can be in any order. If a numpy array, columns must be in the same order as the training data.
374,779
def read(self, client): assert(isinstance(self._bytearray, DB)) assert(self.row_size >= 0) db_nr = self._bytearray.db_number _bytearray = client.db_read(db_nr, self.db_offset, self.row_size) data = self.get_bytearray() for i, b in enumerate(_bytearray):...
read current data of db row from plc
374,780
def find_package_indexes_in_dir(self, simple_dir): packages = sorted( { canonicalize_name(x) for x in os.listdir(simple_dir) } ) packages = [x for x in packages if os.path.isdir(os.path.join(simple_dir, x)...
Given a directory that contains simple packages indexes, return a sorted list of normalized package names. This presumes every directory within is a simple package index directory.
374,781
def get_default_config_help(self): config = super(RiemannHandler, self).get_default_config_help() config.update({ : , : , : , }) return config
Returns the help text for the configuration options for this handler
374,782
def build( self, endpoint, values=None, method=None, force_external=False, append_unknown=True, ): self.map.update() if values: if isinstance(values, MultiDict): temp_values = {} ...
Building URLs works pretty much the other way round. Instead of `match` you call `build` and pass it the endpoint and a dict of arguments for the placeholders. The `build` function also accepts an argument called `force_external` which, if you set it to `True` will force external URLs....
374,783
def extract_files(self, resource): if hasattr(resource, "__iter__"): files = [file for file in resource if self.can_be_extracted(file)] elif os.path.isfile(resource): files = [resource] if self.can_be_extracted(resource) else [] else: files = self._ex...
:param resource str|iterable files, a file or a directory @return: iterable
374,784
def repmct(instr, marker, value, repcase, lenout=None): if lenout is None: lenout = ctypes.c_int(len(instr) + len(marker) + 15) instr = stypes.stringToCharP(instr) marker = stypes.stringToCharP(marker) value = ctypes.c_int(value) repcase = ctypes.c_char(repcase.encode(encoding=)) ou...
Replace a marker with the text representation of a cardinal number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmc_c.html :param instr: Input string. :type instr: str :param marker: Marker to be replaced. :type marker: str :param value: Replacement value. :type value: in...
374,785
def get_date(self, p_tag): string = self.tag_value(p_tag) result = None try: result = date_string_to_date(string) if string else None except ValueError: pass return result
Given a date tag, return a date object.
374,786
def convert(self, newstart: str) -> None: match = self._match ms = match.start() for s, e in reversed(match.spans()): self[s - ms:e - ms] = newstart self.pattern = escape(newstart)
Convert to another list type by replacing starting pattern.
374,787
def create_ascii_table(observation_table, outfile): logging.info("writing text log to %s" % outfile) stamp = " header = "| %20s | %20s | %20s | %20s | %20s | %20s | %20s |\n" % ( "EXPNUM", "OBS-DATE", "FIELD", "EXPTIME(s)", "RA", "DEC", "RUNID") bar = "=" * (len(header) - 1) + "\n" i...
Given a table of observations create an ascii log file for easy parsing. Store the result in outfile (could/should be a vospace dataNode) observation_table: astropy.votable.array object outfile: str (name of the vospace dataNode to store the result to)
374,788
def target_slide(self): slide_jump_actions = ( PP_ACTION.FIRST_SLIDE, PP_ACTION.LAST_SLIDE, PP_ACTION.NEXT_SLIDE, PP_ACTION.PREVIOUS_SLIDE, PP_ACTION.NAMED_SLIDE, ) if self.action not in slide_jump_actions: return ...
A reference to the slide in this presentation that is the target of the slide jump action in this shape. Slide jump actions include `PP_ACTION.FIRST_SLIDE`, `LAST_SLIDE`, `NEXT_SLIDE`, `PREVIOUS_SLIDE`, and `NAMED_SLIDE`. Returns |None| for all other actions. In particular, the `LAST_SLI...
374,789
def num_listeners(self, event=None): if event is not None: return len(self._listeners[event]) else: return sum(len(l) for l in self._listeners.values())
Return the number of listeners for ``event``. Return the total number of listeners for all events on this object if ``event`` is :class:`None`.
374,790
def format_year(year): if isinstance(year, (date, datetime)): return unicode(year.year) else: return unicode(year)
Format the year value of the ``YearArchiveView``, which can be a integer or date object. This tag is no longer needed, but exists for template compatibility. It was a compatibility tag for Django 1.4.
374,791
def store_field(self, state, field_name, field_type, value): field_ref = SimSootValue_InstanceFieldRef(self.heap_alloc_id, self.type, field_name, field_type) state.memory.store(field_ref, value)
Store a field of a given object, without resolving hierachy :param state: angr state where we want to allocate the object attribute :type SimState :param field_name: name of the attribute :type str :param field_value: attibute's value :type SimSootValue
374,792
def _load_stats(self): for attempt in range(0, 3): try: with self.stats_file.open() as f: return json.load(f) except ValueError: if attempt < 2: time.sleep(attempt * 0.2) ...
Load the webpack-stats file
374,793
def event_choices(events): if events is None: msg = "Please add some events in settings.WEBHOOK_EVENTS." raise ImproperlyConfigured(msg) try: choices = [(x, x) for x in events] except TypeError: msg = "settings.WEBHOOK_EVENTS must be an iterable object." ...
Get the possible events from settings
374,794
def replace(self, old, new): if old.type != new.type: raise TypeError("new instruction has a different type") pos = self.instructions.index(old) self.instructions.remove(old) self.instructions.insert(pos, new) for bb in self.parent.basic_blocks: ...
Replace an instruction
374,795
def pep440_dev_version(self, verbose=False, non_local=False): version = capture("python setup.py --version", echo=verbose) if verbose: notify.info("setuptools version = ".format(version)) now = .format(datetime.now()) tag = capture("git describe --long --tags --dirt...
Return a PEP-440 dev version appendix to the main version number. Result is ``None`` if the workdir is in a release-ready state (i.e. clean and properly tagged).
374,796
def iteration(self, node_status=True): self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.stream_execution: u, v = list(self.graph.edges())[0] u_s...
Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status)
374,797
def steady_connection(self): return SteadyPgConnection( self._maxusage, self._setsession, self._closeable, *self._args, **self._kwargs)
Get a steady, non-persistent PyGreSQL connection.
374,798
def post_optimization_step(self, batch_info, device, model, rollout): if batch_info.aggregate_batch_number % self.target_update_frequency == 0: self.target_model.load_state_dict(model.state_dict()) self.target_model.eval()
Steps to take after optimization has been done
374,799
def zonal_mean_column(num_lat=90, num_lev=30, water_depth=10., lat=None, lev=None, **kwargs): if lat is None: latax = Axis(axis_type=, num_points=num_lat) elif isinstance(lat, Axis): latax = lat else: try: latax = Axis(axis_type=, points=lat) ...
Creates two Domains with one water cell, a latitude axis and a level/height axis. * SlabOcean: one water cell and a latitude axis above (similar to :func:`zonal_mean_surface`) * Atmosphere: a latitude axis and a level/height axis (two dimensional) **Function-call argument** \n ...