Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
349,900
def polyder(c, m=1, scl=1, axis=0): s version because this was faster to implement. ' c = list(c) cnt = int(m) if cnt == 0: return c n = len(c) if cnt >= n: c = c[:1]*0 else: for i in range(cnt): n = n - 1 c *= scl der = [0.0 ...
not quite a copy of numpy's version because this was faster to implement.
349,901
def display_slitlet_arrangement(fileobj, grism=None, spfilter=None, bbox=None, adjust=None, geometry=None, debugplot=0): ...
Display slitlet arrangment from CSUP keywords in FITS header. Parameters ---------- fileobj : file object FITS or TXT file object. grism : str Grism. grism : str Filter. bbox : tuple of 4 floats If not None, values for xmin, xmax, ymin and ymax. adjust : bool...
349,902
def next(self): next_file = super(GridOutCursor, self).next() return GridOut(self.__root_collection, file_document=next_file, session=self.session)
Get next GridOut object from cursor.
349,903
def add_component(self, symlink_comp): if not self._initialized: raise pycdlibexception.PyCdlibInternalError() if (self.current_length() + RRSLRecord.Component.length(symlink_comp)) > 255: raise pycdlibexception.PyCdlibInvalidInput() self.symlink_compo...
Add a new component to this symlink record. Parameters: symlink_comp - The string to add to this symlink record. Returns: Nothing.
349,904
def get_window_position(self, windowHandle=): if self.w3c: if windowHandle != : warnings.warn("Only window is supported for W3C compatibile browsers.") position = self.get_window_rect() else: position = self.execute(Command.GET_WINDOW_POSITIO...
Gets the x,y position of the current window. :Usage: :: driver.get_window_position()
349,905
def fill_noncontinous_variables(self, samples): init_points_count = samples.shape[0] for (idx, var) in enumerate(self.space.space_expanded): if isinstance(var, DiscreteVariable) or isinstance(var, CategoricalVariable) : sample_var = np.atleast_2d(np.random.choice(va...
Fill sample values to non-continuous variables in place
349,906
def getShape3D(self, includeJunctions=False): if includeJunctions and not self._edge.isSpecial(): if self._shapeWithJunctions3D is None: self._shapeWithJunctions3D = addJunctionPos(self._shape3D, self._edge.getFrom...
Returns the shape of the lane in 3d. This function returns the shape of the lane, as defined in the net.xml file. The returned shape is a list containing numerical 3-tuples representing the x,y,z coordinates of the shape points where z defaults to zero. For includeJunction=True...
349,907
def get_requirements(*args): requirements = set() with open(get_absolute_path(*args)) as handle: for line in handle: line = re.sub(r, , line) if line and not line.isspace(): requirements.add(re.sub(r, , line)) return sorted(requi...
Get requirements from pip requirement files.
349,908
def wrapped_resource(response): response_content = response.content.decode(response.encoding or ) try: content = json.loads(response_content) except ValueError: content = response_content if isinstance(content, list): result = ResourceList(content) else: ...
Return a response wrapped in the appropriate wrapper type. Lists will be returned as a ```ResourceList``` instance, dicts will be returned as a ```Resource``` instance.
349,909
def register_view(self, view): self.setup_columns() tv = self.view[] sel = tv.get_selection() sel.connect(, self.on_selection_changed) return
Creates treeview columns, and connect missing signals
349,910
def to_bytes(self): return struct.pack(Ethernet._PACKFMT, self._dst.packed, self._src.packed, self._ethertype.value)
Return packed byte representation of the Ethernet header.
349,911
def embed_version(basepath, ref=): import io, zipfile, importlib try: from urllib.request import urlopen except: from urllib import urlopen try: url = response = urlopen(url.format(ref=ref)) zf = zipfile.ZipFile(io.BytesIO(response.read())) ref = ref[1:] if ref.s...
Autover is purely a build time dependency in all cases (conda and pip) except for when you use pip's remote git support [git+url] as 1) you need a dynamically changing version and 2) the environment starts off clean with zero dependencies installed. This function acts as a fallback to make Version avail...
349,912
def load_from_JSON(json_filename): try: jsonfilecontent = json.loads(open(json_filename, ).read()) except ValueError as exc: raise CredentialsFormatError(msg="Invalid JSON syntax: "+str(exc)) instance = PIDClientCredentials(credentials_filename=json_filename,**js...
Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json { "handle_s...
349,913
def assignee(self, assignee_id, action=): if not self.can_update(): self._tcex.handle_error(910, [self.type]) return self.tc_requests.assignee( self.api_type, self.api_sub_type, self.unique_id, assignee_id, action=action )
Adds a assignee to the task Args: assignee_id: The id of the assignee to be added action:
349,914
def form_uri(item_content, item_class): extension = None if in item_content: extension = MIME_TYPE_TO_EXTENSION[item_content[]] out = URIS.get(item_class) if out: out = out.format(extension=extension, **item_content) return out
Form the URI for a music service element. :param item_content: The content dict of the item :type item_content: dict :param item_class: The class of the item :type item_class: Sub-class of :py:class:`soco.data_structures.MusicServiceItem`
349,915
def check_arrays_survival(X, y, **kwargs): event, time = check_y_survival(y) kwargs.setdefault("dtype", numpy.float64) X = check_array(X, ensure_min_samples=2, **kwargs) check_consistent_length(X, event, time) return X, event, time
Check that all arrays have consistent first dimensions. Parameters ---------- X : array-like Data matrix containing feature vectors. y : structured array with two fields A structured array containing the binary event indicator as first field, and time of event or time of censor...
349,916
def is_templatetags_module_valid_constant(node): if node.name not in (, ): return False parent = node.parent while not isinstance(parent, Module): parent = parent.parent if "templatetags." not in parent.name: return False return True
Suppress warnings for valid constants in templatetags module.
349,917
def key_press_event(self, event): input_buffer = self._get_input_buffer() ctrl = int(event.modifiers() & QtCore.Qt.ControlModifier) != 0 shift = int(event.modifiers() & QtCore.Qt.ShiftModifier) != 0 delete = event.key() in [QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete] ...
Manages our own buffer and send it to the subprocess when user pressed RETURN.
349,918
def get_class_that_defined_method(meth): if inspect.ismethod(meth): for cls in inspect.getmro(meth.__self__.__class__): if cls.__dict__.get(meth.__name__) is meth: return cls meth = meth.__func__ if inspect.isfunction(meth): cls = getattr( i...
Gets the class object which defined a given method @meth: a class method -> owner class object
349,919
def user_exists(username): try: pwd.getpwnam(username) user_exists = True except KeyError: user_exists = False return user_exists
Check if a user exists
349,920
def ip_verification_required(func): def wrapper(request, *args, **kwargs): slug = kwargs.get(, "") if not slug: return kickoutt_404("Not found.", content_type="application/json") try: wip = WriteAPIIP.objects.get(slug=slug) ip = get_client_ip(reque...
Put this decorator before your view to check if the function is coming from an IP on file
349,921
def extension(line, cell=None): parser = _commands.CommandParser(prog=, description=) subparser = parser.subcommand(, ) subparser.set_defaults(ext=) parser.set_defaults(func=_extension) return _utils.handle_magic_line(line, cell, parser)
Load an extension. Use %extension --help for more details.
349,922
def euler(dfun, xzero, timerange, timestep): return zip(*list(Euler(dfun, xzero, timerange, timestep)))
Euler method integration. This function wraps the Euler class. :param dfun: derivative function of the system. The differential system arranged as a series of first-order equations: \\dot{X} = dfun(t, x) :param xzero: the initial condition of the system ...
349,923
def configurable(name_or_fn=None, module=None, whitelist=None, blacklist=None): decoration_target = None if callable(name_or_fn): decoration_target = name_or_fn name = None else: name = name_or_fn def perform_decoration(fn_or_cls): return _make_configurable(fn_or_cls, name, module, whitelist...
Decorator to make a function or class configurable. This decorator registers the decorated function/class as configurable, which allows its parameters to be supplied from the global configuration (i.e., set through `bind_parameter` or `parse_config`). The decorated function is associated with a name in the glo...
349,924
def copy(self, deep=False, name=None): if deep: other = deepcopy(self) else: other = copy(self) if hasattr(self, ): other.name = get_default(name, self.name + ) return other
Make a (deep) copy of self. Parameters: deep : bool Make a deep copy. name : str Name of the copy, with default self.name + '_copy'.
349,925
def waitForFocusToMatchCriteria(self, timeout=10, **kwargs): def _matchFocused(retelem, **kwargs): return retelem if retelem._match(**kwargs) else None retelem = None return self._waitFor(timeout, , callback=_matchFocused, ...
Convenience method to wait for focused element to change (to element matching kwargs criteria). Returns: Element or None
349,926
def _get_row_index(self, row: Row) -> int: row_index = -1 for index, table_row in enumerate(self.table_data): if table_row.values == row.values: row_index = index break return row_index
Takes a row and returns its index in the full list of rows. If the row does not occur in the table (which should never happen because this function will only be called with a row that is the result of applying one or more functions on the table rows), the method returns -1.
349,927
def subscribe(config, accounts, region, merge, debug): config = validate.callback(config) subscription = config.get() if subscription is None: log.error("config file: logs subscription missing") sys.exit(1) def converge_destination_policy(client, config): destination_name ...
subscribe accounts log groups to target account log group destination
349,928
def _randomized_roundoff_to_bfloat16(x, noise, cand1, cand2): cand1_f = tf.to_float(cand1) cand2_f = tf.to_float(cand2) step_size = cand2_f - cand1_f fpart = (x - cand1_f) / step_size ret = tf.where(tf.greater(fpart, noise), cand2, cand1) return ret
Round-off x to cand1 or to cand2 in an unbiased way. Cand1 and cand2 are the same shape as x. For every element of x, the corresponding elements of cand1 and cand2 should be the two closest bfloat16 values to x. Order does not matter. cand1 and cand2 must differ from each other. Args: x: A float32 Tens...
349,929
def _check_type_and_load_cert(self, msg, key_type, cert_type): key_types = key_type cert_types = cert_type if isinstance(key_type, string_types): key_types = [key_types] if isinstance(cert_types, string_types): cert_types = [cert_types] ...
Perform message type-checking & optional certificate loading. This includes fast-forwarding cert ``msg`` objects past the nonce, so that the subsequent fields are the key numbers; thus the caller may expect to treat the message as key material afterwards either way. The obtained key ty...
349,930
def query( self ): if ( self.childCount() ): q = Q() operator = for i in range(self.childCount()): item = self.child(i) if ( isinstance(item, XQueryItem) ): if ( operator == ): ...
Returns the query for this item by joining together its children, or building its data. :return <Query> || <QueryCompound>
349,931
def modify(self, func): 2 def modifier(state): return self._optic.over(state, func) return modifier
Apply a function to the focus. >>> from lenses import lens >>> convert_item_one_to_string = lens[1].modify(str) >>> convert_item_one_to_string([1, 2, 3]) [1, '2', 3] >>> add_ten_to_item_one = lens[1].modify(lambda n: n + 10) >>> add_ten_to_item_on...
349,932
def getEconomyData(self,Economy): self.T_sim = Economy.act_T self.kInit = Economy.kSS self.aNrmInitMean = np.log(0.00000001) self.Mgrid = Economy.MSS*self.MgridBase self.AFunc = Economy.AFun...
Imports economy-determined objects into self from a Market. Instances of AggShockConsumerType "live" in some macroeconomy that has attributes relevant to their microeconomic model, like the relationship between the capital-to-labor ratio and the interest and wage rates; this method impor...
349,933
def create_pretraining_model(nlp, tok2vec): output_size = nlp.vocab.vectors.data.shape[1] output_layer = chain( LN(Maxout(300, pieces=3)), Affine(output_size, drop_factor=0.0) ) tok2vec = chain(tok2vec, flatten) model = chain(tok2vec, output_layer) model = masked...
Define a network for the pretraining. We simply add an output layer onto the tok2vec input model. The tok2vec input model needs to be a model that takes a batch of Doc objects (as a list), and returns a list of arrays. Each array in the output needs to have one row per token in the doc.
349,934
def add_rect(self, width, height, rid=None): assert(width > 0 and height >0) rect, _ = self._select_position(width, height) if not rect: return None self._split(rect) self._remove_duplicates() ...
Add rectangle of widthxheight dimensions. Arguments: width (int, float): Rectangle width height (int, float): Rectangle height rid: Optional rectangle user id Returns: Rectangle: Rectangle with placemente coordinates None: If the rectangle co...
349,935
def create(self, project, name, **attrs): attrs.update( { : project, : name } ) return self._new_resource(payload=attrs)
Create a new :class:`CustomAttribute`. :param project: :class:`Project` id :param name: name of the custom attribute :param attrs: optional attributes of the custom attributes
349,936
def make_application(debug=None, apps_dir=, project_dir=None, include_apps=None, debug_console=True, settings_file=None, local_settings_file=None, start=True, default_settings=None, dispatcher_cls=None, dispatcher_kwargs=None, debug_cls=None, debug_kwargs=None, reuse=True, verbose=False, pythonpath=...
Make an application object
349,937
def send_message(self, index, message="Hello from python-ecobee!"): body = {"selection": { "selectionType": "thermostats", "selectionMatch": self.thermostats[index][]}, "functions": [{"type": "sendMessage", "params": { "text": ...
Send a message to the thermostat
349,938
def write_i2c_block_data(self, address, register, value): return self.smbus.write_i2c_block_data(address, register, value)
I2C block transactions do not limit the number of bytes transferred but the SMBus layer places a limit of 32 bytes. I2C Block Write: i2c_smbus_write_i2c_block_data() ================================================== The opposite of the Block Read command, this writes bytes to ...
349,939
def analyse_text(text): result = 0.0 lines = text.split() if len(lines) > 0: if JclLexer._JOB_HEADER_PATTERN.match(lines[0]): result = 1.0 assert 0.0 <= result <= 1.0 return result
Recognize JCL job by header.
349,940
def dski02(handle, dladsc, item, start, room): handle = ctypes.c_int(handle) item = ctypes.c_int(item) start = ctypes.c_int(start) room = ctypes.c_int(room) n = ctypes.c_int() values = stypes.emptyIntVector(room) libspice.dski02_c(handle, dladsc, item, start, room, ctypes.byref(n), valu...
Fetch integer data from a type 2 DSK segment. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dski02_c.html :param handle: DSK file handle. :type handle: int :param dladsc: DLA descriptor. :type dladsc: spiceypy.utils.support_types.SpiceDLADescr :param item: Keyword identifying item t...
349,941
def find_resource_ids(self): all_resources = self.client.get_resources(restApiId=self.api_id) parent_id = None resource_id = None for resource in all_resources[]: if resource[] == "/": parent_id = resource[] if resource[] == self.trigger_s...
Given a resource path and API Id, find resource Id.
349,942
def list(cls, session, mailbox): endpoint = % mailbox.id return super(Conversations, cls).list(session, endpoint)
Return conversations in a mailbox. Args: session (requests.sessions.Session): Authenticated session. mailbox (helpscout.models.Mailbox): Mailbox to list. Returns: RequestPaginator(output_type=helpscout.models.Conversation): Conversations iterator.
349,943
def remove_external_tracker(self, ids=None, ext_type_id=None, ext_type_description=None, ext_type_url=None, ext_bz_bug_id=None, bug_ids=None): params = {} if ids is not None: params[] = self._listify(ids) if ext...
Wrapper method to allow removal of external tracking bugs using the ExternalBugs::WebService::remove_external_bug method. This is documented at https://bugzilla.redhat.com/docs/en/html/api/extensions/ExternalBugs/lib/WebService.html#remove_external_bug ids: A single external tracker bu...
349,944
def p_width(self, p): p[0] = Width(p[2], p[4], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
width : LBRACKET expression COLON expression RBRACKET
349,945
def apply(self, q, bindings, drilldowns): info = [] for drilldown in self.parse(drilldowns): for attribute in self.cube.model.match(drilldown): info.append(attribute.ref) table, column = attribute.bind(self.cube) bindings.append(Bindin...
Apply a set of grouping criteria and project them.
349,946
def help_center_user_subscriptions(self, user_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/subscriptions api_path = "/api/v2/help_center/users/{user_id}/subscriptions.json" api_path = api_path.format(user_id=user_id) return self.call(api_path, **kwargs)
https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#list-subscriptions-by-user
349,947
def generate_handler(): logger.debug("[ client = boto3.client("iam", region_name=PRIMARY_REGION) try: response = client.create_user( UserName=BLOCKADE_USER ) except client.exceptions.EntityAlreadyExistsException: logger.debug("[!] Blockade user already exis...
Create the Blockade user and give them permissions.
349,948
def clean_uri(self): if self.instance.fixed: return self.instance.uri uri = self.cleaned_data[] return uri
Validates the URI
349,949
def set_initial_representations(self): self.standard_settings() cmd.set(, 0) cmd.set(, 0) cmd.set(, ) cmd.clip(, -1000) cmd.clip(, 1000)
General settings for PyMOL
349,950
def get(content, keep_order=False): if keep_order: from collections import OrderedDict dataentry = OrderedDict() else: dataentry = {} found = False for line in content.split(): if line.strip().startswith(): found =...
Get dataentry from *content*. *keep_order* indicates whether to return an ordered dictionnay.
349,951
def _get_cookies_as_dict(): config = ConfigParser.SafeConfigParser() config.read(_config) if config.has_section(): cookie_dict = {} for option in config.options(): option_key = option.upper() if option == else option cookie_dict[option_key] = config.get(, optio...
Get cookies as a dict
349,952
def safe_walk(top, topdown=True, onerror=None, followlinks=True, _seen=None): if _seen is None: _seen = set() try: names = os.listdir(top) except os.error as err: if onerror is not None: onerror(err) return if ...
A clone of the python os.walk function with some checks for recursive symlinks. Unlike os.walk this follows symlinks by default.
349,953
def context_export(zap_helper, name, file_path): with zap_error_handler(): result = zap_helper.zap.context.export_context(name, file_path) if result != : raise ZAPError(.format(result)) console.info(.format(name, file_path))
Export a given context to a file.
349,954
def convert(self, lat, lon, source, dest, height=0, datetime=None, precision=1e-10, ssheight=50*6371): if datetime is None and ( in [source, dest]): raise ValueError() lat = helpers.checklat(lat) if source == dest: return lat, lon ...
Converts between geodetic, modified apex, quasi-dipole and MLT. Parameters ========== lat : array_like Latitude lon : array_like Longitude/MLT source : {'geo', 'apex', 'qd', 'mlt'} Input coordinate system dest : {'geo', 'apex', 'qd', '...
349,955
def zero_to_one(table, option): if option == : m = min(min(table)) ma = max(max(table)) t = [] for row in table: t_row = [] if option != : m, ma = min(row), max(row) for i in row: if ma == m: t_row.append(0) els...
normalize from zero to one for row or table
349,956
def index_row(self, dataframe): return dataframe.loc[self.kwargs[self.lookup_url_kwarg]].to_frame().T
Indexes the row based on the request parameters.
349,957
def mimetype(self): ct = self.headers.get("content-type") if ct: return ct.split(";")[0].strip()
The mimetype (content type without charset etc.)
349,958
def position_half_h(pslit, cpix, backw=4): next_peak = simple_prot(pslit, cpix) if next_peak is None: raise ValueError dis_peak = next_peak - cpix wpos2 = cpix - dis_peak wpos1 = wpos2 - backw left_background = pslit[wpos1:wpos2].min() height = psl...
Find the position where the value is half of the peak
349,959
def callproc(self, name, params, param_types=None): if param_types: placeholders = [self.sql_writer.typecast(self.sql_writer.to_placeholder(), t) for t in param_types] else: placeholders = [self.sql_writer.to_placeholder() for p in params] qs = "select * from {0...
Calls a procedure. :param name: the name of the procedure :param params: a list or tuple of parameters to pass to the procedure. :param param_types: a list or tuple of type names. If given, each param will be cast via sql_writers typecast method. This is useful to disambiguate proce...
349,960
def check_and_set_unreachability(self, hosts, services): parent_is_down = [] for (dep_id, _, _, _) in self.act_depend_of: if dep_id in hosts: dep = hosts[dep_id] else: dep = services[dep_id] if dep.state in [, , , , , , , ]: ...
Check if all dependencies are down, if yes set this object as unreachable. todo: this function do not care about execution_failure_criteria! :param hosts: hosts objects, used to get object in act_depend_of :type hosts: alignak.objects.host.Hosts :param services: services object...
349,961
def proximal(self): if self.quadratic_coeff < 0: raise TypeError( .format(self.quadratic_coeff)) return proximal_quadratic_perturbation( self.functional.proximal, a=self.quadratic_coeff, u=self.linear_term)
Proximal factory of the quadratically perturbed functional.
349,962
def select_cable(network, level, apparent_power): cable_count = 1 if level == : available_cables = network.equipment_data[][ network.equipment_data[][] == network.mv_grid.voltage_nom] suitable_cables = available_cables[ available_cables[] * ...
Selects an appropriate cable type and quantity using given apparent power. Considers load factor. Parameters ---------- network : :class:`~.grid.network.Network` The eDisGo container object level : :obj:`str` Grid level ('mv' or 'lv') apparent_power : :obj:`float` A...
349,963
def nearest_neighbor_threshold(self, vectors, threshold=.5, batch_size=100, show_progressbar=False, return_names=True): vectors ...
Find the nearest neighbors to some arbitrary vector. This function is meant to be used in composition operations. The most_similar function can only handle items that are in vocab, and looks up their vector through a dictionary. Compositions, e.g. "King - man + woman" are necessarily no...
349,964
async def reset(self, force=False): log.debug() for app in self.applications.values(): await app.destroy() for machine in self.machines.values(): await machine.destroy(force=force) await self.block_until( lambda: len(self.machines) == 0 ...
Reset the model to a clean state. :param bool force: Force-terminate machines. This returns only after the model has reached a clean state. "Clean" means no applications or machines exist in the model.
349,965
def device_at_index(self, index): if index >= len(self.__xid_cons): raise ValueError("Invalid device index") return self.__xid_cons[index]
Returns the device at the specified index
349,966
def stop(self): if self._already_running(): return self.reliable_kill() else: message = sys.stderr.write(message) return 0
Stop the daemon
349,967
def send_error_message(sender, error_message): dispatcher.send( signal=ERROR_MESSAGE_SIGNAL, sender=sender, message=error_message)
Send an error message to the listeners. Error messages represents and error. It usually replace the previous message since an error has been happened. .. versionadded:: 3.3 :param sender: The sender. :type sender: object :param error_message: An instance of our rich error message class. ...
349,968
def _validate_type(self, name, obj, *args): if obj is None: return for arg in args: if isinstance(obj, arg): return raise TypeError(self.__class__.__name__ + + name + + type(obj).__name__ + + str(args))
Helper function that checks the input object type against each in a list of classes. This function also allows the input value to be equal to None. :param name: Name of the object. :param obj: Object to check the type of. :param args: List of classes. :raises TypeError: if the i...
349,969
def hide(self, thing_id, _unhide=False): if isinstance(thing_id, six.string_types): thing_id = [thing_id] else: thing_id = list(thing_id) if len(thing_id) == 0: raise ValueError() return_list ...
Hide one or multiple objects in the context of the logged in user. :param thing_id: A single fullname or list of fullnames, representing objects which will be hidden. :param _unhide: If True, unhide the object(s) instead. Use :meth:`~praw.__init__.ReportMixin.unhide` rather than...
349,970
def get_ZPE(viblist): if type(viblist) is str: l = ast.literal_eval(viblist) else: l = viblist l = [float(w) for w in l] ZPE = 0.5*sum(l)*cm2ev return(ZPE)
Returns the zero point energy from a list of frequencies. Parameters ---------- viblist : List of numbers or string of list of numbers. Returns ------- ZPE : Zero point energy in eV.
349,971
def resize_pbc_for_lipids(pbc, relL, relU, absL, absU, uparea, area, hole, proteins): if any(relL) and any(relU): if 0 in (pbc.x, pbc.y, pbc.z): raise PBCException() elif any(absL) or any(absU): ...
Adapt the size of the box to accomodate the lipids. The PBC is changed **in place**.
349,972
def decimate_max(self, a, maxpoints, **kwargs): return self._decimate(numkit.timeseries.max_histogrammed_function, a, maxpoints, **kwargs)
Return data *a* max-decimated on *maxpoints*. Histograms each column into *maxpoints* bins and calculates the maximum in each bin as the decimated data, using :func:`numkit.timeseries.max_histogrammed_function`. The coarse grained time in the first column contains the centers of the his...
349,973
def append_item(self, item): did_remove = self.remove_exit() item.menu = self self.items.append(item) if did_remove: self.add_exit() if self.screen: max_row, max_cols = self.screen.getmaxyx() if max_row < 6 + len(self.items): ...
Add an item to the end of the menu before the exit item :param MenuItem item: The item to be added
349,974
def _cached_results(self, start_time, end_time): cached_buckets = self._bucket_events( self._client.get(self._scratch_stream, start_time, end_time, namespace=self._scratch_namespace)) for bucket_events in cached_buckets: if len(bucket_events) == 1: f...
Retrieves cached results for any bucket that has a single cache entry. If a bucket has two cache entries, there is a chance that two different writers previously computed and cached a result since Kronos has no transaction semantics. While it might be safe to return one of the cached results if there ...
349,975
def disconnect_relationship(cls, id, related_collection_name, request_json): try: this_resource = cls.nodes.get(id=id, active=True) related_collection = getattr(this_resource, related_collection_name) rsrc_identifier_list = request_json[] if not isinstanc...
Disconnect one or more relationship in a collection with cardinality 'Many'. :param id: The 'id' field of the node on the left side of the relationship in the database. The id field must \ be set in the model -- it is not the same as the node id :param related_collection_name: The name of the ...
349,976
def get_preferred_credentials(api_key, site, cred_file=DEFAULT_CITRINATION_CREDENTIALS_FILE): profile_api_key, profile_site = get_credentials_from_file(cred_file) if api_key is None: api_key = os.environ.get(citr_env_vars.CITRINATION_API_KEY) if api_key is None or len(api_key) == 0: ap...
Given an API key, a site url and a credentials file path, runs through a prioritized list of credential sources to find credentials. Specifically, this method ranks credential priority as follows: 1. Those passed in as the first two parameters to this method 2. Those found in the environment as var...
349,977
def fft_shift(in1): ker = SourceModule(, keep=True) fft_shift_ker = ker.get_function("fft_shift_ker") fft_shift_ker(in1, block=(32,32,1), grid=(int(in1.shape[1]//32), int(in1.shape[0]//32))) return in1
This function performs the FFT shift operation on the GPU to restore the correct output shape. INPUTS: in1 (no default): Array containing data which has been FFTed and IFFTed. OUTPUTS: in1 FFT-shifted version of in1.
349,978
def _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax): if not categorical: binning = _mapclassify_choro(hue, scheme, k=k) values = binning.yb binedges = [binning.yb.min()] + binning.bins.tolist() categories = [.format(binedges[i], binedges[i + 1]) ...
Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we assume that the input data is categorical. This code makes extensive use of ``geopand...
349,979
def less(a, b, *args): types = set([type(a), type(b)]) if float in types or int in types: try: a, b = float(a), float(b) except TypeError: return False return a < b and (not args or less(b, *args))
Implements the '<' operator with JS-style type coertion.
349,980
def get_headers_in_order(self): res = list() for bucket in sorted(self.headers_in_order): for idx, k in self.headers_in_order[bucket]: res.append( (idx, k, self.headers[idx][k]) ) return res
Gets the headers in the order they want to be displayed. Returns a list of triplets: (idx, key, header_info)
349,981
def get_column_names(self, X): if isinstance(X, pd.DataFrame): return X.columns return range(X.shape[1])
Return iterable containing columns for the given array X. Args: X: `numpy.ndarray` or `pandas.DataFrame`. Returns: iterable: columns for the given matrix.
349,982
def findAll(self, tag_name, params=None, fn=None, case_sensitive=False): output = [] if self.isAlmostEqual(tag_name, params, fn, case_sensitive): output.append(self) tmp = [] for el in self.childs: tmp = el.findAll(tag_name, params, fn, case_sensitive) ...
Search for elements by their parameters using `Depth-first algorithm <http://en.wikipedia.org/wiki/Depth-first_search>`_. Args: tag_name (str): Name of the tag you are looking for. Set to "" if you wish to use only `fn` parameter. params (dict, defaul...
349,983
def set_group_add_request(self, *, flag, type, approve=True, reason=None): return super().__getattr__() \ (flag=flag, type=type, approve=approve, reason=reason)
处理加群请求、群组成员邀请 ------------ :param str flag: 加群请求的 flag(需从上报的数据中获得) :param str type: `add` 或 `invite`,请求类型(需要和上报消息中的 `sub_type` 字段相符) :param bool approve: 是否同意请求/邀请 :param str reason: 拒绝理由(仅在拒绝时有效) :return: None :rtype: None
349,984
def xor(left, right): maxlength = max(map(len, (left, right))) ileft = string_to_int(rpad(left, maxlength)) iright = string_to_int(rpad(right, maxlength)) xored = ileft ^ iright return int_to_string(xored)
xor 2 strings. They can be shorter than each other, in which case the shortest will be padded with null bytes at its right. :param left: a string to be the left side of the xor :param right: a string to be the left side of the xor
349,985
def do_edit(self, arg, arguments): def _create_file(filename): if not os.path.exists(filename): file(filename, ).close() def _edit(prefix, editors, filename): for editor in editors: if os.path.exists(editor): _create_...
:: Usage: edit FILENAME Edits the file with the given name Arguments: FILENAME the file to edit
349,986
def split_path(path): parts = [] path, tail = os.path.split(path) while path and tail: parts.append(tail) path, tail = os.path.split(path) parts.append(os.path.join(path, tail)) return map(os.path.normpath, parts)[::-1]
"/tmp/test" Becomes: ("/", "tmp", "test")
349,987
def execute(self, sql, *args, **kwargs): try: self.cursor.execute(sql, *args) except self.sqlite3.InterfaceError, msg: raise self.sqlite3.InterfaceError(unicode(msg) + ) rows = self.cursor.fetchall() self.__commit_if_necessary(kwargs) if None == self.cursor.description: retu...
Run raw SQL on the database, and receive relaxing output. This is sort of the foundational method that most of the others build on.
349,988
def get_tok(self, source): if isinstance(source, str): return source if isinstance(source, CatalogEntry): return source._metadata.get(, source._tok) if isinstance(source, DataSource): return source.metadata.get(, source._tok) raise IndexErro...
Get string token from object Strings are assumed to already be a token; if source or entry, see if it is a persisted thing ("original_tok" is in its metadata), else generate its own token.
349,989
def _wsdl2dispatch(options, wsdl): kw = dict() if options.twisted: from pyremotevbox.ZSI.twisted.WSresource import WSResource kw[] = WSResource ss = ServiceDescription(**kw) if options.address is True: raise RuntimeError, else: if options.ad...
TOOD: Remove ServiceContainer stuff, and replace with WSGI.
349,990
def import_file(self, path, **kwargs): from . import Manifest from . import DatasetImport if not in self or not self[]: raise Exception( ) manifest = Manifest() manifest.add(path) return DatasetImpo...
This is a shortcut to creating a DatasetImport. Can't use "import()" because of Python.
349,991
def random_sequences(length_from, length_to, vocab_lower, vocab_upper, batch_size): if length_from > length_to: raise ValueError() def random_length(): if length_from == length_to: return length_from return np.random.randint...
Generates batches of random integer sequences, sequence length in [length_from, length_to], vocabulary in [vocab_lower, vocab_upper]
349,992
def with_joined(cls, *paths): options = [joinedload(path) for path in paths] return cls.query.options(*options)
Eagerload for simple cases where we need to just joined load some relations In strings syntax, you can split relations with dot due to this SQLAlchemy feature: https://goo.gl/yM2DLX :type paths: *List[str] | *List[InstrumentedAttribute] Example 1: ...
349,993
def parse_xml(self, fh=None, etree=None, resources=None, capability=None, sitemapindex=None): if (resources is None): resources = ResourceContainer() if (fh is not None): etree = parse(fh) elif (etree is None): raise ValueError("Neit...
Parse XML Sitemap and add to resources object. Reads from fh or etree and adds resources to a resorces object (which must support the add method). Returns the resources object. Also sets self.resources_created to be the number of resources created. We adopt a very lax approach here. Th...
349,994
def get_search_filter_spec(self, begin_entity, property_spec): ss_strings = [, , , , , , , , ] selec...
Build a PropertyFilterSpec capable of full inventory traversal. By specifying all valid traversal specs we are creating a PFS that can recursively select any object under the given entity. :param begin_entity: The place in the MOB to start the search. :type begin_entity: Manage...
349,995
def reply(self, body): return self.author.send_message(body=body, reply_to=self.id)
Reply to this message. This is a convenience method calling User.send_message. See it for more information on usage. Note that both recipient and reply_to are given by using this convenience method. :param body: The body of the message.
349,996
def get_bgcolor(self, index): if index.column() == 0: color = QColor(Qt.lightGray) color.setAlphaF(.05) elif index.column() < 3: color = QColor(Qt.lightGray) color.setAlphaF(.2) else: color = QColor(Qt.lightGray) ...
Background color depending on value
349,997
def add_logging_args(parser: argparse.ArgumentParser, patch: bool = True, erase_args: bool = True) -> None: parser.add_argument("--log-level", default="INFO", choices=logging._nameToLevel, help="Logging verbosity.") parser.add_argument("--log-structured", action...
Add command line flags specific to logging. :param parser: `argparse` parser where to add new flags. :param erase_args: Automatically remove logging-related flags from parsed args. :param patch: Patch parse_args() to automatically setup logging.
349,998
def _node_data(self, properties=None): if properties: data = copy.copy(properties) else: data = copy.copy(self._properties) mapping = { "base_script_file": "startup_script", "startup_config": "startup_config_conten...
Prepare node data to send to the remote controller :param properties: If properties is None use actual property otherwise use the parameter
349,999
def publish(self, topic, data, defer=None, block=True, timeout=None, raise_error=True): result = AsyncResult() conn = self._get_connection(block=block, timeout=timeout) try: self._response_queues[conn].append(result) conn.publish(topic, data, def...
Publish a message to the given topic. :param topic: the topic to publish to :param data: bytestring data to publish :param defer: duration in milliseconds to defer before publishing (requires nsq 0.3.6) :param block: wait for a connection to become available before ...