Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
344,300
def wet_bulb_temperature(pressure, temperature, dewpoint): if not hasattr(pressure, ): pressure = atleast_1d(pressure) temperature = atleast_1d(temperature) dewpoint = atleast_1d(dewpoint) it = np.nditer([pressure, temperature, dewpoint, None], op_dtypes=[, , , ]...
Calculate the wet-bulb temperature using Normand's rule. This function calculates the wet-bulb temperature using the Normand method. The LCL is computed, and that parcel brought down to the starting pressure along a moist adiabat. The Normand method (and others) are described and compared by [Knox2017]_. ...
344,301
def is_relative(modname, from_file): if not os.path.isdir(from_file): from_file = os.path.dirname(from_file) if from_file in sys.path: return False try: stream, _, _ = imp.find_module(modname.split(".")[0], [from_file]) if stream: stream.close() ...
return true if the given module name is relative to the given file name :type modname: str :param modname: name of the module we are interested in :type from_file: str :param from_file: path of the module from which modname has been imported :rtype: bool :return: true if the m...
344,302
def from_pauli(pauli, coeff=1.0): if pauli.is_identity or coeff == 0: return Term((), coeff) return Term((pauli,), coeff)
Make new Term from an Pauli operator
344,303
def _write_file_iface(iface, data, folder, pattern): filename = os.path.join(folder, pattern.format(iface)) if not os.path.exists(folder): msg = msg = msg.format(filename, folder) log.error(msg) raise AttributeError(msg) with salt.utils.files.fopen(filename, ) as fp_: ...
Writes a file to disk
344,304
def write_skills_data(self, data=None): data = data or self.skills_data if skills_data_hash(data) != self.skills_data_hash: write_skills_data(data) self.skills_data_hash = skills_data_hash(data)
Write skills data hash if it has been modified.
344,305
def index_list(self): request = self.session url = % (self.host, self.port) response = request.get(url) if request.status_code==200: return response.get(,{}).get(,{}).keys() else: return response
Lists indices
344,306
def _parse_list(cls, value, separator=): if isinstance(value, list): return value if in value: value = value.splitlines() else: value = value.split(separator) return [chunk.strip() for chunk in value if chunk.strip()]
Represents value as a list. Value is split either by separator (defaults to comma) or by lines. :param value: :param separator: List items separator character. :rtype: list
344,307
def convert_to_vcard(name, value, allowed_object_type): if isinstance(value, str): if allowed_object_type == ObjectType.list_with_strings: raise ValueError( "Error: " + name + " must not contain a single string.") else: return value.strip() elif isins...
converts user input into vcard compatible data structures :param name: object name, only required for error messages :type name: str :param value: user input :type value: str or list(str) :param allowed_object_type: set the accepted return type for vcard attribute :type allowed_object_ty...
344,308
def skipped(x, y, method=): from pingouin.utils import _is_sklearn_installed _is_sklearn_installed(raise_error=True) from scipy.stats import chi2 from sklearn.covariance import MinCovDet X = np.column_stack((x, y)) nrows, ncols = X.shape gval = np.sqrt(chi2.ppf(0.975, 2)) ...
Skipped correlation (Rousselet and Pernet 2012). Parameters ---------- x, y : array_like First and second set of observations. x and y must be independent. method : str Method used to compute the correlation after outlier removal. Can be either 'spearman' (default) or 'pearson'....
344,309
def short_hash(*buffers): hashed = hashlib.sha1() for buffer in buffers: hashed.update(buffer) return to_ascii(hashed.digest())[:8]
:param buffer: a binary buffer (e.g. serialized blob) :return: the first 8 characters of base64 ASCII rendition SHA-1
344,310
def update_resource(self, path, data, if_match=None): response = self._http_request(resource=path, method="PUT", body=data, if_match=if_match) try: return response.json() except ValueError: raise exception.ServiceException("I...
Update the required resource.
344,311
def first(self): self.open() seq = SeqIO.parse(self.handle, self.format).next() self.close() return seq
Just the first sequence
344,312
def asl_obctrl_send(self, timestamp, uElev, uThrot, uThrot2, uAilL, uAilR, uRud, obctrl_status, force_mavlink1=False): return self.send(self.asl_obctrl_encode(timestamp, uElev, uThrot, uThrot2, uAilL, uAilR, uRud, obctrl_status), force_mavlink1=force_mavlink1)
Off-board controls/commands for ASLUAVs timestamp : Time since system start [us] (uint64_t) uElev : Elevator command [~] (float) uThrot : Throttle command [~] (float) uThrot2 : Throt...
344,313
def join(self, n1): if self.id == n1.get_id(): for i in range(k): self.finger[i] = self.proxy self.predecessor = self.proxy self.run = True return True else: try: self.init_finger_table(n1) e...
if join returns false, the node did not entry the ring. Retry it
344,314
def _collect_uncolored_outputs(unspent_outputs, amount): total_amount = 0 result = [] for output in unspent_outputs: if output.output.asset_id is None: result.append(output) total_amount += output.output.value if total_amount >= a...
Returns a list of uncolored outputs for the specified amount. :param list[SpendableOutput] unspent_outputs: The list of available outputs. :param int amount: The amount to collect. :return: A list of outputs, and the total amount collected. :rtype: (list[SpendableOutput], int)
344,315
def handle_violation(self, asset, amount, datetime, metadata=None): constraint = self._constraint_msg(metadata) if self.on_error == : raise TradingControlViolation( asset=asset, amount=amount, datetime=datetime, constr...
Handle a TradingControlViolation, either by raising or logging and error with information about the failure. If dynamic information should be displayed as well, pass it in via `metadata`.
344,316
def walk(self, relpath, topdown=True): for root, dirs, files in self._walk_raw(relpath, topdown): matched_dirs = self.ignore.match_files([os.path.join(root, "{}/".format(d)) for d in dirs]) matched_files = self.ignore.match_files([os.path.join(root, f) for f in files]) for matched_dir in matc...
Walk the file tree rooted at `path`. Works like os.walk but returned root value is relative path. Ignored paths will not be returned.
344,317
def is_managed(using=None): if using is None: managed = False for using in tldap.backend.connections: connection = tldap.backend.connections[using] if connection.is_managed(): managed = True return managed connection = tldap.backend.connection...
Checks whether the transaction manager is in manual or in auto state.
344,318
def srbt1(bt_address, pkts, *args, **kargs): a, b = srbt(bt_address, pkts, *args, **kargs) if len(a) > 0: return a[0][1]
send and receive 1 packet using a bluetooth socket
344,319
def crypto_kx_client_session_keys(client_public_key, client_secret_key, server_public_key): ensure(isinstance(client_public_key, bytes) and len(client_public_key) == crypto_kx_PUBLIC_KEY_BYTES, .format( cry...
Generate session keys for the client. :param client_public_key: :type client_public_key: bytes :param client_secret_key: :type client_secret_key: bytes :param server_public_key: :type server_public_key: bytes :return: (rx_key, tx_key) :rtype: (bytes, bytes)
344,320
def update_empty_fields(self, **kwargs): if self._is_deprecated is None: self._is_deprecated = kwargs.get() if self._is_dubious is None: self._is_dubious = kwargs.get() if self._is_synonym is None: self._is_synonym = kwargs.get() if self._syno...
Updates the field of info about an OTU that might not be filled in by a match_names or taxon call.
344,321
def bits_clear_in_range( bits, range_start, range_end ): end = range_start while 1: start = bits.next_clear( end ) if start >= range_end: break end = min( bits.next_set( start ), range_end ) yield start, end
Yield start,end tuples for each span of clear bits in [range_start,range_end)
344,322
def _init_map(self, record_types=None, **kwargs): osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map[] = self._rubric_default self._my_map[] = [str(kwargs[])] self._my_map[] = self._level_default if self._supports_simple_sequencing(): ...
Initialize form map
344,323
def process_user_input(self): user_input = self.get_input() go_to_max = ord("9") if len(self.items) >= 9 else ord(str(len(self.items))) if ord() <= user_input <= go_to_max: self.go_to(user_input - ord() - 1) elif user_input == curses.KEY_DOWN: self.go_d...
Gets the next single character and decides what to do with it
344,324
def get_table_data(self, tableid, octetcount=None, offset=None): if self.caching_enabled and tableid in self._cacheable_tables and tableid in self._table_cache.keys(): self.logger.info( + str(tableid)) return self._table_cache[tableid] self.send(C1218ReadRequest(tableid, offset, octetcount)) data = self....
Read data from a table. If successful, all of the data from the requested table will be returned. :param int tableid: The table number to read from (0x0000 <= tableid <= 0xffff) :param int octetcount: Limit the amount of data read, only works if the meter supports this type of reading. :param int offset: T...
344,325
def ufunc_functional_factory(name, nargin, nargout, docstring): assert 0 <= nargin <= 2 def __init__(self, field): if not isinstance(field, Field): raise TypeError(.format(space)) if _is_integer_only_ufunc(name): raise ValueError("ufunc only defined with...
Create a ufunc `Functional` from a given specification.
344,326
def prepare_axes(axes, title, size, cmap=None): if axes is None: return None axes.set_xlim([0, size[1]]) axes.set_ylim([size[0], 0]) axes.set_aspect() axes.axis() if isinstance(cmap, str): title = .format(title, cmap) axes.set_title(title) axes_image = i...
Prepares an axes object for clean plotting. Removes x and y axes labels and ticks, sets the aspect ratio to be equal, uses the size to determine the drawing area and fills the image with random colors as visual feedback. Creates an AxesImage to be shown inside the axes object and sets the needed p...
344,327
def fit(self, X, C): X, C = _check_fit_input(X, C) self.nclasses = C.shape[1] ncombs = int( self.nclasses * (self.nclasses - 1) / 2 ) self.classifiers = [ deepcopy(self.base_classifier) for c in range(ncombs) ] self.classes_compared = [None for i in range(ncombs)] ...
Fit one classifier comparing each pair of classes Parameters ---------- X : array (n_samples, n_features) The data on which to fit a cost-sensitive classifier. C : array (n_samples, n_classes) The cost of predicting each label for each observation (more m...
344,328
def get_sources(self, cuts=None, distance=None, skydir=None, minmax_ts=None, minmax_npred=None, exclude=None, square=False): coordsys = self.config[][] return self.roi.get_sources(skydir, distance, cuts, minmax_ts, min...
Retrieve list of sources in the ROI satisfying the given selections. Returns ------- srcs : list A list of `~fermipy.roi_model.Model` objects.
344,329
def as_tensorflow_layer(odl_op, name=, differentiable=True): default_name = name def py_func(func, inp, Tout, stateful=True, name=None, grad=None): if grad is None: return tf.py_func(func, inp, Tout, stateful=stateful, name=name) else: ...
Convert `Operator` or `Functional` to a tensorflow layer. Parameters ---------- odl_op : `Operator` or `Functional` The operator that should be wrapped as a tensorflow layer. name : str Default name for tensorflow layers created. differentiable : boolean ``True`` if the laye...
344,330
def choice(choices): def decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): series = function(*args, **kwargs) return series.isin(set(choices)) return wrapper return decorator
Test that the data items are members of the set `choices`.
344,331
def _read_offset_value(self, f, offset, size): f.seek(offset, 0) if (size == 8): return int.from_bytes(f.read(8), , signed=True) else: return int.from_bytes(f.read(4), , signed=True)
Reads an integer value from file "f" at location "offset".
344,332
def tag_user(self, tag_id, user_id): data = {: tag_id} if isinstance(user_id, (tuple, list)): data[] = user_id else: data[] = [user_id, ] return self._post(, data=data)
批量为用户打标签 :param tag_id: 标签 ID :param user_id: 用户 ID, 可以是单个或者列表 :return: 返回的 JSON 数据包
344,333
def value_name(cls, value): for k, v in list(cls.__dict__.items()): if v == value: return k return value
Returns the label from a value if label exists otherwise returns the value since method does a reverse look up it is slow
344,334
def set_volume(self, volume): for data in self._group.get(): client = self._server.client(data.get()) yield from client.set_volume(volume, update_group=False) client.update_volume({ : { : volume, : client.muted ...
Set volume.
344,335
def is_chat_admin(user): from indico_chat.plugin import ChatPlugin return ChatPlugin.settings.acls.contains_user(, user)
Checks if a user is a chat admin
344,336
def _find_ids(self, data_list, prop, lookup_index, lookup_doc_type, lookup_field): lg = logging.getLogger("%s.%s" % (self.ln, inspect.stack()[0][3])) lg.setLevel(self.log_level) rtn_list...
Reads a list of data and replaces the ids with es id of the item args: data_list: list of items to find in replace prop: full prop name in es format i.e. make.id lookup_src: dictionary with index doc_type ie. {"es_index": "reference", "doc_type": "devic...
344,337
def compute_followup_snr_series(data_reader, htilde, trig_time, duration=0.095, check_state=True, coinc_window=0.05): if check_state: state_start_time = trig_time - duration / 2 - htilde.length_in_time state_end_time = tri...
Given a StrainBuffer, a template frequency series and a trigger time, compute a portion of the SNR time series centered on the trigger for its rapid sky localization and followup. If the trigger time is too close to the boundary of the valid data segment the SNR series is calculated anyway and might be...
344,338
def simplex(x, rho): u = np.flipud(np.sort(x.ravel())) lambdas = (1 - np.cumsum(u)) / (1. + np.arange(u.size)) ix = np.where(u + lambdas > 0)[0].max() return np.maximum(x + lambdas[ix], 0)
Projection onto the probability simplex http://arxiv.org/pdf/1309.1541v1.pdf
344,339
def metric(self, slug, num=1, category=None, expire=None, date=None): self.r.sadd(self._metric_slugs_key, slug) if category: self._categorize(slug, category) keys = self._build_keys(slug, date=date) pipe = self.r.pipeline() ...
Records a metric, creating it if it doesn't exist or incrementing it if it does. All metrics are prefixed with 'm', and automatically aggregate for Seconds, Minutes, Hours, Day, Week, Month, and Year. Parameters: * ``slug`` -- a unique value to identify the metric; used in co...
344,340
def display(surface): screen = pygame.display.get_surface() screen.blit(surface, (0, 0)) pygame.display.flip()
Displays a pygame.Surface in the window. in pygame the window is represented through a surface, on which you can draw as on any other pygame.Surface. A refernce to to the screen can be optained via the :py:func:`pygame.display.get_surface` function. To display the contents of the screen surface in ...
344,341
def to_array(self): array = super(InlineKeyboardMarkup, self).to_array() array[] = self._as_array(self.inline_keyboard) return array
Serializes this InlineKeyboardMarkup to a dictionary. :return: dictionary representation of this object. :rtype: dict
344,342
def cpp_checker(code, working_directory): return gcc_checker(code, , [os.getenv(, ), ] + INCLUDE_FLAGS, working_directory=working_directory)
Return checker.
344,343
def add_precedence_relations(self): assert len(self.tokens) > 1, \ "There are no tokens to add precedence relations to." self.add_edge(self.root, self.tokens[0], layers={self.ns, self.ns+}, edge_type=EdgeTypes.precedence_relation) ...
add precedence relations to the document graph (i.e. an edge from the root node to the first token node, an edge from the first token node to the second one etc.)
344,344
def transpose(self, *args, **kwargs): new_data = self.data.transpose(*args, **kwargs) new_manager = self.__constructor__(new_data, self.columns, self.index) new_manager._is_transposed = self._is_transposed ^ 1 return new_manager
Transposes this DataManager. Returns: Transposed new DataManager.
344,345
def install_sql_hook(): try: from django.db.backends.utils import CursorWrapper except ImportError: from django.db.backends.util import CursorWrapper try: real_execute = CursorWrapper.execute real_executemany = CursorWrapper.executemany except AttributeErro...
If installed this causes Django's queries to be captured.
344,346
def get_required_arguments_metricnames(self): try: metricnames = self.get_arguments(constants.PARAM_METRICNAME) if not metricnames: raise tornado.web.MissingArgumentError(constants.PARAM_METRICNAME) return metricnames except tornado.web.MissingArgumentError as e: raise Excep...
Helper function to get metricname arguments. Notice that it is get_argument"s" variation, which means that this can be repeated. Raises exception if argument is missing. Returns a list of metricname arguments
344,347
def _render_value(self, val, context, delimiters=None): if not is_string(val): val = self.to_str(val) if type(val) is not unicode: val = self.literal(val) return self.render(val, context, delimiters)
Render an arbitrary value.
344,348
async def service_observable(self, limit) -> int: if not self.isReady(): return 0 o = self._service_observable_out_box(limit) i = await self._observable.serviceQueues(limit) return o + i
Service the observable's inBox and outBox :return: the number of messages successfully serviced
344,349
def create(self, virtual_interfaces): data = {: virtual_interfaces} return super(ApiV4VirtualInterface, self).post\ (, data)
Method to create Virtual Interfaces :param Virtual Interfaces: List containing Virtual Interfaces desired to be created on database :return: None
344,350
def sk_log_loss(y_true: Union[List[List[float]], List[List[int]], np.ndarray], y_predicted: Union[List[List[float]], List[List[int]], np.ndarray]) -> float: return log_loss(y_true, y_predicted)
Calculates log loss. Args: y_true: list or array of true values y_predicted: list or array of predicted values Returns: Log loss
344,351
def launch(self, timeout=2): self.start_time = time.time() self.end_time = time.time() instance = self.app.launch(environment=self.env) time.sleep(2) assert instance.running(timeout=timeout), "Monitor didnActivedestroyt get Destroyed after short time" stopped =...
Hierapp instance, with environment dependencies: - can be launched within short timeout - auto-destroys shortly
344,352
def _compute_centers(self, X, sparse, rs): super(GRBFRandomLayer, self)._compute_centers(X, sparse, rs) centers = self.components_[] sorted_distances = np.sort(squareform(pdist(centers))) self.dF_vals = sorted_distances[:, -1] self.dN_vals = sorted_distances[:, 1]/100....
Generate centers, then compute tau, dF and dN vals
344,353
def clickMouseButtonLeftWithMods(self, coord, modifiers, interval=None): modFlags = self._pressModifiers(modifiers) self._queueMouseButton(coord, Quartz.kCGMouseButtonLeft, modFlags) self._releaseModifiers(modifiers) if interval: self._postQueuedEvents(interval=inter...
Click the left mouse button with modifiers pressed. Parameters: coordinates to click; modifiers (list) (e.g. [SHIFT] or [COMMAND, SHIFT] (assuming you've first used from pyatom.AXKeyCodeConstants import *)) Returns: None
344,354
def get_nonmonotonic_neurites(neuron, tol=1e-6): return [n for n in neuron.neurites if not is_monotonic(n, tol)]
Get neurites that are not monotonic Args: neurite(Neurite): neurite to operate on tol(float): the tolerance or the ratio Returns: list of neurites that do not satisfy monotonicity test
344,355
def json_request_response(f): @wraps(f) def wrapper(*args, **kwargs): response = f(*args, **kwargs) response.raise_for_status() return json.loads(response.content.decode()) API_FUNCTIONS[f.__name__] = f return wrapper
Parse the JSON from an API response. We do this in a decorator so that our Twisted library can reuse the underlying functions
344,356
def sed2(img, contour=None, shape=[3, 4]): plt.imshow(slices(img, shape), cmap=) if contour is not None: plt.contour(slices(contour, shape))
plot tiled image of multiple slices :param img: :param contour: :param shape: :return:
344,357
def _dumps(obj, cls=pyjson.JSONEncoder): class WithBytes(cls): def default(self, o): if isinstance(o, bytes): warnings.warn( "Eliot will soon stop supporting encoding bytes in JSON" " on Python 3", DeprecationWarning ...
Encode to bytes, and presume bytes in inputs are UTF-8 encoded strings.
344,358
def enable_selfalias(config, id_name): def context_found_subscriber(event): request = event.request user = getattr(request, , None) if (request.matchdict and request.matchdict.get(id_name, None) == and user): request.matchdict[id_name] = use...
This allows replacing id_name with "self". e.g. /users/joe/account == /users/self/account if joe is in the session as an authorized user
344,359
def packstr(instr, textwidth=160, breakchars=, break_words=True, newline_prefix=, indentation=, nlprefix=None, wordsep=, remove_newlines=True): if not isinstance(instr, six.string_types): instr = repr(instr) if nlprefix is not None: newline_prefix = nlprefix str_...
alias for pack_into. has more up to date kwargs
344,360
def commandline_to_list(self, cmdline_str, trigger_string): cmdline = salt.utils.args.shlex_split(cmdline_str[len(trigger_string):]) cmdlist = [] for cmditem in cmdline: pattern = r mtch = re.match(pattern, cmditem) if mtch:...
cmdline_str is the string of the command line trigger_string is the trigger string, to be removed
344,361
def remove_root_gradebook(self, gradebook_id): if self._catalog_session is not None: return self._catalog_session.remove_root_catalog(catalog_id=gradebook_id) return self._hierarchy_session.remove_root(id_=gradebook_id)
Removes a root gradebook. arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook raise: NotFound - ``gradebook_id`` is not a root raise: NullArgument - ``gradebook_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorizat...
344,362
def check_input_files_for_numbered_seq(sourceDir, suffix, containers): for container in containers: files = glob.glob( os.path.join( sourceDir, container, container + + suffix ) ) for currentFile in sorted( files ): if check_header_comment( currentFile ): retur...
Check if files, used as input when pre-processing MPL-containers in their numbered form, need fixing.
344,363
def getOldestRequestTime(self): bldrid = yield self.getBuilderId() unclaimed = yield self.master.data.get( (, bldrid, ), [resultspec.Filter(, , [False])], order=[], limit=1) if unclaimed: return unclaimed[0][]
Returns the submitted_at of the oldest unclaimed build request for this builder, or None if there are no build requests. @returns: datetime instance or None, via Deferred
344,364
def write_sparse(self, file_path: str): coo = sparse.coo_matrix(self.X) data = OrderedDict([(0, coo.row+1), (1, coo.col+1), (2, coo.data)]) df = pd.DataFrame(data, columns=data.keys()) with open(file_path, ) as ofh: ofh.write() ofh.write( % .join(self.ge...
Write a sparse representation to a tab-delimited text file. TODO: docstring
344,365
def get_releases(self): return github.PaginatedList.PaginatedList( github.GitRelease.GitRelease, self._requester, self.url + "/releases", None )
:calls: `GET /repos/:owner/:repo/releases <http://developer.github.com/v3/repos>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.GitRelease.GitRelease`
344,366
def decode(self, packet): ssu=packet.retrieve("Complete uuids") found=False for x in ssu: if EDDY_UUID in x: found=True break if not found: return None found=False adv=packet.retrieve("Advertised Data") ...
Check a parsed packet and figure out if it is an Eddystone Beacon. If it is , return the relevant data as a dictionary. Return None, it is not an Eddystone Beacon advertising packet
344,367
def create(filename: str, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], row_attrs: Union[loompy.AttributeManager, Dict[str, np.ndarray]], col_attrs: Union[loompy.AttributeManager, Dict[str, np.ndarray]], *, file_attrs: Dict[str, str] = None) -> None: if isinstance(row_attrs, loompy.Attribut...
Create a new Loom file from the given data. Args: filename (str): The filename (typically using a ``.loom`` file extension) layers: One of the following: * Two-dimensional (N-by-M) numpy ndarray of float values * Sparse matrix (e.g. :class:`scipy.sparse.csr_matrix`) * Dictiona...
344,368
def import_vol_mesh(file_name): raw_content = read_file(file_name) raw_content = raw_content.split("\n") content = [] for rc in raw_content: temp = rc.strip().split() content.append(temp) if int(content[0][0]) != 3: raise TypeError("Input mesh must be 3-dimensiona...
Generates a NURBS volume object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS volume :rtype: NURBS.Volume
344,369
def parsed_top_level_errors(parsed, errors, component_type: str = "") -> Errors: fn_cnt = 0 rel_cnt = 0 nested_cnt = 0 for key in parsed: if parsed[key]["type"] == "Function": fn_cnt += 1 if parsed[key]["type"] == "Relation": rel_cnt += 1 if par...
Check full parse for errors Args: parsed: errors: component_type: Empty string or 'subject' or 'object' to indicate that we are parsing the subject or object field input
344,370
def get_template(request, query, meta, proxyMode): templateContent = None if not proxyMode: templateContent = plugIt.getTemplate(query, meta) if not templateContent: return (None, gen404(request, baseURI, )) return (templateContent, None)
Return (if needed) the template to use
344,371
def _list_objects(self, client_kwargs, path, max_request_entries): kwargs = dict(prefix=path) if max_request_entries: kwargs[] = max_request_entries else: kwargs[] = True with _handle_client_exception(): response = self.client.get_container( ...
Lists objects. args: client_kwargs (dict): Client arguments. path (str): Path relative to current locator. max_request_entries (int): If specified, maximum entries returned by request. Returns: generator of tuple: object name str, object ...
344,372
def packagePlugin(self, dir=os.getcwd(), extraArgs=[]): distDir = os.path.join(os.path.abspath(dir), ) self.runUAT([ , + self.getPluginDescriptor(dir), + distDir ] + extraArgs)
Packages a build of the Unreal plugin in the specified directory, suitable for use as a prebuilt Engine module
344,373
def _collapse_variants_by_function(graph: BELGraph, func: str) -> None: for parent_node, variant_node, data in graph.edges(data=True): if data[RELATION] == HAS_VARIANT and parent_node.function == func: collapse_pair(graph, from_node=variant_node, to_node=parent_node)
Collapse all of the given functions' variants' edges to their parents, in-place.
344,374
def _parse_bbox_list(bbox_list): if isinstance(bbox_list, BBoxCollection): return bbox_list.bbox_list, bbox_list.crs if not isinstance(bbox_list, list) or not bbox_list: raise ValueError() for bbox in bbox_list: if not isinstance(bbox, BBox): ...
Helper method for parsing a list of bounding boxes
344,375
def get_groups(self, username): username = ldap.filter.escape_filter_chars(self._byte_p2(username)) userdn = self._get_user(username, NO_ATTR) searchfilter = self.group_filter_tmpl % { : userdn, : username } groups = self._search(searchfilter, N...
Get all groups of a user
344,376
def subset(self, *args): df = self._subset(*args) if df is None: self.err("Can get subset of data") return self.df = df
Set the main dataframe to a subset based in positions Select a subset of the main dataframe based on position: ex: ds.subset(0,10) or ds.subset(10) is equivalent: it starts at the first row if only one argument is provided
344,377
def list_diskgroups(cache_disk_ids=None, service_instance=None): s details instead of the arguments service_instance Service instance (vim.ServiceInstance) of the vCenter/ESXi host. Default is None. .. code-block:: bash salt vsphere.list_diskgroups salt vsphere....
Returns a list of disk group dict representation on an ESXi host. The list of disk groups can be filtered by the cache disks canonical names. If no filtering is applied, all disk groups are returned. cache_disk_ids: List of cache disk canonical names of the disk groups to be retrieved. Defa...
344,378
def count_sources_in_cluster(n_src, cdict, rev_dict): ret_val = np.zeros((n_src), int) for i in range(n_src): try: key = rev_dict[i] except KeyError: key = i try: n = len(cdict[key]) except: n = 0 ret_val[i] = n ret...
Make a vector of sources in each cluster Parameters ---------- n_src : number of sources cdict : dict(int:[int,]) A dictionary of clusters. Each cluster is a source index and the list of other source in the cluster. rev_dict : dict(int:int) A single valued dictio...
344,379
def panset_xy(self, data_x, data_y, no_reset=False): pan_coord = self.t_[] if pan_coord == : image = self.get_image() if image is None: return pan_x, pan_y = image.pixtoradec(data_x, data_y) else: pan_x, pan_y = da...
Similar to :meth:`set_pan`, except that input pan positions are always in data space.
344,380
def create_field_ref(self, class_: str, field: str, descriptor: str) \ -> FieldReference: self.append(( 9, self.create_class(class_).index, self.create_name_and_type(field, descriptor).index )) return self.get(self.raw_count - 1)
Creates a new :class:`ConstantFieldRef`, adding it to the pool and returning it. :param class_: The name of the class to which `field` belongs. :param field: The name of the field. :param descriptor: The descriptor for `field`.
344,381
def get_object_map(self): obj_map = self._payload.get_object_map() obj_map[] = [] for asset_content in self.get_asset_contents(): obj_map[].append(asset_content.object_map) return obj_map
stub
344,382
def get_timezone_converter(from_timezone, to_tz=None, tz_aware=False): if not from_timezone: return None is_true(HAS_DATEUTIL, "`pip install python_dateutil` required") is_true(HAS_PYTZ, "`pip install pytz` required") from_tz = pytz.timezone(from_timezone) return partial(_get_timezone_c...
return a function that converts a given datetime object from a timezone to utc :param from_timezone: timezone name as string
344,383
def configure_client(cls, host: str = , port: int = 11211, **client_args): assert check_argument_types() client = Client(host, port, **client_args) return client
Configure a Memcached client. :param host: host name or ip address to connect to :param port: port number to connect to :param client_args: extra keyword arguments passed to :class:`aiomcache.Client`
344,384
def async_stats_job_data(klass, account, url, **kwargs): resource = urlparse(url) domain = .format(resource.scheme, resource.netloc) response = Request(account.client, , resource.path, domain=domain, raw_body=True, stream=True).perform() return respo...
Returns the results of the specified async job IDs
344,385
def hwvtep_add_ve_interface(self, **kwargs): name = kwargs.pop() ve_id = kwargs.pop() vrrp_id = kwargs.pop() ve_args = dict(name=name, ve_id=ve_id) method_name = method_class = self._brocade_tunnels ve_attr = getattr(method_class, method_name) co...
Add virtual ethernet (ve) interface to the overlay-gateway Args: name (str): gateway-name int_id (int): ve id vrrp_id (int): VRPP-E group ID callback (function): A function executed upon completion of the ...
344,386
def _get_edge_sentences( G: AnalysisGraph, source: str, target: str ) -> List[str]: return chain.from_iterable( [ [repr(e.text) for e in s.evidence] for s in G.edges[source, target]["InfluenceStatements"] ] )
Return the sentences that led to the construction of a specified edge. Args: G source: The source of the edge. target: The target of the edge.
344,387
def has_child_logs(self, log_id): if self._catalog_session is not None: return self._catalog_session.has_child_catalogs(catalog_id=log_id) return self._hierarchy_session.has_children(id_=log_id)
Tests if a log has any children. arg: log_id (osid.id.Id): the ``Id`` of a log return: (boolean) - ``true`` if the ``log_id`` has children, ``false`` otherwise raise: NotFound - ``log_id`` is not found raise: NullArgument - ``log_id`` is ``null`` raise: Ope...
344,388
def validate(data): try: return Schema(Validator.SCHEMA).validate(data) except SchemaError as exception: logging.getLogger(__name__).error(exception) return None
Validate data against the schema. Args: data(dict): data structure to validate. Returns: dict: data as provided and defaults where defined in schema.
344,389
def wavenumber(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval): r PTM, PTE = greenfct(zsrc, zrec, lsrc, lrec, depth, etaH, etaV, zetaH, zetaV, lambd, ab, xdirect, msrc, mrec, use_ne_eval) PJ0 ...
r"""Calculate wavenumber domain solution. Return the wavenumber domain solutions ``PJ0``, ``PJ1``, and ``PJ0b``, which have to be transformed with a Hankel transform to the frequency domain. ``PJ0``/``PJ0b`` and ``PJ1`` have to be transformed with Bessel functions of order 0 (:math:`J_0`) and 1 (:math:...
344,390
def measure_int_put(self, measure, value): if value < 0: logger.warning("Cannot record negative values") self._measurement_map[measure] = value
associates the measure of type Int with the given value
344,391
def write(cls, fname, vertices, faces, normals, texcoords, name=, reshape_faces=True): fmt = op.splitext(fname)[1].lower() if fmt not in (, ): raise ValueError( % (fmt,)) opener = open if fmt == else gzip_open f = ...
This classmethod is the entry point for writing mesh data to OBJ. Parameters ---------- fname : string The filename to write to. Must end with ".obj" or ".gz". vertices : numpy array The vertex data faces : numpy array The face data te...
344,392
def load_werkzeug(path): sys.path[0] = path wz.__dict__.clear() for key in sys.modules.keys(): if key.startswith("werkzeug.") or key == "werkzeug": sys.modules.pop(key, None) import werkzeug for key in werkzeug.__all__: setattr(wz, key, getattr(werkzeug,...
Load werkzeug.
344,393
def setitem(self, indexer, value): if value is None: if self.is_numeric: value = np.nan values = self.values try: values, value = self._try_coerce_args(values, value) if hasattr(value, ) and is_dtype_equ...
Set the value inplace, returning a a maybe different typed block. Parameters ---------- indexer : tuple, list-like, array-like, slice The subset of self.values to set value : object The value being set Returns ------- Block Notes...
344,394
def _add_state_callback(self, state_id, state): summary = self.summarize(state) if summary is None: return with self.locked_context(, dict) as ctx: ctx[state_id] = summary
Save summarize(state) on policy shared context before the state is stored
344,395
def reshape(self, dims): adims = numpy.array(dims, ndmin=1, dtype=) self._FITS.reshape_image(self._ext+1, adims)
reshape an existing image to the requested dimensions parameters ---------- dims: sequence Any sequence convertible to i8
344,396
def UTF8Strsub(utf, start, len): ret = libxml2mod.xmlUTF8Strsub(utf, start, len) return ret
Create a substring from a given UTF-8 string Note: positions are given in units of UTF-8 chars
344,397
def unzip(self): logger.info() with zipfile.ZipFile(self.zip_path, ) as zipped_archive: data_file = zipped_archive.namelist()[0] zipped_archive.extract(data_file, self.extract_path)
Unzip the archive.
344,398
def _get_user_processes(): uid = os.getuid() for proc in psutil.process_iter(): try: if proc.uids.real == uid: yield (proc, proc.exe) except psutil.AccessDenied: try: path = common.which(proc.name) ...
Gets process information owned by the current user. Returns generator of tuples: (``psutil.Process`` instance, path).
344,399
def section(self, dept, course_number, sect_number): section_id = dept + course_number + sect_number sections = self.search({: section_id}) try: return next(sections) except StopIteration: raise ValueError( % section_id)
Return a single section object for the given section. All arguments should be strings. Throws a `ValueError` if the section is not found. >>> lgst101_bfs = r.course('lgst', '101', '301')