positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def GetBatchJob(client, batch_job_id): """Retrieves the BatchJob with the given id. Args: client: an instantiated AdWordsClient used to retrieve the BatchJob. batch_job_id: a long identifying the BatchJob to be retrieved. Returns: The BatchJob associated with the given id. """ batch_job_service =...
Retrieves the BatchJob with the given id. Args: client: an instantiated AdWordsClient used to retrieve the BatchJob. batch_job_id: a long identifying the BatchJob to be retrieved. Returns: The BatchJob associated with the given id.
def on_success(self, retval, task_id, args, kwargs): """ Store results in the backend even if we're always eager. This ensures the `delay_or_run` calls always at least have results. """ if self.request.is_eager: # Store the result because celery wouldn't otherwise ...
Store results in the backend even if we're always eager. This ensures the `delay_or_run` calls always at least have results.
def handle_add(queue_name): """Adds a task to a queue.""" source = request.form.get('source', request.remote_addr, type=str) try: task_id = work_queue.add( queue_name, payload=request.form.get('payload', type=str), content_type=request.form.get('content_type', typ...
Adds a task to a queue.
def grad(func, wrt=(0,), optimized=True, preserve_result=False, check_dims=True, verbose=0): """Return the gradient of a function `func`. Args: func: The function to take the gradient of. wrt: A tuple of argument indices to differentiate with respect to. By ...
Return the gradient of a function `func`. Args: func: The function to take the gradient of. wrt: A tuple of argument indices to differentiate with respect to. By default the derivative is taken with respect to the first argument. optimized: Whether to optimize the gradient function (`True` by defa...
def images_to_matrix(image_list, mask=None, sigma=None, epsilon=0.5 ): """ Read images into rows of a matrix, given a mask - much faster for large datasets as it is based on C++ implementations. ANTsR function: `imagesToMatrix` Arguments --------- image_list : list of ANTsImage types ...
Read images into rows of a matrix, given a mask - much faster for large datasets as it is based on C++ implementations. ANTsR function: `imagesToMatrix` Arguments --------- image_list : list of ANTsImage types images to convert to ndarray mask : ANTsImage (optional) image cont...
def resizeTile(index, size): """Apply Antialiasing resizing to tile""" resized = tiles[index].resize(size, Image.ANTIALIAS) return sImage(resized.tostring(), resized.size, resized.mode)
Apply Antialiasing resizing to tile
def update_actualremoterelieve_v1(self): """Constrain the actual relieve discharge to a remote location. Required control parameter: |HighestRemoteDischarge| Required derived parameter: |HighestRemoteSmoothPar| Updated flux sequence: |ActualRemoteRelieve| Basic equation - disco...
Constrain the actual relieve discharge to a remote location. Required control parameter: |HighestRemoteDischarge| Required derived parameter: |HighestRemoteSmoothPar| Updated flux sequence: |ActualRemoteRelieve| Basic equation - discontinous: :math:`ActualRemoteRelieve = min(...
def stream_agents_list(self, department_id=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/apis#get-all-agents-status" api_path = "/stream/agents" api_query = {} if "query" in kwargs.keys(): api_query.update(kwargs["query"]) del kwargs["query"] ...
https://developer.zendesk.com/rest_api/docs/chat/apis#get-all-agents-status
def _time_marker_move(self, event): """Callback for <B1-Motion> Event: Move the selected marker""" limit = self.pixel_width x = self._canvas_ticks.canvasx(event.x) x = min(max(x, 0), limit) _, y = self._canvas_ticks.coords(self._time_marker_image) self._canvas_ticks.coord...
Callback for <B1-Motion> Event: Move the selected marker
def parse_attributes( fields ): """Parse list of key=value strings into a dict""" attributes = {} for field in fields: pair = field.split( '=' ) attributes[ pair[0] ] = pair[1] return attributes
Parse list of key=value strings into a dict
def get_max_id(self, object_type, role): """Get the highest used ID.""" if object_type == 'user': objectclass = 'posixAccount' ldap_attr = 'uidNumber' elif object_type == 'group': # pragma: no cover objectclass = 'posixGroup' ldap_attr = 'gidNumbe...
Get the highest used ID.
def get_activity_comments(self, activity_id, markdown=False, limit=None): """ Gets the comments for an activity. http://strava.github.io/api/v3/comments/#list :param activity_id: The activity for which to fetch comments. :type activity_id: int :param markdown: Whether ...
Gets the comments for an activity. http://strava.github.io/api/v3/comments/#list :param activity_id: The activity for which to fetch comments. :type activity_id: int :param markdown: Whether to include markdown in comments (default is false/filterout). :type markdown: bool ...
def append(self, obj): """ If it is a list it will append the obj, if it is a dictionary it will convert it to a list and append :param obj: dict or list of the object to append :return: None """ if isinstance(obj, dict) and self._col_names: obj = [obj...
If it is a list it will append the obj, if it is a dictionary it will convert it to a list and append :param obj: dict or list of the object to append :return: None
def retrieve_product(self, product_id): """Retrieve details on a single product.""" response = self.request(E.retrieveProductSslCertRequest( E.id(product_id) )) return response.as_model(SSLProduct)
Retrieve details on a single product.
def crop_image(image, threshold): """ Найти непрозрачную область на изображении и вырезать её :param image: Изображение :param threshold: Порог прозрачности для обрезания :return: cropped_image - вырезанное изображение x, y, width, height - координаты и размер вырезаннго прямоугольника ...
Найти непрозрачную область на изображении и вырезать её :param image: Изображение :param threshold: Порог прозрачности для обрезания :return: cropped_image - вырезанное изображение x, y, width, height - координаты и размер вырезаннго прямоугольника
def tplot_restore(filename): """ This function will restore tplot variables that have been saved with the "tplot_save" command. .. note:: This function is compatible with the IDL tplot_save routine. If you have a ".tplot" file generated from IDL, this procedure will restore the data c...
This function will restore tplot variables that have been saved with the "tplot_save" command. .. note:: This function is compatible with the IDL tplot_save routine. If you have a ".tplot" file generated from IDL, this procedure will restore the data contained in the file. Not all plo...
def cmd_serial(self, args): '''serial control commands''' usage = "Usage: serial <lock|unlock|set|send>" if len(args) < 1: print(usage) return if args[0] == "lock": self.serial_lock(True) elif args[0] == "unlock": self.serial_lock(F...
serial control commands
def scan_build_files(project_tree, base_relpath, build_ignore_patterns=None): """Looks for all BUILD files :param project_tree: Project tree to scan in. :type project_tree: :class:`pants.base.project_tree.ProjectTree` :param base_relpath: Directory under root_dir to scan. :param build_ignore_pattern...
Looks for all BUILD files :param project_tree: Project tree to scan in. :type project_tree: :class:`pants.base.project_tree.ProjectTree` :param base_relpath: Directory under root_dir to scan. :param build_ignore_patterns: .gitignore like patterns to exclude from BUILD files scan. :type build_ignore_...
def get(self, default=None): """ Get the result of the Job, or return *default* if the job is not finished or errored. This function will never explicitly raise an exception. Note that the *default* value is also returned if the job was cancelled. # Arguments default (any): The value to return ...
Get the result of the Job, or return *default* if the job is not finished or errored. This function will never explicitly raise an exception. Note that the *default* value is also returned if the job was cancelled. # Arguments default (any): The value to return when the result can not be obtained.
def deploy_gateway(collector): """Deploy the apigateway to a particular stage""" configuration = collector.configuration aws_syncr = configuration['aws_syncr'] aws_syncr, amazon, stage, gateway = find_gateway(aws_syncr, configuration) gateway.deploy(aws_syncr, amazon, stage) if not configuratio...
Deploy the apigateway to a particular stage
def _checkIfClusterExists(self): """ Try deleting the resource group. This will fail if it exists and raise an exception. """ ansibleArgs = { 'resgrp': self.clusterName, 'region': self._zone } try: self.callPlaybook(self.playbook['check...
Try deleting the resource group. This will fail if it exists and raise an exception.
def schema_class(self, object_schema, model_name, classes=False): """ Create a object-class based on the object_schema. Use this class to create specific instances, and validate the data values. See the "python-jsonschema-objects" package for details on further usage. ...
Create a object-class based on the object_schema. Use this class to create specific instances, and validate the data values. See the "python-jsonschema-objects" package for details on further usage. Parameters ---------- object_schema : dict The JSON-schema...
def base_url(klass, space_id='', resource_id=None, environment_id=None, **kwargs): """ Returns the URI for the resource. """ url = "spaces/{0}".format( space_id) if environment_id is not None: url = url = "{0}/environments/{1}".format(url, environment_id...
Returns the URI for the resource.
def edit(self, instance_id, userdata=None, hostname=None, domain=None, notes=None, tags=None): """Edit hostname, domain name, notes, and/or the user data of a VS. Parameters set to None will be ignored and not attempted to be updated. :param integer instance_id: the instance ID to...
Edit hostname, domain name, notes, and/or the user data of a VS. Parameters set to None will be ignored and not attempted to be updated. :param integer instance_id: the instance ID to edit :param string userdata: user data on VS to edit. If none exist it will be...
def order_assimilation(args): """ Internal helper method for BorgQueen to process assimilation """ (path, drone, data, status) = args newdata = drone.assimilate(path) if newdata: data.append(json.dumps(newdata, cls=MontyEncoder)) status['count'] += 1 count = status['count'] t...
Internal helper method for BorgQueen to process assimilation
def get_lbry_api_function_docs(url=LBRY_API_RAW_JSON_URL): """ Scrapes the given URL to a page in JSON format to obtain the documentation for the LBRY API :param str url: URL to the documentation we need to obtain, pybry.constants.LBRY_API_RAW_JSON_URL by default :return: List of functions retrieved f...
Scrapes the given URL to a page in JSON format to obtain the documentation for the LBRY API :param str url: URL to the documentation we need to obtain, pybry.constants.LBRY_API_RAW_JSON_URL by default :return: List of functions retrieved from the `url` given :rtype: list
def process_npdu(self, npdu): """encode NPDUs from the network service access point and send them to the proxy.""" if _debug: ProxyServiceNetworkAdapter._debug("process_npdu %r", npdu) # encode the npdu as if it was about to be delivered to the network pdu = PDU() npdu.encode(pd...
encode NPDUs from the network service access point and send them to the proxy.
def gather_blocks_2d(x, indices): """Gathers flattened blocks from x.""" x_shape = common_layers.shape_list(x) x = reshape_range(x, 2, 4, [tf.reduce_prod(x_shape[2:4])]) # [length, batch, heads, dim] x_t = tf.transpose(x, [2, 0, 1, 3]) x_new = tf.gather(x_t, indices) # returns [batch, heads, num_blocks, b...
Gathers flattened blocks from x.
def remove(self, stuff): """Remove variables and constraints. Parameters ---------- stuff : iterable, str, Variable, Constraint Either an iterable containing variables and constraints to be removed from the model or a single variable or contstraint (or their names). ...
Remove variables and constraints. Parameters ---------- stuff : iterable, str, Variable, Constraint Either an iterable containing variables and constraints to be removed from the model or a single variable or contstraint (or their names). Returns ------- Non...
def read_until_done(self, command, timeout=None): """Yield messages read until we receive a 'DONE' command. Read messages of the given command until we receive a 'DONE' command. If a command different than the requested one is received, an AdbProtocolError is raised. Args: command: The comm...
Yield messages read until we receive a 'DONE' command. Read messages of the given command until we receive a 'DONE' command. If a command different than the requested one is received, an AdbProtocolError is raised. Args: command: The command to expect, like 'DENT' or 'DATA'. timeout: The ...
def _partition_spec(self, shape, partition_info): """Build magic (and sparsely documented) shapes_and_slices spec string.""" if partition_info is None: return '' # Empty string indicates a non-partitioned tensor. ssi = tf.Variable.SaveSliceInfo( full_name=self._var_name, full_shape=pa...
Build magic (and sparsely documented) shapes_and_slices spec string.
def search( self, base=False, trim=False, objects=False, **kwargs ): """ Returns matching entries for search in ldap structured as [(dn, {attributes})] UNLESS searching by dn, in which case the first match is returned """ scope = pyldap.SCOPE_SUBTREE i...
Returns matching entries for search in ldap structured as [(dn, {attributes})] UNLESS searching by dn, in which case the first match is returned
def min_base_size_mask(self, size, hs_dims=None, prune=False): """Returns MinBaseSizeMask object with correct row, col and table masks. The returned object stores the necessary information about the base size, as well as about the base values. It can create corresponding masks in teh row, ...
Returns MinBaseSizeMask object with correct row, col and table masks. The returned object stores the necessary information about the base size, as well as about the base values. It can create corresponding masks in teh row, column, and table directions, based on the corresponding base values ...
def sync_readmes(): """ just copies README.md into README for pypi documentation """ print("syncing README") with open("README.md", 'r') as reader: file_text = reader.read() with open("README", 'w') as writer: writer.write(file_text)
just copies README.md into README for pypi documentation
def merge_perchrom_mutations(job, chrom, mutations, univ_options): """ Merge the mutation calls for a single chromosome. :param str chrom: Chromosome to process :param dict mutations: dict of dicts of the various mutation caller names as keys, and a dict of per chromosome job store ids for v...
Merge the mutation calls for a single chromosome. :param str chrom: Chromosome to process :param dict mutations: dict of dicts of the various mutation caller names as keys, and a dict of per chromosome job store ids for vcfs as value :param dict univ_options: Dict of universal options used by al...
def convert_month(date, shorten=True, cable=True): """Replace month by shortening or lengthening it. :param shorten: Set to True to shorten month name. :param cable: Set to True if category is Cable. """ month = date.split()[0].lower() if 'sept' in month: shorten = False if cable else T...
Replace month by shortening or lengthening it. :param shorten: Set to True to shorten month name. :param cable: Set to True if category is Cable.
def softDeactivate(rh): """ Deactivate a virtual machine by first shutting down Linux and then log it off. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'SOFTOFF' userid - userid of the virtual machine parm...
Deactivate a virtual machine by first shutting down Linux and then log it off. Input: Request Handle with the following properties: function - 'POWERVM' subfunction - 'SOFTOFF' userid - userid of the virtual machine parms['maxQueries'] - Maximum number...
def _GetMetadataRequest(self, metadata_url, params=None, timeout=None): """Performs a GET request with the metadata headers. Args: metadata_url: string, the URL to perform a GET request on. params: dictionary, the query parameters in the GET request. timeout: int, timeout in seconds for metad...
Performs a GET request with the metadata headers. Args: metadata_url: string, the URL to perform a GET request on. params: dictionary, the query parameters in the GET request. timeout: int, timeout in seconds for metadata requests. Returns: HTTP response from the GET request. Rais...
def new_histogram_with_implicit_reservoir(name, reservoir_type='uniform', *reservoir_args, **reservoir_kwargs): """ Build a new histogram metric and a reservoir from the given parameters """ reservoir = new_reservoir(reservoir_type, *reservoir_args, **reservoir_kwargs) return new_histogram(name, re...
Build a new histogram metric and a reservoir from the given parameters
def get_resource_component_and_children( self, resource_id, resource_type="collection", level=1, sort_data={}, **kwargs ): """ Fetch detailed metadata for the specified resource_id and all of its children. :param long resource_id: The resource for which to fetch metadata. :p...
Fetch detailed metadata for the specified resource_id and all of its children. :param long resource_id: The resource for which to fetch metadata. :param string resource_type: The level of description of the record. :param int recurse_max_level: The maximum depth level to fetch when fetching chi...
def expand_countryname_abbrevs(cls, country): # type: (str) -> List[str] """Expands abbreviation(s) in country name in various ways (eg. FED -> FEDERATED, FEDERAL etc.) Args: country (str): Country with abbreviation(s)to expand Returns: List[str]: Uppercase coun...
Expands abbreviation(s) in country name in various ways (eg. FED -> FEDERATED, FEDERAL etc.) Args: country (str): Country with abbreviation(s)to expand Returns: List[str]: Uppercase country name with abbreviation(s) expanded in various ways
def languages(self, **kwargs): """Get languages used in the project with percentage value. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabGetError: If the server faile...
Get languages used in the project with percentage value. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabGetError: If the server failed to perform the request
def script_status(self, script_id): """ Returns the run status of a stored script as well as the current values of parameters 0 to 9. script_id:= id of stored script. The run status may be . . PI_SCRIPT_INITING PI_SCRIPT_HALTED PI_SCRIPT_RUNNING...
Returns the run status of a stored script as well as the current values of parameters 0 to 9. script_id:= id of stored script. The run status may be . . PI_SCRIPT_INITING PI_SCRIPT_HALTED PI_SCRIPT_RUNNING PI_SCRIPT_WAITING PI_SCRIPT_FAILED ...
def dump_sensor_memory(self, cb_compress=False, custom_compress=False, custom_compress_file=None, auto_collect_result=False): """Customized function for dumping sensor memory. :arguments cb_compress: If True, use CarbonBlack's built-in compression. :arguments custom_compress_file: Supply path t...
Customized function for dumping sensor memory. :arguments cb_compress: If True, use CarbonBlack's built-in compression. :arguments custom_compress_file: Supply path to lr_tools/compress_file.bat to fork powershell compression :collect_mem_file: If True, wait for memdump + and compression to com...
def readNextMibObjects(self, *varBinds, **context): """Read Managed Objects Instances next to the given ones. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read all or none of the Managed Objects Instances next to the referenced ones. Parameters ---------...
Read Managed Objects Instances next to the given ones. Given one or more py:class:`~pysnmp.smi.rfc1902.ObjectType` objects, read all or none of the Managed Objects Instances next to the referenced ones. Parameters ---------- varBinds: :py:class:`tuple` of :py:class:`~pysnmp.smi...
def http_log_resp(resp, body): """ When pyrax.get_http_debug() is True, outputs the response received from the API request. """ if not pyrax.get_http_debug(): return log = logging.getLogger("pyrax") log.debug("RESP: %s\n%s", resp, resp.headers) if body: log.debug("RESP BO...
When pyrax.get_http_debug() is True, outputs the response received from the API request.
def get_default_config(self): """ Return the default config for the handler """ config = super(GraphitePickleHandler, self).get_default_config() config.update({ 'port': 2004, }) return config
Return the default config for the handler
def one(self): """ Return a single row of the results or None if empty. This is basically a shortcut to `result_set.current_rows[0]` and should only be used when you know a query returns a single row. Consider using an iterator if the ResultSet contains more than one row. ...
Return a single row of the results or None if empty. This is basically a shortcut to `result_set.current_rows[0]` and should only be used when you know a query returns a single row. Consider using an iterator if the ResultSet contains more than one row.
def black(m): """Return a function that maps all values from [0.0,m] to 0, and maps the range [m,1.0] into [0.0, 1.0] linearly. """ m = float(m) def f(x): if x <= m: return 0.0 return (x - m) / (1.0 - m) return f
Return a function that maps all values from [0.0,m] to 0, and maps the range [m,1.0] into [0.0, 1.0] linearly.
def figure(self): """ The [`matplotlib.pyplot.figure`][1] instance. [1]: http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure """ if not hasattr(self, '_figure'): self._figure = matplotlib.pyplot.figure() return self._figure
The [`matplotlib.pyplot.figure`][1] instance. [1]: http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure
def requires_role(role_s, logical_operator=all): """ Requires that the calling Subject be authorized to the extent that is required to satisfy the role_s specified and the logical operation upon them. :param role_s: a collection of the role(s) required, specified by ...
Requires that the calling Subject be authorized to the extent that is required to satisfy the role_s specified and the logical operation upon them. :param role_s: a collection of the role(s) required, specified by identifiers (such as a role name) :type role...
def _ensure_running(name, no_start=False, path=None): ''' If the container is not currently running, start it. This function returns the state that the container was in before changing path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: ...
If the container is not currently running, start it. This function returns the state that the container was in before changing path path to the container parent directory default: /var/lib/lxc (system) .. versionadded:: 2015.8.0
def update_certificate(self, certificate_id, **kwargs): """Update a certificate. :param str certificate_id: The certificate id (Required) :param str certificate_data: X509.v3 trusted certificate in PEM format. :param str signature: This parameter has been DEPRECATED in the API and does ...
Update a certificate. :param str certificate_id: The certificate id (Required) :param str certificate_data: X509.v3 trusted certificate in PEM format. :param str signature: This parameter has been DEPRECATED in the API and does not need to be provided. :param str type: type ...
def clean_title(title): """ Clean title -> remove dates, remove duplicated spaces and strip title. Args: title (str): Title. Returns: str: Clean title without dates, duplicated, trailing and leading spaces. """ date_pattern = re.compile(r'\W*' r'\...
Clean title -> remove dates, remove duplicated spaces and strip title. Args: title (str): Title. Returns: str: Clean title without dates, duplicated, trailing and leading spaces.
def row_csv_limiter(rows, limits=None): """ Limit row passing a value or detect limits making the best effort. """ limits = [None, None] if limits is None else limits if len(exclude_empty_values(limits)) == 2: upper_limit = limits[0] lower_limit = limits[1] elif len(exclude_emp...
Limit row passing a value or detect limits making the best effort.
def close(self, code=None): '''return a `close` :class:`Frame`. ''' code = code or 1000 body = pack('!H', code) body += self._close_codes.get(code, '').encode('utf-8') return self.encode(body, opcode=0x8)
return a `close` :class:`Frame`.
def survey_change_name(request, pk): """ Works well with: http://www.appelsiini.net/projects/jeditable """ survey = get_object_or_404(Survey, pk=pk) if not request.user.has_perm("formly.change_survey_name", obj=survey): raise PermissionDenied() survey.name = request.POST.get("nam...
Works well with: http://www.appelsiini.net/projects/jeditable
def make_router(): """Return a WSGI application that searches requests to controllers """ global router routings = [ ('GET', '^/$', index), ('GET', '^/api/?$', index), ('POST', '^/api/1/calculate/?$', calculate.api1_calculate), ('GET', '^/api/2/entities/?$', entities.api2_ent...
Return a WSGI application that searches requests to controllers
def get_class_method(cls_or_inst, method_name): """ Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with properties and cached properties. """ cls = cls_or_inst if isinstance(cls_or_inst, type) else cls_or_inst.__class__ meth = geta...
Returns a method from a given class or instance. When the method doest not exist, it returns `None`. Also works with properties and cached properties.
def capability_info(self, name=None): """Return information about the requested capability from this list. Will return None if there is no information about the requested capability. """ for r in self.resources: if (r.capability == name): return(r) re...
Return information about the requested capability from this list. Will return None if there is no information about the requested capability.
def preparer(telefoon): ''' Edit a phone value to a value that can be validated as a phone number. This takes the incoming value and : Removes all whitespace ( space, tab , newline , ... ) characters Removes the following characters: " / - . " If no + ...
Edit a phone value to a value that can be validated as a phone number. This takes the incoming value and : Removes all whitespace ( space, tab , newline , ... ) characters Removes the following characters: " / - . " If no + is present at frond, add the country code ...
def move_datetime_year(dt, direction, num_shifts): """ Move datetime 1 year in the chosen direction. unit is a no-op, to keep the API the same as the day case """ delta = relativedelta(years=+num_shifts) return _move_datetime(dt, direction, delta)
Move datetime 1 year in the chosen direction. unit is a no-op, to keep the API the same as the day case
def dataframe(self): """ Returns a pandas DataFrame where each row is a representation of the Game class. Rows are indexed by the boxscore string. """ frames = [] for game in self.__iter__(): df = game.dataframe if df is not None: f...
Returns a pandas DataFrame where each row is a representation of the Game class. Rows are indexed by the boxscore string.
def init_app(self, app, minters_entry_point_group=None, fetchers_entry_point_group=None): """Flask application initialization. Initialize: * The CLI commands. * Initialize the logger (Default: `app.debug`). * Initialize the default admin object link endpoint....
Flask application initialization. Initialize: * The CLI commands. * Initialize the logger (Default: `app.debug`). * Initialize the default admin object link endpoint. (Default: `{"rec": "recordmetadata.details_view"}` if `invenio-records` is installed, otherwi...
def chemsys(self) -> set: """ Returns: set representing the chemical system, e.g., {"Li", "Fe", "P", "O"} """ chemsys = set() for e in self.entries: chemsys.update([el.symbol for el in e.composition.keys()]) return chemsys
Returns: set representing the chemical system, e.g., {"Li", "Fe", "P", "O"}
def _construct_email(self, email, **extra): """ Converts incoming data to properly structured dictionary. """ if isinstance(email, dict): email = Email(manager=self._manager, **email) elif isinstance(email, (MIMEText, MIMEMultipart)): email = Email.from_mi...
Converts incoming data to properly structured dictionary.
def show_plane(orig, n, scale=1.0, **kwargs): """ Show the plane with the given origin and normal. scale give its size """ b1 = orthogonal_vector(n) b1 /= la.norm(b1) b2 = np.cross(b1, n) b2 /= la.norm(b2) verts = [orig + scale*(-b1 - b2), orig + scale*(b1 - b2), ...
Show the plane with the given origin and normal. scale give its size
def update(self): """Calculate the smoothing parameter value. The following example is explained in some detail in module |smoothtools|: >>> from hydpy.models.dam import * >>> parameterstep() >>> highestremotedischarge(1.0) >>> highestremotetolerance(0.0) ...
Calculate the smoothing parameter value. The following example is explained in some detail in module |smoothtools|: >>> from hydpy.models.dam import * >>> parameterstep() >>> highestremotedischarge(1.0) >>> highestremotetolerance(0.0) >>> derived.highestremotesm...
def ParseDom(self, dom, feed): """ Parses the given kml dom tree and updates the Google transit feed object. Args: dom - kml dom tree feed - an instance of Schedule class to be updated """ shape_num = 0 for node in dom.getElementsByTagName('Placemark'): p = self.ParsePlacemark...
Parses the given kml dom tree and updates the Google transit feed object. Args: dom - kml dom tree feed - an instance of Schedule class to be updated
def mask_image(image: SpatialImage, mask: np.ndarray, data_type: type = None ) -> np.ndarray: """Mask image after optionally casting its type. Parameters ---------- image Image to mask. Can include time as the last dimension. mask Mask to apply. Must have the same sha...
Mask image after optionally casting its type. Parameters ---------- image Image to mask. Can include time as the last dimension. mask Mask to apply. Must have the same shape as the image data. data_type Type to cast image to. Returns ------- np.ndarray M...
def unicode_compatible(cls): """ A decorator that defines ``__str__`` and ``__unicode__`` methods under Python 2. """ if not is_py3: cls.__unicode__ = cls.__str__ cls.__str__ = lambda self: self.__unicode__().encode('utf-8') return cls
A decorator that defines ``__str__`` and ``__unicode__`` methods under Python 2.
def lgeometricmean (inlist): """ Calculates the geometric mean of the values in the passed list. That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list. Usage: lgeometricmean(inlist) """ mult = 1.0 one_over_n = 1.0/len(inlist) for item in inlist: mult = mult * pow(item,one_over_n) ...
Calculates the geometric mean of the values in the passed list. That is: n-th root of (x1 * x2 * ... * xn). Assumes a '1D' list. Usage: lgeometricmean(inlist)
def parse_args(): """Parse the arguments.""" parser = argparse.ArgumentParser( description='Show available clusters.' ) parser.add_argument( '-v', '--version', action='version', version="%(prog)s {0}".format(__version__), ) parser.add_argument( '--...
Parse the arguments.
def fix_e702(self, result, logical): """Put semicolon-separated compound statement on separate lines.""" if not logical: return [] # pragma: no cover logical_lines = logical[2] # Avoid applying this when indented. # https://docs.python.org/reference/compound_stmts.h...
Put semicolon-separated compound statement on separate lines.
def set_volume(self, volume): """ Sets player volume (note, this does not change host computer main volume). """ msg = cr.Message() msg.type = cr.SET_VOLUME msg.request_set_volume.volume = int(volume) self.send_message(msg)
Sets player volume (note, this does not change host computer main volume).
def update(self, **params): """Updates the current parameter positions and resets stats. If any sampling transforms are specified, they are applied to the params before being stored. """ self._current_params = self._transform_params(**params) self._current_stats = ModelS...
Updates the current parameter positions and resets stats. If any sampling transforms are specified, they are applied to the params before being stored.
def _iter_process(): """Iterate through processes, yielding process ID and properties of each. Example usage:: >>> for pid, info in _iter_process(): ... print(pid, '->', info) 1509 -> {'parent_pid': 1201, 'executable': 'python.exe'} """ # TODO: Process32{First,Next} does no...
Iterate through processes, yielding process ID and properties of each. Example usage:: >>> for pid, info in _iter_process(): ... print(pid, '->', info) 1509 -> {'parent_pid': 1201, 'executable': 'python.exe'}
def _validate_read_indexer(self, key, indexer, axis, raise_missing=False): """ Check that indexer can be used to return a result (e.g. at least one element was found, unless the list of keys was actually empty). Parameters ---------- key : list-like Target la...
Check that indexer can be used to return a result (e.g. at least one element was found, unless the list of keys was actually empty). Parameters ---------- key : list-like Target labels (only used to show correct error message) indexer: array-like of booleans ...
def from_networkx(cls, graph, weight='weight'): r"""Import a graph from NetworkX. Edge weights are retrieved as an edge attribute, under the name specified by the ``weight`` parameter. Signals are retrieved from node attributes, and stored in the :attr:`signals` dictionary unde...
r"""Import a graph from NetworkX. Edge weights are retrieved as an edge attribute, under the name specified by the ``weight`` parameter. Signals are retrieved from node attributes, and stored in the :attr:`signals` dictionary under the attribute name. `N`-dimensional signals th...
def _set_traffic_class(self, v, load=False): """ Setter method for traffic_class, mapped from YANG variable /interface/port_channel/qos/random_detect/traffic_class (list) If this variable is read-only (config: false) in the source YANG file, then _set_traffic_class is considered as a private method....
Setter method for traffic_class, mapped from YANG variable /interface/port_channel/qos/random_detect/traffic_class (list) If this variable is read-only (config: false) in the source YANG file, then _set_traffic_class is considered as a private method. Backends looking to populate this variable should do...
def dump_br_version(project): """ Dump an enhanced version json including - The version from package.json - The current branch (if it can be found) - The current sha """ normalized = get_version(project) sha = subprocess.check_output( ['git', 'rev-parse', 'HEAD'], cwd=HERE).strip() ...
Dump an enhanced version json including - The version from package.json - The current branch (if it can be found) - The current sha
def address(self): """The full proxied address to this page""" path = urlsplit(self.target).path suffix = '/' if not path or path.endswith('/') else '' return '%s%s/%s%s' % (self._ui_address[:-1], self._proxy_prefix, self.route, suffix)
The full proxied address to this page
def extract_slitlet2d(self, image_2k2k): """Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : numpy array Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2) Returns ------- slitlet2d : numpy arra...
Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : numpy array Original image (dimensions EMIR_NAXIS1 * EMIR_NAXIS2) Returns ------- slitlet2d : numpy array Image corresponding to the slitlet reg...
def prism_barycentric_coordinates(tri1, tri2, pt): ''' prism_barycentric_coordinates(tri1, tri2, point) yields a list of weights for each vertex in the given tetrahedron in the same order as the vertices given. If all weights are 0, then the point is not inside the tetrahedron. The returned weights ...
prism_barycentric_coordinates(tri1, tri2, point) yields a list of weights for each vertex in the given tetrahedron in the same order as the vertices given. If all weights are 0, then the point is not inside the tetrahedron. The returned weights are (a,b,d) in a numpy array; the values a, b, and c are ...
def get_gear(self, gear_id): """ Get details for an item of gear. http://strava.github.io/api/v3/gear/#show :param gear_id: The gear id. :type gear_id: str :return: The Bike or Shoe subclass object. :rtype: :class:`stravalib.model.Gear` """ retu...
Get details for an item of gear. http://strava.github.io/api/v3/gear/#show :param gear_id: The gear id. :type gear_id: str :return: The Bike or Shoe subclass object. :rtype: :class:`stravalib.model.Gear`
def delete_page_property(self, page_id, page_property): """ Delete the page (content) property e.g. delete key of hash :param page_id: content_id format :param page_property: key of property :return: """ url = 'rest/api/content/{page_id}/property/{page_property}'....
Delete the page (content) property e.g. delete key of hash :param page_id: content_id format :param page_property: key of property :return:
def _payload_to_dict(self): """When an error status the payload is holding an AsyncException that is converted to a serializable dict. """ if self.status != self.ERROR or not self.payload: return self.payload import traceback return { "error": se...
When an error status the payload is holding an AsyncException that is converted to a serializable dict.
def refresh( self ): """ Clears out the actions for this menu and then loads the files. """ self.clear() for i, filename in enumerate(self.filenames()): name = '%i. %s' % (i+1, os.path.basename(filename)) action = self.addAction(name) ...
Clears out the actions for this menu and then loads the files.
def json_conversion(obj: Any) -> JSON: """Encode additional objects to JSON.""" try: # numpy isn't an explicit dependency of bowtie # so we can't assume it's available import numpy as np if isinstance(obj, (np.ndarray, np.generic)): return obj.tolist() except Impo...
Encode additional objects to JSON.
def send(sms_to, sms_body, **kwargs): """ Site: https://www.twilio.com/ API: https://www.twilio.com/docs/api/rest/sending-messages """ headers = { "Content-type": "application/x-www-form-urlencoded", "User-Agent": "DBMail/%s" % get_version(), 'Authorization': 'Basic %s' % b64...
Site: https://www.twilio.com/ API: https://www.twilio.com/docs/api/rest/sending-messages
def WriteFile(self, printer): """Write the messages file to out.""" self.Validate() extended_descriptor.WritePythonFile( self.__file_descriptor, self.__package, self.__client_info.version, printer)
Write the messages file to out.
def remove_unhealthy_peers( self, count, con=None, path=None, peer_table=None, min_request_count=10, min_health=MIN_PEER_HEALTH ): """ Remove up to @count unhealthy peers Return the list of peers we removed """ if path is None: path = self.atlasdb_path ...
Remove up to @count unhealthy peers Return the list of peers we removed
def paginate(limit, start_arg="next_token", limit_arg="max_results"): """Returns a limited result list, and an offset into list of remaining items Takes the next_token, and max_results kwargs given to a function and handles the slicing of the results. The kwarg `next_token` is the offset into the list ...
Returns a limited result list, and an offset into list of remaining items Takes the next_token, and max_results kwargs given to a function and handles the slicing of the results. The kwarg `next_token` is the offset into the list to begin slicing from. `max_results` is the size of the result required ...
def get_magic_comment(self, name, expand_macros=False): """Return a value of # name=value comment in spec or None.""" match = re.search(r'^#\s*?%s\s?=\s?(\S+)' % re.escape(name), self.txt, flags=re.M) if not match: return None val = match.group(1) ...
Return a value of # name=value comment in spec or None.
def _expand_alts_in_vcf_record_list(cls, vcf_records): '''Input: list of vcf_records. Returns new list, where any records with >ALT is replaced with one vcf record per ALT. This doesn't change FORMAT or INFO columns, which means they are now broken for those records''' new_vcf_re...
Input: list of vcf_records. Returns new list, where any records with >ALT is replaced with one vcf record per ALT. This doesn't change FORMAT or INFO columns, which means they are now broken for those records
def required_role(req_role): """ Decorator applied to functions requiring caller to possess the specified role """ def dec_wrapper(wfunc): @wraps(wfunc) def wrapped(*args, **kwargs): user_id = kwargs.get("user_id") try: res = db.DBSession.query...
Decorator applied to functions requiring caller to possess the specified role
def legacy_decrypt(jwe, jwk, adata='', validate_claims=True, expiry_seconds=None): """ Decrypts a deserialized :class:`~jose.JWE` :param jwe: An instance of :class:`~jose.JWE` :param jwk: A `dict` representing the JWK required to decrypt the content of the :class:`~jose.J...
Decrypts a deserialized :class:`~jose.JWE` :param jwe: An instance of :class:`~jose.JWE` :param jwk: A `dict` representing the JWK required to decrypt the content of the :class:`~jose.JWE`. :param adata: Arbitrary string data used during encryption for additional authentic...
def merge_text(initial_config=None, initial_path=None, merge_config=None, merge_path=None, saltenv='base'): ''' Return the merge result of the ``initial_config`` with the ``merge_config``, as plain text. initial_config The initial conf...
Return the merge result of the ``initial_config`` with the ``merge_config``, as plain text. initial_config The initial configuration sent as text. This argument is ignored when ``initial_path`` is set. initial_path Absolute or remote path from where to load the initial configuratio...
def _format_char(char): """Prepares a single character for passing to ctypes calls, needs to return an integer but can also pass None which will keep the current character instead of overwriting it. This is called often and needs to be optimized whenever possible. """ if char is None: r...
Prepares a single character for passing to ctypes calls, needs to return an integer but can also pass None which will keep the current character instead of overwriting it. This is called often and needs to be optimized whenever possible.
def p_bexpr_func(p): """ bexpr : ID bexpr """ args = make_arg_list(make_argument(p[2], p.lineno(2))) p[0] = make_call(p[1], p.lineno(1), args) if p[0] is None: return if p[0].token in ('STRSLICE', 'VAR', 'STRING'): entry = SYMBOL_TABLE.access_call(p[1], p.lineno(1)) entr...
bexpr : ID bexpr