positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def likelihood(self, x, cl): """ X = numpy.random.random([2,3,4]) # we have data 2x3 with fature vector with 4 fatures Use likelihoodFromImage() function for 3d image input m.likelihood(X,0) """ # sha = x.shape # xr = x.reshape(-1, sha[-1]) # out...
X = numpy.random.random([2,3,4]) # we have data 2x3 with fature vector with 4 fatures Use likelihoodFromImage() function for 3d image input m.likelihood(X,0)
def export_scalars(self, path): """Exports to the given path an ASCII file containing all the scalars written so far by this instance, with the following format: {writer_id : [[timestamp, step, value], ...], ...} """ if os.path.exists(path) and os.path.isfile(path): l...
Exports to the given path an ASCII file containing all the scalars written so far by this instance, with the following format: {writer_id : [[timestamp, step, value], ...], ...}
def stormcmd(self): ''' A storm sub-query aware command line splitter. ( not for storm commands, but for commands which may take storm ) ''' argv = [] while self.more(): self.ignore(whitespace) if self.nextstr('{'): self.offs += 1 ...
A storm sub-query aware command line splitter. ( not for storm commands, but for commands which may take storm )
def event_handler(event_name): """ Decorator for designating a handler for an event type. ``event_name`` must be a string representing the name of the event type. The decorated function must accept a parameter: the body of the received event, which will be a Python object that can be encoded as a J...
Decorator for designating a handler for an event type. ``event_name`` must be a string representing the name of the event type. The decorated function must accept a parameter: the body of the received event, which will be a Python object that can be encoded as a JSON (dict, list, str, int, bool, float ...
def restore_edge(self, edge): """ Restores a previously hidden edge back into the graph. """ try: head_id, tail_id, data = self.hidden_edges[edge] self.nodes[tail_id][0].append(edge) self.nodes[head_id][1].append(edge) self.edges[edge] = he...
Restores a previously hidden edge back into the graph.
def check_reaction_on_surface(self, chemical_composition, reactants, products): """ Check if entry with same surface and reaction is allready written to database file Parameters ---------- chemcial_composition: str reactants: dic...
Check if entry with same surface and reaction is allready written to database file Parameters ---------- chemcial_composition: str reactants: dict products: dict Returns id or None
def get_ph_bs_symm_line_from_dict(bands_dict, has_nac=False, labels_dict=None): """ Creates a pymatgen PhononBandStructure object from the dictionary extracted by the band.yaml file produced by phonopy. The labels will be extracted from the dictionary, if present. If the 'eigenvector' key is found t...
Creates a pymatgen PhononBandStructure object from the dictionary extracted by the band.yaml file produced by phonopy. The labels will be extracted from the dictionary, if present. If the 'eigenvector' key is found the eigendisplacements will be calculated according to the formula:: ex...
def _set_priority(self, v, load=False): """ Setter method for priority, mapped from YANG variable /qos_mpls/map/traffic_class_exp/priority (list) If this variable is read-only (config: false) in the source YANG file, then _set_priority is considered as a private method. Backends looking to populate ...
Setter method for priority, mapped from YANG variable /qos_mpls/map/traffic_class_exp/priority (list) If this variable is read-only (config: false) in the source YANG file, then _set_priority is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._...
def download(self, path, progress_callback=None, chunk_size=1024**2): """ Download the export archive. .. warning:: If you pass this function an open file-like object as the ``path`` parameter, the function will not close that file for you. If a ``path`` parame...
Download the export archive. .. warning:: If you pass this function an open file-like object as the ``path`` parameter, the function will not close that file for you. If a ``path`` parameter is a directory, this function will use the Export name to determine the name o...
def unpack_rpc_payload(resp_format, payload): """Unpack an RPC payload according to resp_format. Args: resp_format (str): a struct format code (without the <) for the parameter format for this RPC. This format code may include the final character V, which means that it expects ...
Unpack an RPC payload according to resp_format. Args: resp_format (str): a struct format code (without the <) for the parameter format for this RPC. This format code may include the final character V, which means that it expects a variable length bytearray. payload (bytes):...
def reindex(cls, lastblock, firstblock=None, opts=None): """ Generate a subdomains db from scratch, using the names db and the atlas db and zone file collection. Best to do this in a one-off command (i.e. *not* in the blockstackd process) """ if opts is None: opts = g...
Generate a subdomains db from scratch, using the names db and the atlas db and zone file collection. Best to do this in a one-off command (i.e. *not* in the blockstackd process)
def list_users(host=None, admin_username=None, admin_password=None, module=None): ''' List all DRAC users CLI Example: .. code-block:: bash salt dell dracr.list_users ''' users = {} _username = '' for idx in range(1, 17): c...
List all DRAC users CLI Example: .. code-block:: bash salt dell dracr.list_users
def prepare_calc_dir(self): ''' Prepare the calculation directory for VASP execution. This needs to be re-implemented for each local setup. The following code reflects just my particular setup. ''' with open("vasprun.conf","w") as f: f.write('NODES="nodes=%s:p...
Prepare the calculation directory for VASP execution. This needs to be re-implemented for each local setup. The following code reflects just my particular setup.
def load(self): """Load all available DRPs in 'entry_point'.""" for drpins in self.iload(self.entry): self.drps[drpins.name] = drpins return self
Load all available DRPs in 'entry_point'.
def create(cls, name, certificate): """ Create a new external VPN CA for signing internal gateway certificates. :param str name: Name of VPN CA :param str certificate: file name, path or certificate string. :raises CreateElementFailed: Failed creating cert with r...
Create a new external VPN CA for signing internal gateway certificates. :param str name: Name of VPN CA :param str certificate: file name, path or certificate string. :raises CreateElementFailed: Failed creating cert with reason :rtype: VPNCertificateCA
def save(self, config_loc=None): """Saves current user credentials to user directory. Args: config_loc (str, optional): Location where credentials are to be stored. If no argument is provided, it will be send to the default location. Example: ...
Saves current user credentials to user directory. Args: config_loc (str, optional): Location where credentials are to be stored. If no argument is provided, it will be send to the default location. Example: .. code:: from cartof...
def get_utm_crs(lng, lat, source_crs=CRS.WGS84): """ Get CRS for UTM zone in which (lat, lng) is contained. :param lng: longitude :type lng: float :param lat: latitude :type lat: float :param source_crs: source CRS :type source_crs: constants.CRS :return: CRS of the zone containing the ...
Get CRS for UTM zone in which (lat, lng) is contained. :param lng: longitude :type lng: float :param lat: latitude :type lat: float :param source_crs: source CRS :type source_crs: constants.CRS :return: CRS of the zone containing the lat,lon point :rtype: constants.CRS
def get_completions(self, info): """Return a list of (completion, type) tuples Simple completion based on python-like identifiers and whitespace """ if not info['obj']: return items = [] obj = info['obj'] if info['context']: lexe...
Return a list of (completion, type) tuples Simple completion based on python-like identifiers and whitespace
def build(level, code, validity=None): '''Serialize a GeoID from its parts''' spatial = ':'.join((level, code)) if not validity: return spatial elif isinstance(validity, basestring): return '@'.join((spatial, validity)) elif isinstance(validity, datetime): return '@'.join((sp...
Serialize a GeoID from its parts
def get_pod_for_build(self, build_id): """ :return: PodResponse object for pod relating to the build """ pods = self.os.list_pods(label='openshift.io/build.name=%s' % build_id) serialized_response = pods.json() pod_list = [PodResponse(pod) for pod in serialized_response["...
:return: PodResponse object for pod relating to the build
def main(): """ Retrieve run folder paths from the command line Ensure only metrics required for summary are loaded Load the run metrics Calculate the summary metrics Display error by lane, read """ logging.basicConfig(level=logging.INFO) run_metrics = py_interop_run_metrics.run_metrics...
Retrieve run folder paths from the command line Ensure only metrics required for summary are loaded Load the run metrics Calculate the summary metrics Display error by lane, read
def delete_cluster_admin(self, username): """Delete cluster admin.""" url = "cluster_admins/{0}".format(username) self.request( url=url, method='DELETE', expected_response_code=200 ) return True
Delete cluster admin.
def isetdiff_flags(list1, list2): """ move to util_iter """ set2 = set(list2) return (item not in set2 for item in list1)
move to util_iter
def _set_join(self, query=None): """ Set the join clause for the query. """ if not query: query = self._query foreign_key = '%s.%s' % (self._related.get_table(), self._second_key) query.join(self._parent.get_table(), self.get_qualified_parent_key_name(), '='...
Set the join clause for the query.
def safe_unicode(obj, *args): """ return the unicode representation of obj """ try: return unicode(obj, *args) # noqa for undefined-variable except UnicodeDecodeError: # obj is byte string ascii_text = str(obj).encode('string_escape') try: return unicode(ascii_te...
return the unicode representation of obj
def get_blocks_byte_array(self, buffer=False): """Return a list of all blocks in this chunk.""" if buffer: length = len(self.blocksList) return BytesIO(pack(">i", length)+self.get_blocks_byte_array()) else: return array.array('B', self.blocksList).tostring()
Return a list of all blocks in this chunk.
def layer_register( log_shape=False, use_scope=True): """ Args: log_shape (bool): log input/output shape of this layer use_scope (bool or None): Whether to call this layer with an extra first argument as variable scope. When set to None, it can be called e...
Args: log_shape (bool): log input/output shape of this layer use_scope (bool or None): Whether to call this layer with an extra first argument as variable scope. When set to None, it can be called either with or without the scope name argument, depend on whether the f...
def distATT(x1,y1,x2,y2): """Compute the ATT distance between two points (see TSPLIB documentation)""" xd = x2 - x1 yd = y2 - y1 rij = math.sqrt((xd*xd + yd*yd) /10.) tij = int(rij + .5) if tij < rij: return tij + 1 else: return tij
Compute the ATT distance between two points (see TSPLIB documentation)
def index_at_event(self, event): """Get the index under the position of the given MouseEvent :param event: the mouse event :type event: :class:`QtGui.QMouseEvent` :returns: the index :rtype: :class:`QtCore.QModelIndex` :raises: None """ # find index at mo...
Get the index under the position of the given MouseEvent :param event: the mouse event :type event: :class:`QtGui.QMouseEvent` :returns: the index :rtype: :class:`QtCore.QModelIndex` :raises: None
def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, use_shared_mem, dtype): """Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False Returns ------- ret : NDArray original_length : ND...
Inner Implementation of the Pad batchify Parameters ---------- arrs : list pad_axis : int pad_val : number use_shared_mem : bool, default False Returns ------- ret : NDArray original_length : NDArray
def bk_default(cls): "Make the current background color the default." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.BACKGROUND_MASK #wAttributes |= win32.BACKGROUND_BLACK wAttributes &= ~win32.BACKGROUND_INTENSITY cls._set_text_attributes(wAttributes)
Make the current background color the default.
def add_properties(self, filename): """ Add properties to config based on filename replacing previous values. :param filename: str path to YAML file to pull top level properties from """ filename = os.path.expanduser(filename) if os.path.exists(filename): with...
Add properties to config based on filename replacing previous values. :param filename: str path to YAML file to pull top level properties from
def from_pcount(nevents): """We assume a Poisson process. nevents is the number of events in some interval. The distribution of values is the distribution of the Poisson rate parameter given this observed number of events, where the "rate" is in units of events per interval of the same d...
We assume a Poisson process. nevents is the number of events in some interval. The distribution of values is the distribution of the Poisson rate parameter given this observed number of events, where the "rate" is in units of events per interval of the same duration. The max-likelihood v...
def children_not_empty(self): """ Return the direct not empty children of the root of the fragments tree, as ``TextFile`` objects. :rtype: list of :class:`~aeneas.textfile.TextFile` """ children = [] for child_node in self.fragments_tree.children_not_empty: ...
Return the direct not empty children of the root of the fragments tree, as ``TextFile`` objects. :rtype: list of :class:`~aeneas.textfile.TextFile`
def deploy_models(self, ret): ''' Method to deploy swagger file's definition objects and associated schema to AWS Apigateway as Models ret a dictionary for returning status to Saltstack ''' for model, schema in self.models(): # add in a few attributes in...
Method to deploy swagger file's definition objects and associated schema to AWS Apigateway as Models ret a dictionary for returning status to Saltstack
def getenforce(): ''' Return the mode selinux is running in CLI Example: .. code-block:: bash salt '*' selinux.getenforce ''' _selinux_fs_path = selinux_fs_path() if _selinux_fs_path is None: return 'Disabled' try: enforce = os.path.join(_selinux_fs_path, 'enfo...
Return the mode selinux is running in CLI Example: .. code-block:: bash salt '*' selinux.getenforce
def load_plugins(self, args=None): """Load all plugins in the 'plugins' folder.""" for item in os.listdir(plugins_path): if (item.startswith(self.header) and item.endswith(".py") and item != (self.header + "plugin.py")): # Load the plug...
Load all plugins in the 'plugins' folder.
def update(self, model_alias, code='general', name=None, order=None, display_filter=None): """ Update given tab :param model_alias: :param code: :param name: :param order: :param display_filter: :return: """ model_alias = self.get_model_al...
Update given tab :param model_alias: :param code: :param name: :param order: :param display_filter: :return:
def _convert_to_color(cls, color_spec): """ Convert ``color_spec`` to an openpyxl v2 Color object Parameters ---------- color_spec : str, dict A 32-bit ARGB hex string, or a dict with zero or more of the following keys. 'rgb' ...
Convert ``color_spec`` to an openpyxl v2 Color object Parameters ---------- color_spec : str, dict A 32-bit ARGB hex string, or a dict with zero or more of the following keys. 'rgb' 'indexed' 'auto' 'theme' ...
def create_channels(chan_name=None, n_chan=None): """Create instance of Channels with random xyz coordinates Parameters ---------- chan_name : list of str names of the channels n_chan : int if chan_name is not specified, this defines the number of channels Returns ------- ...
Create instance of Channels with random xyz coordinates Parameters ---------- chan_name : list of str names of the channels n_chan : int if chan_name is not specified, this defines the number of channels Returns ------- instance of Channels where the location of the...
def card_names_and_ids(self): """Returns [(name, id), ...] pairs of cards from current board""" b = Board(self.client, self.board_id) cards = b.getCards() card_names_and_ids = [(unidecode(c.name), c.id) for c in cards] return card_names_and_ids
Returns [(name, id), ...] pairs of cards from current board
def update_safe(filename: str, **kw: Any) -> Generator[IO, None, None]: """Rewrite a file atomically. Clients are allowed to delete the tmpfile to signal that they don't want to have it updated. """ with tempfile.NamedTemporaryFile( dir=os.path.dirname(filename), delete=False, ...
Rewrite a file atomically. Clients are allowed to delete the tmpfile to signal that they don't want to have it updated.
def load_stl_ascii(file_obj): """ Load an ASCII STL file from a file object. Parameters ---------- file_obj: open file- like object Returns ---------- loaded: kwargs for a Trimesh constructor with keys: vertices: (n,3) float, vertices faces: (m,3)...
Load an ASCII STL file from a file object. Parameters ---------- file_obj: open file- like object Returns ---------- loaded: kwargs for a Trimesh constructor with keys: vertices: (n,3) float, vertices faces: (m,3) int, indexes of vertices fa...
def add_missing_components(network): # Munich """Add missing transformer at Heizkraftwerk Nord in Munich and missing transformer in Stuttgart Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network...
Add missing transformer at Heizkraftwerk Nord in Munich and missing transformer in Stuttgart Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- network : :class:`pypsa.Network Overall container of PyPSA
def mouseDoubleClickEvent( self, event ): """ Handles the mouse double click event. :param event | <QMouseEvent> """ scene_point = self.mapToScene(event.pos()) date = self.scene().dateAt(scene_point) date_time = self.scene().dateTime...
Handles the mouse double click event. :param event | <QMouseEvent>
def resource_view_attrs(raml_resource, singular=False): """ Generate view method names needed for `raml_resource` view. Collects HTTP method names from resource siblings and dynamic children if exist. Collected methods are then translated to `nefertari.view.BaseView` method names, each of which is use...
Generate view method names needed for `raml_resource` view. Collects HTTP method names from resource siblings and dynamic children if exist. Collected methods are then translated to `nefertari.view.BaseView` method names, each of which is used to process a particular HTTP method request. Maps of ...
def format_image(self, image, image_format, **kwargs): """Returns an image in the request format""" image_format = image_format.lower() accept = self.request.META['HTTP_ACCEPT'].split(',') if FORCE_WEBP and 'image/webp' in accept: image_format = 'webp' elif image_fo...
Returns an image in the request format
def _unassigned_ports(): """ Returns a set of all unassigned ports (according to IANA and Wikipedia) """ free_ports = ranges_to_set(_parse_ranges(_iana_unassigned_port_ranges())) known_ports = ranges_to_set(_wikipedia_known_port_ranges()) return free_ports.difference(known_ports)
Returns a set of all unassigned ports (according to IANA and Wikipedia)
def get_client(client_type, **kwargs): ''' Dynamically load the selected client and return a management client object ''' client_map = {'compute': 'ComputeManagement', 'authorization': 'AuthorizationManagement', 'dns': 'DnsManagement', 'storage': 'St...
Dynamically load the selected client and return a management client object
def remove_file_from_s3(awsclient, bucket, key): """Remove a file from an AWS S3 bucket. :param awsclient: :param bucket: :param key: :return: """ client_s3 = awsclient.get_client('s3') response = client_s3.delete_object(Bucket=bucket, Key=key)
Remove a file from an AWS S3 bucket. :param awsclient: :param bucket: :param key: :return:
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'used_bytes') and self.used_bytes is not None: _dict['used_bytes'] = self.used_bytes return _dict
Return a json dictionary representing this model.
def append_unreleased_entries(app, manager, releases): """ Generate new abstract 'releases' for unreleased issues. There's one for each combination of bug-vs-feature & major release line. When only one major release line exists, that dimension is ignored. """ for family, lines in six.iteritems...
Generate new abstract 'releases' for unreleased issues. There's one for each combination of bug-vs-feature & major release line. When only one major release line exists, that dimension is ignored.
def QA_indicator_MA(DataFrame,*args,**kwargs): """MA Arguments: DataFrame {[type]} -- [description] Returns: [type] -- [description] """ CLOSE = DataFrame['close'] return pd.DataFrame({'MA{}'.format(N): MA(CLOSE, N) for N in list(args)})
MA Arguments: DataFrame {[type]} -- [description] Returns: [type] -- [description]
def pareto_front(self, *args, **kwargs): """ Returns ------- P : np.array The Pareto front of a given problem. It is only loaded or calculate the first time and then cached. For a single-objective problem only one point is returned but still in a two dimensional a...
Returns ------- P : np.array The Pareto front of a given problem. It is only loaded or calculate the first time and then cached. For a single-objective problem only one point is returned but still in a two dimensional array.
def remove_child_objective_banks(self, objective_bank_id): """Removes all children from an objective bank. arg: objective_bank_id (osid.id.Id): the ``Id`` of an objective bank raise: NotFound - ``objective_bank_id`` not in hierarchy raise: NullArgument - ``objective...
Removes all children from an objective bank. arg: objective_bank_id (osid.id.Id): the ``Id`` of an objective bank raise: NotFound - ``objective_bank_id`` not in hierarchy raise: NullArgument - ``objective_bank_id`` is ``null`` raise: OperationFailed - unable to com...
def __convert_to_df(a, val_col=None, group_col=None, val_id=None, group_id=None): '''Hidden helper method to create a DataFrame with input data for further processing. Parameters ---------- a : array_like or pandas DataFrame object An array, any object exposing the array interface or a pan...
Hidden helper method to create a DataFrame with input data for further processing. Parameters ---------- a : array_like or pandas DataFrame object An array, any object exposing the array interface or a pandas DataFrame. Array must be two-dimensional. Second dimension may vary, i...
def _post_create(self, auto_refresh=False): ''' resource.create() hook For PCDM File ''' # set PCDM triple as Collection self.add_triple(self.rdf.prefixes.rdf.type, self.rdf.prefixes.pcdm.File) self.update(auto_refresh=auto_refresh)
resource.create() hook For PCDM File
def as_pyemu_matrix(self,typ=Matrix): """ Create a pyemu.Matrix from the Ensemble. Parameters ---------- typ : pyemu.Matrix or derived type the type of matrix to return Returns ------- pyemu.Matrix : pyemu.Matrix """ ...
Create a pyemu.Matrix from the Ensemble. Parameters ---------- typ : pyemu.Matrix or derived type the type of matrix to return Returns ------- pyemu.Matrix : pyemu.Matrix
def main_color(self): """ What is the most commonly occurring color. Returns ------------ color: (4,) uint8, most common color """ if self.kind is None: return DEFAULT_COLOR elif self.kind == 'face': colors = self.face_colors ...
What is the most commonly occurring color. Returns ------------ color: (4,) uint8, most common color
def set_patient_medhx_flag(self, patient_id, medhx_status): """ invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param patient_id :param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and erro...
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param patient_id :param medhx_status - Field in EEHR expects U, G, or D. SP defaults to Null and errors out if included. U=Unknown G=Granted D=Declined :ret...
def age(self, **kwargs): """ Age this particle. parameters (optional, only one allowed): days (default) hours minutes seconds """ if kwargs.get('days', None) is not None: self._age += kwargs.get('days') retu...
Age this particle. parameters (optional, only one allowed): days (default) hours minutes seconds
def prefixed_name(self, unprefixed_name, max_length=0): """ Returns a uuid pefixed identifier Args: unprefixed_name(str): Name to add a prefix to max_length(int): maximum length of the resultant prefixed name, will adapt the given name and the length of th...
Returns a uuid pefixed identifier Args: unprefixed_name(str): Name to add a prefix to max_length(int): maximum length of the resultant prefixed name, will adapt the given name and the length of the uuid ot fit it Returns: str: prefixed identifier for t...
def calc_percentiles(self, col_name, where_col_list, where_value_list): """ calculates the percentiles of col_name WHERE [where_col_list] = [where_value_list] """ #col_data = self.get_col_data_by_name(col_name) col_data = self.select_where(where_col_list, where_value_li...
calculates the percentiles of col_name WHERE [where_col_list] = [where_value_list]
def _reset_on_error(self, server, func, *args, **kwargs): """Execute an operation. Reset the server on network error. Returns fn()'s return value on success. On error, clears the server's pool and marks the server Unknown. Re-raises any exception thrown by fn(). """ try...
Execute an operation. Reset the server on network error. Returns fn()'s return value on success. On error, clears the server's pool and marks the server Unknown. Re-raises any exception thrown by fn().
def delete_custom_service_account(self, account, nickname, password): """ 删除客服帐号。 :param account: 客服账号的用户名 :param nickname: 客服账号的昵称 :param password: 客服账号的密码 :return: 返回的 JSON 数据包 """ return self.post( url="https://api.weixin.qq.com/customservi...
删除客服帐号。 :param account: 客服账号的用户名 :param nickname: 客服账号的昵称 :param password: 客服账号的密码 :return: 返回的 JSON 数据包
def create_from_historics(self, historics_id, name, output_type, output_params, initial_status=None, start=None, end=None): """ Create a new push subscription using the given Historic ID. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcr...
Create a new push subscription using the given Historic ID. Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/pushcreate :param historics_id: The ID of a Historics query :type historics_id: str :param name: The name to give the newly created sub...
def interpolate(T0, T1, t): """Return an interpolation of two RigidTransforms. Parameters ---------- T0 : :obj:`RigidTransform` The first RigidTransform to interpolate. T1 : :obj:`RigidTransform` The second RigidTransform to interpolate. t : flo...
Return an interpolation of two RigidTransforms. Parameters ---------- T0 : :obj:`RigidTransform` The first RigidTransform to interpolate. T1 : :obj:`RigidTransform` The second RigidTransform to interpolate. t : float The interpolation step i...
def set(self, reference, document_data, merge=False): """Add a "change" to replace a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.set` for more information on how ``option`` determines how the change is applied. Args: reference (~.fire...
Add a "change" to replace a document. See :meth:`~.firestore_v1beta1.document.DocumentReference.set` for more information on how ``option`` determines how the change is applied. Args: reference (~.firestore_v1beta1.document.DocumentReference): A docu...
def curve(self): """Curve of the super helix.""" return HelicalCurve.pitch_and_radius( self.major_pitch, self.major_radius, handedness=self.major_handedness)
Curve of the super helix.
def interface(cls): ''' Marks the decorated class as an abstract interface. Injects following classmethods: .. py:method:: .all(context) Returns a list of instances of each component in the ``context`` implementing this ``@interface`` :param context: context to look in ...
Marks the decorated class as an abstract interface. Injects following classmethods: .. py:method:: .all(context) Returns a list of instances of each component in the ``context`` implementing this ``@interface`` :param context: context to look in :type context: :class...
def _list_of_dictionaries_to_csv( self, csvType="human"): """Convert a python list of dictionaries to pretty csv output **Key Arguments:** - ``csvType`` -- human, machine or reST **Return:** - ``output`` -- the contents of a CSV file """ ...
Convert a python list of dictionaries to pretty csv output **Key Arguments:** - ``csvType`` -- human, machine or reST **Return:** - ``output`` -- the contents of a CSV file
def set_permissions(filename, uid=None, gid=None, mode=0775): """ Set pemissions for given `filename`. Args: filename (str): name of the file/directory uid (int, default proftpd): user ID - if not set, user ID of `proftpd` is used gid (int): group...
Set pemissions for given `filename`. Args: filename (str): name of the file/directory uid (int, default proftpd): user ID - if not set, user ID of `proftpd` is used gid (int): group ID, if not set, it is not changed mode (int, default 0775): unix ...
def process_full_position(data, header, var_only=False): """ Return genetic data when all alleles called on same line. Returns an array containing one item, a tuple of five items: (string) chromosome (string) start position (1-based) (array of strings) matching dbSNP entries ...
Return genetic data when all alleles called on same line. Returns an array containing one item, a tuple of five items: (string) chromosome (string) start position (1-based) (array of strings) matching dbSNP entries (string) reference allele sequence (array of strings) the ge...
def format_failure(failure): """Format how an error or warning should be displayed.""" return "Line {}, Column {} - #{}: {} - Category: {}, Severity: {}".format( failure.getLine(), failure.getColumn(), failure.getErrorId(), failure.getMessage(), failure.getCategoryAsStrin...
Format how an error or warning should be displayed.
def p_param(self, p): 'param : PARAMETER param_substitution_list COMMA' paramlist = [Parameter(rname, rvalue, lineno=p.lineno(2)) for rname, rvalue in p[2]] p[0] = Decl(tuple(paramlist), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
param : PARAMETER param_substitution_list COMMA
def send_ready_for_review(build_id, release_name, release_number): """Sends an email indicating that the release is ready for review.""" build = models.Build.query.get(build_id) if not build.send_email: logging.debug( 'Not sending ready for review email because build does not have ' ...
Sends an email indicating that the release is ready for review.
def wngram2idngram(input_file, vocab_file, output_file, buffersize=100, hashtablesize=2000000, files=20, compress=False, verbosity=2, n=3, write_ascii=False, fof_size=10): """ Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurr...
Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format. Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this...
def consumer(self, name): """ Create a new consumer for the :py:class:`ConsumerGroup`. :param name: name of consumer :returns: a :py:class:`ConsumerGroup` using the given consumer name. """ return type(self)(self.database, self.name, self.keys, name)
Create a new consumer for the :py:class:`ConsumerGroup`. :param name: name of consumer :returns: a :py:class:`ConsumerGroup` using the given consumer name.
def _get_aligner_index(aligner, data): """Handle multiple specifications of aligner indexes, returning value to pass to aligner. Original bcbio case -- a list of indices. CWL case: a single file with secondaryFiles staged in the same directory. """ aligner_indexes = tz.get_in(("reference", get_alig...
Handle multiple specifications of aligner indexes, returning value to pass to aligner. Original bcbio case -- a list of indices. CWL case: a single file with secondaryFiles staged in the same directory.
def heartbeat_send(self, type, autopilot, base_mode, custom_mode, system_status, mavlink_version=2, force_mavlink1=False): ''' The heartbeat message shows that a system is present and responding. The type of the MAV and Autopilot hardware allow the receivi...
The heartbeat message shows that a system is present and responding. The type of the MAV and Autopilot hardware allow the receiving system to treat further messages from this system appropriate (e.g. by laying out the user interface based on the autopilot)...
def smart_email_list(self, status="all", client_id=None): """Gets the smart email list.""" if client_id is None: response = self._get( "/transactional/smartEmail?status=%s" % status) else: response = self._get( "/transactional/smartEmail?st...
Gets the smart email list.
def bind(self, study, **kwargs): # @UnusedVariable """ Used for duck typing Collection objects with Spec and Match in source and sink initiation. Checks IDs match sessions in study. """ if self.frequency == 'per_subject': tree_subject_ids = list(study.tree.subject_id...
Used for duck typing Collection objects with Spec and Match in source and sink initiation. Checks IDs match sessions in study.
def comboBoxRowsInserted(self, _parent, start, end): """ Called when the user has entered a new value in the combobox. Puts the combobox values back into the cti. """ assert start == end, "Bug, please report: more than one row inserted" configValue = self.comboBox.itemText(st...
Called when the user has entered a new value in the combobox. Puts the combobox values back into the cti.
def get_cached_placeholder_output(parent_object, placeholder_name): """ Return cached output for a placeholder, if available. This avoids fetching the Placeholder object. """ if not PlaceholderRenderingPipe.may_cache_placeholders(): return None language_code = get_parent_language_code(p...
Return cached output for a placeholder, if available. This avoids fetching the Placeholder object.
def normalize_tuple_slice(node): """ Normalize an ast.Tuple node representing the internals of a slice. Returns the node wrapped in an ast.Index. Returns an ExtSlice node built from the tuple elements if there are any slices. """ if not any(isinstance(elt, ast.Slice) for elt in node.elts): ...
Normalize an ast.Tuple node representing the internals of a slice. Returns the node wrapped in an ast.Index. Returns an ExtSlice node built from the tuple elements if there are any slices.
def list_blobs(call=None, kwargs=None): # pylint: disable=unused-argument ''' List blobs. ''' if kwargs is None: kwargs = {} if 'container' not in kwargs: raise SaltCloudSystemExit( 'A container must be specified' ) storageservice = _get_block_blob_service(...
List blobs.
def pop(self, count): """Returns new context stack, which doesn't contain few levels """ if len(self._contexts) - 1 < count: _logger.error("#pop value is too big %d", len(self._contexts)) if len(self._contexts) > 1: return ContextStack(self._contexts[:1], ...
Returns new context stack, which doesn't contain few levels
def generate_statistics_pdf(activities=None, start_date=None, all_years=False, year=None): ''' Accepts EighthActivity objects and outputs a PDF file. ''' if activities is None: activities = EighthActivity.objects.all().order_by("name") if year is None: year = current_school_year() if no...
Accepts EighthActivity objects and outputs a PDF file.
def get(self, name): """Provides a method to retrieve all routemap configuration related to the name attribute. Args: name (string): The name of the routemap. Returns: None if the specified routemap does not exists. If the routermap exists a dictiona...
Provides a method to retrieve all routemap configuration related to the name attribute. Args: name (string): The name of the routemap. Returns: None if the specified routemap does not exists. If the routermap exists a dictionary will be provided as follows::...
def train(symbol_data, train_iterator, valid_iterator, data_column_names, target_names): """Train cnn model Parameters ---------- symbol_data: symbol train_iterator: DataIter Train DataIter valid_iterator: DataIter Valid DataIter data_column_names: li...
Train cnn model Parameters ---------- symbol_data: symbol train_iterator: DataIter Train DataIter valid_iterator: DataIter Valid DataIter data_column_names: list of str Defaults to ('data') for a typical model used in image classifi...
def re_sub(pattern, repl, string, count=0, flags=0, custom_flags=0): """Replace regular expression. Parameters ---------- pattern : `str` or `_sre.SRE_Pattern` Compiled regular expression. repl : `str` or `function` Replacement. string : `str` Input string. count: `i...
Replace regular expression. Parameters ---------- pattern : `str` or `_sre.SRE_Pattern` Compiled regular expression. repl : `str` or `function` Replacement. string : `str` Input string. count: `int` Maximum number of pattern occurrences. flags : `int` ...
def dframe(self, dimensions=None, multi_index=False): """Convert dimension values to DataFrame. Returns a pandas dataframe of columns along each dimension, either completely flat or indexed by key dimensions. Args: dimensions: Dimensions to return as columns mul...
Convert dimension values to DataFrame. Returns a pandas dataframe of columns along each dimension, either completely flat or indexed by key dimensions. Args: dimensions: Dimensions to return as columns multi_index: Convert key dimensions to (multi-)index Return...
def pre_dissect(self, s): """ Decrypt, verify and decompress the message. """ if len(s) < 5: raise Exception("Invalid record: header is too short.") if isinstance(self.tls_session.rcs.cipher, Cipher_NULL): self.deciphered_len = None return s ...
Decrypt, verify and decompress the message.
def load_environment_vars(self, prefix=SANIC_PREFIX): """ Looks for prefixed environment variables and applies them to the configuration if present. """ for k, v in os.environ.items(): if k.startswith(prefix): _, config_key = k.split(prefix, 1) ...
Looks for prefixed environment variables and applies them to the configuration if present.
def _classify(self, X, tree, proba=False): """ Private function that classify a dataset using tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. tree : object proba : bool, optional (default=False) ...
Private function that classify a dataset using tree. Parameters ---------- X : array-like of shape = [n_samples, n_features] The input samples. tree : object proba : bool, optional (default=False) If True then return probabilities else return class ...
def scan_uow_candidates(self): """ method performs two actions: - enlist stale or invalid units of work into reprocessing queue - cancel UOWs that are older than 2 days and have been submitted more than 1 hour ago """ try: since = settings.settings['synergy_start_time...
method performs two actions: - enlist stale or invalid units of work into reprocessing queue - cancel UOWs that are older than 2 days and have been submitted more than 1 hour ago
def fetch_table_names(self, include_system_table=False): """ :return: List of table names in the database. :rtype: list :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| ...
:return: List of table names in the database. :rtype: list :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises simplesqlite.OperationalError: |raises_operational_error| :Sample Code: .. code:: python from simplesql...
def setup(self, publishers=None, subscribers=None, services=None, topics=None, params=None): """ :param publishers: :param subscribers: :param services: :param topics: ONLY HERE for BW compat :param params: :return: """ super(PyrosMock, self).setup...
:param publishers: :param subscribers: :param services: :param topics: ONLY HERE for BW compat :param params: :return:
def set_register(self, motors): """ Gets the value from :class:`~pypot.dynamixel.motor.DxlMotor` and sets it to the specified register. """ if not motors: return ids = [m.id for m in motors] values = (m.__dict__[self.varname] for m in motors) getattr(self.io, 'set_{}...
Gets the value from :class:`~pypot.dynamixel.motor.DxlMotor` and sets it to the specified register.
def sshAppliance(self, *args, **kwargs): """ :param args: arguments to execute in the appliance :param kwargs: tty=bool tells docker whether or not to create a TTY shell for interactive SSHing. The default value is False. Input=string is passed as input to the Popen call....
:param args: arguments to execute in the appliance :param kwargs: tty=bool tells docker whether or not to create a TTY shell for interactive SSHing. The default value is False. Input=string is passed as input to the Popen call.