code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def device_id_partition_keygen(request_envelope): # type: (RequestEnvelope) -> str """Retrieve device id from request envelope, to use as partition key. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :return: De...
Retrieve device id from request envelope, to use as partition key. :param request_envelope: Request Envelope passed during skill invocation :type request_envelope: ask_sdk_model.RequestEnvelope :return: Device Id retrieved from request envelope :rtype: str :raises: :py:class:`ask_sdk_core.e...
def read(self, size=1): """ Read byte buffer with specified size from input file. Raise exception in two cases: - File already closed. - Not enough data to read. Keyword arguments: size -- size of buffer to read (default 1) """ if self.is_...
Read byte buffer with specified size from input file. Raise exception in two cases: - File already closed. - Not enough data to read. Keyword arguments: size -- size of buffer to read (default 1)
def compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.'): """compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.') Creates a Python module from a Qt Designer .ui file. uifile is a file na...
compileUi(uifile, pyfile, execute=False, indent=4, from_imports=False, resource_suffix='_rc', import_from='.') Creates a Python module from a Qt Designer .ui file. uifile is a file name or file-like object containing the .ui file. pyfile is the file-like object to which the Python code will be written...
def isActiveDashboardOverlay(self, ulOverlayHandle): """returns true if the dashboard is visible and the specified overlay is the active system Overlay""" fn = self.function_table.isActiveDashboardOverlay result = fn(ulOverlayHandle) return result
returns true if the dashboard is visible and the specified overlay is the active system Overlay
def ParseArguments(self): """Parses the command line arguments. Returns: bool: True if the arguments were successfully parsed. """ loggers.ConfigureLogging() argument_parser = argparse.ArgumentParser( description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False, formatter...
Parses the command line arguments. Returns: bool: True if the arguments were successfully parsed.
def response(credentials, password, request): """Compile digest auth response If the qop directive's value is "auth" or "auth-int" , then compute the response as follows: RESPONSE = MD5(HA1:nonce:nonceCount:clienNonce:qop:HA2) Else if the qop directive is unspecified, then compute the response as fo...
Compile digest auth response If the qop directive's value is "auth" or "auth-int" , then compute the response as follows: RESPONSE = MD5(HA1:nonce:nonceCount:clienNonce:qop:HA2) Else if the qop directive is unspecified, then compute the response as follows: RESPONSE = MD5(HA1:nonce:HA2) Argu...
def open(self): """ Open device. Returns an USBDeviceHandle instance. """ handle = libusb1.libusb_device_handle_p() mayRaiseUSBError(libusb1.libusb_open(self.device_p, byref(handle))) result = USBDeviceHandle(self.__context, handle, self) self.__close_set....
Open device. Returns an USBDeviceHandle instance.
def create_dashboards(resource_root, dashboard_list): """ Creates the list of dashboards. If any of the dashboards already exist this whole command will fail and no dashboards will be created. @since: API v6 @return: The list of dashboards created. """ return call(resource_root.post, DASHBOARDS_PATH, ApiD...
Creates the list of dashboards. If any of the dashboards already exist this whole command will fail and no dashboards will be created. @since: API v6 @return: The list of dashboards created.
def get_active_lineage(): """ Query the lineage of the current timer level. Provides only timer names, not stamp names (as these have not been decided yet!). Returns: str: Formatted sequence of timer names in one string. """ lin_str = '' for active_timer in f.timer_stack: l...
Query the lineage of the current timer level. Provides only timer names, not stamp names (as these have not been decided yet!). Returns: str: Formatted sequence of timer names in one string.
def cythonize(*args, **kwargs): ''' dirty hack, only import cythonize at the time you use it. if you don't write Cython extension, you won't fail even if you don't install Cython. ''' global cythonize from Cython.Build import cythonize return cythonize(*args, **kwargs)
dirty hack, only import cythonize at the time you use it. if you don't write Cython extension, you won't fail even if you don't install Cython.
def fetch(self, category=CATEGORY_EVENT, from_date=DEFAULT_DATETIME, to_date=None, filter_classified=False): """Fetch the events from the server. This method fetches those events of a group stored on the server that were updated since the given date. Data comments and rsvps ...
Fetch the events from the server. This method fetches those events of a group stored on the server that were updated since the given date. Data comments and rsvps are included within each event. :param category: the category of items to fetch :param from_date: obtain events upd...
def iter_window(iterable, size=2, step=1, wrap=False): r""" iterates through iterable with a window size generalizeation of itertwo Args: iterable (iter): an iterable sequence size (int): window size (default = 2) wrap (bool): wraparound (default = False) Returns: i...
r""" iterates through iterable with a window size generalizeation of itertwo Args: iterable (iter): an iterable sequence size (int): window size (default = 2) wrap (bool): wraparound (default = False) Returns: iter: returns windows in a sequence CommandLine: ...
def setdefault(self, key, default=None): """ If *key* is in the dictionary, return its value. If not, insert *key* with a value of *default* and return *default*. *default* defaults to ``None``. """ if key in self: return self[key] else: ...
If *key* is in the dictionary, return its value. If not, insert *key* with a value of *default* and return *default*. *default* defaults to ``None``.
def _delete_compressed(collection_name, spec, opts, flags, ctx): """Internal compressed unacknowledged delete message helper.""" op_delete, max_bson_size = _delete(collection_name, spec, opts, flags) rid, msg = _compress(2006, op_delete, ctx) return rid, msg, max_bson_size
Internal compressed unacknowledged delete message helper.
def asarray(arraylike, strict=True): """ Converts arraylike objects to NumPy ndarray types. Errors if object is not arraylike and strict option is enabled. """ if isinstance(arraylike, np.ndarray): return arraylike elif isinstance(arraylike, list): return np.asarray(arraylike, dt...
Converts arraylike objects to NumPy ndarray types. Errors if object is not arraylike and strict option is enabled.
def _import_classes(self, class_names): """ Import a list of classes. """ classes = [] for name in class_names: classes.extend(self._import_class_or_module(name)) return classes
Import a list of classes.
def _populate_cache(platform, pkg_cache, mount_dir): ''' If a ``pkg_cache`` directory is specified, then use it to populate the disk image. ''' if not pkg_cache: return if not os.path.isdir(pkg_cache): return if platform == 'pacman': cache_dir = '{0}/var/cache/pacman...
If a ``pkg_cache`` directory is specified, then use it to populate the disk image.
def get_top_artists(self, limit=None, cacheable=True): """Returns the most played artists as a sequence of TopItem objects.""" params = {} if limit: params["limit"] = limit doc = _Request(self, "chart.getTopArtists", params).execute(cacheable) return _extract_top_a...
Returns the most played artists as a sequence of TopItem objects.
def calc_pident_ignore_gaps(a, b): """ calculate percent identity """ m = 0 # matches mm = 0 # mismatches for A, B in zip(list(a), list(b)): if A == '-' or A == '.' or B == '-' or B == '.': continue if A == B: m += 1 else: mm += 1 t...
calculate percent identity
def parse_chain(*args): """Creates a new parser that executes the passed parsers (args) with the previous results and yields a tuple of the results. >>> list(parse_chain(lambda: (None, 1), lambda one: (None, 2))) [None, None, (1, 2)] @param args: parsers @returns: parser """ items = [] for parser in args: ...
Creates a new parser that executes the passed parsers (args) with the previous results and yields a tuple of the results. >>> list(parse_chain(lambda: (None, 1), lambda one: (None, 2))) [None, None, (1, 2)] @param args: parsers @returns: parser
def get_polygons(self, by_spec=False, depth=None): """ Returns a list of polygons created by this reference. Parameters ---------- by_spec : bool If ``True``, the return value is a dictionary with the polygons of each individual pair (layer, datatype). ...
Returns a list of polygons created by this reference. Parameters ---------- by_spec : bool If ``True``, the return value is a dictionary with the polygons of each individual pair (layer, datatype). depth : integer or ``None`` If not ``None``, defines ...
def guided_registration(request, page_number=None): ''' Goes through the registration process in order, making sure user sees all valid categories. The user must be logged in to see this view. Parameter: page_number: 1) Profile form (and e-mail address?) 2) Ticket type ...
Goes through the registration process in order, making sure user sees all valid categories. The user must be logged in to see this view. Parameter: page_number: 1) Profile form (and e-mail address?) 2) Ticket type 3) Remaining products 4) Mark regist...
def to_credentials(arg): ''' to_credentials(arg) converts arg into a pair (key, secret) if arg can be coerced into such a pair and otherwise raises an error. Possible inputs include: * A tuple (key, secret) * A mapping with the keys 'key' and 'secret' * The name of a file that c...
to_credentials(arg) converts arg into a pair (key, secret) if arg can be coerced into such a pair and otherwise raises an error. Possible inputs include: * A tuple (key, secret) * A mapping with the keys 'key' and 'secret' * The name of a file that can load credentials via the load_cred...
def status(self): '''returns rates''' counts = {} for bucket in self.buckets: for x in bucket: if not x in counts: counts[x] = 0 counts[x] += bucket[x] ret = "" mtypes = counts.keys() mtypes.sort() f...
returns rates
def cost_sampling(X, y, cost_mat, method='RejectionSampling', oversampling_norm=0.1, max_wc=97.5): """Cost-proportionate sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground...
Cost-proportionate sampling. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. y : array-like of shape = [n_samples] Ground truth (correct) labels. cost_mat : array-like of shape = [n_samples, 4] Cost matrix ...
def get_signature_request(self, signature_request_id, ux_version=None): ''' Get a signature request by its ID Args: signature_request_id (str): The id of the SignatureRequest to retrieve ux_version (int): UX version, either 1 (default) or 2. Returns:...
Get a signature request by its ID Args: signature_request_id (str): The id of the SignatureRequest to retrieve ux_version (int): UX version, either 1 (default) or 2. Returns: A SignatureRequest object
def get_entity(self, entity_id, at=None): """ Returns entity with given ID, optionally until position. """ # Get a snapshot (None if none exist). if self._snapshot_strategy is not None: snapshot = self._snapshot_strategy.get_snapshot(entity_id, lte=at) else: ...
Returns entity with given ID, optionally until position.
def AddGroupMemberships(self): """Adds aggregate group membership from group, gshadow and passwd.""" self.groups = {g.name: self._Members(g) for g in itervalues(self.groups)} # Map the groups a user is a member of, irrespective of primary/extra gid. for g in itervalues(self.groups): for user in g....
Adds aggregate group membership from group, gshadow and passwd.
def _declare_consumer(self, consumer, nowait=False): """Declare consumer so messages can be received from it using :meth:`iterconsume`.""" if consumer.queue not in self._open_consumers: # Use the ConsumerSet's consumer by default, but if the # child consumer has a callbac...
Declare consumer so messages can be received from it using :meth:`iterconsume`.
def create_logical_volume(lv_name, volume_group, size=None): ''' Create a new logical volume in an existing volume group :param lv_name: str: name of logical volume to be created. :param volume_group: str: Name of volume group to use for the new volume. :param size: str: Size of logical volume to c...
Create a new logical volume in an existing volume group :param lv_name: str: name of logical volume to be created. :param volume_group: str: Name of volume group to use for the new volume. :param size: str: Size of logical volume to create (100% if not supplied) :raises subprocess.CalledProcessError: i...
def getStuckRelayCheckEnabled(self): """Returns True if enabled, False if disabled""" command = '$GE' settings = self.sendCommand(command) flags = int(settings[2], 16) return not (flags & 0x0010)
Returns True if enabled, False if disabled
def create_installer(self, rpm_py_version, **kwargs): """Create Installer object.""" return FedoraInstaller(rpm_py_version, self.python, self.rpm, **kwargs)
Create Installer object.
def pre_process_code_block(block): """Preprocess the content of a code block, modifying the code block in place. Just dedents indented code. """ if 'indent' in block and block['indent']: indent = r'^' + block['indent'] block['content'] = re.sub(indent, ''...
Preprocess the content of a code block, modifying the code block in place. Just dedents indented code.
def _get_longest(value_lst: List) -> List: """ Get the longest match for overlap Args: value_lst: List Returns: List """ value_lst.sort() result = [] pivot = value_lst[0] start, end = pivot[0], pivot[1] pivot_e = end p...
Get the longest match for overlap Args: value_lst: List Returns: List
def password_generator(length): """Generate a random password. :param length: integer. """ return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length))
Generate a random password. :param length: integer.
def on_get(self, req, resp, **kwargs): """Respond on GET requests using ``self.retrieve()`` handler.""" return super().on_get( req, resp, handler=self._retrieve, **kwargs )
Respond on GET requests using ``self.retrieve()`` handler.
def network_create(request, **kwargs): """Create a network object. :param request: request context :param tenant_id: (optional) tenant id of the network created :param name: (optional) name of the network created :returns: Network object """ LOG.debug("network_create(): kwargs = %s", kwarg...
Create a network object. :param request: request context :param tenant_id: (optional) tenant id of the network created :param name: (optional) name of the network created :returns: Network object
def _repr_html_(self): """ Jupyter Notebook hook to print this element as HTML. """ nbreset = f'<style>{css_nbreset}</style>' resources = ''.join(map(str, self.resources)) return f'<div>{nbreset}{resources}<div class="hrepr">{self}</div></div>'
Jupyter Notebook hook to print this element as HTML.
def parse_pandoc(self, attrs): """Read pandoc attributes.""" id = attrs[0] classes = attrs[1] kvs = OrderedDict(attrs[2]) return id, classes, kvs
Read pandoc attributes.
def pesach_dow(self): """Return the first day of week for Pesach.""" jdn = conv.hdate_to_jdn(HebrewDate(self.hdate.year, Months.Nisan, 15)) return (jdn + 1) % 7 + 1
Return the first day of week for Pesach.
def validate_variable_type(var_name, var_type, value): """Ensures the value is the correct variable type. Args: var_name (str): The name of the defined variable on a blueprint. var_type (type): The type that the value should be. value (obj): The object representing the value provided fo...
Ensures the value is the correct variable type. Args: var_name (str): The name of the defined variable on a blueprint. var_type (type): The type that the value should be. value (obj): The object representing the value provided for the variable Returns: object: Retur...
def packages(self): """Return queue list from /var/lib/queue/queue_list file. """ queue_list = [] for read in self.queued.splitlines(): read = read.lstrip() if not read.startswith("#"): queue_list.append(read.replace("\n", "")) retu...
Return queue list from /var/lib/queue/queue_list file.
def walk_dict(d): """Walk a tree (nested dicts). For each 'path', or dict, in the tree, returns a 3-tuple containing: (path, sub-dicts, values) where: * path is the path to the dict * sub-dicts is a tuple of (key,dict) pairs for each sub-dict in this dict * values is a tuple of (key,value)...
Walk a tree (nested dicts). For each 'path', or dict, in the tree, returns a 3-tuple containing: (path, sub-dicts, values) where: * path is the path to the dict * sub-dicts is a tuple of (key,dict) pairs for each sub-dict in this dict * values is a tuple of (key,value) pairs for each (non-dict...
def alloc(subseqs): """Allocate memory for 1-dimensional link sequences.""" print(' . setlength') lines = Lines() lines.add(1, 'cpdef inline alloc(self, name, int length):') for seq in subseqs: lines.add(2, 'if name == "%s":' % seq.name) lines.a...
Allocate memory for 1-dimensional link sequences.
def find_changelog(session, repo_url, deep=True): """ Tries to find changelogs on the given `repo_url`. :param session: requests Session instance :param repo_url: str, URL to the repo :param deep: bool, deep search :return: str, URL to the raw changelog content """ logger.debug("Trying t...
Tries to find changelogs on the given `repo_url`. :param session: requests Session instance :param repo_url: str, URL to the repo :param deep: bool, deep search :return: str, URL to the raw changelog content
def to_header(self): """Convert the etags set into a HTTP header string.""" if self.star_tag: return "*" return ", ".join( ['"%s"' % x for x in self._strong] + ['W/"%s"' % x for x in self._weak] )
Convert the etags set into a HTTP header string.
def _setup_global_state_for_execution(laser_evm, transaction) -> None: """Sets up global state and cfg for a transactions execution. :param laser_evm: :param transaction: """ # TODO: Resolve circular import between .transaction and ..svm to import LaserEVM here global_state = transaction.initia...
Sets up global state and cfg for a transactions execution. :param laser_evm: :param transaction:
def create_or_update(sysmeta_pyxb, sciobj_url=None): """Create or update database representation of a System Metadata object and closely related internal state. - If ``sciobj_url`` is not passed on create, storage in the internal sciobj store is assumed - If ``sciobj_url`` is passed on create, it...
Create or update database representation of a System Metadata object and closely related internal state. - If ``sciobj_url`` is not passed on create, storage in the internal sciobj store is assumed - If ``sciobj_url`` is passed on create, it can reference a location in the internal sciobj store...
def intercept_service(self, continuation, handler_call_details): """Intercepts incoming RPCs before handing them over to a handler See `grpc.ServerInterceptor.intercept_service`. """ rpc_method_handler = self._get_rpc_handler(handler_call_details) if rpc_method_handler.response...
Intercepts incoming RPCs before handing them over to a handler See `grpc.ServerInterceptor.intercept_service`.
def user_delete(auth=None, **kwargs): ''' Delete a user CLI Example: .. code-block:: bash salt '*' keystoneng.user_delete name=user1 salt '*' keystoneng.user_delete name=user2 domain_id=b62e76fbeeff4e8fb77073f591cf211e salt '*' keystoneng.user_delete name=a42cbbfa1e894e839fd0f...
Delete a user CLI Example: .. code-block:: bash salt '*' keystoneng.user_delete name=user1 salt '*' keystoneng.user_delete name=user2 domain_id=b62e76fbeeff4e8fb77073f591cf211e salt '*' keystoneng.user_delete name=a42cbbfa1e894e839fd0f584d22e321f
def radec2sky(ra, dec): """ Convert [ra], [dec] to [(ra[0], dec[0]),....] and also ra,dec to [(ra,dec)] if ra/dec are not iterable Parameters ---------- ra, dec : float or iterable Sky coordinates Returns ------- sky : numpy.array ...
Convert [ra], [dec] to [(ra[0], dec[0]),....] and also ra,dec to [(ra,dec)] if ra/dec are not iterable Parameters ---------- ra, dec : float or iterable Sky coordinates Returns ------- sky : numpy.array array of (ra,dec) coordinates.
def execd_submodule_paths(command, execd_dir=None): """Generate a list of full paths to the specified command within exec_dir. """ for module_path in execd_module_paths(execd_dir): path = os.path.join(module_path, command) if os.access(path, os.X_OK) and os.path.isfile(path): yie...
Generate a list of full paths to the specified command within exec_dir.
def iter_gists(self, username=None, number=-1, etag=None): """If no username is specified, GET /gists, otherwise GET /users/:username/gists :param str login: (optional), login of the user to check :param int number: (optional), number of gists to return. Default: -1 returns ...
If no username is specified, GET /gists, otherwise GET /users/:username/gists :param str login: (optional), login of the user to check :param int number: (optional), number of gists to return. Default: -1 returns all available gists :param str etag: (optional), ETag from a p...
def unfold(tensor, mode): """Returns the mode-`mode` unfolding of `tensor`. Parameters ---------- tensor : ndarray mode : int Returns ------- ndarray unfolded_tensor of shape ``(tensor.shape[mode], -1)`` Author ------ Jean Kossaifi <https://github.com/tensorly> ...
Returns the mode-`mode` unfolding of `tensor`. Parameters ---------- tensor : ndarray mode : int Returns ------- ndarray unfolded_tensor of shape ``(tensor.shape[mode], -1)`` Author ------ Jean Kossaifi <https://github.com/tensorly>
def _read_arg(arg): """ If arg is a list with 1 element that corresponds to a valid file path, use set_io.grp to read the grp file. Otherwise, check that arg is a list of strings. Args: arg (list or None) Returns: arg_out (list or None) """ # If arg is None, just return it...
If arg is a list with 1 element that corresponds to a valid file path, use set_io.grp to read the grp file. Otherwise, check that arg is a list of strings. Args: arg (list or None) Returns: arg_out (list or None)
def check_calendar_dates( feed: "Feed", *, as_df: bool = False, include_warnings: bool = False ) -> List: """ Analog of :func:`check_agency` for ``feed.calendar_dates``. """ table = "calendar_dates" problems = [] # Preliminary checks if feed.calendar_dates is None: return proble...
Analog of :func:`check_agency` for ``feed.calendar_dates``.
def get_in(keys, coll, default=None, no_default=False): """ NB: This is a straight copy of the get_in implementation found in the toolz library (https://github.com/pytoolz/toolz/). It works with persistent data structures as well as the corresponding datastructures from the stdlib. ...
NB: This is a straight copy of the get_in implementation found in the toolz library (https://github.com/pytoolz/toolz/). It works with persistent data structures as well as the corresponding datastructures from the stdlib. Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. If c...
def _cell_magic(line, query): """Underlying function for bigquery cell magic Note: This function contains the underlying logic for the 'bigquery' cell magic. This function is not meant to be called directly. Args: line (str): "%%bigquery" followed by arguments as required q...
Underlying function for bigquery cell magic Note: This function contains the underlying logic for the 'bigquery' cell magic. This function is not meant to be called directly. Args: line (str): "%%bigquery" followed by arguments as required query (str): SQL query to run Ret...
def _get_cgroup_from_proc(self, cgroup, pid, filename): """Find a specific cgroup file, containing metrics to extract.""" params = { "file": filename, } return DockerUtil.find_cgroup_from_proc(self._mountpoints, pid, cgroup, self.docker_util._docker_root) % (params)
Find a specific cgroup file, containing metrics to extract.
def call_good_cb(self): """ If good_cb returns True then keep it :return: """ with LiveExecution.lock: if self.good_cb and not self.good_cb(): self.good_cb = None
If good_cb returns True then keep it :return:
def GetDataStreamByPathSpec(self, path_spec): """Retrieves a data stream for a path specification. Args: path_spec (PathSpec): a path specification. Returns: DataStream: a data stream or None if not available. """ file_entry = self.GetFileEntryByPathSpec(path_spec) if not file_entr...
Retrieves a data stream for a path specification. Args: path_spec (PathSpec): a path specification. Returns: DataStream: a data stream or None if not available.
def index(): """ Base testsuite view. """ # setup_env() logs = Table('log', metadata, autoload=True) criticals = logs.select().where(logs.c.log_level == 50).order_by( 'siteconfig', 'date_created') criticals_count = logs.count(logs.c.log_level == 50) errors = logs.select().where(logs....
Base testsuite view.
def datasets_upload_file(self, file_name, content_length, last_modified_date_utc, **kwargs): # noqa: E501 """Get URL and token to start uploading a data file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
Get URL and token to start uploading a data file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_upload_file(file_name, content_length, last_modified_date_utc, async_req=True) ...
def stem(self): """The final path component, minus its last suffix.""" name = self.name i = name.rfind('.') if 0 < i < len(name) - 1: return name[:i] else: return name
The final path component, minus its last suffix.
def get_sections(self, s, base, sections=[ 'Parameters', 'Other Parameters', 'Possible types']): """ Extract the specified sections out of the given string The same as the :meth:`docrep.DocstringProcessor.get_sections` method but uses the ``'Possible types'`` section by defa...
Extract the specified sections out of the given string The same as the :meth:`docrep.DocstringProcessor.get_sections` method but uses the ``'Possible types'`` section by default, too Parameters ---------- %(DocstringProcessor.get_sections.parameters)s Returns -...
def frame(I=None, second=5, saveable=True, name='frame', cmap=None, fig_idx=12836): """Display a frame. Make sure OpenAI Gym render() is disable before using it. Parameters ---------- I : numpy.array The image. second : int The display second(s) for the image(s), if saveable is Fals...
Display a frame. Make sure OpenAI Gym render() is disable before using it. Parameters ---------- I : numpy.array The image. second : int The display second(s) for the image(s), if saveable is False. saveable : boolean Save or plot the figure. name : str A name to...
def make_data(): """ 1..T: set of periods K: set of resources P: set of items f[t,p]: set-up costs g[t,p]: set-up times c[t,p]: variable costs d[t,p]: demand values h[t,p]: holding costs a[t,k,p]: amount of resource k for producing product p in period. t M[t,k]: resource uppe...
1..T: set of periods K: set of resources P: set of items f[t,p]: set-up costs g[t,p]: set-up times c[t,p]: variable costs d[t,p]: demand values h[t,p]: holding costs a[t,k,p]: amount of resource k for producing product p in period. t M[t,k]: resource upper bounds UB[t,p]: upper b...
def bytes_to_c_string(data): """ Convert the hexadecimal string in to C-style string. """ rows = chunked_join(data, 20, 2, '"\n "', '', r'\x' + X) logging.debug(_('Returning rows: %s'), rows) return '"{}";'.format(rows)
Convert the hexadecimal string in to C-style string.
def edit(id: int, parent: int, alloc: Decimal): """ Edit asset class """ saved = False # load app = AppAggregate() item = app.get(id) if not item: raise KeyError("Asset Class with id %s not found.", id) if parent: assert parent != id, "Parent can not be set to self." ...
Edit asset class
def compiler(self, target): """Returns the thrift compiler to use for the given target. :param target: The target to extract the thrift compiler from. :type target: :class:`pants.backend.codegen.thrift.java.java_thrift_library.JavaThriftLibrary` :returns: The thrift compiler to use. :rtype: string ...
Returns the thrift compiler to use for the given target. :param target: The target to extract the thrift compiler from. :type target: :class:`pants.backend.codegen.thrift.java.java_thrift_library.JavaThriftLibrary` :returns: The thrift compiler to use. :rtype: string
def prepare_injection_directions(self): """provide genotypic directions for TPA and selective mirroring, with no specific length normalization, to be used in the coming iteration. Details: This method is called in the end of `tell`. The result is assigned to ``self.pop_i...
provide genotypic directions for TPA and selective mirroring, with no specific length normalization, to be used in the coming iteration. Details: This method is called in the end of `tell`. The result is assigned to ``self.pop_injection_directions`` and used in `ask_geno...
def get_assessment_parts_by_item(self, item_id): """Gets the assessment parts containing the given item. In plenary mode, the returned list contains all known assessment parts or an error results. Otherwise, the returned list may contain only those assessment parts that are accessible t...
Gets the assessment parts containing the given item. In plenary mode, the returned list contains all known assessment parts or an error results. Otherwise, the returned list may contain only those assessment parts that are accessible through this session. arg: item_id (osid....
def up(self, i): """The value of heap[i] has decreased. Maintain heap invariant.""" x = self.heap[i] while i > 1 and x < self.heap[i // 2]: self.heap[i] = self.heap[i // 2] self.rank[self.heap[i // 2]] = i i //= 2 self.heap[i] = x # insertion ind...
The value of heap[i] has decreased. Maintain heap invariant.
def get_subscribers(obj): """ Returns the subscribers for a given object. :param obj: Any object. """ ctype = ContentType.objects.get_for_model(obj) return Subscription.objects.filter(content_type=ctype, object_id=obj.pk)
Returns the subscribers for a given object. :param obj: Any object.
def add_options(self): """ Add program options. """ self.add_bool_option("--reveal", help="show full announce URL including keys") self.add_bool_option("--raw", help="print the metafile's raw content in all detail") self.add_bool_option("-V", "--skip-valid...
Add program options.
def get_mode(device_filter): """Determine which beacons the scanner should look for.""" from .device_filters import IBeaconFilter, EddystoneFilter, BtAddrFilter, EstimoteFilter if device_filter is None or len(device_filter) == 0: return ScannerMode.MODE_ALL mode = ScannerMode.MODE_NONE for ...
Determine which beacons the scanner should look for.
def sub_slots(x,match_fn,path=(),arr=None,match=False,recurse_into_matches=True): """given a BaseX in x, explore its ATTRS (doing the right thing for VARLEN). return a list of tree-paths (i.e. tuples) for tree children that match match_fn. The root elt won't match. """ # todo: rename match to topmatch for clari...
given a BaseX in x, explore its ATTRS (doing the right thing for VARLEN). return a list of tree-paths (i.e. tuples) for tree children that match match_fn. The root elt won't match.
def bezout(a, b): """Bezout coefficients for a and b :param a,b: non-negative integers :complexity: O(log a + log b) """ if b == 0: return (1, 0) else: u, v = bezout(b, a % b) return (v, u - (a // b) * v)
Bezout coefficients for a and b :param a,b: non-negative integers :complexity: O(log a + log b)
def simplify_text(text): """ Simplify text to allow comparison. >>> simplify_text("Awesome Coder wanted at Awesome Company") 'awesome coder wanted at awesome company' >>> simplify_text("Awesome Coder, wanted at Awesome Company! ") 'awesome coder wanted at awesome company' >>> simplify_text...
Simplify text to allow comparison. >>> simplify_text("Awesome Coder wanted at Awesome Company") 'awesome coder wanted at awesome company' >>> simplify_text("Awesome Coder, wanted at Awesome Company! ") 'awesome coder wanted at awesome company' >>> simplify_text(u"Awesome Coder, wanted at Awesome ...
def print_col_perc_table(table, row_labels, col_labels): """ given a table, print the cols as percentages """ r1c1, r1c2, r2c1, r2c2 = map(float, table) col1 = r1c1 + r2c1 col2 = r1c2 + r2c2 blocks = [ (r1c1, col1), (r1c2, col2), (r2c1, col1), (r2c2, col2)] ...
given a table, print the cols as percentages
def download(self, remotepath = '/', localpath = ''): ''' Usage: download [remotepath] [localpath] - \ download a remote directory (recursively) / file remotepath - remote path at Baidu Yun (after app root directory), if not specified, it is set to the root directory at Baidu Yun localpath - local path. if not sp...
Usage: download [remotepath] [localpath] - \ download a remote directory (recursively) / file remotepath - remote path at Baidu Yun (after app root directory), if not specified, it is set to the root directory at Baidu Yun localpath - local path. if not specified, it is set to the current directory
def _on_loop_start(self, variables): """ performs on-loop-start actions like callbacks variables contains local namespace variables. Parameters --------- variables : dict of available variables Returns ------- None """ for callba...
performs on-loop-start actions like callbacks variables contains local namespace variables. Parameters --------- variables : dict of available variables Returns ------- None
def create_from_flux_points(cls, txtfile): """Create a Castro data object from a text file containing a sequence of differential flux points.""" tab = Table.read(txtfile, format='ascii.ecsv') dnde_unit = u.ph / (u.MeV * u.cm ** 2 * u.s) loge = np.log10(np.array(tab['e_ref'].to(u...
Create a Castro data object from a text file containing a sequence of differential flux points.
def get_element_dos(self): """ Get element projected Dos. Returns: dict of {Element: Dos} """ el_dos = {} for site, atom_dos in self.pdos.items(): el = site.specie for pdos in atom_dos.values(): if el not in el_dos: ...
Get element projected Dos. Returns: dict of {Element: Dos}
def scale_and_shift_cmap(self, scale_pct, shift_pct): """Stretch and/or shrink the color map. See :meth:`ginga.RGBMap.RGBMapper.scale_and_shift`. """ rgbmap = self.get_rgbmap() rgbmap.scale_and_shift(scale_pct, shift_pct)
Stretch and/or shrink the color map. See :meth:`ginga.RGBMap.RGBMapper.scale_and_shift`.
def ctcp_unpack_message(info): """Given a an input message (privmsg/pubmsg/notice), return events.""" verb = info['verb'] message = info['params'][1] # NOTE: full CTCP dequoting and unpacking is not done here, only a subset # this is because doing the full thing breaks legitimate messages # ...
Given a an input message (privmsg/pubmsg/notice), return events.
def _signal(self, sig, pid=None): """ Send a signal to one or all pids associated with this task. Never fails, but logs signalling faults as warnings. """ log = self._params.get('log', self._discard) if pid is None: pids = self.get_pids() else: ...
Send a signal to one or all pids associated with this task. Never fails, but logs signalling faults as warnings.
def set_network(self, machines, local_listen_port=12400, listen_time_out=120, num_machines=1): """Set the network configuration. Parameters ---------- machines : list, set or string Names of machines. local_listen_port : int, optional (default=124...
Set the network configuration. Parameters ---------- machines : list, set or string Names of machines. local_listen_port : int, optional (default=12400) TCP listen port for local machines. listen_time_out : int, optional (default=120) Socket t...
def is_between(self, low, high): """Asserts that val is numeric and is between low and high.""" val_type = type(self.val) self._validate_between_args(val_type, low, high) if self.val < low or self.val > high: if val_type is datetime.datetime: self._err('Expec...
Asserts that val is numeric and is between low and high.
def bind(self, __fun, *args, **kwargs): """ Bind a worker function to the future. This worker function will be executed when the future is executed. """ with self._lock: if self._running or self._completed or self._cancelled: raise RuntimeError('Future object can not be reused') ...
Bind a worker function to the future. This worker function will be executed when the future is executed.
def get_fields(self): """ Return all field objects :rtype: a list of :class:`EncodedField` objects """ l = [] for i in self.classes.class_def: for j in i.get_fields(): l.append(j) return l
Return all field objects :rtype: a list of :class:`EncodedField` objects
def tarFile(source): """Compress file under tar mode which type more popular use in Unix operating system when compress failed with return source path :param source: source file path :return: zip file path """ # source = source.decode('UTF-8') target = source[0:source.rindex('.')...
Compress file under tar mode which type more popular use in Unix operating system when compress failed with return source path :param source: source file path :return: zip file path
def run_suite(case, config, summary): """ Run the full suite of performance tests """ config["name"] = case timing_data = dict() model_dir = os.path.join(livvkit.model_dir, config['data_dir'], case) bench_dir = os.path.join(livvkit.bench_dir, config['data_dir'], case) plot_dir = os.path.join(liv...
Run the full suite of performance tests
def _do_stack(self, cmd, args): """\ Manage the shell stack. stack Display the stack. stack <depth> Exit to the stack by its depth. """ if not args: self.__dump_stack() return if len(args) > 1: self.s...
\ Manage the shell stack. stack Display the stack. stack <depth> Exit to the stack by its depth.
def accept(self): """accept a connection attempt from a remote client returns a two-tuple with the ssl-context-wrapped connection, and the address of the remote client """ while 1: try: sock, addr = self._sock.accept() return (type(sel...
accept a connection attempt from a remote client returns a two-tuple with the ssl-context-wrapped connection, and the address of the remote client
def _safe_get(self, revision, key): """ Get an answer data (vote or rationale) by revision Args: revision (int): the revision number for student answer, could be 0 (original) or 1 (revised) key (str); key for retrieve answer data, could be VOTE_KEY or ...
Get an answer data (vote or rationale) by revision Args: revision (int): the revision number for student answer, could be 0 (original) or 1 (revised) key (str); key for retrieve answer data, could be VOTE_KEY or RATIONALE_KEY Returns: ...
def authenticate(username, password): ''' Returns True if the given username and password authenticate for the given service. Returns False otherwise ``username``: the username to authenticate ``password``: the password in plain text ''' service = __opts__.get('auth.pam.service', 'login')...
Returns True if the given username and password authenticate for the given service. Returns False otherwise ``username``: the username to authenticate ``password``: the password in plain text
def nvmlDeviceClearEccErrorCounts(handle, counterType): r""" /** * Clear the ECC error and other memory error counts for the device. * * For Kepler &tm; or newer fully supported devices. * Only applicable to devices with ECC. * Requires \a NVML_INFOROM_ECC version 2.0 or higher to clear...
r""" /** * Clear the ECC error and other memory error counts for the device. * * For Kepler &tm; or newer fully supported devices. * Only applicable to devices with ECC. * Requires \a NVML_INFOROM_ECC version 2.0 or higher to clear aggregate location-based ECC counts. * Requires \a NVM...
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods for which t...
r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods for which the data exists for. Called ...
def declare_consuming(self, exchange_name, routing_key, queue_name, callback): """ 声明一个主题交换机队列,并且将队列和交换机进行绑定,同时监听这个队列 :param exchange_name: :param routing_key: :param queue_name: :param callback: :return: """ self.bind_topic_exchange(exchange_name,...
声明一个主题交换机队列,并且将队列和交换机进行绑定,同时监听这个队列 :param exchange_name: :param routing_key: :param queue_name: :param callback: :return: