code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def attach_mock(self, mock, attribute): """ Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one.""" mock._mock_parent = None mock._mock_new_pare...
Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one.
def _jars_to_directories(self, target): """Extracts and maps jars to directories containing their contents. :returns: a set of filepaths to directories containing the contents of jar. """ files = set() jar_import_products = self.context.products.get_data(JarImportProducts) imports = jar_import_...
Extracts and maps jars to directories containing their contents. :returns: a set of filepaths to directories containing the contents of jar.
def update_factor(self, name, body): """Update Guardian factor Useful to enable / disable factor Args: name (str): Either push-notification or sms body (dict): Attributes to modify. See: https://auth0.com/docs/api/management/v2#!/Guardian/put_factors_by_name ...
Update Guardian factor Useful to enable / disable factor Args: name (str): Either push-notification or sms body (dict): Attributes to modify. See: https://auth0.com/docs/api/management/v2#!/Guardian/put_factors_by_name
def connect(self): """ Method automatically called by the run() method of the AgentProxyThread """ if ('SSH_AUTH_SOCK' in os.environ) and (sys.platform != 'win32'): conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: retry_on_signal(lambd...
Method automatically called by the run() method of the AgentProxyThread
def verify_high(self, high): ''' Verify that the high data is viable and follows the data structure ''' errors = [] if not isinstance(high, dict): errors.append('High data is not a dictionary and is invalid') reqs = OrderedDict() for name, body in six....
Verify that the high data is viable and follows the data structure
def register_activity_type(domain=None, name=None, version=None, description=None, defaultTaskStartToCloseTimeout=None, defaultTaskHeartbeatTimeout=None, defaultTaskList=None, defaultTaskPriority=None, defaultTaskScheduleToStartTimeout=None, defaultTaskScheduleToCloseTimeout=None): """ Registers a new activity ...
Registers a new activity type along with its configuration settings in the specified domain. Access Control You can use IAM policies to control this action's access to Amazon SWF resources as follows: If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outsi...
def pdf_from_post(self): """Returns a pdf stream with the stickers """ html = self.request.form.get("html") style = self.request.form.get("style") reporthtml = "<html><head>{0}</head><body>{1}</body></html>" reporthtml = reporthtml.format(style, html) reporthtml =...
Returns a pdf stream with the stickers
def _launch_editor(starting_text=''): "Launch editor, let user write text, then return that text." # TODO: What is a reasonable default for windows? Does this approach even # make sense on windows? editor = os.environ.get('EDITOR', 'vim') with tempfile.TemporaryDirectory() as dirname: filen...
Launch editor, let user write text, then return that text.
def to_python(self, value): """ Strips any dodgy HTML tags from the input """ if value in self.empty_values: try: return self.empty_value except AttributeError: # CharField.empty_value was introduced in Django 1.11; in prior ...
Strips any dodgy HTML tags from the input
def compute_return(self, start_date, end_date, rate="MID"): """ Compute the return of the currency between two dates """ if rate not in ["MID", "ASK", "BID"]: raise ValueError("Unknown rate type (%s)- must be 'MID', 'ASK' or 'BID'" % str(rate)) if end_date <= start_d...
Compute the return of the currency between two dates
def merge_pot1_files(self, delete_source=True): """ This method is called when all the q-points have been computed. It runs `mrgdvdb` in sequential on the local machine to produce the final DVDB file in the outdir of the `Work`. Args: delete_source: True if POT1 file...
This method is called when all the q-points have been computed. It runs `mrgdvdb` in sequential on the local machine to produce the final DVDB file in the outdir of the `Work`. Args: delete_source: True if POT1 files should be removed after (successful) merge. Returns: ...
def writeB1logfile(filename, data): """Write a header structure into a B1 logfile. Inputs: filename: name of the file. data: header dictionary Notes: exceptions pass through to the caller. """ allkeys = list(data.keys()) f = open(filename, 'wt', encoding='utf-8') fo...
Write a header structure into a B1 logfile. Inputs: filename: name of the file. data: header dictionary Notes: exceptions pass through to the caller.
def transform_api_header_authorization(param, value): """Transform a username:password value into a base64 string.""" try: username, password = value.split(":", 1) except ValueError: raise click.BadParameter( "Authorization header needs to be Authorization=username:password", ...
Transform a username:password value into a base64 string.
def add_mip_obj(model): """Add a mixed-integer version of a minimal medium to the model. Changes the optimization objective to finding the medium with the least components:: minimize size(R) where R part of import_reactions Arguments --------- model : cobra.model The model to ...
Add a mixed-integer version of a minimal medium to the model. Changes the optimization objective to finding the medium with the least components:: minimize size(R) where R part of import_reactions Arguments --------- model : cobra.model The model to modify.
def file_type(self, file): """Use python-magic to determine file type. Returns 'png' or 'jpg' on success, nothing on failure. """ try: magic_text = magic.from_file(file) if (isinstance(magic_text, bytes)): # In python2 and travis python3 (?!) deco...
Use python-magic to determine file type. Returns 'png' or 'jpg' on success, nothing on failure.
def get_limits(self, coord='data'): """Get the bounding box of the viewer extents. Returns ------- limits : tuple Bounding box in coordinates of type `coord` in the form of ``(ll_pt, ur_pt)``. """ limits = self.t_['limits'] if limits ...
Get the bounding box of the viewer extents. Returns ------- limits : tuple Bounding box in coordinates of type `coord` in the form of ``(ll_pt, ur_pt)``.
def zoom_in(self): """Increase zoom factor and redraw TimeLine""" index = self._zoom_factors.index(self._zoom_factor) if index + 1 == len(self._zoom_factors): # Already zoomed in all the way return self._zoom_factor = self._zoom_factors[index + 1] if self....
Increase zoom factor and redraw TimeLine
def load_image(self, idx): """ Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order """ im = Image.open('{}/Images/spatial_envelope_256x256_static_8outdoorcate...
Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order
def get_activity_lookup_session(self, proxy, *args, **kwargs): """Gets the ``OsidSession`` associated with the activity lookup service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ActivityLookupSession`` :rtype: ``osid.learning.ActivityLookupSession`` ...
Gets the ``OsidSession`` associated with the activity lookup service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ActivityLookupSession`` :rtype: ``osid.learning.ActivityLookupSession`` :raise: ``NullArgument`` -- ``proxy`` is ``null`` :raise: `...
def create_call(self, raw_request, **kwargs): """create a call object that has endpoints understandable request and response instances""" req = self.create_request(raw_request, **kwargs) res = self.create_response(**kwargs) rou = self.create_router(**kwargs) c = self.call...
create a call object that has endpoints understandable request and response instances
def _define(self): """ gate cu3(theta,phi,lambda) c, t { u1((lambda-phi)/2) t; cx c,t; u3(-theta/2,0,-(phi+lambda)/2) t; cx c,t; u3(theta/2,phi,0) t; } """ definition = [] q = QuantumRegister(2, "q") rule = [ (U1Gate((self.p...
gate cu3(theta,phi,lambda) c, t { u1((lambda-phi)/2) t; cx c,t; u3(-theta/2,0,-(phi+lambda)/2) t; cx c,t; u3(theta/2,phi,0) t; }
def _set_axis_ticks(self, axis, ticks, log=False, rotation=0): """ Allows setting the ticks for a particular axis either with a tuple of ticks, a tick locator object, an integer number of ticks, a list of tuples containing positions and labels or a list of positions. Also support...
Allows setting the ticks for a particular axis either with a tuple of ticks, a tick locator object, an integer number of ticks, a list of tuples containing positions and labels or a list of positions. Also supports enabling log ticking if an integer number of ticks is supplied and settin...
def _add_var(var, value): ''' Add a new var to the make.conf. If using layman, the source line for the layman make.conf needs to be at the very end of the config. This ensures that the new var will be above the source line. ''' makeconf = _get_makeconf() layman = 'source /var/lib/layman/...
Add a new var to the make.conf. If using layman, the source line for the layman make.conf needs to be at the very end of the config. This ensures that the new var will be above the source line.
def full_text(self, level: int = 1) -> str: """ Returns text of the current section as well as all its subsections. :param level: indentation level :return: text of the current section as well as all its subsections """ res = "" if self.wiki.extract_format == Ext...
Returns text of the current section as well as all its subsections. :param level: indentation level :return: text of the current section as well as all its subsections
def QA_fetch_index_list_adv(collections=DATABASE.index_list): ''' '获取股票列表' :param collections: mongodb 数据库 :return: DataFrame ''' index_list_items = QA_fetch_index_list(collections) if len(index_list_items) == 0: print("QA Error QA_fetch_index_list_adv call item for item in collectio...
'获取股票列表' :param collections: mongodb 数据库 :return: DataFrame
def is_active(self, timeout=2): """ :param timeout: int :return: boolean """ try: result = Result(*self.perform_request('HEAD', '/', params={'request_timeout': timeout})) except ConnectionError: return False except TransportError: ...
:param timeout: int :return: boolean
def step(self, observations): """ Sample action from an action space for given state """ log_histogram = self(observations) actions = self.q_head.sample(log_histogram) return { 'actions': actions, 'log_histogram': log_histogram }
Sample action from an action space for given state
def print_square(row_queue, t): """ Prints a row queue as its conceptual square array. """ occupied_rows = {y: row for _, y, row in row_queue} empty_row = ', '.join('...' for _ in range(t)) for y in range(t): print('|', end=' ') if y not in occupied_rows: print(empty...
Prints a row queue as its conceptual square array.
def match_regexp(self, value, q, strict=False): """if value matches a regexp q""" value = stringify(value) mr = re.compile(q) if value is not None: if mr.match(value): return self.shout('%r not matching the regexp %r', strict, value, q)
if value matches a regexp q
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_low_priority(priority) self.needs_no_rtr(rtr) #self.needs_data(data, 6) self.set_attributes(priority, address, rtr) self.module_type =...
:return: None
def rec_edit(self, zone, record_type, record_id, name, content, ttl=1, service_mode=None, priority=None, service=None, service_name=None, protocol=None, weight=None, port=None, target=None): """ Edit a DNS record for the given zone. :param zone: domain name :type zone: s...
Edit a DNS record for the given zone. :param zone: domain name :type zone: str :param record_type: Type of DNS record. Valid values are [A/CNAME/MX/TXT/SPF/AAAA/NS/SRV/LOC] :type record_type: str :param record_id: DNS Record ID. Available by using the rec_load_all call. :...
def V_horiz_spherical(D, L, a, h, headonly=False): r'''Calculates volume of a tank with spherical heads, according to [1]_. .. math:: V_f = A_fL + \frac{\pi a}{6}(3R^2 + a^2),\;\; h = R, |a|\le R .. math:: V_f = A_fL + \frac{\pi a}{3}(3R^2 + a^2),\;\; h = D, |a|\le R .. math:: ...
r'''Calculates volume of a tank with spherical heads, according to [1]_. .. math:: V_f = A_fL + \frac{\pi a}{6}(3R^2 + a^2),\;\; h = R, |a|\le R .. math:: V_f = A_fL + \frac{\pi a}{3}(3R^2 + a^2),\;\; h = D, |a|\le R .. math:: V_f = A_fL + \pi a h^2\left(1 - \frac{h}{3R}\right),\;...
def simple_ins_from_obs(obsnames, insfilename='model.output.ins'): """ writes an instruction file that assumes wanting to read the values names in obsnames in order one per line from a model output file Args: obsnames: list of obsnames to read in insfilename: filename for INS file (defau...
writes an instruction file that assumes wanting to read the values names in obsnames in order one per line from a model output file Args: obsnames: list of obsnames to read in insfilename: filename for INS file (default: model.output.ins) Returns: writes a file <insfilename> with ea...
def build_rank_score_dict(rank_scores): """ Take a list with annotated rank scores for each family and returns a dictionary with family_id as key and a list of genetic models as value. Args: rank_scores : A list on the form ['1:12','2:20'] Returns: scores : A dict...
Take a list with annotated rank scores for each family and returns a dictionary with family_id as key and a list of genetic models as value. Args: rank_scores : A list on the form ['1:12','2:20'] Returns: scores : A dictionary with family id:s as key and scores as value ...
def _remove(self, removeList, selfValue): '''Remove elements from a list by matching the elements in the other list. This method only looks inside current instance's value, not recursive. There is no need for a recursive one anyway. Match by == operation. Args: remo...
Remove elements from a list by matching the elements in the other list. This method only looks inside current instance's value, not recursive. There is no need for a recursive one anyway. Match by == operation. Args: removeList (list): The list of matching elements. ...
def write_compounds(self, stream, compounds, properties=None): """Write iterable of compounds as YAML object to stream. Args: stream: File-like object. compounds: Iterable of compound entries. properties: Set of compound properties to output (or None to output ...
Write iterable of compounds as YAML object to stream. Args: stream: File-like object. compounds: Iterable of compound entries. properties: Set of compound properties to output (or None to output all).
def parse_bind(bind): """Parses a connection string and creates SQL trace metadata""" if isinstance(bind, Connection): engine = bind.engine else: engine = bind m = re.match(r"Engine\((.*?)\)", str(engine)) if m is not None: u = urlparse(m.group(1)) # Add Scheme to use...
Parses a connection string and creates SQL trace metadata
def draw(self): ''' Draws samples from the `true` distribution. Returns: `np.ndarray` of samples. ''' if self.__conditional_flag is True: return np.concatenate((self.__create_samples(), self.__create_samples()), axis=1) else: ...
Draws samples from the `true` distribution. Returns: `np.ndarray` of samples.
def replace_parameter(self, name, value=None): """ Replace a query parameter values with a new value. If a new value does not match current specifications, then exception is raised :param name: parameter name to replace :param value: new parameter value. None is for empty (null) value :return: None """ s...
Replace a query parameter values with a new value. If a new value does not match current specifications, then exception is raised :param name: parameter name to replace :param value: new parameter value. None is for empty (null) value :return: None
def run_analysis(self, argv): """Run this analysis""" args = self._parser.parse_args(argv) # Read the input maps ccube_dirty = HpxMap.create_from_fits(args.ccube_dirty, hdu='SKYMAP') bexpcube_dirty = HpxMap.create_from_fits(args.bexpcube_dirty, hdu='HPXEXPOSURES') ccube_...
Run this analysis
def import_certificate( ctx, slot, management_key, pin, cert, password, verify): """ Import a X.509 certificate. Write a certificate to one of the slots on the YubiKey. \b SLOT PIV slot to import the certificate to. CERTIFICATE File containing the certificate. Use '-' to...
Import a X.509 certificate. Write a certificate to one of the slots on the YubiKey. \b SLOT PIV slot to import the certificate to. CERTIFICATE File containing the certificate. Use '-' to use stdin.
def get_num_confirmations(tx_hash, coin_symbol='btc', api_key=None): ''' Given a tx_hash, return the number of confirmations that transactions has. Answer is going to be from 0 - current_block_height. ''' return get_transaction_details(tx_hash=tx_hash, coin_symbol=coin_symbol, limit=1, ...
Given a tx_hash, return the number of confirmations that transactions has. Answer is going to be from 0 - current_block_height.
def _processMsg(self, type, msg): """ Process Debug Messages """ now = datetime.datetime.now() # Check If Path not provided if self.LOG_FILE_PATH == '': self.LOG_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) + '/' # Build absolute Path log_file = se...
Process Debug Messages
def create_cursor(self, name=None): """Creates a cursor. Assumes that a connection is established.""" cursor = self.connection.cursor() cursor.tzinfo_factory = self.tzinfo_factory return cursor
Creates a cursor. Assumes that a connection is established.
def on_drag_data_received(self, widget, context, x, y, data, info, time): """Receives state_id from LibraryTree and moves the state to the position of the mouse :param widget: :param context: :param x: Integer: x-position of mouse :param y: Integer: y-position of mouse :...
Receives state_id from LibraryTree and moves the state to the position of the mouse :param widget: :param context: :param x: Integer: x-position of mouse :param y: Integer: y-position of mouse :param data: SelectionData: contains state_id :param info: :param time...
def close(self): """ Closes this QEMU VM. """ if not (yield from super().close()): return False self.acpi_shutdown = False yield from self.stop() for adapter in self._ethernet_adapters: if adapter is not None: for nio in ...
Closes this QEMU VM.
def select_newest_project(dx_project_ids): """ Given a list of DNAnexus project IDs, returns the one that is newest as determined by creation date. Args: dx_project_ids: `list` of DNAnexus project IDs. Returns: `str`. """ if len(dx_project_ids) == 1: return dx_proj...
Given a list of DNAnexus project IDs, returns the one that is newest as determined by creation date. Args: dx_project_ids: `list` of DNAnexus project IDs. Returns: `str`.
def activateRandomLocation(self): """ Set the location to a random point. """ self.activePhases = np.array([np.random.random(2)]) if self.anchoringMethod == "discrete": # Need to place the phase in the middle of a cell self.activePhases = np.floor( self.activePhases * self.cellDi...
Set the location to a random point.
def save(self, output_file, overwrite=False): """Save the model to disk""" if os.path.exists(output_file) and overwrite is False: raise ModelFileExists("The file %s exists already. If you want to overwrite it, use the 'overwrite=True' " "options as 'model...
Save the model to disk
def urlunparse(data): """Put a parsed URL back together again. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had redundant delimiters, e.g. a ? with an empty query (the draft states that these are equivalent).""" scheme, netloc, url, params, quer...
Put a parsed URL back together again. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had redundant delimiters, e.g. a ? with an empty query (the draft states that these are equivalent).
def get_exchange_rates(self, **params): """https://developers.coinbase.com/api/v2#exchange-rates""" response = self._get('v2', 'exchange-rates', params=params) return self._make_api_object(response, APIObject)
https://developers.coinbase.com/api/v2#exchange-rates
def edit_custom_examples(program, config): """ Edit custom examples for the given program, creating the file if it does not exist. """ if (not config.custom_dir) or (not os.path.exists(config.custom_dir)): _inform_cannot_edit_no_custom_dir() return # resolve aliases resolved...
Edit custom examples for the given program, creating the file if it does not exist.
def _match_net(self, net): """Match a query for a specific network/list of networks""" if self.network: return match_list(self.network, net) else: return True
Match a query for a specific network/list of networks
def _make_scaled_srcmap(self): """Make an exposure cube with the same binning as the counts map.""" self.logger.info('Computing scaled source map.') bexp0 = fits.open(self.files['bexpmap_roi']) bexp1 = fits.open(self.config['gtlike']['bexpmap']) srcmap = fits.open(self.config['...
Make an exposure cube with the same binning as the counts map.
def removeCallback(cls, eventType, func, record=None): """ Removes a callback from the model's event callbacks. :param eventType: <str> :param func: <callable> """ callbacks = cls.callbacks() callbacks.setdefault(eventType, []) for i in xrange(len(callb...
Removes a callback from the model's event callbacks. :param eventType: <str> :param func: <callable>
def fetch(dbconn, tablename, n=1, uuid=None, end=True): """ Returns `n` rows from the table's start or end :param dbconn: database connection :param tablename: name of the table :param n: number of rows to return from the end of the table :param uuid: Optional UUID to select from :return: If...
Returns `n` rows from the table's start or end :param dbconn: database connection :param tablename: name of the table :param n: number of rows to return from the end of the table :param uuid: Optional UUID to select from :return: If n > 1, a list of rows. If n=1, a single row
def _get_fields(self, event, pull, message=None): """Constructs a dictionary of fields and replacement values based on the specified event and the status of the pull request. :arg event: one of ["start", "error", "finish"]. :arg pull: an instance of PullRequest that has details ...
Constructs a dictionary of fields and replacement values based on the specified event and the status of the pull request. :arg event: one of ["start", "error", "finish"]. :arg pull: an instance of PullRequest that has details about the current status of the pull request testin...
def find_ent_endurance_tier_price(package, tier_level): """Find the price in the given package with the specified tier level :param package: The Enterprise (Endurance) product package :param tier_level: The endurance tier for which a price is desired :return: Returns the price for the given tier, or an...
Find the price in the given package with the specified tier level :param package: The Enterprise (Endurance) product package :param tier_level: The endurance tier for which a price is desired :return: Returns the price for the given tier, or an error if not found
def repr2(x): """Analogous to repr(), but will suppress 'u' prefix when repr-ing a unicode string.""" s = repr(x) if len(s) >= 2 and s[0] == "u" and (s[1] == "'" or s[1] == '"'): s = s[1:] return s
Analogous to repr(), but will suppress 'u' prefix when repr-ing a unicode string.
def send_to_redshift( instance, data, replace=True, batch_size=1000, types=None, primary_key=(), create_boolean=False): """ data = { "table_name" : 'name_of_the_redshift_schema' + '.' + 'name_of_the_redshift_table' #Must already exist, "co...
data = { "table_name" : 'name_of_the_redshift_schema' + '.' + 'name_of_the_redshift_table' #Must already exist, "columns_name" : [first_column_name,second_column_name,...,last_column_name], "rows" : [[first_raw_value,second_raw_value,...,last_raw_value],...] }
def embed_snippet(views, drop_defaults=True, state=None, indent=2, embed_url=None, requirejs=True, cors=True ): """Return a snippet that can be embedded in an HTML file. Parameters -...
Return a snippet that can be embedded in an HTML file. Parameters ---------- {views_attribute} {embed_kwargs} Returns ------- A unicode string with an HTML snippet containing several `<script>` tags.
def private_vlan_mode(self, **kwargs): """Set PVLAN mode (promiscuous, host, trunk). Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, etc) name (str): Name of interface. (1/0/5, 1/0/10, etc) mode (str): The switchport PVL...
Set PVLAN mode (promiscuous, host, trunk). Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, etc) name (str): Name of interface. (1/0/5, 1/0/10, etc) mode (str): The switchport PVLAN mode. callback (function): A functi...
def load(self): """Load the projects config data from local path Returns: Dict: project_name -> project_data """ projects = {} path = os.path.expanduser(self.path) if not os.path.isdir(path): return projects logger.debug("Load project c...
Load the projects config data from local path Returns: Dict: project_name -> project_data
def allow_network_access_grading(self): """ Return True if the grading container should have access to the network """ vals = self._hook_manager.call_hook('task_network_grading', course=self.get_course(), task=self, default=self._network_grading) return vals[0] if len(vals) else self._network_gr...
Return True if the grading container should have access to the network
def create_package(self, output=None): """ Ensure that the package can be properly configured, and then create it. """ # Create the Lambda zip package (includes project and virtualenvironment) # Also define the path the handler file so it can be copied to the zip ...
Ensure that the package can be properly configured, and then create it.
def export(self, nidm_version, export_dir): """ Create prov entities and activities. """ # In FSL we have a single thresholding (extent, height) applied to all # contrasts # FIXME: Deal with two-tailed inference? atts = ( (PROV['type'], self.type), ...
Create prov entities and activities.
def visit_ClassDef(self, node): # pylint: disable=invalid-name """Visit top-level classes.""" # Resolve everything as root scope contains everything from the process module. for base in node.bases: # Cover `from resolwe.process import ...`. if isinstance(base, ast.Name) ...
Visit top-level classes.
def get_users_in_project(self, projectname): """ Get list of users in project from MAM. """ ds_project = self.get_project(projectname) if ds_project is None: logger.error( "Project '%s' does not exist in MAM" % projectname) raise RuntimeError( ...
Get list of users in project from MAM.
def get_dhcp_options(dhcp_options_name=None, dhcp_options_id=None, region=None, key=None, keyid=None, profile=None): ''' Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfu...
Return a dict with the current values of the requested DHCP options set CLI Example: .. code-block:: bash salt myminion boto_vpc.get_dhcp_options 'myfunnydhcpoptionsname' .. versionadded:: 2016.3.0
def present_active_subjunctive(self): """ Strong verbs I >>> verb = StrongOldNorseVerb() >>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"]) >>> verb.present_active_subjunctive() ['líta', 'lítir', 'líti', 'lítim', 'lítið', 'líti'] II ...
Strong verbs I >>> verb = StrongOldNorseVerb() >>> verb.set_canonic_forms(["líta", "lítr", "leit", "litu", "litinn"]) >>> verb.present_active_subjunctive() ['líta', 'lítir', 'líti', 'lítim', 'lítið', 'líti'] II >>> verb = StrongOldNorseVerb() >>> verb.se...
def get_spaces(self, space_key=None, expand=None, start=None, limit=None, callback=None): """ Returns information about the spaces present in the Confluence instance. :param space_key (string): OPTIONAL: A list of space keys to filter on. Default: None. :param expand (string): OPTIONAL: ...
Returns information about the spaces present in the Confluence instance. :param space_key (string): OPTIONAL: A list of space keys to filter on. Default: None. :param expand (string): OPTIONAL: A comma separated list of properties to expand on the spaces. Default: Empty ...
def ext_pillar(hyper_id, pillar, name, key): ''' Accept the key for the VM on the hyper, if authorized. ''' vk = salt.utils.virt.VirtKey(hyper_id, name, __opts__) ok = vk.accept(key) pillar['virtkey'] = {name: ok} return {}
Accept the key for the VM on the hyper, if authorized.
def default_logging(grab_log=None, # '/tmp/grab.log', network_log=None, # '/tmp/grab.network.log', level=logging.DEBUG, mode='a', propagate_network_logger=False): """ Customize logging output to display all log messages except grab network logs. ...
Customize logging output to display all log messages except grab network logs. Redirect grab network logs into file.
def output_xml(self, text): """ Output results in JSON format """ # Create the main document nodes document = Element('results') comment = Comment('Generated by TrueSight Pulse measurement-get CLI') document.append(comment) aggregates = SubElement(documen...
Output results in JSON format
def make_generic_c_patterns(keywords, builtins, instance=None, define=None, comment=None): "Strongly inspired from idlelib.ColorDelegator.make_pat" kw = r"\b" + any("keyword", keywords.split()) + r"\b" builtin = r"\b" + any("builtin", builtins.split()+C_TYPES.split()) + r"\b"...
Strongly inspired from idlelib.ColorDelegator.make_pat
def memberness(context): '''The likelihood that the context is a "member".''' if context: texts = context.xpath('.//*[local-name()="explicitMember"]/text()').extract() text = str(texts).lower() if len(texts) > 1: return 2 elif 'country' in text: return 2 ...
The likelihood that the context is a "member".
def _load_model(self): """ Loads the peg and the hole models. """ super()._load_model() self.mujoco_robot.set_base_xpos([0, 0, 0]) # Add arena and robot self.model = MujocoWorldBase() self.arena = EmptyArena() if self.use_indicator_object: ...
Loads the peg and the hole models.
def set_(device, **kwargs): ''' Calls out to setquota, for a specific user or group CLI Example: .. code-block:: bash salt '*' quota.set /media/data user=larry block-soft-limit=1048576 salt '*' quota.set /media/data group=painters file-hard-limit=1000 ''' empty = {'block-soft-...
Calls out to setquota, for a specific user or group CLI Example: .. code-block:: bash salt '*' quota.set /media/data user=larry block-soft-limit=1048576 salt '*' quota.set /media/data group=painters file-hard-limit=1000
def _decode_argv(self, argv, enc=None): """decode argv if bytes, using stin.encoding, falling back on default enc""" uargv = [] if enc is None: enc = DEFAULT_ENCODING for arg in argv: if not isinstance(arg, unicode): # only decode if not already de...
decode argv if bytes, using stin.encoding, falling back on default enc
def run(self): """Main thread for processing messages.""" self.OnStartup() try: while True: message = self._in_queue.get() # A message of None is our terminal message. if message is None: break try: self.HandleMessage(message) # Catch a...
Main thread for processing messages.
def ExecuteCmd(cmd, quiet=False): """ Run a command in a shell. """ result = None if quiet: with open(os.devnull, "w") as fnull: result = subprocess.call(cmd, shell=True, stdout=fnull, stderr=fnull) else: result = subprocess.call(cmd, shell=True) return result
Run a command in a shell.
def tar_add_bytes(tf, filename, bytestring): """ Add a file to a tar archive Args: tf (tarfile.TarFile): tarfile to add the file to filename (str): path within the tar file bytestring (bytes or str): file contents. Must be :class:`bytes` or ascii-encodable :class:`str` "...
Add a file to a tar archive Args: tf (tarfile.TarFile): tarfile to add the file to filename (str): path within the tar file bytestring (bytes or str): file contents. Must be :class:`bytes` or ascii-encodable :class:`str`
def perm_by_group_and_perm_name( cls, resource_id, group_id, perm_name, db_session=None ): """ fetch permissions by group and permission name :param resource_id: :param group_id: :param perm_name: :param db_session: :return: """ db_ses...
fetch permissions by group and permission name :param resource_id: :param group_id: :param perm_name: :param db_session: :return:
def add_user_to_user_groups(self, id, **kwargs): # noqa: E501 """Adds specific user groups to the user # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.add_use...
Adds specific user groups to the user # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.add_user_to_user_groups(id, async_req=True) >>> result = thread.get() ...
def getfile2(url, auth=None, outdir=None): """Function to fetch files using requests Works with https authentication """ import requests print("Retrieving: %s" % url) fn = os.path.split(url)[-1] if outdir is not None: fn = os.path.join(outdir, fn) if auth is not None: r...
Function to fetch files using requests Works with https authentication
def get_resource_url(cls, resource, base_url): """ Construct the URL for talking to this resource. i.e.: http://myapi.com/api/resource Note that this is NOT the method for calling individual instances i.e. http://myapi.com/api/resource/1 Args: res...
Construct the URL for talking to this resource. i.e.: http://myapi.com/api/resource Note that this is NOT the method for calling individual instances i.e. http://myapi.com/api/resource/1 Args: resource: The resource class instance base_url: The Base U...
def save_loop(filename, framerate=30, time=3.0, axis=np.array([0.,0.,1.]), clf=True, **kwargs): """Off-screen save a GIF of one rotation about the scene. Parameters ---------- filename : str The filename in which to save the output image (should have extension .gif) ...
Off-screen save a GIF of one rotation about the scene. Parameters ---------- filename : str The filename in which to save the output image (should have extension .gif) framerate : int The frame rate at which to animate motion. time : float The...
def _fire_event(self, event_name, *event_args, **event_kwargs): """Execute all the handlers associated with given event. This method executes all handlers associated with the event `event_name`. Optional positional and keyword arguments can be used to pass arguments to **all** handlers ...
Execute all the handlers associated with given event. This method executes all handlers associated with the event `event_name`. Optional positional and keyword arguments can be used to pass arguments to **all** handlers added with this event. These aguments updates arguments passed usin...
def read(self): """Read data from serial port and returns a ``bytearray``.""" data = bytearray() while True: incoming_bytes = self.comport.inWaiting() if incoming_bytes == 0: break else: content = self.comport.read(size=incoming...
Read data from serial port and returns a ``bytearray``.
def wrap(self, starter_cls): """ If starter_cls is not a ProcessStarter, assume it's the legacy preparefunc and return it bound to a CompatStarter. """ if isinstance(starter_cls, type) and issubclass(starter_cls, ProcessStarter): return starter_cls depr_msg = ...
If starter_cls is not a ProcessStarter, assume it's the legacy preparefunc and return it bound to a CompatStarter.
def data_to_binary(self): """ :return: bytes """ return bytes([ COMMAND_CODE, self.channels_to_byte(self.led_on), self.channels_to_byte(self.led_slow_blinking), self.channels_to_byte(self.led_fast_blinking) ])
:return: bytes
def list(self): """Get a list of the names of the functions stored in this database.""" return [x["_id"] for x in self._db.system.js.find(projection=["_id"])]
Get a list of the names of the functions stored in this database.
def get_translations_sorted(codes): """ Returns a sorted list of (code, translation) tuples for codes """ codes = codes or self.codes return self._get_priority_translations(priority, codes)
Returns a sorted list of (code, translation) tuples for codes
def labels(self): """All labels present in the match patterns. RETURNS (set): The string labels. DOCS: https://spacy.io/api/entityruler#labels """ all_labels = set(self.token_patterns.keys()) all_labels.update(self.phrase_patterns.keys()) return tuple(all_labels...
All labels present in the match patterns. RETURNS (set): The string labels. DOCS: https://spacy.io/api/entityruler#labels
def send(self, node_id, request, wakeup=True): """Send a request to a specific node. Bytes are placed on an internal per-connection send-queue. Actual network I/O will be triggered in a subsequent call to .poll() Arguments: node_id (int): destination node request...
Send a request to a specific node. Bytes are placed on an internal per-connection send-queue. Actual network I/O will be triggered in a subsequent call to .poll() Arguments: node_id (int): destination node request (Struct): request object (not-encoded) wakeup...
def restoreSettings(self, settings): """ Restores the files for this menu from the settings. :param settings | <QSettings> """ value = unwrapVariant(settings.value('recent_files')) if value: self.setFilenames(value.split(os.path.pathsep))
Restores the files for this menu from the settings. :param settings | <QSettings>
def run(self): """Starts the sender.""" # Create the thread pool. executor = concurrent.futures.ThreadPoolExecutor( max_workers=self._config['num_workers']) # Wait to ensure multiple senders can be synchronised. now = int(datetime.datetime.utcnow().timestamp()) ...
Starts the sender.
def plot(self, channel_names, kind='histogram', gates=None, gate_colors=None, gate_lw=1, **kwargs): """Plot the flow cytometry data associated with the sample on the current axis. To produce the plot, follow up with a call to matplotlib's show() function. Parameters ------...
Plot the flow cytometry data associated with the sample on the current axis. To produce the plot, follow up with a call to matplotlib's show() function. Parameters ---------- {graph_plotFCM_pars} {FCMeasurement_plot_pars} {common_plot_ax} gates : [None, Gate, li...
def get_cursor(cls, cursor_type=_CursorType.PLAIN) -> Cursor: """ Yields: new client-side cursor from existing db connection pool """ _cur = None if cls._use_pool: _connection_source = yield from cls.get_pool() else: _connection_source ...
Yields: new client-side cursor from existing db connection pool
def apply_T5(word): # BROKEN '''If a (V)VVV-sequence contains a VV-sequence that could be an /i/-final diphthong, there is a syllable boundary between it and the third vowel, e.g., [raa.ois.sa], [huo.uim.me], [la.eis.sa], [sel.vi.äi.si], [tai.an], [säi.e], [oi.om.me].''' T5 = '' WORD = word.spl...
If a (V)VVV-sequence contains a VV-sequence that could be an /i/-final diphthong, there is a syllable boundary between it and the third vowel, e.g., [raa.ois.sa], [huo.uim.me], [la.eis.sa], [sel.vi.äi.si], [tai.an], [säi.e], [oi.om.me].