code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def split_kv_pairs(lines, comment_char="#", filter_string=None, split_on="=", use_partition=False, ordered=False): """Split lines of a list into key/value pairs Use this function to filter and split all lines of a list of strings into a dictionary. Named arguments may be used to control how the line is spl...
Split lines of a list into key/value pairs Use this function to filter and split all lines of a list of strings into a dictionary. Named arguments may be used to control how the line is split, how lines are filtered and the type of output returned. See parameters for more information. When splitting ...
def find_source_files(input_path, excludes): """ Get a list of filenames for all Java source files within the given directory. """ java_files = [] input_path = os.path.normpath(os.path.abspath(input_path)) for dirpath, dirnames, filenames in os.walk(input_path): if is_excluded(dirpat...
Get a list of filenames for all Java source files within the given directory.
def _get_stddevs(self, coeffs, stddev_types): """ Equation (11) on p. 207 for total standard error at a given site: ``σ{ln(ε_site)} = sqrt(σ{ln(ε_br)}**2 + σ{ln(δ_site)}**2)`` """ for stddev_type in stddev_types: assert stddev_type in self.DEFINED_FOR_STANDARD_DEVIAT...
Equation (11) on p. 207 for total standard error at a given site: ``σ{ln(ε_site)} = sqrt(σ{ln(ε_br)}**2 + σ{ln(δ_site)}**2)``
def generateImplicitParameters(cls, obj): """ Create PRODID, VERSION, and VTIMEZONEs if needed. VTIMEZONEs will need to exist whenever TZID parameters exist or when datetimes with tzinfo exist. """ for comp in obj.components(): if comp.behavior is not None: ...
Create PRODID, VERSION, and VTIMEZONEs if needed. VTIMEZONEs will need to exist whenever TZID parameters exist or when datetimes with tzinfo exist.
def list_voices( self, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Returns a list of ``Voice`` supported for synthesis. Example: >>> from google....
Returns a list of ``Voice`` supported for synthesis. Example: >>> from google.cloud import texttospeech_v1beta1 >>> >>> client = texttospeech_v1beta1.TextToSpeechClient() >>> >>> response = client.list_voices() Args: language_code...
def power(maf=0.5,beta=0.1, N=100, cutoff=5e-8): """ estimate power for a given allele frequency, effect size beta and sample size N Assumption: z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) )...
estimate power for a given allele frequency, effect size beta and sample size N Assumption: z-score = beta_ML distributed as p(0) = N(0,1.0(maf*(1-maf)*N))) under the null hypothesis the actual beta_ML is distributed as p(alt) = N( beta , 1.0/(maf*(1-maf)N) ) Arguments: maf: minor allele frequency of the ...
def message(self, to, subject, text): """Alias for :meth:`compose`.""" return self.compose(to, subject, text)
Alias for :meth:`compose`.
def as_pseudo(cls, obj): """ Convert obj into a pseudo. Accepts: * Pseudo object. * string defining a valid path. """ return obj if isinstance(obj, cls) else cls.from_file(obj)
Convert obj into a pseudo. Accepts: * Pseudo object. * string defining a valid path.
def change_site(self, old_site_name, new_site_name, new_location_name=None, new_er_data=None, new_pmag_data=None, replace_data=False): """ Find actual data objects for site and location. Then call the Site class change method to update site name and data. """ ...
Find actual data objects for site and location. Then call the Site class change method to update site name and data.
def confirm_answer(self, answer, message=None): """ Prompts the user to confirm a question with a yes/no prompt. If no message is specified, the default message is: "You entered {}. Is this correct?" :param answer: the answer to confirm. :param message: a message to display rath...
Prompts the user to confirm a question with a yes/no prompt. If no message is specified, the default message is: "You entered {}. Is this correct?" :param answer: the answer to confirm. :param message: a message to display rather than the default message. :return: True if the user confi...
def get_tectonic_regionalisation(self, regionalisation, region_type=None): ''' Defines the tectonic region and updates the shear modulus, magnitude scaling relation and displacement to length ratio using the regional values, if not previously defined for the fault :param regiona...
Defines the tectonic region and updates the shear modulus, magnitude scaling relation and displacement to length ratio using the regional values, if not previously defined for the fault :param regionalistion: Instance of the :class: openquake.hmtk.faults.tectonic_regiona...
def download_to_bytes(url, chunk_size=1024 * 1024 * 10, loadbar_length=10): """Download a url to bytes. if chunk_size is not None, prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook) :param url: str or url :param chunk_size: None or int in bytes :param loadbar...
Download a url to bytes. if chunk_size is not None, prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook) :param url: str or url :param chunk_size: None or int in bytes :param loadbar_length: int length of load bar :return: (bytes, encoding)
def split_traversal(traversal, edges, edges_hash=None): """ Given a traversal as a list of nodes, split the traversal if a sequential index pair is not in the given edges. Parameters -------------- edges : (n, 2) int Graph edge indexes traversa...
Given a traversal as a list of nodes, split the traversal if a sequential index pair is not in the given edges. Parameters -------------- edges : (n, 2) int Graph edge indexes traversal : (m,) int Traversal through edges edge_hash : (n,) Edges sorted on axis=1 and pa...
def _print_task_data(self, task): """Pretty-prints task data. Args: task: Task dict generated by Turbinia. """ print(' {0:s} ({1:s})'.format(task['name'], task['id'])) paths = task.get('saved_paths', []) if not paths: return for path in paths: if path.endswith('worker-log....
Pretty-prints task data. Args: task: Task dict generated by Turbinia.
def make_stream_features(self, stream, features): """Add resource binding feature to the <features/> element of the stream. [receving entity only] :returns: update <features/> element. """ self.stream = stream if stream.peer_authenticated and not stream.peer.res...
Add resource binding feature to the <features/> element of the stream. [receving entity only] :returns: update <features/> element.
def _process_data(self, sd, ase, offsets, data): # type: (SyncCopy, blobxfer.models.synccopy.Descriptor, # blobxfer.models.azure.StorageEntity, # blobxfer.models.synccopy.Offsets, bytes) -> None """Process downloaded data for upload :param SyncCopy self: this ...
Process downloaded data for upload :param SyncCopy self: this :param blobxfer.models.synccopy.Descriptor sd: synccopy descriptor :param blobxfer.models.azure.StorageEntity ase: storage entity :param blobxfer.models.synccopy.Offsets offsets: offsets :param bytes data: data to proc...
def truncate(self, table): """Send DDL to truncate the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None """ truncate_sql, serial_key_sql =...
Send DDL to truncate the specified `table` :Parameters: - `table`: an instance of a :py:class:`mysql2pgsql.lib.mysql_reader.MysqlReader.Table` object that represents the table to read/write. Returns None
def _PSat_h(h): """Define the saturated line, P=f(h) for region 3 Parameters ---------- h : float Specific enthalpy, [kJ/kg] Returns ------- P : float Pressure, [MPa] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * h'(623.15K...
Define the saturated line, P=f(h) for region 3 Parameters ---------- h : float Specific enthalpy, [kJ/kg] Returns ------- P : float Pressure, [MPa] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * h'(623.15K) ≤ h ≤ h''(623.15K) ...
def points_from_sql(self, db_name): """ Retrieve point list from SQL database """ points = self._read_from_sql("SELECT * FROM history;", db_name) return list(points.columns.values)[1:]
Retrieve point list from SQL database
def set_pixel_size(self, deltaPix): """ update pixel size :param deltaPix: :return: """ self._pixel_size = deltaPix if self.psf_type == 'GAUSSIAN': try: del self._kernel_point_source except: pass
update pixel size :param deltaPix: :return:
def emit(self, record): """ Function inserts log messages to list_view """ msg = record.getMessage() list_store = self.list_view.get_model() Gdk.threads_enter() if msg: # Underline URLs in the record message msg = replace_markup_chars(recor...
Function inserts log messages to list_view
def data_to_binary(self): """ :return: bytes """ if self.channel == 0x01: tmp = 0x03 else: tmp = 0x0C return bytes([ COMMAND_CODE, tmp ]) + struct.pack('>L', self.delay_time)[-3:]
:return: bytes
def update_scope(self, patch_document, scope_id): """UpdateScope. [Preview API] :param :class:`<[JsonPatchOperation]> <azure.devops.v5_0.identity.models.[JsonPatchOperation]>` patch_document: :param str scope_id: """ route_values = {} if scope_id is not None: ...
UpdateScope. [Preview API] :param :class:`<[JsonPatchOperation]> <azure.devops.v5_0.identity.models.[JsonPatchOperation]>` patch_document: :param str scope_id:
def is_legal_sequence(self, packet: DataPacket) -> bool: """ Check if the Sequence number of the DataPacket is legal. For more information see page 17 of http://tsp.esta.org/tsp/documents/docs/E1-31-2016.pdf. :param packet: the packet to check :return: true if the sequence is leg...
Check if the Sequence number of the DataPacket is legal. For more information see page 17 of http://tsp.esta.org/tsp/documents/docs/E1-31-2016.pdf. :param packet: the packet to check :return: true if the sequence is legal. False if the sequence number is bad
def firmware_checksum(self, firmware_checksum): """ Sets the firmware_checksum of this DeviceDataPostRequest. The SHA256 checksum of the current firmware image. :param firmware_checksum: The firmware_checksum of this DeviceDataPostRequest. :type: str """ if firmw...
Sets the firmware_checksum of this DeviceDataPostRequest. The SHA256 checksum of the current firmware image. :param firmware_checksum: The firmware_checksum of this DeviceDataPostRequest. :type: str
def handle_event(self, event): """Handle incoming packet from rflink gateway.""" if event.get('command'): if event['command'] == 'on': cmd = 'off' else: cmd = 'on' task = self.send_command_ack(event['id'], cmd) self.loop.cr...
Handle incoming packet from rflink gateway.
def label_from_func(self, func:Callable, label_cls:Callable=None, **kwargs)->'LabelList': "Apply `func` to every input to get its label." return self._label_from_list([func(o) for o in self.items], label_cls=label_cls, **kwargs)
Apply `func` to every input to get its label.
def get_select_sql(self, columns, order=None, limit=0, skip=0): """ Build a SELECT query based on the current state of the builder. :param columns: SQL fragment describing which columns to select i.e. 'e.obstoryID, s.statusID' :param order: Optional ordering cons...
Build a SELECT query based on the current state of the builder. :param columns: SQL fragment describing which columns to select i.e. 'e.obstoryID, s.statusID' :param order: Optional ordering constraint, i.e. 'e.eventTime DESC' :param limit: Optional, used to ...
def is_valid(self): # type: () -> bool """ Checks if the component is valid :return: Always True if it doesn't raise an exception :raises AssertionError: Invalid properties """ assert self._bundle_context assert self._container_props is not None a...
Checks if the component is valid :return: Always True if it doesn't raise an exception :raises AssertionError: Invalid properties
def get_argument_topology(self): """ Helper function to get topology argument. Raises exception if argument is missing. Returns the topology argument. """ try: topology = self.get_argument(constants.PARAM_TOPOLOGY) return topology except tornado.web.MissingArgumentError as e: ...
Helper function to get topology argument. Raises exception if argument is missing. Returns the topology argument.
def num_batches(n, batch_size): """Compute the number of mini-batches required to cover a data set of size `n` using batches of size `batch_size`. Parameters ---------- n: int the number of samples in the data set batch_size: int the mini-batch size Returns ------- ...
Compute the number of mini-batches required to cover a data set of size `n` using batches of size `batch_size`. Parameters ---------- n: int the number of samples in the data set batch_size: int the mini-batch size Returns ------- int: the number of batches required
def check_need_install(): """Check if installed package are exactly the same to this one. By checking md5 value of all files. """ need_install_flag = False for root, _, basename_list in os.walk(SRC): if os.path.basename(root) != "__pycache__": for basename in basename_list: ...
Check if installed package are exactly the same to this one. By checking md5 value of all files.
def typechecked_module(md, force_recursive = False): """Works like typechecked, but is only applicable to modules (by explicit call). md must be a module or a module name contained in sys.modules. """ if not pytypes.checking_enabled: return md if isinstance(md, str): if md in sys.mod...
Works like typechecked, but is only applicable to modules (by explicit call). md must be a module or a module name contained in sys.modules.
def safety_set_allowed_area_encode(self, target_system, target_component, frame, p1x, p1y, p1z, p2x, p2y, p2z): ''' Set a safety zone (volume), which is defined by two corners of a cube. This message can be used to tell the MAV which setpoints/MISSIONs to ...
Set a safety zone (volume), which is defined by two corners of a cube. This message can be used to tell the MAV which setpoints/MISSIONs to accept and which to reject. Safety areas are often enforced by national or competition regulations. ...
def isNull(self): """ Returns whether or not this option set has been modified. :return <bool> """ check = self.raw_values.copy() scope = check.pop('scope', {}) return len(check) == 0 and len(scope) == 0
Returns whether or not this option set has been modified. :return <bool>
def patch(self, patch: int) -> None: """ param patch Patch version number property. Must be a non-negative integer. """ self.filter_negatives(patch) self._patch = patch
param patch Patch version number property. Must be a non-negative integer.
def _CreateMethod(self, method_name): """Create a method wrapping an invocation to the SOAP service. Args: method_name: A string identifying the name of the SOAP method to call. Returns: A callable that can be used to make the desired SOAP request. """ soap_service_method = getattr(sel...
Create a method wrapping an invocation to the SOAP service. Args: method_name: A string identifying the name of the SOAP method to call. Returns: A callable that can be used to make the desired SOAP request.
def is_fundamental(type_): """returns True, if type represents C++ fundamental type""" return does_match_definition( type_, cpptypes.fundamental_t, (cpptypes.const_t, cpptypes.volatile_t)) \ or does_match_definition( type_, cpptypes.fundamental_t, ...
returns True, if type represents C++ fundamental type
def get_densities(self, spin=None): """ Returns the density of states for a particular spin. Args: spin: Spin Returns: Returns the density of states for a particular spin. If Spin is None, the sum of all spins is returned. """ if self...
Returns the density of states for a particular spin. Args: spin: Spin Returns: Returns the density of states for a particular spin. If Spin is None, the sum of all spins is returned.
def render_field(self, field, render_kw): """ Returns the rendered field after adding auto–attributes. Calls the field`s widget with the following kwargs: 1. the *render_kw* set on the field are used as based 2. and are updated with the *render_kw* arguments from the render cal...
Returns the rendered field after adding auto–attributes. Calls the field`s widget with the following kwargs: 1. the *render_kw* set on the field are used as based 2. and are updated with the *render_kw* arguments from the render call 3. this is used as an argument for a call to `get_ht...
def closeEvent(self, event): """ things to be done when gui closes, like save the settings """ self.save_config(self.gui_settings['gui_settings']) self.script_thread.quit() self.read_probes.quit() event.accept() print('\n\n===============================...
things to be done when gui closes, like save the settings
def register_json_encoder(self, encoder_type: type, encoder: JSONEncoder): """ Register the given JSON encoder for use with the given object type. :param encoder_type: the type of object to encode :param encoder: the JSON encoder :return: this builder """ self._js...
Register the given JSON encoder for use with the given object type. :param encoder_type: the type of object to encode :param encoder: the JSON encoder :return: this builder
def session(self): """Return an instance of Requests Session configured for the ThreatConnect API.""" if self._session is None: from .tcex_session import TcExSession self._session = TcExSession(self) return self._session
Return an instance of Requests Session configured for the ThreatConnect API.
def get_similar_users(self, users=None, k=10): """Get the k most similar users for each entry in `users`. Each type of recommender has its own model for the similarity between users. For example, the factorization_recommender will return the nearest users based on the cosine similarity ...
Get the k most similar users for each entry in `users`. Each type of recommender has its own model for the similarity between users. For example, the factorization_recommender will return the nearest users based on the cosine similarity between latent user factors. (This method is not ...
async def self_check(self): """ Checks that the platforms configuration is all right. """ platforms = set() for platform in get_platform_settings(): try: name = platform['class'] cls: Type[Platform] = import_class(name) ex...
Checks that the platforms configuration is all right.
def visit_FunctionDef(self, node, **kwargs): """ Handles function definitions within code. Process a function's docstring, keeping well aware of the function's context and whether or not it's part of an interface definition. """ if self.options.debug: stderr....
Handles function definitions within code. Process a function's docstring, keeping well aware of the function's context and whether or not it's part of an interface definition.
def calc_integral_merger_rate(self): ''' calculates the integral int_0^t (k(t')-1)/2Tc(t') dt' and stores it as self.integral_merger_rate. This differences of this quantity evaluated at different times points are the cost of a branch. ''' # integrate the piecewise constan...
calculates the integral int_0^t (k(t')-1)/2Tc(t') dt' and stores it as self.integral_merger_rate. This differences of this quantity evaluated at different times points are the cost of a branch.
def truncate(self, index, chain=-1): """Tell the traces to truncate themselves at the given index.""" chain = range(self.chains)[chain] for name in self.trace_names[chain]: self._traces[name].truncate(index, chain)
Tell the traces to truncate themselves at the given index.
def add_log_hooks_to_pytorch_module(self, module, name=None, prefix='', log_parameters=True, log_gradients=True, log_freq=0): """ This instuments hooks into the pytorch module log_parameters - log parameters after a forward pass log_gradients - log gradients after a backward pass log_fre...
This instuments hooks into the pytorch module log_parameters - log parameters after a forward pass log_gradients - log gradients after a backward pass log_freq - log gradients/parameters every N batches
def forward_char_extend_selection(self, e): # u"""Move forward a character. """ self.l_buffer.forward_char_extend_selection(self.argument_reset) self.finalize()
u"""Move forward a character.
def autoregister(self, cls): """ Autoregister a class that is encountered for the first time. :param cls: The class that should be registered. """ params = self.get_meta_attributes(cls) return self.register(cls, params)
Autoregister a class that is encountered for the first time. :param cls: The class that should be registered.
def parse_ethnicity(parts): """ Parse the ethnicity from the Backpage ad. Returns the higher level ethnicities associated with an ethnicity. For example, if "russian" is found in the ad, this function will return ["russian", "eastern_european", "white_non_hispanic"]. This allows for us to look at ethnicit...
Parse the ethnicity from the Backpage ad. Returns the higher level ethnicities associated with an ethnicity. For example, if "russian" is found in the ad, this function will return ["russian", "eastern_european", "white_non_hispanic"]. This allows for us to look at ethnicities numerically and uniformally. N...
def startup(api=None): """Runs the provided function on startup, passing in an instance of the api""" def startup_wrapper(startup_function): apply_to_api = hug.API(api) if api else hug.api.from_object(startup_function) apply_to_api.add_startup_handler(startup_function) return startup_fun...
Runs the provided function on startup, passing in an instance of the api
def apply_default_prefetch(input_source_or_dataflow, trainer): """ Apply a set of default rules to make a fast :class:`InputSource`. Args: input_source_or_dataflow(InputSource | DataFlow): trainer (Trainer): Returns: InputSource """ if not isinstance(input_source_or_dat...
Apply a set of default rules to make a fast :class:`InputSource`. Args: input_source_or_dataflow(InputSource | DataFlow): trainer (Trainer): Returns: InputSource
def format_vertices_section(self): """format vertices section. assign_vertexid() should be called before this method, because self.valid_vetices should be available and member self.valid_vertices should have valid index. """ buf = io.StringIO() buf.write('vertices...
format vertices section. assign_vertexid() should be called before this method, because self.valid_vetices should be available and member self.valid_vertices should have valid index.
def shutdown(self): 'Close all peer connections and stop listening for new ones' log.info("shutting down") for peer in self._dispatcher.peers.values(): peer.go_down(reconnect=False) if self._listener_coro: backend.schedule_exception( errors._...
Close all peer connections and stop listening for new ones
def _outlier_rejection(self, params, model, signal, ii): """ Helper function to reject outliers DRY! """ # Z score across repetitions: z_score = (params - np.mean(params, 0))/np.std(params, 0) # Silence warnings: with warnings.catch_warnings(): ...
Helper function to reject outliers DRY!
def attr(self, kw=None, _attributes=None, **attrs): """Add a general or graph/node/edge attribute statement. Args: kw: Attributes target (``None`` or ``'graph'``, ``'node'``, ``'edge'``). attrs: Attributes to be set (must be strings, may be empty). See the :ref:`usage e...
Add a general or graph/node/edge attribute statement. Args: kw: Attributes target (``None`` or ``'graph'``, ``'node'``, ``'edge'``). attrs: Attributes to be set (must be strings, may be empty). See the :ref:`usage examples in the User Guide <attributes>`.
def enable_pointer_type(self): """ If a type is a pointer, a platform-independent POINTER_T type needs to be in the generated code. """ # 2015-01 reactivating header templates #log.warning('enable_pointer_type deprecated - replaced by generate_headers') # return #...
If a type is a pointer, a platform-independent POINTER_T type needs to be in the generated code.
def _build_ocsp_response(self, ocsp_request: OCSPRequest) -> OCSPResponse: """ Create and return an OCSP response from an OCSP request. """ # Get the certificate serial tbs_request = ocsp_request['tbs_request'] request_list = tbs_request['request_list'] if len(req...
Create and return an OCSP response from an OCSP request.
def runcode(self, code): """Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in thi...
Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not always be caught...
def get_folder_children(self, folder_id, name_contains=None): """ Get direct files and folders of a folder. :param folder_id: str: uuid of the folder :param name_contains: str: filter children based on a pattern :return: File|Folder """ return self._create_array_r...
Get direct files and folders of a folder. :param folder_id: str: uuid of the folder :param name_contains: str: filter children based on a pattern :return: File|Folder
def write_single_response(self, response_obj): """ Writes a json rpc response ``{"result": result, "error": error, "id": id}``. If the ``id`` is ``None``, the response will not contain an ``id`` field. The response is sent to the client as an ``application/json`` response. Only one call ...
Writes a json rpc response ``{"result": result, "error": error, "id": id}``. If the ``id`` is ``None``, the response will not contain an ``id`` field. The response is sent to the client as an ``application/json`` response. Only one call per response is allowed :param response_obj: A Jso...
def dedupFasta(reads): """ Remove sequence duplicates (based on sequence) from FASTA. @param reads: a C{dark.reads.Reads} instance. @return: a generator of C{dark.reads.Read} instances with no duplicates. """ seen = set() add = seen.add for read in reads: hash_ = md5(read.sequen...
Remove sequence duplicates (based on sequence) from FASTA. @param reads: a C{dark.reads.Reads} instance. @return: a generator of C{dark.reads.Read} instances with no duplicates.
def do_list_queue(self, line): """list_queue <peer> """ def f(p, args): o = p.get() if o.resources.queue: for q in o.resources.queue: print('%s %s' % (q.resource_id, q.port)) self._request(line, f)
list_queue <peer>
def main(): '''i am winston wolfe, i solve problems''' arguments = docopt(__doc__, version=__version__) if arguments['on']: print 'Mr. Wolfe is at your service' print 'If any of your programs run into an error' print 'use wolfe $l' print 'To undo the changes made by mr wolfe in your bashrc, do wo...
i am winston wolfe, i solve problems
def get_requirements(filename='requirements.txt'): """ Get the contents of a file listing the requirements. :param filename: path to a requirements file :type filename: str :returns: the list of requirements :return type: list """ with open(filename) as f: return [ ...
Get the contents of a file listing the requirements. :param filename: path to a requirements file :type filename: str :returns: the list of requirements :return type: list
def restore_from_disk(self, clean_old_snapshot=False): """Restore the state of the BF using previous snapshots. :clean_old_snapshot: Delete the old snapshot on the disk (period < current - expiration) """ base_filename = "%s/%s_%s_*.dat" % (self.snapshot_path, self.name, self.expiration...
Restore the state of the BF using previous snapshots. :clean_old_snapshot: Delete the old snapshot on the disk (period < current - expiration)
def get_project(self, project_short_name): """Return project object.""" project = pbclient.find_project(short_name=project_short_name, all=self.all) if (len(project) == 1): return project[0] else: raise ProjectNotFound(proje...
Return project object.
def write_byte(self, addr, val): """Write a single byte to the specified device.""" assert self._device is not None, 'Bus must be opened before operations are made against it!' self._select_device(addr) data = bytearray(1) data[0] = val & 0xFF self._device.write(data)
Write a single byte to the specified device.
def pull(self): """Print out summary information about each packet from the input_stream""" # For each packet in the pcap process the contents for item in self.input_stream: # Print out the timestamp in UTC print('%s -' % item['timestamp'], end='') # Transp...
Print out summary information about each packet from the input_stream
def list_all(prefix=None, app=None, owner=None, description_contains=None, name_not_contains=None, profile="splunk"): ''' Get all splunk search details. Produces results that can be used to create an sls file. if app or owner are specified, results will be limited to matching saved sea...
Get all splunk search details. Produces results that can be used to create an sls file. if app or owner are specified, results will be limited to matching saved searches. if description_contains is specified, results will be limited to those where "description_contains in description" is true if n...
def perfect_platonic_per_pixel(N, R, scale=11, pos=None, zscale=1.0, returnpix=None): """ Create a perfect platonic sphere of a given radius R by supersampling by a factor scale on a grid of size N. Scale must be odd. We are able to perfectly position these particles up to 1/scale. Therefore, let'...
Create a perfect platonic sphere of a given radius R by supersampling by a factor scale on a grid of size N. Scale must be odd. We are able to perfectly position these particles up to 1/scale. Therefore, let's only allow those types of shifts for now, but return the actual position used for the placem...
def _set_drop_precedence_force(self, v, load=False): """ Setter method for drop_precedence_force, mapped from YANG variable /ipv6_acl/ipv6/access_list/extended/seq/drop_precedence_force (ip-access-list:drop-prec-uint) If this variable is read-only (config: false) in the source YANG file, then _set_drop_...
Setter method for drop_precedence_force, mapped from YANG variable /ipv6_acl/ipv6/access_list/extended/seq/drop_precedence_force (ip-access-list:drop-prec-uint) If this variable is read-only (config: false) in the source YANG file, then _set_drop_precedence_force is considered as a private method. Backends ...
def get_3_tuple(self,obj,default=None): """Return 3-tuple from number -> (obj,default[1],default[2]) 0-sequence|None -> default 1-sequence -> (obj[0],default[1],default[2]) 2-sequence -> (obj[0],obj[1],default[2]) (3 or more)-sequence -> (obj[0],obj[1],obj[2]) """...
Return 3-tuple from number -> (obj,default[1],default[2]) 0-sequence|None -> default 1-sequence -> (obj[0],default[1],default[2]) 2-sequence -> (obj[0],obj[1],default[2]) (3 or more)-sequence -> (obj[0],obj[1],obj[2])
def motto(self): """获取用户自我介绍,由于历史原因,我还是把这个属性叫做motto吧. :return: 用户自我介绍 :rtype: str """ if self.url is None: return '' else: if self.soup is not None: bar = self.soup.find( 'div', class_='title-section') ...
获取用户自我介绍,由于历史原因,我还是把这个属性叫做motto吧. :return: 用户自我介绍 :rtype: str
def length_between(min_len, max_len, open_left=False, # type: bool open_right=False # type: bool ): """ 'Is length between' validation_function generator. Returns a validation_function to check that `min_len <= len(x) <= max_len (...
'Is length between' validation_function generator. Returns a validation_function to check that `min_len <= len(x) <= max_len (default)`. `open_right` and `open_left` flags allow to transform each side into strict mode. For example setting `open_left=True` will enforce `min_len < len(x) <= max_len`. :pa...
def get_single_series(self, id): """Fetches a single comic series by id. get /v1/public/series/{seriesId} :param id: ID of Series :type params: int :returns: SeriesDataWrapper >>> m = Marvel(public_key, private_key) >>> response = m.get_single...
Fetches a single comic series by id. get /v1/public/series/{seriesId} :param id: ID of Series :type params: int :returns: SeriesDataWrapper >>> m = Marvel(public_key, private_key) >>> response = m.get_single_series(12429) >>> print response.da...
def transform(x): """ Transform from Timeddelta to numerical format """ # microseconds try: x = np.array([_x.total_seconds()*10**6 for _x in x]) except TypeError: x = x.total_seconds()*10**6 return x
Transform from Timeddelta to numerical format
def terminate(self, devices): """Terminate one or more running or stopped instances. """ for device in devices: self.logger.info('Terminating: %s', device.id) try: device.delete() except packet.baseapi.Error: raise PacketManager...
Terminate one or more running or stopped instances.
def find_point_in_section_list(point, section_list): """Returns the start of the section the given point belongs to. The given list is assumed to contain start points of consecutive sections, except for the final point, assumed to be the end point of the last section. For example, the list [5, 8, 30, 3...
Returns the start of the section the given point belongs to. The given list is assumed to contain start points of consecutive sections, except for the final point, assumed to be the end point of the last section. For example, the list [5, 8, 30, 31] is interpreted as the following list of sections: [5-...
def handler(self): """gets the security handler for the class""" if hasNTLM: if self._handler is None: passman = request.HTTPPasswordMgrWithDefaultRealm() passman.add_password(None, self._parsed_org_url, self._login_username, self._password) se...
gets the security handler for the class
def addMethod(self, m): """ Adds a L{Method} to the interface """ if m.nargs == -1: m.nargs = len([a for a in marshal.genCompleteTypes(m.sigIn)]) m.nret = len([a for a in marshal.genCompleteTypes(m.sigOut)]) self.methods[m.name] = m self._xml = Non...
Adds a L{Method} to the interface
def txtopn(fname): """ Internal undocumented command for opening a new text file for subsequent write access. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ftncls_c.html#Files https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ftncls_c.html#Examples :param fname: name of the n...
Internal undocumented command for opening a new text file for subsequent write access. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ftncls_c.html#Files https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ftncls_c.html#Examples :param fname: name of the new text file to be opened. ...
def gha(julian_day, f): """ returns greenwich hour angle """ rad = old_div(np.pi, 180.) d = julian_day - 2451545.0 + f L = 280.460 + 0.9856474 * d g = 357.528 + 0.9856003 * d L = L % 360. g = g % 360. # ecliptic longitude lamb = L + 1.915 * np.sin(g * rad) + .02 * np.sin(2 * g * ...
returns greenwich hour angle
def radius_server_host_timeout(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") radius_server = ET.SubElement(config, "radius-server", xmlns="urn:brocade.com:mgmt:brocade-aaa") host = ET.SubElement(radius_server, "host") hostname_key = ET.SubEleme...
Auto Generated Code
def transmit_content_metadata(self, user): """ Transmit content metadata to integrated channel. """ exporter = self.get_content_metadata_exporter(user) transmitter = self.get_content_metadata_transmitter() transmitter.transmit(exporter.export())
Transmit content metadata to integrated channel.
def create_process(daemon, name, callback, *callbackParams): """创建进程 :param daemon: True主进程关闭而关闭, False主进程必须等待子进程结束 :param name: 进程名称 :param callback: 回调函数 :param callbackParams: 回调函数参数 :return: 返回一个进程对象 """ bp = Process(daemon=daemon, name=name, target=callback, args=callbackParams) ...
创建进程 :param daemon: True主进程关闭而关闭, False主进程必须等待子进程结束 :param name: 进程名称 :param callback: 回调函数 :param callbackParams: 回调函数参数 :return: 返回一个进程对象
def requestAvatarId(self, credentials): """ Return the ID associated with these credentials. @param credentials: something which implements one of the interfaces in self.credentialInterfaces. @return: a Deferred which will fire a string which identifies an avatar, an em...
Return the ID associated with these credentials. @param credentials: something which implements one of the interfaces in self.credentialInterfaces. @return: a Deferred which will fire a string which identifies an avatar, an empty tuple to specify an authenticated anonymous user ...
def normalize(self, expr, operation): """ Return a normalized expression transformed to its normal form in the given AND or OR operation. The new expression arguments will satisfy these conditions: - operation(*args) == expr (here mathematical equality is meant) - the op...
Return a normalized expression transformed to its normal form in the given AND or OR operation. The new expression arguments will satisfy these conditions: - operation(*args) == expr (here mathematical equality is meant) - the operation does not occur in any of its arg. - NOT is...
def restart(): """Restarts scapy""" if not conf.interactive or not os.path.isfile(sys.argv[0]): raise OSError("Scapy was not started from console") if WINDOWS: try: res_code = subprocess.call([sys.executable] + sys.argv) except KeyboardInterrupt: res_code = 1 ...
Restarts scapy
def apply_mesh_programs(self, mesh_programs=None): """Applies mesh programs to meshes""" if not mesh_programs: mesh_programs = [ColorProgram(), TextureProgram(), FallbackProgram()] for mesh in self.meshes: for mp in mesh_programs: instance = mp.apply(mesh...
Applies mesh programs to meshes
def request_halt(self, req, msg): """Halt the device server. Returns ------- success : {'ok', 'fail'} Whether scheduling the halt succeeded. Examples -------- :: ?halt !halt ok """ f = Future() @gen.c...
Halt the device server. Returns ------- success : {'ok', 'fail'} Whether scheduling the halt succeeded. Examples -------- :: ?halt !halt ok
def has_key(tup, key): """has(tuple, string) -> bool Return whether a given tuple has a key and the key is bound. """ if isinstance(tup, framework.TupleLike): return tup.is_bound(key) if isinstance(tup, dict): return key in tup if isinstance(tup, list): if not isinstance(key, int): raise ...
has(tuple, string) -> bool Return whether a given tuple has a key and the key is bound.
def main(): """Main function called upon script execution.""" # First get the wireless interface index. pack = struct.pack('16sI', OPTIONS['<interface>'].encode('ascii'), 0) sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: info = struct.unpack('16sI', fcntl.ioctl(sk.fileno(), 0x893...
Main function called upon script execution.
def set_rotation(self, r=0, redraw=True): """ Sets the LED matrix rotation for viewing, adjust if the Pi is upside down or sideways. 0 is with the Pi HDMI port facing downwards """ if r in self._pix_map.keys(): if redraw: pixel_list = self.get_pixels(...
Sets the LED matrix rotation for viewing, adjust if the Pi is upside down or sideways. 0 is with the Pi HDMI port facing downwards
def _process_ping(self): """ The server will be periodically sending a PING, and if the the client does not reply a PONG back a number of times, it will close the connection sending an `-ERR 'Stale Connection'` error. """ yield self.send_command(PONG_PROTO) if sel...
The server will be periodically sending a PING, and if the the client does not reply a PONG back a number of times, it will close the connection sending an `-ERR 'Stale Connection'` error.
async def check_ping_timeout(self): """Make sure the client is still sending pings. This helps detect disconnections for long-polling clients. """ if self.closed: raise exceptions.SocketIsClosedError() if time.time() - self.last_ping > self.server.ping_interval + 5: ...
Make sure the client is still sending pings. This helps detect disconnections for long-polling clients.
def _get_symbolic_function_initial_state(self, function_addr, fastpath_mode_state=None): """ Symbolically execute the first basic block of the specified function, then returns it. We prepares the state using the already existing state in fastpath mode (if avaiable). :param functi...
Symbolically execute the first basic block of the specified function, then returns it. We prepares the state using the already existing state in fastpath mode (if avaiable). :param function_addr: The function address :return: A symbolic state if succeeded, None otherwise
def GetNextWrittenEventSource(self): """Retrieves the next event source that was written after open. Returns: EventSource: event source or None if there are no newly written ones. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed. """ ...
Retrieves the next event source that was written after open. Returns: EventSource: event source or None if there are no newly written ones. Raises: IOError: when the storage writer is closed. OSError: when the storage writer is closed.