positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def request(self, method, url, **kwargs): """Constructs a :class:`requests.Request`, prepares it and sends it. Raises HTTPErrors by default. :param method: method for the new :class:`Request` object. :type method: :class:`str` :param url: URL for the new :class:`Request` object....
Constructs a :class:`requests.Request`, prepares it and sends it. Raises HTTPErrors by default. :param method: method for the new :class:`Request` object. :type method: :class:`str` :param url: URL for the new :class:`Request` object. :type url: :class:`str` :param kwarg...
def can_pay_cost(self, card): """ Returns whether the player can pay the resource cost of a card. """ if self.spells_cost_health and card.type == CardType.SPELL: return self.hero.health > card.cost return self.mana >= card.cost
Returns whether the player can pay the resource cost of a card.
def calculate_similarity(container1=None, container2=None, comparison=None, metric=None): '''calculate_similarity will calculate similarity of two containers by files content, default will calculate 2.0*len(intersect) / to...
calculate_similarity will calculate similarity of two containers by files content, default will calculate 2.0*len(intersect) / total package1 + total package2 Parameters ========== container1: container 1 container2: container 2 must be defined or metric a function to take a total...
def _parse_datetime_default_value(property_name, default_value_string): """Parse and return the default value for a datetime property.""" # OrientDB doesn't use ISO-8601 datetime format, so we have to parse it manually # and then turn it into a python datetime object. strptime() will raise an exception ...
Parse and return the default value for a datetime property.
def sc_cuts_coarse(self, viewer, event, msg=True): """Adjust cuts interactively by setting the low AND high cut levels. This function adjusts it coarsely. """ if self.cancut: # adjust the cut by 10% on each end self._adjust_cuts(viewer, event.direction, 0.1, msg=...
Adjust cuts interactively by setting the low AND high cut levels. This function adjusts it coarsely.
def delete(self, row): """Delete a track value""" i = self._get_key_index(row) del self.keys[i]
Delete a track value
def extract_blocks(ubi): """Get a list of UBI block objects from file Arguments:. Obj:ubi -- UBI object. Returns: Dict -- Of block objects keyed by PEB number. """ blocks = {} ubi.file.seek(ubi.file.start_offset) peb_count = 0 cur_offset = 0 bad_blocks = [] # r...
Get a list of UBI block objects from file Arguments:. Obj:ubi -- UBI object. Returns: Dict -- Of block objects keyed by PEB number.
def highres_imu_encode(self, time_usec, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag, abs_pressure, diff_pressure, pressure_alt, temperature, fields_updated): ''' The IMU readings in SI units in NED body frame time_usec : Timestamp (microsecond...
The IMU readings in SI units in NED body frame time_usec : Timestamp (microseconds, synced to UNIX time or since system boot) (uint64_t) xacc : X acceleration (m/s^2) (float) yacc : Y acceleration (m/s^2) (float) ...
def file(self, name, *args, **kwargs): """Open a file. :param name: Filename appended to self.root :param args: passed to open() :param kwargs: passed to open() :rtype: file """ return open(self(name), *args, **kwargs)
Open a file. :param name: Filename appended to self.root :param args: passed to open() :param kwargs: passed to open() :rtype: file
def exists(self, record_key): ''' a method to determine if a record exists in collection :param record_key: string with key of record :return: boolean reporting status ''' title = '%s.exists' % self.__class__.__name__ # validate...
a method to determine if a record exists in collection :param record_key: string with key of record :return: boolean reporting status
def get_package_version(self, feed, group_id, artifact_id, version, show_deleted=None): """GetPackageVersion. [Preview API] Get information about a package version. :param str feed: Name or ID of the feed. :param str group_id: Group ID of the package. :param str artifact_id: Arti...
GetPackageVersion. [Preview API] Get information about a package version. :param str feed: Name or ID of the feed. :param str group_id: Group ID of the package. :param str artifact_id: Artifact ID of the package. :param str version: Version of the package. :param bool sho...
def delete_subscription(self, subscription_id): """ Delete single subscription """ url = self.SUBSCRIPTIONS_ID_URL % subscription_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
Delete single subscription
def save_selected_state_as(): """Save selected state as separate state machine :return True if successfully stored, False if the storing process was canceled or stopped by condition fail :rtype bool: :raises exceptions.ValueError: If dialog response ids are out of bounds """ state_machine_mana...
Save selected state as separate state machine :return True if successfully stored, False if the storing process was canceled or stopped by condition fail :rtype bool: :raises exceptions.ValueError: If dialog response ids are out of bounds
def _send_block_request(self, transaction): """ A former request resulted in a block wise transfer. With this method, the block wise transfer will be continued, including triggering of the retry mechanism. :param transaction: The former transaction including the request which sh...
A former request resulted in a block wise transfer. With this method, the block wise transfer will be continued, including triggering of the retry mechanism. :param transaction: The former transaction including the request which should be continued.
def issue(self, id, fields=None, expand=None): """Get an issue Resource from the server. :param id: ID or key of the issue to get :type id: Union[Issue, str] :param fields: comma-separated string of issue fields to include in the results :type fields: Optional[str] :para...
Get an issue Resource from the server. :param id: ID or key of the issue to get :type id: Union[Issue, str] :param fields: comma-separated string of issue fields to include in the results :type fields: Optional[str] :param expand: extra information to fetch inside each resource ...
def const(const): '''Convenience wrapper to yield the value of a constant''' try: return getattr(_c, const) except AttributeError: raise FSQEnvError(errno.EINVAL, u'No such constant:'\ u' {0}'.format(const)) except TypeError: raise TypeError(errno.E...
Convenience wrapper to yield the value of a constant
async def generate_access_token(self, user): """ Generate an access token for a given user. """ payload = await self._get_payload(user) secret = self._get_secret(True) algorithm = self._get_algorithm() return jwt.encode(payload, secret, algorithm=algorithm).decod...
Generate an access token for a given user.
def list_datastore_full(service_instance, datastore): ''' Returns a dictionary with the basic information for the given datastore: name, type, url, capacity, free, used, usage, hosts service_instance The Service Instance Object from which to obtain datastores. datastore Name of...
Returns a dictionary with the basic information for the given datastore: name, type, url, capacity, free, used, usage, hosts service_instance The Service Instance Object from which to obtain datastores. datastore Name of the datastore.
def _create_err(self, errclass: str, *args) -> "Err": """ Create an error """ error = self._new_err(errclass, *args) self._add(error) return error
Create an error
def clean(df,error_rate = 0): """ Superficially cleans data, i.e. changing simple things about formatting. Parameters: df - DataFrame DataFrame to clean error_rate - float {0 <= error_rate <= 1}, default 0 Maximum amount of errors/inconsistencies caused explicitly by cleaning, expressed ...
Superficially cleans data, i.e. changing simple things about formatting. Parameters: df - DataFrame DataFrame to clean error_rate - float {0 <= error_rate <= 1}, default 0 Maximum amount of errors/inconsistencies caused explicitly by cleaning, expressed as a percentage of total dataf...
def copy(self, path, dest, raise_if_exists=False): """ Copies the contents of a single file path to dest """ if raise_if_exists and dest in self.get_all_data(): raise RuntimeError('Destination exists: %s' % path) contents = self.get_all_data()[path] self.get_a...
Copies the contents of a single file path to dest
def __get_return_value_no_withargs(self, *args, **kwargs): """ Pre-conditions: (1) The user has created a stub and specified the stub behaviour (2) The user has called the stub function with the specified "args" and "kwargs" (3) No 'withArgs' conditions were applicab...
Pre-conditions: (1) The user has created a stub and specified the stub behaviour (2) The user has called the stub function with the specified "args" and "kwargs" (3) No 'withArgs' conditions were applicable in this case Args: args: tuple, the arguments inputed by the...
def get_sub_array_ids(self): """Get list of sub array ids""" # Initialise empty list _scheduling_block_ids = [] _sub_array_ids = [] for blocks_id in self.get_sched_block_instance_ids(): _scheduling_block_ids.append(blocks_id) block_details = self.get_block_d...
Get list of sub array ids
def wiki_pages(self, extra_params=None): """ All Wiki Pages with access to this Space """ return self.api._get_json( WikiPage, space=self, rel_path=self._build_rel_path('wiki_pages'), extra_params=extra_params, )
All Wiki Pages with access to this Space
def create_compiler_path(xml_generator, compiler_path): """ Try to guess a path for the compiler. If you want ot use a specific compiler, please provide the compiler path manually, as the guess may not be what you are expecting. Providing the path can be done by passing it as an argument (compiler_...
Try to guess a path for the compiler. If you want ot use a specific compiler, please provide the compiler path manually, as the guess may not be what you are expecting. Providing the path can be done by passing it as an argument (compiler_path) to the xml_generator_configuration_t() or by defining it i...
def _set_circ_chstats(self, v, load=False): """ Setter method for circ_chstats, mapped from YANG variable /isis_state/interface_detail/isis_intf/circ_chstats (container) If this variable is read-only (config: false) in the source YANG file, then _set_circ_chstats is considered as a private method. B...
Setter method for circ_chstats, mapped from YANG variable /isis_state/interface_detail/isis_intf/circ_chstats (container) If this variable is read-only (config: false) in the source YANG file, then _set_circ_chstats is considered as a private method. Backends looking to populate this variable should do ...
def load_session_from_file(self, username: str, filename: Optional[str] = None) -> None: """Internally stores :class:`requests.Session` object loaded from file. If filename is None, the file with the default session path is loaded. :raises FileNotFoundError: If the file does not exist. ...
Internally stores :class:`requests.Session` object loaded from file. If filename is None, the file with the default session path is loaded. :raises FileNotFoundError: If the file does not exist.
def clean(self): """Remove internal fields""" doc = self._resource result = {k: v for k, v in doc.iteritems() if k not in self.internal_fields} if '_id' in doc and 'id' not in result: result['id'] = doc['_id'] return result
Remove internal fields
def get_state_all(self): """Returns all device states""" state_dict = {} for device in self.get_device_names().keys(): state_dict[device] = self.get_state(device) return state_dict
Returns all device states
def _get_timestamp(dirname_full, remove): """ Get the timestamp from the timestamp file. Optionally mark it for removal if we're going to write another one. """ record_filename = os.path.join(dirname_full, RECORD_FILENAME) if not os.path.exists(record_filename): return None mtime ...
Get the timestamp from the timestamp file. Optionally mark it for removal if we're going to write another one.
def replace_parent(self, parent_simples): """If ``&`` (or the legacy xCSS equivalent ``self``) appears in this selector, replace it with the given iterable of parent selectors. Returns a tuple of simple selectors. """ assert parent_simples ancestors = parent_simples[:-1...
If ``&`` (or the legacy xCSS equivalent ``self``) appears in this selector, replace it with the given iterable of parent selectors. Returns a tuple of simple selectors.
def get_description(self, twig=None, **kwargs): """ TODO: add documentation """ return self.get_parameter(twig=twig, **kwargs).get_description()
TODO: add documentation
def typedefs( self, name=None, function=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of typedef declarations, that are matched defined criteria""" return ( ...
returns a set of typedef declarations, that are matched defined criteria
def debug(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None) -> None: """ Logs a message to the Pulumi CLI's debug channel, associating it with a resource and stream_id if provided. :param str msg: The message to send to the Pulumi CLI. :param Optional[Resource] resou...
Logs a message to the Pulumi CLI's debug channel, associating it with a resource and stream_id if provided. :param str msg: The message to send to the Pulumi CLI. :param Optional[Resource] resource: If provided, associate this message with the given resource in the Pulumi CLI. :param Optional[int] stre...
def parse(cls, parser, token): """ Custom parsing for the ``{% ajax_comment_tags for ... %}`` tag. """ # Process the template line. tag_name, args, kwargs = parse_token_kwargs( parser, token, allowed_kwargs=cls.allowed_kwargs, compile_args=Fals...
Custom parsing for the ``{% ajax_comment_tags for ... %}`` tag.
def set_timezone(tz=None, deploy=False): ''' Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false ...
Set the timezone of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: tz (str): The name of the timezone to set. deploy (bool): If true then commit the full candidate configuration, if false only set pending change. .. code-block:: bash ...
def detect_hooks(): """ Returns True if the import hooks are installed, False if not. """ flog.debug('Detecting hooks ...') present = any([hasattr(hook, 'RENAMER') for hook in sys.meta_path]) if present: flog.debug('Detected.') else: flog.debug('Not detected.') return pre...
Returns True if the import hooks are installed, False if not.
def add_files(self, files): """ Adds files to this project. :param files: List of files or a Collection object. """ for file in files: file.copy(project=self.id)
Adds files to this project. :param files: List of files or a Collection object.
def __header(self, line): """Build the header (contain the number of CPU). CPU0 CPU1 CPU2 CPU3 0: 21 0 0 0 IO-APIC 2-edge timer """ self.cpu_number = len(line.split()) return self.cpu_number
Build the header (contain the number of CPU). CPU0 CPU1 CPU2 CPU3 0: 21 0 0 0 IO-APIC 2-edge timer
def restore(self, time=None): """ Undeletes the object. Returns True if undeleted, False if it was already not deleted """ if self.deleted: time = time if time else self.deleted_at if time == self.deleted_at: self.deleted = False se...
Undeletes the object. Returns True if undeleted, False if it was already not deleted
def perturb_vec(q, cone_half_angle=2): r"""Perturb a vector randomly qp = perturb_vec(q, cone_half_angle=2) Parameters ---------- q : (n,) numpy array Vector to perturb cone_half_angle : float Maximum angle to perturb the vector in degrees Returns ------- perturbed...
r"""Perturb a vector randomly qp = perturb_vec(q, cone_half_angle=2) Parameters ---------- q : (n,) numpy array Vector to perturb cone_half_angle : float Maximum angle to perturb the vector in degrees Returns ------- perturbed : (n,) numpy array Perturbed numpy...
def tenses(self, verb, parse=True): """ Returns a list of possible tenses for the given inflected verb. """ verb = verb.lower() a = set() b = self.lemma(verb, parse=parse) v = [] if b in self: v = self[b] elif parse is True: # rule-based ...
Returns a list of possible tenses for the given inflected verb.
def schedule_forced_svc_check(self, service, check_time): """Schedule a forced check on a service Format of the line that triggers function call:: SCHEDULE_FORCED_SVC_CHECK;<host_name>;<service_description>;<check_time> :param service: service to check :type service: alignak.ob...
Schedule a forced check on a service Format of the line that triggers function call:: SCHEDULE_FORCED_SVC_CHECK;<host_name>;<service_description>;<check_time> :param service: service to check :type service: alignak.object.service.Service :param check_time: time to check ...
def _process_macro_args(self): """Macro args are pretty tricky! Arg names themselves are simple, but you can set arbitrary default values, including doing stuff like: {% macro my_macro(arg="x" + ("}% {# {% endmacro %}" * 2)) %} Which makes you a jerk, but is valid jinja. """ ...
Macro args are pretty tricky! Arg names themselves are simple, but you can set arbitrary default values, including doing stuff like: {% macro my_macro(arg="x" + ("}% {# {% endmacro %}" * 2)) %} Which makes you a jerk, but is valid jinja.
def prepend_path(orig, text, pathsep=os.pathsep): """Returns a $PATH-like environment variable with `text` prepended. `orig` is the original variable value, or None. `pathsep` is the character separating path elements, defaulting to `os.pathsep`. Example: newpath = cli.prepend_path(oldpath, '/mypa...
Returns a $PATH-like environment variable with `text` prepended. `orig` is the original variable value, or None. `pathsep` is the character separating path elements, defaulting to `os.pathsep`. Example: newpath = cli.prepend_path(oldpath, '/mypackage/bin') See also `prepend_environ_path`.
def parse_line(self, line): """Parse a line into a dictionary""" match = re.findall(self.date_regex, line) if match: fields = self.fields elif self.backup_format_regex and not match: match = re.findall(self.backup_date_regex, line) fields = self.backup...
Parse a line into a dictionary
def get_final_numbers(filename, out_dir): """Copy the final_files file and get the number of markers and samples. :param filename: the name of the file. :param out_dir: the output directory. :type filename: str :type out_dir: str :returns: the final number of markers and samples :rtype: t...
Copy the final_files file and get the number of markers and samples. :param filename: the name of the file. :param out_dir: the output directory. :type filename: str :type out_dir: str :returns: the final number of markers and samples :rtype: tuple
def mutect_caller(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Run the MuTect paired analysis algorithm. """ config = items[0]["config"] if out_file is None: out_file = "%s-paired-variants.vcf.gz" % os.path.splitext(align_bams[0])[0] if not file...
Run the MuTect paired analysis algorithm.
def copy_assets(self, assets_path): """Banana banana """ if not os.path.exists(assets_path): os.mkdir(assets_path) extra_files = self._get_extra_files() for ex_files in Formatter.get_extra_files_signal(self): extra_files.extend(ex_files) for src...
Banana banana
def get_library_meta(self): ''' Fetches the meta data for the current library. The data could be in the superlib meta data file. If we can't find the data None is returned. ''' parent_dir = os.path.dirname(self.library_dir) if self.test_file_exists(os.path.join(self.libra...
Fetches the meta data for the current library. The data could be in the superlib meta data file. If we can't find the data None is returned.
def stop(self, unique_id, configs=None): """Stop the service. If the deployer has not started a service with`unique_id` the deployer will raise an Exception There are two configs that will be considered: 'terminate_only': if this config is passed in then this method is the same as terminate(unique_id) (thi...
Stop the service. If the deployer has not started a service with`unique_id` the deployer will raise an Exception There are two configs that will be considered: 'terminate_only': if this config is passed in then this method is the same as terminate(unique_id) (this is also the behavior if stop_command is No...
def get_resampled_coordinates(lons, lats): """ Resample polygon line segments and return the coordinates of the new vertices. This limits distortions when projecting a polygon onto a spherical surface. Parameters define longitudes and latitudes of a point collection in the form of lists or nump...
Resample polygon line segments and return the coordinates of the new vertices. This limits distortions when projecting a polygon onto a spherical surface. Parameters define longitudes and latitudes of a point collection in the form of lists or numpy arrays. :return: A tuple of two numpy ar...
def _get_var_name(self, register_name, mode): """Get variable name for a register considering pre and post mode. """ var_name = { "pre": self._translator.get_name_init(register_name), "post": self._translator.get_name_curr(register_name), } return var_nam...
Get variable name for a register considering pre and post mode.
def delete(gandi, fqdn, name, type, force): """Delete record entry for a domain.""" domains = gandi.dns.list() domains = [domain['fqdn'] for domain in domains] if fqdn not in domains: gandi.echo('Sorry domain %s does not exist' % fqdn) gandi.echo('Please use one of the following: %s' % '...
Delete record entry for a domain.
def root(self): """ Reset all nodes and branches to 'root'. """ str_treeRoot = '/' self.l_cwd = [str_treeRoot] self.snode_current = self.snode_root self.sbranch_current = self.sbranch_root
Reset all nodes and branches to 'root'.
def fetch( self, limit=None, offset=0, start_cursor=None, end_cursor=None, client=None, eventual=False, ): """Execute the Query; return an iterator for the matching entities. For example:: >>> from google.cloud import datastore ...
Execute the Query; return an iterator for the matching entities. For example:: >>> from google.cloud import datastore >>> client = datastore.Client() >>> query = client.query(kind='Person') >>> query.add_filter('name', '=', 'Sally') >>> list(query.fetch()) ...
def datetimes_to_durations( start_times, end_times, fill_date=datetime.today(), freq="D", dayfirst=False, na_values=None ): """ This is a very flexible function for transforming arrays of start_times and end_times to the proper format for lifelines: duration and event observation arrays. Parameters...
This is a very flexible function for transforming arrays of start_times and end_times to the proper format for lifelines: duration and event observation arrays. Parameters ---------- start_times: an array, Series or DataFrame iterable representing start times. These can be strings, or datetime ...
def _get_jacobian_hessian_strategy(self): """ Figure out how to calculate the jacobian and hessian. Will return a tuple describing how best to calculate the jacobian and hessian, repectively. If None, it should be calculated using the available analytical method. :return...
Figure out how to calculate the jacobian and hessian. Will return a tuple describing how best to calculate the jacobian and hessian, repectively. If None, it should be calculated using the available analytical method. :return: tuple of jacobian_method, hessian_method
def create(self, name, **kwargs): ''' Create a dataset, including the field types. Optionally, specify args such as: description : description of the dataset columns : list of columns (see docs/tests for list structure) category : must exist in /admin/metadata ...
Create a dataset, including the field types. Optionally, specify args such as: description : description of the dataset columns : list of columns (see docs/tests for list structure) category : must exist in /admin/metadata tags : list of tag strings row_identi...
def plot_elbow_curve(clf, X, title='Elbow Plot', cluster_ranges=None, ax=None, figsize=None, title_fontsize="large", text_fontsize="medium"): """Plots elbow curve of different values of K for KMeans clustering. Args: clf: Clusterer instance that implements ``fi...
Plots elbow curve of different values of K for KMeans clustering. Args: clf: Clusterer instance that implements ``fit`` and ``fit_predict`` methods and a ``score`` parameter. X (array-like, shape (n_samples, n_features)): Data to cluster, where n_samples is the number of sa...
def check_version(dstore): """ :param dstore: a DataStore instance :returns: a message if the stored version is different from the current version """ ds_version = dstore.hdf5.attrs['engine_version'] if ds_version != __version__: return (': the datastore is at version %s, but the...
:param dstore: a DataStore instance :returns: a message if the stored version is different from the current version
def counter(self): """ Rolling counter that ensures same-machine and same-time cuids don't collide. """ self._counter += 1 if self._counter >= DISCRETE_VALUES: self._counter = 0 return self._counter
Rolling counter that ensures same-machine and same-time cuids don't collide.
def parseInline(self, src): """Parses CSS inline source string using the current cssBuilder. Use to parse a tag's 'sytle'-like attribute.""" self.cssBuilder.beginInline() try: try: src, properties = self._parseDeclarationGroup(src.strip(), braces=False) ...
Parses CSS inline source string using the current cssBuilder. Use to parse a tag's 'sytle'-like attribute.
def create_table(cls): """ create_table Manually create a temporary table for model in test data base. :return: """ schema_editor = getattr(connection, 'schema_editor', None) if schema_editor: with schema_editor() as schema_editor: sch...
create_table Manually create a temporary table for model in test data base. :return:
def base64(self, charset=None): '''Data encoded as base 64''' return b64encode(self.bytes()).decode(charset or self.charset)
Data encoded as base 64
def get_index_config(self, project_name, logstore_name): """ get index config detail of a logstore Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_nam...
get index config detail of a logstore Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type logstore_name: string :param logstore_name: the logstore name :return: GetIndexResponse :...
def _copy(self): """Copies this instance. Its IonEvent (if any) is not preserved. Keeping this protected until/unless we decide there's use for it publicly. """ args, kwargs = self._to_constructor_args(self) value = self.__class__(*args, **kwargs) value.ion_event = None ...
Copies this instance. Its IonEvent (if any) is not preserved. Keeping this protected until/unless we decide there's use for it publicly.
def insert_data(self, node, data, start, end): """loops through all the data and inserts them into the empty tree""" for item in data: self.recursive_insert(node, [item[0], item[1]], item[-1], start, end)
loops through all the data and inserts them into the empty tree
def blackbox_network(): """A micro-network to demonstrate blackboxing. Diagram:: +----------+ +-------------------->+ A (COPY) + <---------------+ | +----------+ | | +----------+ ...
A micro-network to demonstrate blackboxing. Diagram:: +----------+ +-------------------->+ A (COPY) + <---------------+ | +----------+ | | +----------+ | | +---------...
def set_cookie( # type: ignore self, key: str, value: AnyStr='', max_age: Optional[Union[int, timedelta]]=None, expires: Optional[datetime]=None, path: str='/', domain: Optional[str]=None, secure: bool=False, ht...
Set a cookie in the response headers. The arguments are the standard cookie morsels and this is a wrapper around the stdlib SimpleCookie code.
def evaluate_world_model( agent_type, loop_hparams, planner_hparams, model_dir, policy_dir, random_starts_step_limit, debug_video_path, log_every_steps ): """Evaluates the world model.""" if debug_video_path: debug_video_path = os.path.join(debug_video_path, "0.avi") storage_env = rl_utils.setup_env(...
Evaluates the world model.
def keyPressEvent(self, event): """Reimplement Qt method to allow cyclic behavior.""" if event.key() == Qt.Key_Down: self.select_row(1) elif event.key() == Qt.Key_Up: self.select_row(-1)
Reimplement Qt method to allow cyclic behavior.
def select(self, return_models=False, nest=False, bypass_safe_limit=False, sql=None, sql_args=None): """ Executes the SELECT statement and returns the rows as a list of dictionaries or a list of model instances :type return_models: bool :param return_models: Set to True to retur...
Executes the SELECT statement and returns the rows as a list of dictionaries or a list of model instances :type return_models: bool :param return_models: Set to True to return a list of models instead of a list of dictionaries. Defaults to False :type nest: bool :pa...
def run(generate_pks, show_pks, host, port, uri): """Connect sandman to <URI> and start the API server/admin interface.""" app.config['SQLALCHEMY_DATABASE_URI'] = uri app.config['SANDMAN_GENERATE_PKS'] = generate_pks app.config['SANDMAN_SHOW_PKS'] = show_pks app.config['SERVER_HOST'] = host ...
Connect sandman to <URI> and start the API server/admin interface.
def minlen(min_length, strict=False # type: bool ): """ 'Minimum length' validation_function generator. Returns a validation_function to check that len(x) >= min_length (strict=False, default) or len(x) > min_length (strict=True) :param min_length: minimum length for x :p...
'Minimum length' validation_function generator. Returns a validation_function to check that len(x) >= min_length (strict=False, default) or len(x) > min_length (strict=True) :param min_length: minimum length for x :param strict: Boolean flag to switch between len(x) >= min_length (strict=False) and len...
def electric_field_amplitude_top(P, a, Omega=1e6, units="ad-hoc"): """Return the amplitude of the electric field for a top hat beam. This is the amplitude of a laser beam of power P (in Watts) and a top-hat\ intensity distribution of radius a (in meters). The value of E0 is given in\ rescaled units acco...
Return the amplitude of the electric field for a top hat beam. This is the amplitude of a laser beam of power P (in Watts) and a top-hat\ intensity distribution of radius a (in meters). The value of E0 is given in\ rescaled units according to the frequency scale Omega (in Hertz)\ understood as absolute fr...
def create_from_taskfile(self, taskfile): """Create a new TaskFileInfo and return it for the given taskfile :param taskfile: the taskfile to represent :type taskfile: :class:`jukeboxcore.djadapter.models.TaskFile` :returns: a taskfileinfo :rtype: :class:`TaskFileInfo` :r...
Create a new TaskFileInfo and return it for the given taskfile :param taskfile: the taskfile to represent :type taskfile: :class:`jukeboxcore.djadapter.models.TaskFile` :returns: a taskfileinfo :rtype: :class:`TaskFileInfo` :raises: None
def editor_multi_agent_example(): """This editor example shows how to interact with holodeck worlds that have multiple agents. This is specifically for when working with UE4 directly and not a prebuilt binary. """ agent_definitions = [ AgentDefinition("uav0", agents.UavAgent, [Sensors.PIXEL_CAME...
This editor example shows how to interact with holodeck worlds that have multiple agents. This is specifically for when working with UE4 directly and not a prebuilt binary.
def execute_route(self, meta_data, request_pdu): """ Execute configured route based on requests meta data and request PDU. :param meta_data: A dict with meta data. It must at least contain key 'unit_id'. :param request_pdu: A bytearray containing request PDU. :return...
Execute configured route based on requests meta data and request PDU. :param meta_data: A dict with meta data. It must at least contain key 'unit_id'. :param request_pdu: A bytearray containing request PDU. :return: A bytearry containing reponse PDU.
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Stop CPC (requires DPM mode).""" assert wait_for_completion is True # async not supported yet cpc_oid = uri_parms[0] try: cpc = hmc.cpcs.lookup_by_oid(cpc_oid) ...
Operation: Stop CPC (requires DPM mode).
def check_no_element_by_selector(self, selector): """Assert an element does not exist matching the given selector.""" elems = find_elements_by_jquery(world.browser, selector) if elems: raise AssertionError("Expected no matching elements, found {}.".format( len(elems)))
Assert an element does not exist matching the given selector.
def best_assemblyfile(self): """ Determine whether the contigs.fasta output file from the assembler is present. If not, set the .bestassembly attribute to 'NA' """ for sample in self.metadata: try: # Set the name of the filtered assembly file ...
Determine whether the contigs.fasta output file from the assembler is present. If not, set the .bestassembly attribute to 'NA'
def _other_to_dict(self, other): """When serializing models, this allows attached models (children, parents, etc.) to also be serialized. """ if isinstance(other, ModelBase): return other.to_dict() elif isinstance(other, list): # TODO: what if it's not a list? return [self._other_t...
When serializing models, this allows attached models (children, parents, etc.) to also be serialized.
def _apply_list(self, methods): """Return a single callable that applies a list of methods to a value. If a method returns None, the last value is kept; if it returns some other value, that replaces the last value. Exceptions are not caught. """ def call(value): for method in methods: ...
Return a single callable that applies a list of methods to a value. If a method returns None, the last value is kept; if it returns some other value, that replaces the last value. Exceptions are not caught.
def get_symbol_map(self): """ If you need the symbol map, use this method. The symbol map is an array of string pairs mapping common tokens to X Keysym strings, such as "alt" to "Alt_L" :return: array of strings. """ # todo: make sure we return a list of strings...
If you need the symbol map, use this method. The symbol map is an array of string pairs mapping common tokens to X Keysym strings, such as "alt" to "Alt_L" :return: array of strings.
def update_security_group(self, security_group, body=None): """Updates a security group.""" return self.put(self.security_group_path % security_group, body=body)
Updates a security group.
def execute(st, **kwargs): """ Work around for Python3 exec function which doesn't allow changes to the local namespace because of scope. This breaks a lot of the old functionality in the code which was origionally in Python2. So this function runs just like exec except that it returns the output of the...
Work around for Python3 exec function which doesn't allow changes to the local namespace because of scope. This breaks a lot of the old functionality in the code which was origionally in Python2. So this function runs just like exec except that it returns the output of the input statement to the local namespace...
def main(args=None, **kwargs): """Run the Tango SDP Master device server.""" LOG.info('Starting %s', __service_id__) return run([SDPMasterDevice], verbose=True, msg_stream=sys.stdout, args=args, **kwargs)
Run the Tango SDP Master device server.
def global_state_code(self): """ Returns global variables for generating function from ``func_code`` as code. Includes compiled regular expressions and imports. """ self._generate_func_code() if not self._compile_regexps: return '\n'.join( [ ...
Returns global variables for generating function from ``func_code`` as code. Includes compiled regular expressions and imports.
def handle_exception(klass, exc, tb, coro=None): """run all the registered exception handlers the first 3 arguments to this function match the output of ``sys.exc_info()`` :param klass: the exception klass :type klass: type :param exc: the exception instance :type exc: Exception :param...
run all the registered exception handlers the first 3 arguments to this function match the output of ``sys.exc_info()`` :param klass: the exception klass :type klass: type :param exc: the exception instance :type exc: Exception :param tb: the traceback object :type tb: Traceback :p...
def versioning_model_classname(manager, model): """Get the name of the versioned model class.""" if manager.options.get('use_module_name', True): return '%s%sVersion' % ( model.__module__.title().replace('.', ''), model.__name__) else: return '%sVersion' % (model.__name__,)
Get the name of the versioned model class.
def generated_target_ps(is_suffix, type, prop_set): """ Returns suffix that should be used when generating target of 'type', with the specified properties. If not suffix were specified for 'type', returns suffix for base type, if any. """ if __debug__: from .property_set import Prope...
Returns suffix that should be used when generating target of 'type', with the specified properties. If not suffix were specified for 'type', returns suffix for base type, if any.
def _q_to_dcm(self, q): """ Create DCM (Matrix3) from q :param q: array q which represents a quaternion [w, x, y, z] :returns: Matrix3 """ assert(len(q) == 4) arr = super(Quaternion, self)._q_to_dcm(q) return self._dcm_array_to_matrix3(arr)
Create DCM (Matrix3) from q :param q: array q which represents a quaternion [w, x, y, z] :returns: Matrix3
def read_actions(): """Yields actions for pressed keys.""" while True: key = get_key() # Handle arrows, j/k (qwerty), and n/e (colemak) if key in (const.KEY_UP, const.KEY_CTRL_N, 'k', 'e'): yield const.ACTION_PREVIOUS elif key in (const.KEY_DOWN, const.KEY_CTRL_P, 'j...
Yields actions for pressed keys.
def stats_on_depth(d, depth): """Display the node stats info on specific depth in this dict """ root_nodes, leaf_nodes = 0, 0 for _, node in DictTree.kv_depth(d, depth): if DictTree.length(node) == 0: leaf_nodes += 1 else: root_node...
Display the node stats info on specific depth in this dict
def _get_log_entries(self) -> List[Tuple[int, bytes, List[int], bytes]]: """ Return the log entries for this computation and its children. They are sorted in the same order they were emitted during the transaction processing, and include the sequential counter as the first element of th...
Return the log entries for this computation and its children. They are sorted in the same order they were emitted during the transaction processing, and include the sequential counter as the first element of the tuple representing every entry.
def autoconf(self): """Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise. """ apacheInfo = ApacheInfo(self._host, self._port, self._user, self._password, ...
Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise.
def __sort_up(self): """Sort the updatable objects according to ascending order""" if self.__do_need_sort_up: self.__up_objects.sort(key=cmp_to_key(self.__up_cmp)) self.__do_need_sort_up = False
Sort the updatable objects according to ascending order
def get_transaction_by_index( self, block_number: BlockNumber, transaction_index: int, transaction_class: Type['BaseTransaction']) -> 'BaseTransaction': """ Returns the transaction at the specified `transaction_index` from the block specified by `b...
Returns the transaction at the specified `transaction_index` from the block specified by `block_number` from the canonical chain. Raises TransactionNotFound if no block
def vector_angle_between(vector1, vector2, **kwargs): """ Computes the angle between the two input vectors. If the keyword argument ``degrees`` is set to *True*, then the angle will be in degrees. Otherwise, it will be in radians. By default, ``degrees`` is set to *True*. :param vector1: vector :t...
Computes the angle between the two input vectors. If the keyword argument ``degrees`` is set to *True*, then the angle will be in degrees. Otherwise, it will be in radians. By default, ``degrees`` is set to *True*. :param vector1: vector :type vector1: list, tuple :param vector2: vector :type ...