code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def ko_data(queryset, field_names=None, name=None, safe=False, return_json=False): """ Given a QuerySet, return just the serialized representation based on the knockout_fields as JavaScript. """ try: try: # Get an inital instance of the QS. queryset_instance = query...
Given a QuerySet, return just the serialized representation based on the knockout_fields as JavaScript.
def _matrix_integration(q, h, t): ''' Returns the dp metric for a single horsetail curve at a given value of the epistemic uncertainties''' N = len(q) # correction if CDF has gone out of trapezium range if h[-1] < 0.9: h[-1] = 1.0 W = np.zeros([N, N]) for i in range(N): W[i, i] = ...
Returns the dp metric for a single horsetail curve at a given value of the epistemic uncertainties
def set_lock(key, value=None, expiry_time=60): """Force to set a distribute lock""" from uliweb.utils.common import get_uuid redis = get_redis() value = value or get_uuid() return redis.set(key, value, ex=expiry_time, xx=True)
Force to set a distribute lock
def write_lst(self): """ Dump the variable name lst file :return: succeed flag """ ret = False out = '' system = self.system dae = self.system.dae varname = self.system.varname template = '{:>6g}, {:>25s}, {:>35s}\n' # header lin...
Dump the variable name lst file :return: succeed flag
def get_impls(interfaces): """Get impls from their interfaces.""" if interfaces is None: return None elif isinstance(interfaces, Mapping): return {name: interfaces[name]._impl for name in interfaces} elif isinstance(interfaces, Sequence): return [interfaces._impl for interfaces...
Get impls from their interfaces.
def log_pdf(self, y, mu, weights=None): """ computes the log of the pdf or pmf of the values under the current distribution Parameters ---------- y : array-like of length n target values mu : array-like of length n expected values weights ...
computes the log of the pdf or pmf of the values under the current distribution Parameters ---------- y : array-like of length n target values mu : array-like of length n expected values weights : array-like shape (n,) or None, default: None s...
def get_absolute_url(self, endpoint): """Get absolute for secret link (using https scheme). The endpoint is passed to ``url_for`` with ``token`` and ``extra_data`` as keyword arguments. E.g.:: >>> link.extra_data dict(recid=1) >>> link.get_absolute_url('reco...
Get absolute for secret link (using https scheme). The endpoint is passed to ``url_for`` with ``token`` and ``extra_data`` as keyword arguments. E.g.:: >>> link.extra_data dict(recid=1) >>> link.get_absolute_url('record.metadata') translates into:: ...
def substitute_variables(command, level, name, value, target=None, **kwargs): """Substitute variables in command fragments by values e.g. ${level} => 'warning'.""" rule = kwargs.get('rule', {}) rule_value = rule.get('value', '') if rule else '' substitutes = { '${level}': str(level), '${...
Substitute variables in command fragments by values e.g. ${level} => 'warning'.
def catalog(self): """Primary registered catalog for the wrapped portal type """ if self._catalog is None: logger.debug("SuperModel::catalog: *Fetch catalog*") self._catalog = self.get_catalog_for(self.brain) return self._catalog
Primary registered catalog for the wrapped portal type
def find_previous_siblings(self, *args, **kwargs): """ Like :meth:`find_all`, but searches through :attr:`previous_siblings` """ op = operator.methodcaller('find_previous_siblings', *args, **kwargs) return self._wrap_multi(op)
Like :meth:`find_all`, but searches through :attr:`previous_siblings`
def aggregate_in(Data, On=None, AggFuncDict=None, AggFunc=None, AggList=None, interspersed=True): """ Aggregate a ndarray with structured dtype or recarray and include original data in the result. Take aggregate of data set on specified columns, then add the resulting rows back i...
Aggregate a ndarray with structured dtype or recarray and include original data in the result. Take aggregate of data set on specified columns, then add the resulting rows back into data set to make a composite object containing both original non-aggregate data rows as well as the aggregate rows. ...
def force_type(cls, response, environ=None): """Enforce that the WSGI response is a response object of the current type. Werkzeug will use the :class:`BaseResponse` internally in many situations like the exceptions. If you call :meth:`get_response` on an exception you will get back a r...
Enforce that the WSGI response is a response object of the current type. Werkzeug will use the :class:`BaseResponse` internally in many situations like the exceptions. If you call :meth:`get_response` on an exception you will get back a regular :class:`BaseResponse` object, even if you...
def update_history(self) -> None: """ Update messaging history on disk. :returns: None """ self.log.debug(f"Saving history. History is: \n{self.history}") jsons = [] for item in self.history: json_item = item.__dict__ # Convert sub-entri...
Update messaging history on disk. :returns: None
def create(self, session): """ caches the session and caches an entry to associate the cached session with the subject """ sessionid = super().create(session) # calls _do_create and verify self._cache(session, sessionid) return sessionid
caches the session and caches an entry to associate the cached session with the subject
def trim(self): """ Trim leading and trailing whitespace. @return: self @rtype: L{Element} """ if self.hasText(): self.text = self.text.trim() return self
Trim leading and trailing whitespace. @return: self @rtype: L{Element}
def get_value(self, subsystem, option): """ Read the given value from the given subsystem. Do not include the subsystem name in the option name. Only call this method if the given subsystem is available. """ assert subsystem in self, 'Subsystem {} is missing'.format(subsy...
Read the given value from the given subsystem. Do not include the subsystem name in the option name. Only call this method if the given subsystem is available.
def query_status(self): '''Query the hub for the status of this command''' try: data = self.api_iface._api_get(self.link) self._update_details(data) except APIError as e: print("API error: ") for key,value in e.data.iteritems: print...
Query the hub for the status of this command
def ef_plugin(service_name): """ Decorator for ef plugin classes. Any wrapped classes should contain a run() method which executes the plugin code. Args: service_name (str): The name of the service being extended. Example: @ef_plugin('ef-generate') class NewRelicPlugin(object): def run(self...
Decorator for ef plugin classes. Any wrapped classes should contain a run() method which executes the plugin code. Args: service_name (str): The name of the service being extended. Example: @ef_plugin('ef-generate') class NewRelicPlugin(object): def run(self): exec_code()
def clusters(points, radius): """ Find clusters of points which have neighbours closer than radius Parameters --------- points : (n, d) float Points of dimension d radius : float Max distance between points in a cluster Returns ---------- groups : (m,) sequence of i...
Find clusters of points which have neighbours closer than radius Parameters --------- points : (n, d) float Points of dimension d radius : float Max distance between points in a cluster Returns ---------- groups : (m,) sequence of int Indices of points in a cluster
def czdivide(a, b, null=0): ''' czdivide(a, b) returns the quotient a / b as a numpy array object. Like numpy's divide function or a/b syntax, czdivide will thread over the latest dimension possible. Unlike numpy's divide, czdivide works with sparse matrices. Additionally, czdivide multiplies a by t...
czdivide(a, b) returns the quotient a / b as a numpy array object. Like numpy's divide function or a/b syntax, czdivide will thread over the latest dimension possible. Unlike numpy's divide, czdivide works with sparse matrices. Additionally, czdivide multiplies a by the zinv of b, so divide-by-zero en...
def create_message(self, params={}): """ Creates a message http://dev.wheniwork.com/#create/update-message """ url = "/2/messages/" body = params data = self._post_resource(url, body) return self.message_from_json(data["message"])
Creates a message http://dev.wheniwork.com/#create/update-message
def _manipulate(self, *args, **kwargs): """ This is a semi-private method. It's current use is to manipulate memory file system objects so that you can create certain conditions, to provoke errors that otherwise won't occur. """ self.connection._manipulate(self, *...
This is a semi-private method. It's current use is to manipulate memory file system objects so that you can create certain conditions, to provoke errors that otherwise won't occur.
def create(self, to, from_, parameters=values.unset): """ Create a new ExecutionInstance :param unicode to: The Contact phone number to start a Studio Flow Execution. :param unicode from_: The Twilio phone number to send messages or initiate calls from during the Flow Execution. ...
Create a new ExecutionInstance :param unicode to: The Contact phone number to start a Studio Flow Execution. :param unicode from_: The Twilio phone number to send messages or initiate calls from during the Flow Execution. :param dict parameters: JSON data that will be added to your flow's conte...
def multipointm(self, points): """Creates a MULTIPOINTM shape. Points is a list of xym values. If the m (measure) value is not included, it defaults to None (NoData).""" shapeType = MULTIPOINTM points = [points] # nest the points inside a list to be compatible with the gener...
Creates a MULTIPOINTM shape. Points is a list of xym values. If the m (measure) value is not included, it defaults to None (NoData).
def parse_issues(raw_page): """Parse a JIRA API raw response. The method parses the API response retrieving the issues from the received items :param items: items from where to parse the issues :returns: a generator of issues """ raw_issues = json.loads(raw_pag...
Parse a JIRA API raw response. The method parses the API response retrieving the issues from the received items :param items: items from where to parse the issues :returns: a generator of issues
def main(argv=None): """Run a Tensorflow model on the Iris dataset.""" args = parse_arguments(sys.argv if argv is None else argv) tf.logging.set_verbosity(tf.logging.INFO) learn_runner.run( experiment_fn=get_experiment_fn(args), output_dir=args.job_dir)
Run a Tensorflow model on the Iris dataset.
def underline(self, msg): """Underline the input""" return click.style(msg, underline=True) if self.colorize else msg
Underline the input
def setup_logger(): """Return a logger with a default ColoredFormatter.""" formatter = ColoredFormatter( "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s", datefmt=None, reset=True, log_colors={ 'DEBUG': 'cyan', 'INFO': 'green', ...
Return a logger with a default ColoredFormatter.
def _extract_field_with_regex(self, field): """ extract field from response content with regex. requests.Response body could be json or html text. Args: field (str): regex string that matched r".*\(.*\).*" Returns: str: matched content. Raises: ...
extract field from response content with regex. requests.Response body could be json or html text. Args: field (str): regex string that matched r".*\(.*\).*" Returns: str: matched content. Raises: exceptions.ExtractFailure: If no content matched...
def wrap_targets(self, targets, topological_order=False): """Wrap targets and their computed cache keys in VersionedTargets. If the FingerprintStrategy opted out of providing a fingerprint for a target, that target will not have an associated VersionedTarget returned. Returns a list of VersionedTarget...
Wrap targets and their computed cache keys in VersionedTargets. If the FingerprintStrategy opted out of providing a fingerprint for a target, that target will not have an associated VersionedTarget returned. Returns a list of VersionedTargets, each representing one input target.
def run_actor(self, actor): '''Start running the ``actor``. ''' set_actor(actor) if not actor.mailbox.address: address = ('127.0.0.1', 0) actor._loop.create_task( actor.mailbox.start_serving(address=address) ) actor._loop.run_fo...
Start running the ``actor``.
def add_arg(self, arg): """ Add an argument """ if not isinstance(arg, File): arg = str(arg) self._args += [arg]
Add an argument
def split_from_df(self, col:IntsOrStrs=2): "Split the data from the `col` in the dataframe in `self.inner_df`." valid_idx = np.where(self.inner_df.iloc[:,df_names_to_idx(col, self.inner_df)])[0] return self.split_by_idx(valid_idx)
Split the data from the `col` in the dataframe in `self.inner_df`.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'key') and self.key is not None: _dict['key'] = self.key._to_dict() if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value._to_dict()...
Return a json dictionary representing this model.
def get_detail(self): """ 个人信息,同时会把返回值保存在self.detail中 :return: information of student :rtype: dict """ response = self._post("http://bkjws.sdu.edu.cn/b/grxx/xs/xjxx/detail", data=None) if response['result'] == 'success': s...
个人信息,同时会把返回值保存在self.detail中 :return: information of student :rtype: dict
def lms(args): """ %prog lms ALLMAPS cartoon to illustrate LMS metric. """ from random import randint from jcvi.graphics.chromosome import HorizontalChromosome p = OptionParser(lms.__doc__) opts, args, iopts = p.set_image_options(args, figsize="6x6", dpi=300) fig = plt.figure(1, (...
%prog lms ALLMAPS cartoon to illustrate LMS metric.
def read_cell(self, x, y): """ Reads the cell at position x+1 and y+1; return value :param x: line index :param y: coll index :return: {header: value} """ if isinstance(self.header[y], tuple): header = self.header[y][0] else: header...
Reads the cell at position x+1 and y+1; return value :param x: line index :param y: coll index :return: {header: value}
def get_app_template(name): """ Getter function of templates for each applications. Argument `name` will be interpreted as colon separated, the left value means application name, right value means a template name. get_app_template('blog:dashboarb.mako') It will return a template for dashboard...
Getter function of templates for each applications. Argument `name` will be interpreted as colon separated, the left value means application name, right value means a template name. get_app_template('blog:dashboarb.mako') It will return a template for dashboard page of `blog` application.
def typeseq(types): """ Returns an escape for a terminal text formatting type, or a list of types. Valid types are: * 'i' for 'italic' * 'b' for 'bold' * 'u' for 'underline' * 'r' for 'reverse' """ ret = "" for t in types: ret += termcap.get(fmttypes[t]) ...
Returns an escape for a terminal text formatting type, or a list of types. Valid types are: * 'i' for 'italic' * 'b' for 'bold' * 'u' for 'underline' * 'r' for 'reverse'
def clear_cache(): """Remove all cached objects""" del Cache._keys for k in list(Cache._cache.keys()): it = Cache._cache.pop(k) del it del Cache._cache Cache._keys = [] Cache._cache = {} gc.collect()
Remove all cached objects
def delete_asset(self): """ Delete asset from the release. :rtype: bool """ headers, data = self._requester.requestJsonAndCheck( "DELETE", self.url ) return True
Delete asset from the release. :rtype: bool
def finalize(self): """ finalize simulation for consumer """ # todo sort self.result by path_num if self.result: self.result = sorted(self.result, key=lambda x: x[0]) p, r = map(list, zip(*self.result)) self.result = r
finalize simulation for consumer
def stream_header(self, f): """Stream the block header in the standard way to the file-like object f.""" stream_struct("L##LLL", f, self.version, self.previous_block_hash, self.merkle_root, self.timestamp, self.difficulty, self.nonce)
Stream the block header in the standard way to the file-like object f.
def auth(self, user, pwd): """ Perform a login with the given Skype username and its password. This emulates a login to Skype for Web on ``api.skype.com``. Args: user (str): username of the connecting account pwd (str): password of the connecting account ...
Perform a login with the given Skype username and its password. This emulates a login to Skype for Web on ``api.skype.com``. Args: user (str): username of the connecting account pwd (str): password of the connecting account Returns: (str, datetime.datetime)...
def set_project_pid(project, old_pid, new_pid): """ Project's PID was changed. """ for datastore in _get_datastores(): datastore.save_project(project) datastore.set_project_pid(project, old_pid, new_pid)
Project's PID was changed.
def draw_on_image(self, image, color=(0, 255, 0), alpha=1.0, size=1, copy=True, raise_if_out_of_image=False, thickness=None): """ Draw all bounding boxes onto a given image. Parameters ---------- image : (H,W,3) ndarray The image onto which to d...
Draw all bounding boxes onto a given image. Parameters ---------- image : (H,W,3) ndarray The image onto which to draw the bounding boxes. This image should usually have the same shape as set in BoundingBoxesOnImage.shape. color : int or list of int ...
def zero_disk(self, disk_xml=None): """ Collector and publish not zeroed disk metrics """ troubled_disks = 0 for filer_disk in disk_xml: raid_state = filer_disk.find('raid-state').text if not raid_state == 'spare': continue is_zeroed =...
Collector and publish not zeroed disk metrics
def close(self): """ Stop overwriting display, or update parent. """ if self.parent: self.parent.update(self.parent.offset + self.offset) return self.output.write("\n") self.output.flush()
Stop overwriting display, or update parent.
def get_version(): """ Read version from __init__.py """ version_regex = re.compile( '__version__\\s*=\\s*(?P<q>[\'"])(?P<version>\\d+(\\.\\d+)*(-(alpha|beta|rc)(\\.\\d+)?)?)(?P=q)' ) here = path.abspath(path.dirname(__file__)) init_location = path.join(here, "CHAID/__init__.py") ...
Read version from __init__.py
def get_assets_by_query(self, asset_query=None): """Gets a list of ``Assets`` matching the given asset query. arg: asset_query (osid.repository.AssetQuery): the asset query return: (osid.repository.AssetList) - the returned ``AssetList`` raise: NullArgument - ``asset...
Gets a list of ``Assets`` matching the given asset query. arg: asset_query (osid.repository.AssetQuery): the asset query return: (osid.repository.AssetList) - the returned ``AssetList`` raise: NullArgument - ``asset_query`` is ``null`` raise: OperationFailed - unabl...
def default(self, obj): # pylint: disable=method-hidden """Use the default behavior unless the object to be encoded has a `strftime` attribute.""" if hasattr(obj, 'strftime'): return obj.strftime("%Y-%m-%dT%H:%M:%SZ") elif hasattr(obj, 'get_public_dict'): return...
Use the default behavior unless the object to be encoded has a `strftime` attribute.
def install_service(instance, dbhost, dbname, port): """Install systemd service configuration""" _check_root() log("Installing systemd service") launcher = os.path.realpath(__file__).replace('manage', 'launcher') executable = sys.executable + " " + launcher executable += " --instance " + inst...
Install systemd service configuration
def synchronise_signals(in_signal_1, in_signal_2): """ ----- Brief ----- This function synchronises the input signals using the full cross correlation function between the signals. ----------- Description ----------- Signals acquired with two devices may be dephased. It is possible ...
----- Brief ----- This function synchronises the input signals using the full cross correlation function between the signals. ----------- Description ----------- Signals acquired with two devices may be dephased. It is possible to synchronise the two signals by multiple methods. Here, i...
def _advance_to_next_stage(self, config_ids, losses): """ SuccessiveHalving simply continues the best based on the current loss. """ ranks = np.argsort(np.argsort(losses)) return(ranks < self.num_configs[self.stage])
SuccessiveHalving simply continues the best based on the current loss.
def _parse_incval(incunit, incval): ''' Parse a non-day increment value. Should be an integer or a comma-separated integer list. ''' try: retn = [int(val) for val in incval.split(',')] except ValueError: return None return retn[0] if len(retn) == 1 else retn
Parse a non-day increment value. Should be an integer or a comma-separated integer list.
def change_state(self, item, state): """ Replace the current state of the item. i.e. replace the current state tag but keeps the other tags. :param item: item id :type item: str :param state: "checked", "unchecked" or "tristate": new state of the item :...
Replace the current state of the item. i.e. replace the current state tag but keeps the other tags. :param item: item id :type item: str :param state: "checked", "unchecked" or "tristate": new state of the item :type state: str
def npd_to_pmf(nodal_plane_dist, use_default=False): """ Returns the nodal plane distribution as an instance of the PMF class """ if isinstance(nodal_plane_dist, PMF): # Aready in PMF format - return return nodal_plane_dist else: if use_default: return PMF([(1.0, ...
Returns the nodal plane distribution as an instance of the PMF class
def from_command_line(): """ Run CGI var to gVCF conversion from the command line. """ # Parse options parser = argparse.ArgumentParser( description='Convert Complete Genomics var files to gVCF format.') parser.add_argument( '-d', '--refseqdir', metavar='REFSEQDIR', required=True...
Run CGI var to gVCF conversion from the command line.
def apply_T4(word): # OPTIMIZE '''An agglutination diphthong that ends in /u, y/ usually contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.us], [va.ka.ut.taa].''' WORD = _split_consonants_and_vowels(word) for k, v in WORD.iteritems(): if len(v) == 2 and v.endswith(('u', ...
An agglutination diphthong that ends in /u, y/ usually contains a syllable boundary when -C# or -CCV follow, e.g., [lau.ka.us], [va.ka.ut.taa].
def get_exported(self): """Get a new dict with the exported variables.""" return dict((k, self.vars[k]) for k in self.exported_vars)
Get a new dict with the exported variables.
def process(self, block=True): '''process and display graph''' self.msg_types = set() self.multiplier = [] self.field_types = [] # work out msg types we are interested in self.x = [] self.y = [] self.modes = [] self.axes = [] self.first_on...
process and display graph
def disabledPenColor(self): """ Returns the disabled pen color for this node. :return <QColor> """ palette = self.palette() return palette.color(palette.Disabled, palette.NodeForeground)
Returns the disabled pen color for this node. :return <QColor>
def convert_to_btc_on(self, amount, currency, date_obj): """ Convert X amount to BTC based on given date rate """ if isinstance(amount, Decimal): use_decimal = True else: use_decimal = self._force_decimal start = date_obj.strftime('%Y-%m-%d') ...
Convert X amount to BTC based on given date rate
def get_word_at(self, index: int) -> Union[int, BitVec]: """Access a word from a specified memory index. :param index: integer representing the index to access :return: 32 byte word at the specified index """ try: return symbol_factory.BitVecVal( util...
Access a word from a specified memory index. :param index: integer representing the index to access :return: 32 byte word at the specified index
def port_has_listener(address, port): """ Returns True if the address:port is open and being listened to, else False. @param address: an IP address or hostname @param port: integer port Note calls 'zc' via a subprocess shell """ cmd = ['nc', '-z', address, str(port)] result = subpr...
Returns True if the address:port is open and being listened to, else False. @param address: an IP address or hostname @param port: integer port Note calls 'zc' via a subprocess shell
def service( state, host, *args, **kwargs ): ''' Manage the state of services. This command checks for the presence of all the init systems pyinfra can handle and executes the relevant operation. See init system sepcific operation for arguments. ''' if host.fact.which('systemctl'): ...
Manage the state of services. This command checks for the presence of all the init systems pyinfra can handle and executes the relevant operation. See init system sepcific operation for arguments.
def intword(value, format='%.1f'): """Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. Supports up to decillion (33 digits) and googol (100...
Converts a large integer to a friendly text representation. Works best for numbers over 1 million. For example, 1000000 becomes '1.0 million', 1200000 becomes '1.2 million' and '1200000000' becomes '1.2 billion'. Supports up to decillion (33 digits) and googol (100 digits). You can pass format to change ...
def execute(self, source, splitting_stream, sinks, interval, meta_data_id, output_plate_values): """ Execute the tool over the given time interval. :param source: The source stream :param splitting_stream: The stream over which to split :param sinks: The sink streams :pa...
Execute the tool over the given time interval. :param source: The source stream :param splitting_stream: The stream over which to split :param sinks: The sink streams :param interval: The time interval :param meta_data_id: The meta data id of the output plate :param outp...
def kill_mprocess(process): """kill process Args: process - Popen object for process """ if process and proc_alive(process): process.terminate() process.communicate() return not proc_alive(process)
kill process Args: process - Popen object for process
def get_operator_output_port(self): """Get the output port of this exported stream. Returns: OperatorOutputPort: Output port of this exported stream. """ return OperatorOutputPort(self.rest_client.make_request(self.operatorOutputPort), self.rest_client)
Get the output port of this exported stream. Returns: OperatorOutputPort: Output port of this exported stream.
def pyramid( input_raster, output_dir, pyramid_type=None, output_format=None, resampling_method=None, scale_method=None, zoom=None, bounds=None, overwrite=False, debug=False ): """Create tile pyramid out of input raster.""" bounds = bounds if bounds else None options ...
Create tile pyramid out of input raster.
def _move_end_to_cxn(self, shape, cxn_pt_idx): """ Move the end point of this connector to the coordinates of the connection point of *shape* specified by *cxn_pt_idx*. """ x, y, cx, cy = shape.left, shape.top, shape.width, shape.height self.end_x, self.end_y = { ...
Move the end point of this connector to the coordinates of the connection point of *shape* specified by *cxn_pt_idx*.
def init0(self, dae): """ Set initial voltage and reactive power for PQ. Overwrites Bus.voltage values """ dae.y[self.v] = self.v0 dae.y[self.q] = mul(self.u, self.qg)
Set initial voltage and reactive power for PQ. Overwrites Bus.voltage values
def verify_event_source_current(self, event_uuid, resource_name, service_name, function_arn): # type: (str, str, str, str) -> bool """Check if the uuid matches the resource and function arn provided. Given a uuid representing an event source mapping for a lam...
Check if the uuid matches the resource and function arn provided. Given a uuid representing an event source mapping for a lambda function, verify that the associated source arn and function arn match up to the parameters passed in. Instead of providing the event source arn, the resourc...
def _check_split_list_validity(self): """ See _temporal_split_list above. This function checks if the current split lists are still valid. """ # FIXME: Currently very primitive, but needs to be fast if not (hasattr(self,"_splitListsSet") and (self._splitListsSet)): ...
See _temporal_split_list above. This function checks if the current split lists are still valid.
def json(self): """Get the result of simplejson.loads if possible.""" if 'json' not in self.environ.get('CONTENT_TYPE', ''): raise BadRequest('Not a JSON request') try: return loads(self.data) except Exception: raise BadRequest('Unable to read JSON req...
Get the result of simplejson.loads if possible.
def rec_setattr(obj, attr, value): """Set object's attribute. May use dot notation. >>> class C(object): pass >>> a = C() >>> a.b = C() >>> a.b.c = 4 >>> rec_setattr(a, 'b.c', 2) >>> a.b.c 2 """ attrs = attr.split('.') setattr(reduce(getattr, attrs[:-1], obj), attrs[-1], val...
Set object's attribute. May use dot notation. >>> class C(object): pass >>> a = C() >>> a.b = C() >>> a.b.c = 4 >>> rec_setattr(a, 'b.c', 2) >>> a.b.c 2
def get_volume(self, datacenter_id, volume_id): """ Retrieves a single volume by ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param volume_id: The unique ID of the volume. :type volume_id: ``str`` ...
Retrieves a single volume by ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param volume_id: The unique ID of the volume. :type volume_id: ``str``
def get(self, path_segment="", owner=None, app=None, sharing=None, **query): """Performs a GET operation on the path segment relative to this endpoint. This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for ea...
Performs a GET operation on the path segment relative to this endpoint. This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus at most two additional round trips if the `...
def _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True): """Check that wiremap neither fragments nor leaves duplicate registers. 1. There are no fragmented registers. A register in keyregs is fragmented if not all of its (qu)bits are renamed by edge_map. 2. There are...
Check that wiremap neither fragments nor leaves duplicate registers. 1. There are no fragmented registers. A register in keyregs is fragmented if not all of its (qu)bits are renamed by edge_map. 2. There are no duplicate registers. A register is duplicate if it appears in both self and ...
def info2lists(info, in_place=False): """ Return info with: 1) `packages` dict replaced by a 'packages' list with indexes removed 2) `releases` dict replaced by a 'releases' list with indexes removed info2list(info2dicts(info)) == info """ if 'packages' not in info and 'releases' not in i...
Return info with: 1) `packages` dict replaced by a 'packages' list with indexes removed 2) `releases` dict replaced by a 'releases' list with indexes removed info2list(info2dicts(info)) == info
def send_async( self, queue_identifier: QueueIdentifier, message: Message, ): """Queue the message for sending to recipient in the queue_identifier It may be called before transport is started, to initialize message queues The actual sending is started on...
Queue the message for sending to recipient in the queue_identifier It may be called before transport is started, to initialize message queues The actual sending is started only when the transport is started
def plot_one_day(x, y, xlabel=None, ylabel=None, title=None, ylim=None): """时间跨度为一天。 major tick = every hours minor tick = every 15 minutes """ plt.close("all") fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(x, y) hours = HourLocator(range(24)) ...
时间跨度为一天。 major tick = every hours minor tick = every 15 minutes
def critical_path(self, print_cp=True, cp_limit=100): """ Takes a timing map and returns the critical paths of the system. :param print_cp: Whether to print the critical path to the terminal after calculation :return: a list containing tuples with the 'first' wire as the ...
Takes a timing map and returns the critical paths of the system. :param print_cp: Whether to print the critical path to the terminal after calculation :return: a list containing tuples with the 'first' wire as the first value and the critical paths (which themselves are lists ...
def write_length_and_key(fp, value): """ Helper to write descriptor key. """ written = write_fmt(fp, 'I', 0 if value in _TERMS else len(value)) written += write_bytes(fp, value) return written
Helper to write descriptor key.
def get(self, uuid): """Workaround: missing get entry point""" for token in self.list(): if token.get('uuid') == uuid: return token raise LinShareException(-1, "Can find uuid:" + uuid)
Workaround: missing get entry point
def set(self, option, value): """ Sets an option to a value. """ if self.config is None: self.config = {} self.config[option] = value
Sets an option to a value.
def demo(quiet, shell, speed, prompt, commentecho): """Run a demo doitlive session.""" run( DEMO, shell=shell, speed=speed, test_mode=TESTING, prompt_template=prompt, quiet=quiet, commentecho=commentecho, )
Run a demo doitlive session.
def get_diplomacy(self): """Compute diplomacy.""" if not self._cache['teams']: self.get_teams() player_num = 0 computer_num = 0 for player in self._header.scenario.game_settings.player_info: if player.type == 'human': player_num += 1 ...
Compute diplomacy.
def basic_clean_str(string): """Tokenization/string cleaning for a datasets.""" string = re.sub(r"\n", " ", string) # '\n' --> ' ' string = re.sub(r"\'s", " \'s", string) # it's --> it 's string = re.sub(r"\’s", " \'s", string) string = re.sub(r"\'ve", " have", string) # they've --> t...
Tokenization/string cleaning for a datasets.
def log_to_syslog(): """ Configure logging to syslog. """ # Get root logger rl = logging.getLogger() rl.setLevel('INFO') # Stderr gets critical messages (mostly config/setup issues) # only when not daemonized stderr = logging.StreamHandler(stream=sys.stderr) stderr.setLevel(l...
Configure logging to syslog.
def _recv_ack(self, method_frame): '''Receive an ack from the broker.''' if self._ack_listener: delivery_tag = method_frame.args.read_longlong() multiple = method_frame.args.read_bit() if multiple: while self._last_ack_id < delivery_tag: ...
Receive an ack from the broker.
def allow(self, role, method, resource, with_children=True): """Add allowing rules. :param role: Role of this rule. :param method: Method to allow in rule, include GET, POST, PUT etc. :param resource: Resource also view function. :param with_children: Allow role's children in ru...
Add allowing rules. :param role: Role of this rule. :param method: Method to allow in rule, include GET, POST, PUT etc. :param resource: Resource also view function. :param with_children: Allow role's children in rule as well if with_children is `True`
def to_float(option,value): ''' Converts string values to floats when appropriate ''' if type(value) is str: try: value=float(value) except ValueError: pass return (option,value)
Converts string values to floats when appropriate
def _skip_spaces_and_peek(self): """ Skips all spaces and comments. :return: The first character that follows the skipped spaces and comments or None if the end of the json string has been reached. """ while 1: # skipping spaces self.skip_chars(sel...
Skips all spaces and comments. :return: The first character that follows the skipped spaces and comments or None if the end of the json string has been reached.
def features_properties_null_remove(obj): """ Remove any properties of features in the collection that have entries mapping to a null (i.e., None) value """ features = obj['features'] for i in tqdm(range(len(features))): if 'properties' in features[i]: properties = features[...
Remove any properties of features in the collection that have entries mapping to a null (i.e., None) value
def main(): """ NAME gobing.py DESCRIPTION calculates Bingham parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX gobing.py [options] OPTIONS -f FILE to read from FILE -F, specifies output f...
NAME gobing.py DESCRIPTION calculates Bingham parameters from dec inc data INPUT FORMAT takes dec/inc as first two columns in space delimited file SYNTAX gobing.py [options] OPTIONS -f FILE to read from FILE -F, specifies output file name < filen...
def itemmeta(self): """Returns metadata for members of the collection. Makes a single roundtrip to the server, plus two more at most if the ``autologin`` field of :func:`connect` is set to ``True``. :return: A :class:`splunklib.data.Record` object containing the metadata. **Ex...
Returns metadata for members of the collection. Makes a single roundtrip to the server, plus two more at most if the ``autologin`` field of :func:`connect` is set to ``True``. :return: A :class:`splunklib.data.Record` object containing the metadata. **Example**:: import s...
def _censor_with(x, range, value=None): """ Censor any values outside of range with ``None`` """ return [val if range[0] <= val <= range[1] else value for val in x]
Censor any values outside of range with ``None``
def _check_state_value(cls): """Check initial state value - if is proper and translate it. Initial state is required. """ state_value = cls.context.get_config('initial_state', None) state_value = state_value or getattr( cls.context.new_class, cls.context.state_name, ...
Check initial state value - if is proper and translate it. Initial state is required.