code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def rotate(self, angle, center=(0, 0)): """ Rotate this object. Parameters ---------- angle : number The angle of rotation (in *radians*). center : array-like[2] Center point for the rotation. Returns ------- out : ``Polyg...
Rotate this object. Parameters ---------- angle : number The angle of rotation (in *radians*). center : array-like[2] Center point for the rotation. Returns ------- out : ``PolygonSet`` This object.
def groups_leave(self, room_id, **kwargs): """Causes the callee to be removed from the private group, if they’re part of it and are not the last owner.""" return self.__call_api_post('groups.leave', roomId=room_id, kwargs=kwargs)
Causes the callee to be removed from the private group, if they’re part of it and are not the last owner.
def _recv_callback(self, msg): """ Method is called when there is a message coming from a Mongrel2 server. This message should be a valid Request String. """ m2req = MongrelRequest.parse(msg[0]) MongrelConnection(m2req, self._sending_stream, self.request_callback, ...
Method is called when there is a message coming from a Mongrel2 server. This message should be a valid Request String.
def add_positional_embedding(x, max_length, name=None, positions=None): """Adds positional embedding. Args: x: Tensor with shape [batch, length, depth]. max_length: int representing static maximum size of any dimension. name: str representing name of the embedding tf.Variable. positions: Tensor wit...
Adds positional embedding. Args: x: Tensor with shape [batch, length, depth]. max_length: int representing static maximum size of any dimension. name: str representing name of the embedding tf.Variable. positions: Tensor with shape [batch, length]. Returns: Tensor of same shape as x.
def unusedoptions(self, sections): """Lists options that have not been used to format other values in their sections. Good for finding out if the user has misspelled any of the options. """ unused = set([]) for section in _list(sections): if not sel...
Lists options that have not been used to format other values in their sections. Good for finding out if the user has misspelled any of the options.
def update(self, message=None, subject=None, days=None, downloads=None, notify=None): """Update properties for a transfer. :param message: updated message to recipient(s) :param subject: updated subject for trasfer ...
Update properties for a transfer. :param message: updated message to recipient(s) :param subject: updated subject for trasfer :param days: updated amount of days transfer is available :param downloads: update amount of downloads allowed for transfer :param notify: update whether...
def get_assets(self): """Gets the asset list resulting from a search. return: (osid.repository.AssetList) - the asset list raise: IllegalState - the list has already been retrieved *compliance: mandatory -- This method must be implemented.* """ if self.retrieved: ...
Gets the asset list resulting from a search. return: (osid.repository.AssetList) - the asset list raise: IllegalState - the list has already been retrieved *compliance: mandatory -- This method must be implemented.*
def find_motif_disruptions( position, ref, alt, genome_fasta, matrices, ): """ Determine whether there is a difference between the ref and alt alleles for TF binding. Requires samtools in your path. Parameters ---------- position : str Zero based genomic coor...
Determine whether there is a difference between the ref and alt alleles for TF binding. Requires samtools in your path. Parameters ---------- position : str Zero based genomic coordinates of the reference allele of the form chrom:start-end (chr5:100-101 for a SNV for instance). The ...
def write_table(self, table, rows, append=False, gzip=False): """ Encode and write out *table* to the profile directory. Args: table: The name of the table to write rows: The rows to write to the table append: If `True`, append the encoded rows to any existin...
Encode and write out *table* to the profile directory. Args: table: The name of the table to write rows: The rows to write to the table append: If `True`, append the encoded rows to any existing data. gzip: If `True`, compress the resulting table ...
def modfacl(acl_type, acl_name='', perms='', *args, **kwargs): ''' Add or modify a FACL for the specified file(s) CLI Examples: .. code-block:: bash salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen salt '*' acl.modfacl default:group mygroup rx /tmp/house/kitchen salt '*...
Add or modify a FACL for the specified file(s) CLI Examples: .. code-block:: bash salt '*' acl.modfacl user myuser rwx /tmp/house/kitchen salt '*' acl.modfacl default:group mygroup rx /tmp/house/kitchen salt '*' acl.modfacl d:u myuser 7 /tmp/house/kitchen salt '*' acl.modfacl ...
def _huffman_encode_char(cls, c): # type: (Union[str, EOS]) -> Tuple[int, int] """ huffman_encode_char assumes that the static_huffman_tree was previously initialized @param str|EOS c: a symbol to encode @return (int, int): the bitstring of the symbol and its bitlength @...
huffman_encode_char assumes that the static_huffman_tree was previously initialized @param str|EOS c: a symbol to encode @return (int, int): the bitstring of the symbol and its bitlength @raise AssertionError
def get_proto(self): """ Return the prototype of the method :rtype: string """ if self.proto_idx_value is None: self.proto_idx_value = self.CM.get_proto(self.proto_idx) return self.proto_idx_value
Return the prototype of the method :rtype: string
def open_channel(self): """Open a new channel with RabbitMQ. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika. """ logger.debug('Creating new channel') self._connection.channel(on_open_callback=self.on_channel_open)
Open a new channel with RabbitMQ. When RabbitMQ responds that the channel is open, the on_channel_open callback will be invoked by pika.
def fromBrdict(cls, master, brdict): """ Construct a new L{BuildRequest} from a dictionary as returned by L{BuildRequestsConnectorComponent.getBuildRequest}. This method uses a cache, which may result in return of stale objects; for the most up-to-date information, use the datab...
Construct a new L{BuildRequest} from a dictionary as returned by L{BuildRequestsConnectorComponent.getBuildRequest}. This method uses a cache, which may result in return of stale objects; for the most up-to-date information, use the database connector methods. @param master: cu...
def create(server_): ''' Create a single BareMetal server from a data dict. ''' try: # Check for required profile parameters before sending any API calls. if server_['profile'] and config.is_profile_configured(__opts__, __act...
Create a single BareMetal server from a data dict.
def add_widgets_context(request, context): """ WIDGETS: * Eighth signup (STUDENT) * Eighth attendance (TEACHER or ADMIN) * Bell schedule (ALL) * Birthdays (ALL) * Administration (ADMIN) * Links (ALL) * Seniors (STUDENT; graduation countdown if senior, link to destinations otherwise) ...
WIDGETS: * Eighth signup (STUDENT) * Eighth attendance (TEACHER or ADMIN) * Bell schedule (ALL) * Birthdays (ALL) * Administration (ADMIN) * Links (ALL) * Seniors (STUDENT; graduation countdown if senior, link to destinations otherwise)
def ReadUnicodeTable(filename, nfields, doline): """Generic Unicode table text file reader. The reader takes care of stripping out comments and also parsing the two different ways that the Unicode tables specify code ranges (using the .. notation and splitting the range across multiple lines). Each non-co...
Generic Unicode table text file reader. The reader takes care of stripping out comments and also parsing the two different ways that the Unicode tables specify code ranges (using the .. notation and splitting the range across multiple lines). Each non-comment line in the table is expected to have the given ...
def x_rolls(self, number, count=0, func=sum): '''Iterator of number dice rolls. :param count: [0] Return list of ``count`` sums :param func: [sum] Apply func to list of individual die rolls func([]) ''' for x in range(number): yield self.roll(count, func)
Iterator of number dice rolls. :param count: [0] Return list of ``count`` sums :param func: [sum] Apply func to list of individual die rolls func([])
def visible_object_layers(self): """ This must return layer objects This is not required for custom data formats. :return: Sequence of pytmx object layers/groups """ return (layer for layer in self.tmx.visible_layers if isinstance(layer, pytmx.TiledObjectGroup))
This must return layer objects This is not required for custom data formats. :return: Sequence of pytmx object layers/groups
def chebyshev_distance(point1, point2): """! @brief Calculate Chebyshev distance between between two vectors. \f[ dist(a, b) = \max_{}i\left (\left | a_{i} - b_{i} \right |\right ); \f] @param[in] point1 (array_like): The first vector. @param[in] point2 (array_like): The second ve...
! @brief Calculate Chebyshev distance between between two vectors. \f[ dist(a, b) = \max_{}i\left (\left | a_{i} - b_{i} \right |\right ); \f] @param[in] point1 (array_like): The first vector. @param[in] point2 (array_like): The second vector. @return (double) Chebyshev distance...
def deconstruct(self): """Deconstruct method.""" name, path, args, kwargs = super().deconstruct() if self.populate_from is not None: kwargs['populate_from'] = self.populate_from if self.unique_with != (): kwargs['unique_with'] = self.unique_with kwar...
Deconstruct method.
async def create_cred( self, cred_offer_json, cred_req_json: str, cred_attrs: dict, rr_size: int = None) -> (str, str): """ Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for attribu...
Create credential as Issuer out of credential request and dict of key:value (raw, unencoded) entries for attributes. Return credential json, and if cred def supports revocation, credential revocation identifier. Raise WalletState for closed wallet. If the credential definition supports...
def bookmarks_changed(self): """Bookmarks list has changed.""" bookmarks = self.editor.get_bookmarks() if self.editor.bookmarks != bookmarks: self.editor.bookmarks = bookmarks self.sig_save_bookmarks.emit(self.filename, repr(bookmarks))
Bookmarks list has changed.
def has_gradient(self): """Returns true if _backward and _forward_backward can be called by an attack, False otherwise. """ try: self.__model.gradient self.__model.predictions_and_gradient except AttributeError: return False else: ...
Returns true if _backward and _forward_backward can be called by an attack, False otherwise.
def ws_url(self): """websocket url matching the current request turns http[s]://host[:port] into ws[s]://host[:port] """ proto = self.request.protocol.replace('http', 'ws') host = self.application.ipython_app.websocket_host # default to config value if ho...
websocket url matching the current request turns http[s]://host[:port] into ws[s]://host[:port]
def open(server=None, url=None, ip=None, port=None, name=None, https=None, auth=None, verify_ssl_certificates=True, proxy=None, cookies=None, verbose=True, _msgs=None): r""" Establish connection to an existing H2O server. The connection is not kept alive, so what this method actual...
r""" Establish connection to an existing H2O server. The connection is not kept alive, so what this method actually does is it attempts to connect to the specified server, and checks that the server is healthy and responds to REST API requests. If the H2O server cannot be reached, an :c...
def extract_anomalies(y_true, smoothed_errors, window_size, batch_size, error_buffer): """ Extracts anomalies from the errors. Args: y_true (): smoothed_errors (): window_size (int): batch_size (int): error_buffer (int): Returns: ...
Extracts anomalies from the errors. Args: y_true (): smoothed_errors (): window_size (int): batch_size (int): error_buffer (int): Returns:
def _update_limits_from_api(self): """ Call the service's API action to retrieve limit/quota information, and update AwsLimit objects in ``self.limits`` with this information. """ try: self.connect() resp = self.conn.get_send_quota() except Endpoin...
Call the service's API action to retrieve limit/quota information, and update AwsLimit objects in ``self.limits`` with this information.
def _get_quantile_ratio(self, X, y): """find the expirical quantile of the model Parameters ---------- X : array-like, shape (n_samples, m_features) Training vectors, where n_samples is the number of samples and m_features is the number of features. y : a...
find the expirical quantile of the model Parameters ---------- X : array-like, shape (n_samples, m_features) Training vectors, where n_samples is the number of samples and m_features is the number of features. y : array-like, shape (n_samples,) Target...
def top_priority_effect(effects): """ Given a collection of variant transcript effects, return the top priority object. ExonicSpliceSite variants require special treatment since they actually represent two effects -- the splicing modification and whatever else would happen to the exonic sequence if ...
Given a collection of variant transcript effects, return the top priority object. ExonicSpliceSite variants require special treatment since they actually represent two effects -- the splicing modification and whatever else would happen to the exonic sequence if nothing else gets changed. In cases where ...
def get_file(self, name, filename): """Saves the content of file named ``name`` to ``filename``. Works like :meth:`get_stream`, but ``filename`` is the name of a file which will be created (or overwritten). Returns the full versioned name of the retrieved file. """ ...
Saves the content of file named ``name`` to ``filename``. Works like :meth:`get_stream`, but ``filename`` is the name of a file which will be created (or overwritten). Returns the full versioned name of the retrieved file.
def apply_strategy(self): """ Apply deduplication with the configured strategy. Transform strategy keyword into its method ID, and call it. """ method_id = self.conf.strategy.replace('-', '_') if not hasattr(DuplicateSet, method_id): raise NotImplementedError( ...
Apply deduplication with the configured strategy. Transform strategy keyword into its method ID, and call it.
def do_create(marfile, files, compress, productversion=None, channel=None, signing_key=None, signing_algorithm=None): """Create a new MAR file.""" with open(marfile, 'w+b') as f: with MarWriter(f, productversion=productversion, channel=channel, signing_key=signing_ke...
Create a new MAR file.
def run(self, clf): """ run activity-based voxel selection Sort the voxels based on the cross-validation accuracy of their activity vectors within the searchlight Parameters ---------- clf: classification function the classifier to be used in cross validatio...
run activity-based voxel selection Sort the voxels based on the cross-validation accuracy of their activity vectors within the searchlight Parameters ---------- clf: classification function the classifier to be used in cross validation Returns -----...
def purge(self): """ Purge the stream. This removes all data and clears the calculated intervals :return: None """ self.channel.purge_stream(self.stream_id, remove_definition=False, sandbox=None)
Purge the stream. This removes all data and clears the calculated intervals :return: None
def check(self, feature): """Check that fit can be called on reference data""" mapper = feature.as_dataframe_mapper() mapper.fit(self.X, y=self.y)
Check that fit can be called on reference data
def isempty(path): """Returns True if the given file or directory path is empty. **Examples**: :: auxly.filesys.isempty("foo.txt") # Works on files... auxly.filesys.isempty("bar") # ...or directories! """ if op.isdir(path): return [] == os.listdir(path) elif op.isfile(...
Returns True if the given file or directory path is empty. **Examples**: :: auxly.filesys.isempty("foo.txt") # Works on files... auxly.filesys.isempty("bar") # ...or directories!
def get_scaled(self, factor): """ Get a new time unit, scaled by the given factor """ res = TimeUnit(self) res._factor = self._factor * factor res._unit = self._unit return res
Get a new time unit, scaled by the given factor
def load_essentiality(self, model): """Load and validate all data files.""" data = self.config.get("essentiality") if data is None: return experiments = data.get("experiments") if experiments is None or len(experiments) == 0: return path = self.get...
Load and validate all data files.
def _get_nop_length(cls, insns): """ Calculate the total size of leading nop instructions. :param insns: A list of capstone insn objects. :return: Number of bytes of leading nop instructions. :rtype: int """ nop_length = 0 if insns and cls._is_noop_insn...
Calculate the total size of leading nop instructions. :param insns: A list of capstone insn objects. :return: Number of bytes of leading nop instructions. :rtype: int
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Task object for each one, initializing them one at a time, and changing the attrs attribute (which just ...
The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Task object for each one, initializing them one at a time, and changing the attrs attribute (which just holds a list of plain dictionaries) with a MambuTas...
def parse_deps(orig_doc, options={}): """Generate dependency parse in {'words': [], 'arcs': []} format. doc (Doc): Document do parse. RETURNS (dict): Generated dependency parse keyed by words and arcs. """ doc = Doc(orig_doc.vocab).from_bytes(orig_doc.to_bytes()) if not doc.is_parsed: u...
Generate dependency parse in {'words': [], 'arcs': []} format. doc (Doc): Document do parse. RETURNS (dict): Generated dependency parse keyed by words and arcs.
def post_async(self, url, data, callback=None, params=None, headers=None): """ Asynchronous POST request with the process pool. """ params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url, None) self._authenticate(params, headers) ...
Asynchronous POST request with the process pool.
def supports_object_type(self, object_type=None): """Tests if the given object type is supported. arg: object_type (osid.type.Type): an object Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not an ``OBJ...
Tests if the given object type is supported. arg: object_type (osid.type.Type): an object Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not an ``OBJECT`` raise: NullArgument - ``object_type`` is ``nul...
def mosh_args(conn): """Create SSH command for connecting specified server.""" I, = conn.identities identity = I.identity_dict args = [] if 'port' in identity: args += ['-p', identity['port']] if 'user' in identity: args += [identity['user']+'@'+identity['host']] else: ...
Create SSH command for connecting specified server.
def allowance(self, filename): """Preconditions: - our agent applies to this entry - filename is URL decoded""" for line in self.rulelines: if line.applies_to(filename): return line.allowance return True
Preconditions: - our agent applies to this entry - filename is URL decoded
def bgseq(code): """ Returns the background color terminal escape sequence for the given color code number. """ if isinstance(code, str): code = nametonum(code) if code == -1: return "" s = termcap.get('setab', code) or termcap.get('setb', code) return s
Returns the background color terminal escape sequence for the given color code number.
def consume_messages(self, max_next_messages): """ Get messages batch from Kafka (list at output) """ # get messages list from kafka if self.__next_messages == 0: self.set_next_messages(min(1000, max_next_messages)) self.set_next_messages(min(self.__next_messages, max_next_me...
Get messages batch from Kafka (list at output)
def _search_files(path): """Search a folder for data files .. versionchanged:: 0.6.0 `path` is not searched recursively anymore """ path = pathlib.Path(path) fifo = [] for fp in path.glob("*"): if fp.is_dir(): continue ...
Search a folder for data files .. versionchanged:: 0.6.0 `path` is not searched recursively anymore
def semiyearly(date=datetime.date.today()): """ Twice a year. """ return datetime.date(date.year, 1 if date.month < 7 else 7, 1)
Twice a year.
def update(self, modelID, modelParams, modelParamsHash, metricResult, completed, completionReason, matured, numRecords): """ Insert a new entry or update an existing one. If this is an update of an existing entry, then modelParams will be None Parameters: ----------------------------------...
Insert a new entry or update an existing one. If this is an update of an existing entry, then modelParams will be None Parameters: -------------------------------------------------------------------- modelID: globally unique modelID of this model modelParams: params dict for this model, or...
def aliases(*names): """ Defines alternative command name(s) for given function (along with its original name). Usage:: @aliases('co', 'check') def checkout(args): ... The resulting command will be available as ``checkout``, ``check`` and ``co``. .. note:: This...
Defines alternative command name(s) for given function (along with its original name). Usage:: @aliases('co', 'check') def checkout(args): ... The resulting command will be available as ``checkout``, ``check`` and ``co``. .. note:: This decorator only works with a rece...
def get_channelstate_by_token_network_and_partner( chain_state: ChainState, token_network_id: TokenNetworkID, partner_address: Address, ) -> Optional[NettingChannelState]: """ Return the NettingChannelState if it exists, None otherwise. """ token_network = get_token_network_by_identifier...
Return the NettingChannelState if it exists, None otherwise.
def dumps(obj, *args, **kwargs): ''' Typeless dump an object to json string ''' return json.dumps(obj, *args, cls=TypelessSONEncoder, ensure_ascii=False, **kwargs)
Typeless dump an object to json string
def consistency(self): """ Get a percentage of fill between the min and max time the moc is defined. A value near 0 shows a sparse temporal moc (i.e. the moc does not cover a lot of time and covers very distant times. A value near 1 means that the moc covers a lot of time withou...
Get a percentage of fill between the min and max time the moc is defined. A value near 0 shows a sparse temporal moc (i.e. the moc does not cover a lot of time and covers very distant times. A value near 1 means that the moc covers a lot of time without big pauses. Returns ----...
def _make_plan(plan_dict): """ Construct a Plan or ProfiledPlan from a dictionary of metadata values. :param plan_dict: :return: """ operator_type = plan_dict["operatorType"] identifiers = plan_dict.get("identifiers", []) arguments = plan_dict.get("args", []) children = [_make_plan(chil...
Construct a Plan or ProfiledPlan from a dictionary of metadata values. :param plan_dict: :return:
def GetParametro(self, clave, clave1=None, clave2=None, clave3=None, clave4=None): "Devuelve un parámetro de salida (establecido por llamada anterior)" # útil para parámetros de salida (por ej. campos de TransaccionPlainWS) valor = self.params_out.get(clave) # busco datos "anidados" (lis...
Devuelve un parámetro de salida (establecido por llamada anterior)
def build_job_configs(self, args): """Hook to build job configurations """ job_configs = {} components = Component.build_from_yamlfile(args['comp']) NAME_FACTORY.update_base_dict(args['data']) ret_dict = make_diffuse_comp_info_dict(components=components, ...
Hook to build job configurations
def delay_and_stop(duration, dll, device_number): """Stop vibration aka force feedback aka rumble on Windows after duration miliseconds.""" xinput = getattr(ctypes.windll, dll) time.sleep(duration/1000) xinput_set_state = xinput.XInputSetState xinput_set_state.argtypes = [ ctypes.c_uint,...
Stop vibration aka force feedback aka rumble on Windows after duration miliseconds.
def verify_merkle_path(merkle_root_hex, serialized_path, leaf_hash_hex, hash_function=bin_double_sha256): """ Verify a merkle path. The given path is the path from two leaf nodes to the root itself. merkle_root_hex is a little-endian, hex-encoded hash. serialized_path is the serialized merkle path ...
Verify a merkle path. The given path is the path from two leaf nodes to the root itself. merkle_root_hex is a little-endian, hex-encoded hash. serialized_path is the serialized merkle path path_hex is a list of little-endian, hex-encoded hashes. Return True if the path is consistent with the merkle r...
def _get_job_results(query=None): ''' Executes a query that requires a job for completion. This function will wait for the job to complete and return the results. ''' if not query: raise CommandExecutionError("Query parameters cannot be empty.") response = __proxy__['panos.call'](query)...
Executes a query that requires a job for completion. This function will wait for the job to complete and return the results.
def pace(self): """Average pace (mm:ss/km for the workout""" secs_per_km = self.duration / (self.distance / 1000) return time.strftime('%M:%S', time.gmtime(secs_per_km))
Average pace (mm:ss/km for the workout
def cauldron_extras(self): """ Yield extra tuples containing a field name and a callable that takes a row """ for extra in super(Dimension, self).cauldron_extras: yield extra if self.formatters: prop = self.id + '_raw' else: prop = sel...
Yield extra tuples containing a field name and a callable that takes a row
def add_edges(self): """ Draws all of the edges in the graph. """ for group, edgelist in self.edges.items(): for (u, v, d) in edgelist: self.draw_edge(u, v, d, group)
Draws all of the edges in the graph.
def _definition(self): """|HeaderPart| object containing content of this header.""" headerReference = self._sectPr.get_headerReference(self._hdrftr_index) return self._document_part.header_part(headerReference.rId)
|HeaderPart| object containing content of this header.
def update_layers_esri_mapserver(service, greedy_opt=False): """ Update layers for an ESRI REST MapServer. Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/SampleWorldCities/MapServer/?f=json """ try: esri_service = ArcMapService(service.url) # set srs # both m...
Update layers for an ESRI REST MapServer. Sample endpoint: https://gis.ngdc.noaa.gov/arcgis/rest/services/SampleWorldCities/MapServer/?f=json
def list_ec2(region, filter_by_kwargs): """List running ec2 instances.""" conn = boto.ec2.connect_to_region(region) instances = conn.get_only_instances() return lookup(instances, filter_by=filter_by_kwargs)
List running ec2 instances.
def callprop(self, prop, *args): '''Call a property prop as a method (this will be self). NOTE: dont pass this and arguments here, these will be added automatically!''' if not isinstance(prop, basestring): prop = prop.to_string().value cand = self.get(prop) i...
Call a property prop as a method (this will be self). NOTE: dont pass this and arguments here, these will be added automatically!
def jens_transformation_beta(graph: BELGraph) -> DiGraph: """Apply Jens' Transformation (Type 2) to the graph. 1. Induce a sub-graph over causal and correlative relations 2. Transform edges with the following rules: - increases => backwards decreases - decreases => decreases - posit...
Apply Jens' Transformation (Type 2) to the graph. 1. Induce a sub-graph over causal and correlative relations 2. Transform edges with the following rules: - increases => backwards decreases - decreases => decreases - positive correlation => delete - negative correlation => two w...
def readLiteralContextModes(self): """Read literal context modes. LSB6: lower 6 bits of last char MSB6: upper 6 bits of last char UTF8: rougly dependent on categories: upper 4 bits depend on category of last char: control/whitespace/space/ punctuation/quote/%/...
Read literal context modes. LSB6: lower 6 bits of last char MSB6: upper 6 bits of last char UTF8: rougly dependent on categories: upper 4 bits depend on category of last char: control/whitespace/space/ punctuation/quote/%/open/close/ comma/period/=/dig...
def get_missing_simulations(self, param_list, runs=None): """ Return a list of the simulations among the required ones that are not available in the database. Args: param_list (list): a list of dictionaries containing all the parameters combinations. ...
Return a list of the simulations among the required ones that are not available in the database. Args: param_list (list): a list of dictionaries containing all the parameters combinations. runs (int): an integer representing how many repetitions are wanted ...
def nnz_obs_groups(self): """ get the observation groups that contain at least one non-zero weighted observation Returns ------- nnz_obs_groups : list a list of observation groups that contain at least one non-zero weighted observation """ ...
get the observation groups that contain at least one non-zero weighted observation Returns ------- nnz_obs_groups : list a list of observation groups that contain at least one non-zero weighted observation
def put(self, key, value): '''Stores the object `value` named by `key`. Serializes values on the way in, and stores the serialized data into the ``child_datastore``. Args: key: Key naming `value` value: the object to store. ''' value = self.serializedValue(value) self.child_dat...
Stores the object `value` named by `key`. Serializes values on the way in, and stores the serialized data into the ``child_datastore``. Args: key: Key naming `value` value: the object to store.
def create_api_key(awsclient, api_name, api_key_name): """Create a new API key as reference for api.conf. :param api_name: :param api_key_name: :return: api_key """ _sleep() client_api = awsclient.get_client('apigateway') print('create api key: %s' % api_key_name) response = client...
Create a new API key as reference for api.conf. :param api_name: :param api_key_name: :return: api_key
def _execute(self, method_function, method_name, resource, **params): """ Generic TeleSign REST API request handler. :param method_function: The Requests HTTP request function to perform the request. :param method_name: The HTTP method name, as an upper case string. :param resou...
Generic TeleSign REST API request handler. :param method_function: The Requests HTTP request function to perform the request. :param method_name: The HTTP method name, as an upper case string. :param resource: The partial resource URI to perform the request against, as a string. :param ...
def set_weekly(self, interval, *, days_of_week, first_day_of_week, **kwargs): """ Set to repeat every week on specified days for every x no. of days :param int interval: no. of days to repeat at :param str first_day_of_week: starting day for a week :param list[str] da...
Set to repeat every week on specified days for every x no. of days :param int interval: no. of days to repeat at :param str first_day_of_week: starting day for a week :param list[str] days_of_week: list of days of the week to repeat :keyword date start: Start date of repetition (kwargs)...
def get_recover_position(gzfile, last_good_position): # type: (gzip.GzipFile, int) -> int """ Return position of a next gzip stream in a GzipFile, or -1 if it is not found. XXX: caller must ensure that the same last_good_position is not used multiple times for the same gzfile. """ ...
Return position of a next gzip stream in a GzipFile, or -1 if it is not found. XXX: caller must ensure that the same last_good_position is not used multiple times for the same gzfile.
def _parse(reactor, directory, pemdir, *args, **kwargs): """ Parse a txacme endpoint description. :param reactor: The Twisted reactor. :param directory: ``twisted.python.url.URL`` for the ACME directory to use for issuing certs. :param str pemdir: The path to the certificate directory to us...
Parse a txacme endpoint description. :param reactor: The Twisted reactor. :param directory: ``twisted.python.url.URL`` for the ACME directory to use for issuing certs. :param str pemdir: The path to the certificate directory to use.
def closest_pixel_to_set(self, start, pixel_set, direction, w=13, t=0.5): """Starting at pixel, moves start by direction * t until there is a pixel from pixel_set within a radius w of start. Then, returns start. Parameters ---------- start : :obj:`numpy.ndarray` of float ...
Starting at pixel, moves start by direction * t until there is a pixel from pixel_set within a radius w of start. Then, returns start. Parameters ---------- start : :obj:`numpy.ndarray` of float The initial pixel location at which to start. pixel_set : set of 2-tupl...
def JoinKeyPath(path_segments): """Joins the path segments into key path. Args: path_segments (list[str]): Windows Registry key path segments. Returns: str: key path. """ # This is an optimized way to combine the path segments into a single path # and combine multiple successive path separators to...
Joins the path segments into key path. Args: path_segments (list[str]): Windows Registry key path segments. Returns: str: key path.
def segment_snrs(filters, stilde, psd, low_frequency_cutoff): """ This functions calculates the snr of each bank veto template against the segment Parameters ---------- filters: list of FrequencySeries The list of bank veto templates filters. stilde: FrequencySeries The current ...
This functions calculates the snr of each bank veto template against the segment Parameters ---------- filters: list of FrequencySeries The list of bank veto templates filters. stilde: FrequencySeries The current segment of data. psd: FrequencySeries low_frequency_cutoff: fl...
def access_key(self, data): """ Set a new access code which will be required for future re-programmings of your YubiKey. Supply data as either a raw string, or a hexlified string prefixed by 'h:'. The result, after any hex decoding, must be 6 bytes. """ if data.startswit...
Set a new access code which will be required for future re-programmings of your YubiKey. Supply data as either a raw string, or a hexlified string prefixed by 'h:'. The result, after any hex decoding, must be 6 bytes.
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'section_titles') and self.section_titles is not None: _dict['section_titles'] = [ x._to_dict() for x in self.section_titles ] if hasattr(self, ...
Return a json dictionary representing this model.
def transliterate(self, target_language="en"): """Transliterate the string to the target language.""" return WordList([w.transliterate(target_language) for w in self.words], language=target_language, parent=self)
Transliterate the string to the target language.
def SetSelected( self, node, point=None, propagate=True ): """Set the given node selected in the square-map""" if node == self.selectedNode: return self.selectedNode = node self.UpdateDrawing() if node: wx.PostEvent( self, SquareSelectionEvent( node=node, ...
Set the given node selected in the square-map
def get_operator(self, operator): """ Get a comparison suffix to be used in Django ORM & inversion flag for it :param operator: string, DjangoQL comparison operator :return: (suffix, invert) - a tuple with 2 values: suffix - suffix to be used in ORM query, for example '__gt'...
Get a comparison suffix to be used in Django ORM & inversion flag for it :param operator: string, DjangoQL comparison operator :return: (suffix, invert) - a tuple with 2 values: suffix - suffix to be used in ORM query, for example '__gt' for '>' invert - boolean, True if this co...
def delete_contribution(self, url): """Delete the contribution with this identifier :rtype: bool :returns: True if the contribution was deleted, False otherwise (eg. if it didn't exist) """ # first validate that this is a real contrib try: result = self.api_...
Delete the contribution with this identifier :rtype: bool :returns: True if the contribution was deleted, False otherwise (eg. if it didn't exist)
def assign(self, partitions): """Manually assign a list of TopicPartitions to this consumer. Arguments: partitions (list of TopicPartition): Assignment for this instance. Raises: IllegalStateError: If consumer has already called :meth:`~kafka.KafkaConsumer.s...
Manually assign a list of TopicPartitions to this consumer. Arguments: partitions (list of TopicPartition): Assignment for this instance. Raises: IllegalStateError: If consumer has already called :meth:`~kafka.KafkaConsumer.subscribe`. Warning: ...
def get_bound_form(self, noun, gender): """Return bound form of nound, given its gender.""" syllables = self.syllabifier.syllabify(noun) stem = self.stemmer.get_stem(noun, gender) cv_pattern = self.cv_patterner.get_cv_pattern(stem) # Based on Huehnergard Appendix 6.C.1: base in -...
Return bound form of nound, given its gender.
def datatype(dbtype, description, cursor): """Google AppEngine Helper to convert a data type into a string.""" dt = cursor.db.introspection.get_field_type(dbtype, description) if type(dt) is tuple: return dt[0] else: return dt
Google AppEngine Helper to convert a data type into a string.
def cudaMemcpy_htod(dst, src, count): """ Copy memory from host to device. Copy data from host memory to device memory. Parameters ---------- dst : ctypes pointer Device memory pointer. src : ctypes pointer Host memory pointer. count : int Number of bytes to cop...
Copy memory from host to device. Copy data from host memory to device memory. Parameters ---------- dst : ctypes pointer Device memory pointer. src : ctypes pointer Host memory pointer. count : int Number of bytes to copy.
def run(self, clock, generalLedger): """ Execute the component at the current clock cycle. :param clock: The clock containing the current execution time and period information. :param generalLedger: The general ledger into which to create the transactions. ""...
Execute the component at the current clock cycle. :param clock: The clock containing the current execution time and period information. :param generalLedger: The general ledger into which to create the transactions.
def IPNetwork(address, version=None, strict=False): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by defaul...
Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. version: An Integer, if set, don't try to automa...
def safe_getattr(brain_or_object, attr, default=_marker): """Return the attribute value :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param attr: Attribute name :type attr: str :returns: Attribute value ...
Return the attribute value :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :param attr: Attribute name :type attr: str :returns: Attribute value :rtype: obj
def setval(self, varname, value): """ Set the value of the variable with the given name. """ if varname in self: self[varname]['value'] = value else: self[varname] = Variable(self.default_type, value=value)
Set the value of the variable with the given name.
def retrieve_pt(cls, request, service): """`request` should be the current HttpRequest object `service` a string representing the service for witch we want to retrieve a ticket. The function return a Proxy Ticket or raise `ProxyError` """ try: pgt = cls.object...
`request` should be the current HttpRequest object `service` a string representing the service for witch we want to retrieve a ticket. The function return a Proxy Ticket or raise `ProxyError`
def chunks(l:Collection, n:int)->Iterable: "Yield successive `n`-sized chunks from `l`." for i in range(0, len(l), n): yield l[i:i+n]
Yield successive `n`-sized chunks from `l`.
def handle(self, source, target, app=None, **options): """ command execution """ translation.activate(settings.LANGUAGE_CODE) if app: unpack = app.split('.') if len(unpack) == 2: models = [get_model(unpack[0], unpack[1])] elif len(unpack) == 1...
command execution
def dollarfy(x): """Replaces Math elements in element list 'x' with a $-enclosed string. stringify() passes through TeX math. Use dollarfy(x) first to replace Math elements with math strings set in dollars. 'x' should be a deep copy so that the underlying document is left untouched. Returns 'x'....
Replaces Math elements in element list 'x' with a $-enclosed string. stringify() passes through TeX math. Use dollarfy(x) first to replace Math elements with math strings set in dollars. 'x' should be a deep copy so that the underlying document is left untouched. Returns 'x'.
def _check_forest(self, sensors): """Validate that this sensor doesn't end up referencing itself.""" if self in sensors: raise ValueError('Circular dependency in sensors: %s is its own' 'parent.' % (self.name,)) sensors.add(self) for parent in sel...
Validate that this sensor doesn't end up referencing itself.