prompt
stringlengths
23
36.3k
response
stringlengths
0
1.55k
def get_all_policies(self, as_group=None, policy_names=None, max_records=None, next_token=None): """ Returns descriptions of what each policy does. This action supports pagination. If the response includes a token, there are more records available. To get the additional records, repeat the request with the response token as the NextToken parameter. If no group name or list of policy names are provided, all available policies are returned. :type as_name: str :param as_name: The name of the :class:`boto.ec2.autoscale.group.AutoScalingGroup` to filter for. :type names: list :param names: List of policy names which should be searched for. :type max_records: int :param max_records: Maximum amount of groups to return. """
params = {} if as_group: params['AutoScalingGroupName'] = as_group if policy_names: self.build_list_params(params, policy_names, 'PolicyNames') if max_records: params['MaxRecords'] = max_records if next_token: params['NextToken'] = next_token return self.get_list('DescribePolicies', params, [('member', ScalingPolicy)])
def add(self, **args): """Handles the 'a' command. :args: Arguments supplied to the 'a' command. """
kwargs = self.getKwargs(args) if kwargs: self.model.add(**kwargs)
def add(cls, model, commit=True): """Adds a model instance to session and commits the transaction. Args: model: The instance to add. Examples: >>> customer = Customer.new(name="hari", email="hari@gmail.com") >>> Customer.add(customer) hari@gmail.com """
if not isinstance(model, cls): raise ValueError('%s is not of type %s' % (model, cls)) cls.session.add(model) try: if commit: cls.session.commit() return model except: cls.session.rollback() raise
def cnst_A(self, X, Xf=None): r"""Compute :math:`A \mathbf{x}` component of ADMM problem constraint. In this case :math:`A \mathbf{x} = (G_r^T \;\; G_c^T \;\; H)^T \mathbf{x}`. """
if Xf is None: Xf = sl.rfftn(X, axes=self.axes) return sl.irfftn(self.GAf*Xf[..., np.newaxis], self.axsz, axes=self.axes)
def from_passphrase(cls, passphrase=None): """ Create keypair from a passphrase input (a brain wallet keypair)."""
if not passphrase: # run a rejection sampling algorithm to ensure the private key is # less than the curve order while True: passphrase = create_passphrase(bits_of_entropy=160) hex_private_key = hashlib.sha256(passphrase).hexdigest() if int(hex_private_key, 16) < cls._curve.order: break else: hex_private_key = hashlib.sha256(passphrase).hexdigest() if not (int(hex_private_key, 16) < cls._curve.order): raise ValueError(_errors["PHRASE_YIELDS_INVALID_EXPONENT"]) keypair = cls(hex_private_key) keypair._passphrase = passphrase return keypair
def _convert(frame): """ Helper funcation to build a parameterized url. """
frame = frame.convert_objects(convert_numeric=True) for column in frame: if column in c.dates: frame[column] = frame[column].astype('datetime64') return frame
def save_all_figures_as(self): """Save all the figures to a file."""
self.redirect_stdio.emit(False) dirname = getexistingdirectory(self, caption='Save all figures', basedir=getcwd_or_home()) self.redirect_stdio.emit(True) if dirname: return self.save_all_figures_todir(dirname)
def cds(self): """just the parts of the exons that are translated"""
ces = self.coding_exons if len(ces) < 1: return ces ces[0] = (self.cdsStart, ces[0][1]) ces[-1] = (ces[-1][0], self.cdsEnd) assert all((s < e for s, e in ces)) return ces
def chunks(self, include_inactive=False): """ @return A generator that yields the chunks of the log file starting with the first chunk, which is always found directly after the FileHeader. If `include_inactive` is set to true, enumerate chunks beyond those declared in the file header (and may therefore be corrupt). """
if include_inactive: chunk_count = sys.maxsize else: chunk_count = self.chunk_count() i = 0 ofs = self._offset + self.header_chunk_size() while ofs + 0x10000 <= len(self._buf) and i < chunk_count: yield ChunkHeader(self._buf, ofs) ofs += 0x10000 i += 1
def _normalise(self): """Object is guaranteed to be a unit quaternion after calling this operation UNLESS the object is equivalent to Quaternion(0) """
if not self.is_unit(): n = self.norm if n > 0: self.q = self.q / n
def uniform(self, a: float, b: float, precision: int = 15) -> float: """Get a random number in the range [a, b) or [a, b] depending on rounding. :param a: Minimum value. :param b: Maximum value. :param precision: Round a number to a given precision in decimal digits, default is 15. """
return round(a + (b - a) * self.random(), precision)
def dict(self): """A dict that holds key/values for all of the properties in the object. :return: """
from collections import OrderedDict SKIP_KEYS = () return OrderedDict( (p.key, getattr(self, p.key)) for p in self.__mapper__.attrs if p.key not in SKIP_KEYS)
def unlearn(taskPkgName, deleteAll=False): """ Find the task named taskPkgName, and delete any/all user-owned .cfg files in the user's resource directory which apply to that task. Like a unix utility, this returns 0 on success (no files found or only 1 found but deleted). For multiple files found, this uses deleteAll, returning the file-name-list if deleteAll is False (to indicate the problem) and without deleting any files. MUST check return value. This does not prompt the user or print to the screen. """
# this WILL throw an exception if the taskPkgName isn't found flist = cfgpars.getUsrCfgFilesForPyPkg(taskPkgName) # can raise if flist is None or len(flist) == 0: return 0 if len(flist) == 1: os.remove(flist[0]) return 0 # at this point, we know more than one matching file was found if deleteAll: for f in flist: os.remove(f) return 0 else: return flist
def subcommand(self, description='', arguments={}): """ Decorator for quickly adding subcommands to the omnic CLI """
def decorator(func): self.register_subparser( func, func.__name__.replace('_', '-'), description=description, arguments=arguments, ) return func return decorator
def new_block(self): """ create a new sub block to the current block and return it. the sub block is added to the current block. """
child = Block(self, py3_wrapper=self.py3_wrapper) self.add(child) return child
def vehicleTypes2flt(outSTRM, vtIDm): """ Currently, rather a stub than an implementation. Writes the vehicle ids stored in the given "vtIDm" map formatted as a .flt file readable by PHEM. The following may be a matter of changes: - A default map is assigned to all vehicle types with the same probability """
for q in sorted(vtIDm._m): print("%s,%s,%s" % (vtIDm.g(q), "<VEHDIR>\PC\PC_%s.GEN" % q, 1.), file=outSTRM)
def texture_from_image(renderer, image_name): """Create an SDL2 Texture from an image file"""
soft_surface = ext.load_image(image_name) texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface) SDL_FreeSurface(soft_surface) return texture
def initialize(self, initialization_order=None): """ This function tries to initialize the stateful objects. In the case where an initialization function for `Stock A` depends on the value of `Stock B`, if we try to initialize `Stock A` before `Stock B` then we will get an error, as the value will not yet exist. In this case, just skip initializing `Stock A` for now, and go on to the other state initializations. Then come back to it and try again. """
# Initialize time if self.time is None: if self.time_initialization is None: self.time = Time() else: self.time = self.time_initialization() # if self.time is None: # self.time = time # self.components.time = self.time # self.components.functions.time = self.time # rewrite functions so we don't need this self.components._init_outer_references({ 'scope': self, 'time': self.time }) remaining = set(self._stateful_elements) while remaining: progress = set() for element in remaining: try: element.initialize() progress.add(element) except (KeyError, TypeError, AttributeError): pass if progress: remaining.difference_update(progress) else: raise KeyError('Unresolvable Reference: Probable circular initialization' + '\n'.join([repr(e) for e in remaining]))
def delete_by_path(self, path): """ Delete file/directory identified by `path` argument. Warning: `path` have to be in :attr:`path`. Args: path (str): Path of the file / directory you want to remove. Raises: IOError: If the file / directory doesn't exists, or is not in \ :attr:`path`. """
if not os.path.exists(path): raise IOError("Unknown path '%s'!" % path) if not path.startswith(self.path): raise IOError( "Path '%s' is not in the root of the storage ('%s')!" % ( path, self.path ) ) if os.path.isfile(path): os.unlink(path) return self._recursive_remove_blank_dirs(path) shutil.rmtree(path) self._recursive_remove_blank_dirs(path)
def _check_grad_measurement_matrices(dM, state_dim, grad_params_no, measurement_dim, which = 'dH'): """ Function checks (mostly check dimensions) matrices for marginal likelihood gradient parameters calculation. It check dH, dR matrices. Input: ------------- dM: None, scaler or 3D matrix It is supposed to be (measurement_dim ,state_dim,grad_params_no) for "dH" matrix. (measurement_dim,measurement_dim,grad_params_no) for "dR" If None then zero matrix is assumed. If scalar then the function checks consistency with "state_dim" and "grad_params_no". state_dim: int State dimensionality grad_params_no: int How many parrameters of likelihood gradient in total. measurement_dim: int Dimensionality of measurements. which: string 'dH' or 'dR' Output: -------------- function of (k) which returns the parameters matrix. """
if dM is None: if which == 'dH': dM=np.zeros((measurement_dim ,state_dim,grad_params_no)) elif which == 'dR': dM=np.zeros((measurement_dim,measurement_dim,grad_params_no)) elif isinstance(dM, np.ndarray): if state_dim == 1: if len(dM.shape) < 3: dM.shape = (1,1,1) else: if len(dM.shape) < 3: if which == 'dH': dM.shape = (measurement_dim,state_dim,1) elif which == 'dR': dM.shape = (measurement_dim,measurement_dim,1) elif isinstance(dM, np.int): if state_dim > 1: raise ValueError("When computing likelihood gradient wrong dH dimension.") else: dM = np.ones((1,1,1)) * dM # if not isinstance(dM, types.FunctionType): # f_dM = lambda k: dM # else: # f_dM = dM return dM
def has_provider_support(provider, media_type): """ Verifies if API provider has support for requested media type """
if provider.lower() not in API_ALL: return False provider_const = "API_" + media_type.upper() return provider in globals().get(provider_const, {})
def unders_to_dashes_in_keys(self) -> None: """Replaces underscores with dashes in key names. For each attribute in a mapping, this replaces any underscores \ in its keys with dashes. Handy because Python does not \ accept dashes in identifiers, while some YAML-based formats use \ dashes in their keys. """
for key_node, _ in self.yaml_node.value: key_node.value = key_node.value.replace('_', '-')
def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False): """ Generator method to split a string using the given expression as a separator. May be called with optional ``maxsplit`` argument, to limit the number of splits; and the optional ``includeSeparators`` argument (default= ``False``), if the separating matching text should be included in the split results. Example:: punc = oneOf(list(".,;:/-!?")) print(list(punc.split("This, this?, this sentence, is badly punctuated!"))) prints:: ['This', ' this', '', ' this sentence', ' is badly punctuated', ''] """
splits = 0 last = 0 for t,s,e in self.scanString(instring, maxMatches=maxsplit): yield instring[last:s] if includeSeparators: yield t[0] last = e yield instring[last:]
def check_lt(self): """ Check is the POSTed LoginTicket is valid, if yes invalide it :return: ``True`` if the LoginTicket is valid, ``False`` otherwise :rtype: bool """
# save LT for later check lt_valid = self.request.session.get('lt', []) lt_send = self.request.POST.get('lt') # generate a new LT (by posting the LT has been consumed) self.gen_lt() # check if send LT is valid if lt_send not in lt_valid: return False else: self.request.session['lt'].remove(lt_send) # we need to redo the affectation for django to detect that the list has changed # and for its new value to be store in the session self.request.session['lt'] = self.request.session['lt'] return True
def _populate(self, fields): """this runs all the fields through their iget methods to mimic them freshly coming out of the db, then resets modified :param fields: dict, the fields that were passed in """
schema = self.schema for k, v in fields.items(): fields[k] = schema.fields[k].iget(self, v) self.modify(fields) self.reset_modified()
def parse_options_header(value): """Parse a ``Content-Type`` like header into a tuple with the content type and the options: >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) This should not be used to parse ``Cache-Control`` like headers that use a slightly different format. For these headers use the :func:`parse_dict_header` function. .. versionadded:: 0.5 :param value: the header to parse. :return: (str, options) """
def _tokenize(string): for match in _option_header_piece_re.finditer(string): key, value = match.groups() key = unquote_header_value(key) if value is not None: value = unquote_header_value(value, key == 'filename') yield key, value if not value: return '', {} parts = _tokenize(';' + value) name = next(parts)[0] extra = dict(parts) return name, extra
def _get_deploy_options(self, options): """Return the deployment options based on command line."""
user_data = None if options.user_data and options.b64_user_data: raise CommandError( "Cannot provide both --user-data and --b64-user-data.") if options.b64_user_data: user_data = options.b64_user_data if options.user_data: user_data = base64_file(options.user_data).decode("ascii") return utils.remove_None({ 'distro_series': options.image, 'hwe_kernel': options.hwe_kernel, 'user_data': user_data, 'comment': options.comment, 'wait': False, })
def use_config_file(self): """Find and apply the config file"""
self.config_file = self.find_config_file() if self.config_file: self.apply_config_file(self.config_file)
def get_value_by_parameter(self, parameter_id=None): """Gets a ``Value`` for the given parameter ``Id``. If more than one value exists for the given parameter, the most preferred value is returned. This method can be used as a convenience when only one value is expected. ``get_values_by_parameters()`` should be used for getting all the active values. arg: parameter_id (osid.id.Id): the ``Id`` of the ``Parameter`` to retrieve return: (osid.configuration.Value) - the value raise: NotFound - the ``parameter_id`` not found or no value available raise: NullArgument - the ``parameter_id`` is ``null`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.* """
pass if parameter_id is None: raise NullArgument try: parameter_key = parameter_id.get_identifier() + '.' + parameter_id.get_identifier_namespace() parameter_map = self._catalog._config_map['parameters'][parameter_key] except KeyError: try: parameter_key = parameter_id.get_identifier() parameter_map = self._catalog._config_map['parameters'][parameter_key] except KeyError: raise NotFound(str(parameter_id)) if len(parameter_map['values']) == 0: raise NotFound() lowest_priority_value_map = None for value_map in parameter_map['values']: if lowest_priority_value_map is None or lowest_priority_value_map['priority'] < value_map['priority']: lowest_priority_value_map = value_map return Value(lowest_priority_value_map, Parameter(parameter_map))
def _init_repo(self): """ create and initialize a new Git Repo """
log.debug("initializing new Git Repo: {0}".format(self._engine_path)) if os.path.exists(self._engine_path): log.error("Path already exists! Aborting!") raise RuntimeError else: # create the repo if it doesn't already exist _logg_repo = git.Repo.init(path=self._engine_path, mkdir=True) record = "idid Logg repo initialized on {0}".format(today()) c = _logg_repo.index.commit(record) assert c.type == 'commit' log.info('Created git repo [{0}]'.format(self._engine_path)) return _logg_repo
def run_xenon_simple(workflow, machine, worker_config): """Run a workflow using a single Xenon remote worker. :param workflow: |Workflow| or |PromisedObject| to evaluate. :param machine: |Machine| instance. :param worker_config: Configuration for the pilot job."""
scheduler = Scheduler() return scheduler.run( xenon_interactive_worker(machine, worker_config), get_workflow(workflow) )
def _SnakeCaseToCamelCase(path_name): """Converts a path name from snake_case to camelCase."""
result = [] after_underscore = False for c in path_name: if c.isupper(): raise Error('Fail to print FieldMask to Json string: Path name ' '{0} must not contain uppercase letters.'.format(path_name)) if after_underscore: if c.islower(): result.append(c.upper()) after_underscore = False else: raise Error('Fail to print FieldMask to Json string: The ' 'character after a "_" must be a lowercase letter ' 'in path name {0}.'.format(path_name)) elif c == '_': after_underscore = True else: result += c if after_underscore: raise Error('Fail to print FieldMask to Json string: Trailing "_" ' 'in path name {0}.'.format(path_name)) return ''.join(result)
def fill(self, ax, wcs, **kw_mpl_pathpatch): """ Draws the MOC on a matplotlib axis. This performs the projection of the cells from the world coordinate system to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.patches.PathPatch` (see the `list of valid keywords <https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch>`__). Parameters ---------- ax : `matplotlib.axes.Axes` Matplotlib axis. wcs : `astropy.wcs.WCS` WCS defining the World system <-> Image system projection. kw_mpl_pathpatch Plotting arguments for `matplotlib.patches.PathPatch`. Examples -------- >>> from mocpy import MOC, WCS >>> from astropy.coordinates import Angle, SkyCoord >>> import astropy.units as u >>> # Load a MOC, e.g. the MOC of GALEXGR6-AIS-FUV >>> filename = './../resources/P-GALEXGR6-AIS-FUV.fits' >>> moc = MOC.from_fits(filename) >>> # Plot the MOC using matplotlib >>> import matplotlib.pyplot as plt >>> fig = plt.figure(111, figsize=(15, 15)) >>> # Define a WCS as a context >>> with WCS(fig, ... fov=50 * u.deg, ... center=SkyCoord(0, 20, unit='deg', frame='icrs'), ... coordsys="icrs", ... rotation=Angle(0, u.degree), ... projection="AIT") as wcs: ... ax = fig.add_subplot(1, 1, 1, projection=wcs) ... # Call fill giving the matplotlib axe and the `~astropy.wcs.WCS` object. ... # We will set the matplotlib keyword linewidth to 0 so that it does not plot ... # the border of each HEALPix cell. ... # The color can also be specified along with an alpha value. ... moc.fill(ax=ax, wcs=wcs, linewidth=0, alpha=0.5, fill=True, color="green") >>> plt.xlabel('ra') >>> plt.ylabel('dec') >>> plt.grid(color="black", linestyle="dotted") """
fill.fill(self, ax, wcs, **kw_mpl_pathpatch)
def textContent(self, text: str) -> None: # type: ignore """Set textContent both on this node and related browser node."""
self._set_text_content(text) if self.connected: self._set_text_content_web(text)
def follow_link(self, link=None, *args, **kwargs): """Follow a link. If ``link`` is a bs4.element.Tag (i.e. from a previous call to :func:`links` or :func:`find_link`), then follow the link. If ``link`` doesn't have a *href*-attribute or is None, treat ``link`` as a url_regex and look it up with :func:`find_link`. Any additional arguments specified are forwarded to this function. If the link is not found, raise :class:`LinkNotFoundError`. Before raising, if debug is activated, list available links in the page and launch a browser. :return: Forwarded from :func:`open_relative`. """
link = self._find_link_internal(link, args, kwargs) referer = self.get_url() headers = {'Referer': referer} if referer else None return self.open_relative(link['href'], headers=headers)
def get_colors(num=16, cmap=plt.cm.Set1): """return a list of color tuples to use in plots"""
colors = [] for i in xrange(num): if analysis_params.bw: colors.append('k' if i % 2 == 0 else 'gray') else: i *= 256. if num > 1: i /= num - 1. else: i /= num colors.append(cmap(int(i))) return colors
def cmd_playtune(self, args): """send PLAY_TUNE message"""
if len(args) < 1: print("Usage: playtune TUNE") return tune = args[0] str1 = tune[0:30] str2 = tune[30:] if sys.version_info.major >= 3 and not isinstance(str1, bytes): str1 = bytes(str1, "ascii") if sys.version_info.major >= 3 and not isinstance(str2, bytes): str2 = bytes(str2, "ascii") self.master.mav.play_tune_send(self.settings.target_system, self.settings.target_component, str1, str2)
def query_recent_most(num=8, recent=30): """ Query the records from database that recently updated. :param num: the number that will returned. :param recent: the number of days recent. """
time_that = int(time.time()) - recent * 24 * 3600 return TabPost.select().where( TabPost.time_update > time_that ).order_by( TabPost.view_count.desc() ).limit(num)
def children(self): """ Returns all of the children elements. """
if isinstance(self.content, list): return self.content elif isinstance(self.content, Element): return [self.content] else: return []
def network_stop(name, **kwargs): """ Stop a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults .. versionadded:: 2019.2.0 CLI Example: .. code-block:: bash salt '*' virt.network_stop default """
conn = __get_conn(**kwargs) try: net = conn.networkLookupByName(name) return not bool(net.destroy()) finally: conn.close()
def execute_deposit(self, deposit_params, private_key): """ Function to execute the deposit request by signing the transaction generated by the create deposit function. Execution of this function is as follows:: execute_deposit(deposit_params=create_deposit, private_key=KeyPair) execute_deposit(deposit_params=create_deposit, private_key=eth_private_key) The expected return result for this function is as follows:: { 'result': 'ok' } :param deposit_params: Parameters from the API to be signed and deposited to the Switcheo Smart Contract. :type deposit_params: dict :param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message. :type private_key: KeyPair or str :return: Dictionary with the result status of the deposit attempt. """
deposit_id = deposit_params['id'] api_params = self.sign_execute_deposit_function[self.blockchain](deposit_params, private_key) return self.request.post(path='/deposits/{}/broadcast'.format(deposit_id), json_data=api_params)
def smembers(key, host=None, port=None, db=None, password=None): """ Get members in a Redis set CLI Example: .. code-block:: bash salt '*' redis.smembers foo_set """
server = _connect(host, port, db, password) return list(server.smembers(key))
def set(self, value): """ Atomically sets the value to `value`. :param value: The value to set. """
with self._reference.get_lock(): self._reference.value = value return value
def save(self, *args, **kwargs): """ Update ``self.modified``. """
self.modified = timezone.now() super(AbstractBaseModel, self).save(*args, **kwargs)
def read_uint32(self, little_endian=True): """ Read 4 bytes as an unsigned integer value from the stream. Args: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: """
if little_endian: endian = "<" else: endian = ">" return self.unpack('%sI' % endian, 4)
def _mems_updated_cb(self): """Called when the memories have been identified"""
logger.info('Memories finished updating') self.param.refresh_toc(self._param_toc_updated_cb, self._toc_cache)
def get_yaml_config(config_path): """ Load yaml config file and return dictionary. Todo: * This will need refactoring similar to the test search. """
config_path = os.path.expanduser(config_path) if not os.path.isfile(config_path): raise IpaUtilsException( 'Config file not found: %s' % config_path ) with open(config_path, 'r') as f: config = yaml.safe_load(f) return config
def send_string_clipboard(self, string: str, paste_command: model.SendMode): """ This method is called from the IoMediator for Phrase expansion using one of the clipboard method. :param string: The to-be pasted string :param paste_command: Optional paste command. If None, the mouse selection is used. Otherwise, it contains a keyboard combination string, like '<ctrl>+v', or '<shift>+<insert>' that is sent to the target application, causing a paste operation to happen. """
logger.debug("Sending string via clipboard: " + string) if common.USING_QT: if paste_command is None: self.__enqueue(self.app.exec_in_main, self._send_string_selection, string) else: self.__enqueue(self.app.exec_in_main, self._send_string_clipboard, string, paste_command) else: if paste_command is None: self.__enqueue(self._send_string_selection, string) else: self.__enqueue(self._send_string_clipboard, string, paste_command) logger.debug("Sending via clipboard enqueued.")
def _reconnect_delay(self): """ Calculate reconnection delay. """
if self.RECONNECT_ON_ERROR and self.RECONNECT_DELAYED: if self._reconnect_attempts >= len(self.RECONNECT_DELAYS): return self.RECONNECT_DELAYS[-1] else: return self.RECONNECT_DELAYS[self._reconnect_attempts] else: return 0
def add_device_callback(self, callback): """Register a callback to be invoked when a new device appears."""
_LOGGER.debug('Added new callback %s ', callback) self._cb_new_device.append(callback)
def create(self, mention, max_message_length): """ Create a message :param mention: JSON object containing mention details from Twitter (or an empty dict {}) :param max_message_length: Maximum allowable length for created message :return: A random message created using a Markov chain generator """
message = [] def message_len(): return sum([len(w) + 1 for w in message]) while message_len() < max_message_length: message.append(self.a_random_word(message[-1] if message else None)) return ' '.join(message[:-1])
def __invalid_request(self, error): """ Error response on failure """
# TODO: make this modifiable error = { 'error': { 'message': error } } abort(JsonResponse(status_code=400, data=error))
def update(self,updates={}): """ update csp_default.json with dict if file empty add default-src and create dict """
try: csp = self.read() except: csp = {'default-src':"'self'"} self.write(csp) csp.update(updates) self.write(csp)
def application_list(request): """ a user wants to see all applications possible. """
if util.is_admin(request): queryset = Application.objects.all() else: queryset = Application.objects.get_for_applicant(request.user) q_filter = ApplicationFilter(request.GET, queryset=queryset) table = ApplicationTable(q_filter.qs.order_by("-expires")) tables.RequestConfig(request).configure(table) spec = [] for name, value in six.iteritems(q_filter.form.cleaned_data): if value is not None and value != "": name = name.replace('_', ' ').capitalize() spec.append((name, value)) return render( template_name="kgapplications/application_list.html", context={ 'table': table, 'filter': q_filter, 'spec': spec, 'title': "Application list", }, request=request)
def get_host_port_names(self, host_name): """ return a list of the port names of XIV host """
port_names = list() host = self.get_hosts_by_name(host_name) fc_ports = host.fc_ports iscsi_ports = host.iscsi_ports port_names.extend(fc_ports.split(',') if fc_ports != '' else []) port_names.extend(iscsi_ports.split(',') if iscsi_ports != '' else []) return port_names
def isroutine(object): """Return true if the object is any kind of function or method."""
return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object))
def dir(base_dir: str, rr_id: str) -> str: """ Return correct subdirectory of input base dir for artifacts corresponding to input rev reg id. :param base_dir: base directory for tails files, thereafter split by cred def id :param rr_id: rev reg id """
LOGGER.debug('Tails.dir >>> base_dir: %s, rr_id: %s', base_dir, rr_id) if not ok_rev_reg_id(rr_id): LOGGER.debug('Tails.dir <!< Bad rev reg id %s', rr_id) raise BadIdentifier('Bad rev reg id {}'.format(rr_id)) rv = join(base_dir, rev_reg_id2cred_def_id(rr_id)) LOGGER.debug('Tails.dir <<< %s', rv) return rv
def _get_step(self, name, make_copy=True): """Return step from steps library. Optionally, the step returned is a deep copy from the step in the steps library, so additional information (e.g., about whether the step was scattered) can be stored in the copy. Args: name (str): name of the step in the steps library. make_copy (bool): whether a deep copy of the step should be returned or not (default: True). Returns: Step from steps library. Raises: ValueError: The requested step cannot be found in the steps library. """
self._closed() s = self.steps_library.get_step(name) if s is None: msg = '"{}" not found in steps library. Please check your ' \ 'spelling or load additional steps' raise ValueError(msg.format(name)) if make_copy: s = copy.deepcopy(s) return s
def _limit_and_df(self, query, limit, as_df=False): """adds a limit (limit==None := no limit) to any query and allow a return as pandas.DataFrame :param bool as_df: if is set to True results return as pandas.DataFrame :param `sqlalchemy.orm.query.Query` query: SQL Alchemy query :param int,tuple limit: maximum number of results :return: query result of pyhgnc.manager.models.XY objects """
if limit: if isinstance(limit, int): query = query.limit(limit) if isinstance(limit, Iterable) and len(limit) == 2 and [int, int] == [type(x) for x in limit]: page, page_size = limit query = query.limit(page_size) query = query.offset(page * page_size) if as_df: results = read_sql(query.statement, self.engine) else: try: results = query.all() except: query.session.rollback() results = query.all() return results
def create_leads_list(self, name, team_id=None): """ Create a leads list. :param name: Name of the list to create. Must be defined. :param team_id: The id of the list to share this list with. :return: The created leads list as a dict. """
params = self.base_params payload = {'name': name} if team_id: payload['team_id'] = team_id endpoint = self.base_endpoint.format('leads_lists') return self._query_hunter(endpoint, params, 'post', payload)
def mechanism(self): """tuple[int]: The nodes of the mechanism in the partition."""
return tuple(sorted( chain.from_iterable(part.mechanism for part in self)))
def decrypt(self, binary): """ Decrypt and unpack the original OpenConfig object, serialized using MessagePack. Raise BadSignatureException when the signature was forged or corrupted. """
try: encrypted = self.verify_key.verify(binary) except BadSignatureError: log.error('Signature was forged or corrupt', exc_info=True) raise BadSignatureException('Signature was forged or corrupt') try: packed = self.priv_key.decrypt(encrypted) except CryptoError: log.error('Unable to decrypt', exc_info=True) raise CryptoException('Unable to decrypt') return umsgpack.unpackb(packed)
def convert_to_node(instance, xml_node: XmlNode, node_globals: InheritedDict = None)\ -> InstanceNode: """Wraps passed instance with InstanceNode"""
return InstanceNode(instance, xml_node, node_globals)
def from_sqs(cls, sqs_message): """ :param sqs_message: the SQS message to initializes this instance from, assuiming that the SQS message originates from a SQS queue that is subscribed to an SNS topic :type sqs_message: SQSMessage :return: the parsed message or None if the message is of an unkwown version :rtype: Message """
sns_message = json.loads(sqs_message.get_body()) return Message.from_sns(sns_message['Message'])
def unregister(self, fd): """ Unregister an USB-unrelated fd from poller. Convenience method. """
if fd in self.__fd_set: raise ValueError( 'This fd is a special USB event fd, it must stay registered.' ) self.__poller.unregister(fd)
async def runItemCmdr(item, outp=None, **opts): """ Create a cmdr for the given item and run the cmd loop. Example: runItemCmdr(foo) """
cmdr = await getItemCmdr(item, outp=outp, **opts) await cmdr.runCmdLoop()
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: errata /repositories/<id>/errata files /repositories/<id>/files packages /repositories/<id>/packages module_streams /repositories/<id>/module_streams puppet_modules /repositories/<id>/puppet_modules remove_content /repositories/<id>/remove_content sync /repositories/<id>/sync upload_content /repositories/<id>/upload_content import_uploads /repositories/<id>/import_uploads ``super`` is called otherwise. """
if which in ( 'errata', 'files', 'packages', 'module_streams', 'puppet_modules', 'remove_content', 'sync', 'import_uploads', 'upload_content'): return '{0}/{1}'.format( super(Repository, self).path(which='self'), which ) return super(Repository, self).path(which)
def _getfunctionlist(self): """(internal use) """
try: eventhandler = self.obj.__eventhandler__ except AttributeError: eventhandler = self.obj.__eventhandler__ = {} return eventhandler.setdefault(self.event, [])
def get_download_url(self, instance, default=None): """Calculate the download url """
download = default # calculate the download url download = "{url}/at_download/{fieldname}".format( url=instance.absolute_url(), fieldname=self.get_field_name()) return download
def replace_return_line_item_by_id(cls, return_line_item_id, return_line_item, **kwargs): """Replace ReturnLineItem Replace all attributes of ReturnLineItem This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_return_line_item_by_id(return_line_item_id, return_line_item, async=True) >>> result = thread.get() :param async bool :param str return_line_item_id: ID of returnLineItem to replace (required) :param ReturnLineItem return_line_item: Attributes of returnLineItem to replace (required) :return: ReturnLineItem If the method is called asynchronously, returns the request thread. """
kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._replace_return_line_item_by_id_with_http_info(return_line_item_id, return_line_item, **kwargs) else: (data) = cls._replace_return_line_item_by_id_with_http_info(return_line_item_id, return_line_item, **kwargs) return data
def _find_regular_images(container, contentsinfo): """Find images stored in the container's /Resources /XObject Usually the container is a page, but it could also be a Form XObject that contains images. Generates images with their DPI at time of drawing. """
for pdfimage, xobj in _image_xobjects(container): # For each image that is drawn on this, check if we drawing the # current image - yes this is O(n^2), but n == 1 almost always for draw in contentsinfo.xobject_settings: if draw.name != xobj: continue if draw.stack_depth == 0 and _is_unit_square(draw.shorthand): # At least one PDF in the wild (and test suite) draws an image # when the graphics stack depth is 0, meaning that the image # gets drawn into a square of 1x1 PDF units (or 1/72", # or 0.35 mm). The equivalent DPI will be >100,000. Exclude # these from our DPI calculation for the page. continue yield ImageInfo(name=draw.name, pdfimage=pdfimage, shorthand=draw.shorthand)
def list(self, filter_name=None, filter_ids=None, filter_labels=None, page=None): """ This API endpoint returns a paginated list of the Servers associated with your New Relic account. Servers can be filtered by their name or by a list of server IDs. :type filter_name: str :param filter_name: Filter by server name :type filter_ids: list of ints :param filter_ids: Filter by server ids :type filter_labels: dict of label type: value pairs :param filter_labels: Filter by server labels :type page: int :param page: Pagination index :rtype: dict :return: The JSON response of the API, with an additional 'pages' key if there are paginated results :: { "servers": [ { "id": "integer", "account_id": "integer", "name": "string", "host": "string", "reporting": "boolean", "last_reported_at": "time", "summary": { "cpu": "float", "cpu_stolen": "float", "disk_io": "float", "memory": "float", "memory_used": "integer", "memory_total": "integer", "fullest_disk": "float", "fullest_disk_free": "integer" } } ], "pages": { "last": { "url": "https://api.newrelic.com/v2/servers.json?page=2", "rel": "last" }, "next": { "url": "https://api.newrelic.com/v2/servers.json?page=2", "rel": "next" } } } """
label_param = '' if filter_labels: label_param = ';'.join(['{}:{}'.format(label, value) for label, value in filter_labels.items()]) filters = [ 'filter[name]={0}'.format(filter_name) if filter_name else None, 'filter[ids]={0}'.format(','.join([str(app_id) for app_id in filter_ids])) if filter_ids else None, 'filter[labels]={0}'.format(label_param) if filter_labels else None, 'page={0}'.format(page) if page else None ] return self._get( url='{0}servers.json'.format(self.URL), headers=self.headers, params=self.build_param_string(filters) )
def set_replication(self, path, replication): r""" Set the replication of ``path`` to ``replication``\ . :type path: str :param path: the path of the file :type replication: int :param replication: the replication value :raises: :exc:`~exceptions.IOError` """
_complain_ifclosed(self.closed) return self.fs.set_replication(path, replication)
def skipper(func): """Decorator that memorizes base_dir, in_ext and out_ext from OPTIONS and skips execution for duplicates."""
@functools.wraps(func) def wrapped(): """Dummy docstring to make pylint happy.""" key = (OPTIONS['base_dir'], OPTIONS['in_ext'], OPTIONS['out_ext']) if key not in seen: seen[key] = func() return seen[key] seen = {} return wrapped
def make_driveritem_drivername(driver_name, condition='contains', negate=False, preserve_case=False): """ Create a node for DriverItem/DriverName :return: A IndicatorItem represented as an Element node """
document = 'DriverItem' search = 'DriverItem/DriverName' content_type = 'string' content = driver_name ii_node = ioc_api.make_indicatoritem_node(condition, document, search, content_type, content, negate=negate, preserve_case=preserve_case) return ii_node
def register_start(self, task, event_details=None): """ :meth:`.WSimpleTrackerStorage.register_start` method implementation """
if self.record_start() is True: record_type = WTrackerEvents.start record = WSimpleTrackerStorage.Record(record_type, task, event_details=event_details) self.__store_record(record)
def elements(self): """Iterator over elements repeating each as many times as its count. >>> c = Counter('ABCABC') >>> sorted(c.elements()) ['A', 'A', 'B', 'B', 'C', 'C'] If an element's count has been set to zero or is a negative number, elements() will ignore it. """
for elem, count in self.iteritems(): for _ in repeat(None, count): yield elem
def connect_service(service, credentials, region_name = None, config = None, silent = False): """ Instantiates an AWS API client :param service: :param credentials: :param region_name: :param config: :param silent: :return: """
api_client = None try: client_params = {} client_params['service_name'] = service.lower() session_params = {} session_params['aws_access_key_id'] = credentials['AccessKeyId'] session_params['aws_secret_access_key'] = credentials['SecretAccessKey'] session_params['aws_session_token'] = credentials['SessionToken'] if region_name: client_params['region_name'] = region_name session_params['region_name'] = region_name if config: client_params['config'] = config aws_session = boto3.session.Session(**session_params) if not silent: infoMessage = 'Connecting to AWS %s' % service if region_name: infoMessage = infoMessage + ' in %s' % region_name printInfo('%s...' % infoMessage) api_client = aws_session.client(**client_params) except Exception as e: printException(e) return api_client
def _parse_versioning_config(self, (response, xml_bytes)): """Parse a C{VersioningConfiguration} XML document."""
root = XML(xml_bytes) mfa_delete = root.findtext("MfaDelete") status = root.findtext("Status") return VersioningConfiguration(mfa_delete=mfa_delete, status=status)
def members(self): """ Node members. Members include current node as well as Node's children. """
res = [self] for c in list(self.children.values()): res.extend(c.members) return res
def write(label, plist, scope=USER): """ Writes the given property list to the appropriate file on disk and returns the absolute filename. :param plist: dict :param label: string :param scope: oneOf(USER, USER_ADMIN, DAEMON_ADMIN, USER_OS, DAEMON_OS) """
fname = compute_filename(label, scope) with open(fname, "wb") as f: plistlib.writePlist(plist, f) return fname
def _set_params_callback(self, **params): """Special handling for setting params on callbacks."""
# model after sklearn.utils._BaseCompostion._set_params # 1. All steps if 'callbacks' in params: setattr(self, 'callbacks', params.pop('callbacks')) # 2. Step replacement names, _ = zip(*getattr(self, 'callbacks_')) for key in params.copy(): name = key[11:] # drop 'callbacks__' if '__' not in name and name in names: self._replace_callback(name, params.pop(key)) # 3. Step parameters and other initilisation arguments for key in params.copy(): name = key[11:] part0, part1 = name.split('__') kwarg = {part1: params.pop(key)} callback = dict(self.callbacks_).get(part0) if callback is not None: callback.set_params(**kwarg) else: raise ValueError( "Trying to set a parameter for callback {} " "which does not exist.".format(part0)) return self
def set_or_edit_conditional_breakpoint(self): """Set conditional breakpoint"""
if self.data: editor = self.get_current_editor() editor.debugger.toogle_breakpoint(edit_condition=True)
def keys(self): """Return all valid keys"""
keys = [] for key, value in self.map.items(): if isinstance(value, Shovel): keys.extend([key + '.' + k for k in value.keys()]) else: keys.append(key) return sorted(keys)
def _docker_machine_ssl_context(): """ Create a SSLContext object using DOCKER_* env vars. """
context = ssl.SSLContext(ssl.PROTOCOL_TLS) context.set_ciphers(ssl._RESTRICTED_SERVER_CIPHERS) certs_path = os.environ.get("DOCKER_CERT_PATH", None) if certs_path is None: raise ValueError( "Cannot create ssl context, " "DOCKER_CERT_PATH is not set!" ) certs_path = Path(certs_path) context.load_verify_locations(cafile=certs_path / "ca.pem") context.load_cert_chain( certfile=certs_path / "cert.pem", keyfile=certs_path / "key.pem" ) return context
def refresh(self): """Obtain a new access token."""
grant_type = "https://oauth.reddit.com/grants/installed_client" self._request_token(grant_type=grant_type, device_id=self._device_id)
def intervals_union(S): """Union of intervals :param S: list of pairs (low, high) defining intervals [low, high) :returns: ordered list of disjoint intervals with the same union as S :complexity: O(n log n) """
E = [(low, -1) for (low, high) in S] E += [(high, +1) for (low, high) in S] nb_open = 0 last = None retval = [] for x, _dir in sorted(E): if _dir == -1: if nb_open == 0: last = x nb_open += 1 else: nb_open -= 1 if nb_open == 0: retval.append((last, x)) return retval
def start(self, project, **parameters): """Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for the global parameters. Returns a ``CLAMData`` object or raises exceptions. Note that no exceptions are raised on parameter errors, you have to check for those manually! (Use startsafe instead if want Exceptions on parameter errors):: response = client.start("myprojectname", parameter1="blah", parameterX=4.2) """
#auth = None #if 'auth' in parameters: # auth = parameters['auth'] # del parameters['auth'] for key in parameters: if isinstance(parameters[key],list) or isinstance(parameters[key],tuple): parameters[key] = ",".join(parameters[key]) return self.request(project + '/', 'POST', parameters)
def entity_type(self, entity_type): """Sets the entity_type of this SavedSearch. The Wavefront entity type over which to search # noqa: E501 :param entity_type: The entity_type of this SavedSearch. # noqa: E501 :type: str """
if entity_type is None: raise ValueError("Invalid value for `entity_type`, must not be `None`") # noqa: E501 allowed_values = ["DASHBOARD", "ALERT", "MAINTENANCE_WINDOW", "NOTIFICANT", "EVENT", "SOURCE", "EXTERNAL_LINK", "AGENT", "CLOUD_INTEGRATION", "APPLICATION", "REGISTERED_QUERY", "USER", "USER_GROUP"] # noqa: E501 if entity_type not in allowed_values: raise ValueError( "Invalid value for `entity_type` ({0}), must be one of {1}" # noqa: E501 .format(entity_type, allowed_values) ) self._entity_type = entity_type
def create_sonos_playlist(self, title): """Create a new empty Sonos playlist. Args: title: Name of the playlist :rtype: :py:class:`~.soco.data_structures.DidlPlaylistContainer` """
response = self.avTransport.CreateSavedQueue([ ('InstanceID', 0), ('Title', title), ('EnqueuedURI', ''), ('EnqueuedURIMetaData', ''), ]) item_id = response['AssignedObjectID'] obj_id = item_id.split(':', 2)[1] uri = "file:///jffs/settings/savedqueues.rsq#{0}".format(obj_id) res = [DidlResource(uri=uri, protocol_info="x-rincon-playlist:*:*:*")] return DidlPlaylistContainer( resources=res, title=title, parent_id='SQ:', item_id=item_id)
def get_running_race(self, race_id): """ Gets a running race for a given identifier.t http://strava.github.io/api/v3/running_races/#list :param race_id: id for the race :rtype: :class:`stravalib.model.RunningRace` """
raw = self.protocol.get('/running_races/{id}', id=race_id) return model.RunningRace.deserialize(raw, bind_client=self)
def replace(document, search, replace): """ Replace all occurences of string with a different string, return updated document """
newdocument = document searchre = re.compile(search) for element in newdocument.iter(): if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements if element.text: if searchre.search(element.text): element.text = re.sub(search, replace, element.text) return newdocument
def _normalize_index(self, index, pipe=None): """Convert negative indexes into their positive equivalents."""
pipe = self.redis if pipe is None else pipe len_self = self.__len__(pipe) positive_index = index if index >= 0 else len_self + index return len_self, positive_index
def UploadType(cls, file_path): """ 上传, 一般,上传页面如果是input,原生file文件框, 如: <input type="file" id="test-image-file" name="test" accept="image/gif">,像这样的,定位到该元素,然后使用 send_keys 上传的文件的绝对路径 @param file_name: 文件名(文件必须存在在工程resource目录下) """
if not os.path.isabs(file_path): return False if os.path.isfile(file_path): cls.SendKeys(file_path) else: return False
def copy_metadata(self, other): """Copies all metadata from this file to the other file. Metadata is defined as everything in the top-level ``.attrs``. Parameters ---------- other : InferenceFile An open inference file to write the data to. """
logging.info("Copying metadata") # copy attributes for key in self.attrs.keys(): other.attrs[key] = self.attrs[key]
def set_warndays(name, warndays): """ Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7 """
pre_info = info(name) if warndays == pre_info['warn']: return True cmd = 'passwd -w {0} {1}'.format(warndays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['warn'] != pre_info['warn']: return post_info['warn'] == warndays return False
def add_execution_data(self, context_id, data): """Within a context, append data to the execution result. Args: context_id (str): the context id returned by create_context data (bytes): data to append Returns: (bool): True if the operation is successful, False if the context_id doesn't reference a known context. """
if context_id not in self._contexts: LOGGER.warning("Context_id not in contexts, %s", context_id) return False context = self._contexts.get(context_id) context.add_execution_data(data) return True
def get_buildout_config(buildout_filename): """Parse buildout config with zc.buildout ConfigParser """
print("[localhost] get_buildout_config: {0:s}".format(buildout_filename)) buildout = Buildout(buildout_filename, [('buildout', 'verbosity', '-100')]) while True: try: len(buildout.items()) break except OSError: pass return buildout
def _get_all_objs_of_type(type_, parent): """Get all attributes of the given type from the given object. Parameters ---------- type_ : The desired type parent : The object from which to get the attributes with type matching 'type_' Returns ------- A list (possibly empty) of attributes from 'parent' """
return set([obj for obj in parent.__dict__.values() if isinstance(obj, type_)])
def _play(self): """Send play command to receiver command via HTTP post."""
# Use pause command only for sources which support NETAUDIO if self._input_func in self._netaudio_func_list: body = {"cmd0": "PutNetAudioCommand/CurEnter", "cmd1": "aspMainZone_WebUpdateStatus/", "ZoneName": "MAIN ZONE"} try: if self.send_post_command( self._urls.command_netaudio_post, body): self._state = STATE_PLAYING return True else: return False except requests.exceptions.RequestException: _LOGGER.error("Connection error: play command not sent.") return False