code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_equivalent_nodes(self, node: BaseEntity) -> Set[BaseEntity]: """Get a set of equivalent nodes to this node, excluding the given node.""" if isinstance(node, BaseEntity): return set(self.iter_equivalent_nodes(node)) return set(self.iter_equivalent_nodes(node))
Get a set of equivalent nodes to this node, excluding the given node.
Below is the the instruction that describes the task: ### Input: Get a set of equivalent nodes to this node, excluding the given node. ### Response: def get_equivalent_nodes(self, node: BaseEntity) -> Set[BaseEntity]: """Get a set of equivalent nodes to this node, excluding the given node.""" if isinstance(node, BaseEntity): return set(self.iter_equivalent_nodes(node)) return set(self.iter_equivalent_nodes(node))
def next_month(today: datetime=None, tz=None): """ Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: today = datetime.utcnow() begin = datetime(day=1, month=today.month, year=today.year) next_mo = begin + timedelta(days=32) begin = datetime(day=1, month=next_mo.month, year=next_mo.year) following_mo = begin + timedelta(days=32) end = datetime(day=1, month=following_mo.month, year=following_mo.year) return localize_time_range(begin, end, tz)
Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
Below is the the instruction that describes the task: ### Input: Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) ### Response: def next_month(today: datetime=None, tz=None): """ Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: today = datetime.utcnow() begin = datetime(day=1, month=today.month, year=today.year) next_mo = begin + timedelta(days=32) begin = datetime(day=1, month=next_mo.month, year=next_mo.year) following_mo = begin + timedelta(days=32) end = datetime(day=1, month=following_mo.month, year=following_mo.year) return localize_time_range(begin, end, tz)
def trim(self): """ Trims leaves from tree that are not observed at highest-resolution level This is a bit hacky-- what it does is """ # Only allow leaves to stay on list (highest-resolution) level return for l in self._levels[-2::-1]: for n in l: if n.is_leaf: n.parent.remove_child(n.label) self._clear_all_leaves()
Trims leaves from tree that are not observed at highest-resolution level This is a bit hacky-- what it does is
Below is the the instruction that describes the task: ### Input: Trims leaves from tree that are not observed at highest-resolution level This is a bit hacky-- what it does is ### Response: def trim(self): """ Trims leaves from tree that are not observed at highest-resolution level This is a bit hacky-- what it does is """ # Only allow leaves to stay on list (highest-resolution) level return for l in self._levels[-2::-1]: for n in l: if n.is_leaf: n.parent.remove_child(n.label) self._clear_all_leaves()
def show_grid_from_file(self, fname): """ reads a saved grid file and paints it on the canvas """ with open(fname, "r") as f: for y, row in enumerate(f): for x, val in enumerate(row): self.draw_cell(y, x, val)
reads a saved grid file and paints it on the canvas
Below is the the instruction that describes the task: ### Input: reads a saved grid file and paints it on the canvas ### Response: def show_grid_from_file(self, fname): """ reads a saved grid file and paints it on the canvas """ with open(fname, "r") as f: for y, row in enumerate(f): for x, val in enumerate(row): self.draw_cell(y, x, val)
def _init_proc(self): """Start processes if not already started""" if not self.proc: self.proc = [ mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn)) for i in range(self.num_proc) ] self.alive.value = True for p in self.proc: p.start()
Start processes if not already started
Below is the the instruction that describes the task: ### Input: Start processes if not already started ### Response: def _init_proc(self): """Start processes if not already started""" if not self.proc: self.proc = [ mp.Process(target=self._proc_loop, args=(i, self.alive, self.queue, self.fn)) for i in range(self.num_proc) ] self.alive.value = True for p in self.proc: p.start()
def preamble(): """ Log the Andes command-line preamble at the `logging.INFO` level Returns ------- None """ from . import __version__ as version logger.info('ANDES {ver} (Build {b}, Python {p} on {os})' .format(ver=version[:5], b=version[-8:], p=platform.python_version(), os=platform.system())) try: username = os.getlogin() + ', ' except OSError: username = '' logger.info('Session: {}{}'.format(username, strftime("%m/%d/%Y %I:%M:%S %p"))) logger.info('')
Log the Andes command-line preamble at the `logging.INFO` level Returns ------- None
Below is the the instruction that describes the task: ### Input: Log the Andes command-line preamble at the `logging.INFO` level Returns ------- None ### Response: def preamble(): """ Log the Andes command-line preamble at the `logging.INFO` level Returns ------- None """ from . import __version__ as version logger.info('ANDES {ver} (Build {b}, Python {p} on {os})' .format(ver=version[:5], b=version[-8:], p=platform.python_version(), os=platform.system())) try: username = os.getlogin() + ', ' except OSError: username = '' logger.info('Session: {}{}'.format(username, strftime("%m/%d/%Y %I:%M:%S %p"))) logger.info('')
def delete(self, key): """Delete a document by id.""" assert key, "A key must be supplied for delete operations" self._collection.remove(spec_or_id={'_id': key}) LOG.debug("DB REMOVE: %s.%s", self.collection_name, key)
Delete a document by id.
Below is the the instruction that describes the task: ### Input: Delete a document by id. ### Response: def delete(self, key): """Delete a document by id.""" assert key, "A key must be supplied for delete operations" self._collection.remove(spec_or_id={'_id': key}) LOG.debug("DB REMOVE: %s.%s", self.collection_name, key)
def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime: """ Convert date/time with timezone to UTC (with UTC timezone). """ dt = coerce_to_pendulum(dt) tz = get_tz_utc() return dt.in_tz(tz)
Convert date/time with timezone to UTC (with UTC timezone).
Below is the the instruction that describes the task: ### Input: Convert date/time with timezone to UTC (with UTC timezone). ### Response: def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime: """ Convert date/time with timezone to UTC (with UTC timezone). """ dt = coerce_to_pendulum(dt) tz = get_tz_utc() return dt.in_tz(tz)
def normal_case(name): """Converts "CamelCaseHere" to "camel case here".""" s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name) return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s1).lower()
Converts "CamelCaseHere" to "camel case here".
Below is the the instruction that describes the task: ### Input: Converts "CamelCaseHere" to "camel case here". ### Response: def normal_case(name): """Converts "CamelCaseHere" to "camel case here".""" s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', name) return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s1).lower()
def ShouldRetry(self, exception): """Returns true if should retry based on the passed-in exception. :param (errors.HTTPFailure instance) exception: :rtype: boolean """ if not self.connection_policy.EnableEndpointDiscovery: return False if self.failover_retry_count >= self.Max_retry_attempt_count: return False self.failover_retry_count += 1 if self.location_endpoint: if _OperationType.IsReadOnlyOperation(self.request.operation_type): #Mark current read endpoint as unavailable self.global_endpoint_manager.mark_endpoint_unavailable_for_read(self.location_endpoint) else: self.global_endpoint_manager.mark_endpoint_unavailable_for_write(self.location_endpoint) # set the refresh_needed flag to ensure that endpoint list is # refreshed with new writable and readable locations self.global_endpoint_manager.refresh_needed = True # clear previous location-based routing directive self.request.clear_route_to_location() # set location-based routing directive based on retry count # simulating single master writes by ensuring usePreferredLocations # is set to false self.request.route_to_location_with_preferred_location_flag(self.failover_retry_count, False) # Resolve the endpoint for the request and pin the resolution to the resolved endpoint # This enables marking the endpoint unavailability on endpoint failover/unreachability self.location_endpoint = self.global_endpoint_manager.resolve_service_endpoint(self.request) self.request.route_to_location(self.location_endpoint) return True
Returns true if should retry based on the passed-in exception. :param (errors.HTTPFailure instance) exception: :rtype: boolean
Below is the the instruction that describes the task: ### Input: Returns true if should retry based on the passed-in exception. :param (errors.HTTPFailure instance) exception: :rtype: boolean ### Response: def ShouldRetry(self, exception): """Returns true if should retry based on the passed-in exception. :param (errors.HTTPFailure instance) exception: :rtype: boolean """ if not self.connection_policy.EnableEndpointDiscovery: return False if self.failover_retry_count >= self.Max_retry_attempt_count: return False self.failover_retry_count += 1 if self.location_endpoint: if _OperationType.IsReadOnlyOperation(self.request.operation_type): #Mark current read endpoint as unavailable self.global_endpoint_manager.mark_endpoint_unavailable_for_read(self.location_endpoint) else: self.global_endpoint_manager.mark_endpoint_unavailable_for_write(self.location_endpoint) # set the refresh_needed flag to ensure that endpoint list is # refreshed with new writable and readable locations self.global_endpoint_manager.refresh_needed = True # clear previous location-based routing directive self.request.clear_route_to_location() # set location-based routing directive based on retry count # simulating single master writes by ensuring usePreferredLocations # is set to false self.request.route_to_location_with_preferred_location_flag(self.failover_retry_count, False) # Resolve the endpoint for the request and pin the resolution to the resolved endpoint # This enables marking the endpoint unavailability on endpoint failover/unreachability self.location_endpoint = self.global_endpoint_manager.resolve_service_endpoint(self.request) self.request.route_to_location(self.location_endpoint) return True
def wait_for_writability(self): """ Stop current thread until the channel is writable. :Return: `False` if it won't be readable (e.g. is closed) """ with self.lock: while True: if self._state in ("closing", "closed", "aborted"): return False if self._socket and bool(self._write_queue): return True self._write_queue_cond.wait() return False
Stop current thread until the channel is writable. :Return: `False` if it won't be readable (e.g. is closed)
Below is the the instruction that describes the task: ### Input: Stop current thread until the channel is writable. :Return: `False` if it won't be readable (e.g. is closed) ### Response: def wait_for_writability(self): """ Stop current thread until the channel is writable. :Return: `False` if it won't be readable (e.g. is closed) """ with self.lock: while True: if self._state in ("closing", "closed", "aborted"): return False if self._socket and bool(self._write_queue): return True self._write_queue_cond.wait() return False
def S(a,b): """ Simple interface to the overlap function. >>> from pyquante2 import pgbf,cgbf >>> s = pgbf(1) >>> isclose(S(s,s),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,sc),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,s),1.0) True >>> isclose(S(s,sc),1.0) True """ if b.contracted: return sum(cb*S(pb,a) for (cb,pb) in b) elif a.contracted: return sum(ca*S(b,pa) for (ca,pa) in a) return a.norm*b.norm*overlap(a.exponent,a.powers, a.origin,b.exponent,b.powers,b.origin)
Simple interface to the overlap function. >>> from pyquante2 import pgbf,cgbf >>> s = pgbf(1) >>> isclose(S(s,s),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,sc),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,s),1.0) True >>> isclose(S(s,sc),1.0) True
Below is the the instruction that describes the task: ### Input: Simple interface to the overlap function. >>> from pyquante2 import pgbf,cgbf >>> s = pgbf(1) >>> isclose(S(s,s),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,sc),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,s),1.0) True >>> isclose(S(s,sc),1.0) True ### Response: def S(a,b): """ Simple interface to the overlap function. >>> from pyquante2 import pgbf,cgbf >>> s = pgbf(1) >>> isclose(S(s,s),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,sc),1.0) True >>> sc = cgbf(exps=[1],coefs=[1]) >>> isclose(S(sc,s),1.0) True >>> isclose(S(s,sc),1.0) True """ if b.contracted: return sum(cb*S(pb,a) for (cb,pb) in b) elif a.contracted: return sum(ca*S(b,pa) for (ca,pa) in a) return a.norm*b.norm*overlap(a.exponent,a.powers, a.origin,b.exponent,b.powers,b.origin)
def rst_content(self, prefix: str = "", suffix: str = "", heading_underline_char: str = "=", method: AutodocMethod = None) -> str: """ Returns the text contents of an RST file that will automatically document our source file. Args: prefix: prefix, e.g. RST copyright comment suffix: suffix, after the part we're creating heading_underline_char: RST character to use to underline the heading method: optional method to override ``self.method``; see constructor Returns: the RST contents """ spacer = " " # Choose our final method if method is None: method = self.method is_python = self.is_python if method == AutodocMethod.BEST: if is_python: method = AutodocMethod.AUTOMODULE else: method = AutodocMethod.CONTENTS elif method == AutodocMethod.AUTOMODULE: if not is_python: method = AutodocMethod.CONTENTS # Write the instruction if method == AutodocMethod.AUTOMODULE: if self.source_rst_title_style_python: title = self.python_module_name else: title = self.source_filename_rel_project_root instruction = ".. automodule:: {modulename}\n :members:".format( modulename=self.python_module_name ) elif method == AutodocMethod.CONTENTS: title = self.source_filename_rel_project_root # Using ".. include::" with options like ":code: python" doesn't # work properly; everything comes out as Python. # Instead, see http://www.sphinx-doc.org/en/1.4.9/markup/code.html; # we need ".. literalinclude::" with ":language: LANGUAGE". instruction = ( ".. literalinclude:: {filename}\n" "{spacer}:language: {language}".format( filename=self.source_filename_rel_rst_file, spacer=spacer, language=self.pygments_language ) ) else: raise ValueError("Bad method!") # Create the whole file content = """ .. {filename} {AUTOGENERATED_COMMENT} {prefix} {underlined_title} {instruction} {suffix} """.format( filename=self.rst_filename_rel_project_root, AUTOGENERATED_COMMENT=AUTOGENERATED_COMMENT, prefix=prefix, underlined_title=rst_underline( title, underline_char=heading_underline_char), instruction=instruction, suffix=suffix, ).strip() + "\n" return content
Returns the text contents of an RST file that will automatically document our source file. Args: prefix: prefix, e.g. RST copyright comment suffix: suffix, after the part we're creating heading_underline_char: RST character to use to underline the heading method: optional method to override ``self.method``; see constructor Returns: the RST contents
Below is the the instruction that describes the task: ### Input: Returns the text contents of an RST file that will automatically document our source file. Args: prefix: prefix, e.g. RST copyright comment suffix: suffix, after the part we're creating heading_underline_char: RST character to use to underline the heading method: optional method to override ``self.method``; see constructor Returns: the RST contents ### Response: def rst_content(self, prefix: str = "", suffix: str = "", heading_underline_char: str = "=", method: AutodocMethod = None) -> str: """ Returns the text contents of an RST file that will automatically document our source file. Args: prefix: prefix, e.g. RST copyright comment suffix: suffix, after the part we're creating heading_underline_char: RST character to use to underline the heading method: optional method to override ``self.method``; see constructor Returns: the RST contents """ spacer = " " # Choose our final method if method is None: method = self.method is_python = self.is_python if method == AutodocMethod.BEST: if is_python: method = AutodocMethod.AUTOMODULE else: method = AutodocMethod.CONTENTS elif method == AutodocMethod.AUTOMODULE: if not is_python: method = AutodocMethod.CONTENTS # Write the instruction if method == AutodocMethod.AUTOMODULE: if self.source_rst_title_style_python: title = self.python_module_name else: title = self.source_filename_rel_project_root instruction = ".. automodule:: {modulename}\n :members:".format( modulename=self.python_module_name ) elif method == AutodocMethod.CONTENTS: title = self.source_filename_rel_project_root # Using ".. include::" with options like ":code: python" doesn't # work properly; everything comes out as Python. # Instead, see http://www.sphinx-doc.org/en/1.4.9/markup/code.html; # we need ".. literalinclude::" with ":language: LANGUAGE". instruction = ( ".. literalinclude:: {filename}\n" "{spacer}:language: {language}".format( filename=self.source_filename_rel_rst_file, spacer=spacer, language=self.pygments_language ) ) else: raise ValueError("Bad method!") # Create the whole file content = """ .. {filename} {AUTOGENERATED_COMMENT} {prefix} {underlined_title} {instruction} {suffix} """.format( filename=self.rst_filename_rel_project_root, AUTOGENERATED_COMMENT=AUTOGENERATED_COMMENT, prefix=prefix, underlined_title=rst_underline( title, underline_char=heading_underline_char), instruction=instruction, suffix=suffix, ).strip() + "\n" return content
def _strip_leading_dirname(self, path): '''Strip leading directory name from the given path''' return os.path.sep.join(path.split(os.path.sep)[1:])
Strip leading directory name from the given path
Below is the the instruction that describes the task: ### Input: Strip leading directory name from the given path ### Response: def _strip_leading_dirname(self, path): '''Strip leading directory name from the given path''' return os.path.sep.join(path.split(os.path.sep)[1:])
def gaussian(x, a, b, c, d=0): ''' a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation or Gaussian RMS width d -> offset ''' return a * np.exp( -(((x-b)**2 )/ (2*(c**2))) ) + d
a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation or Gaussian RMS width d -> offset
Below is the the instruction that describes the task: ### Input: a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation or Gaussian RMS width d -> offset ### Response: def gaussian(x, a, b, c, d=0): ''' a -> height of the curve's peak b -> position of the center of the peak c -> standard deviation or Gaussian RMS width d -> offset ''' return a * np.exp( -(((x-b)**2 )/ (2*(c**2))) ) + d
def prepare(self): ''' Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Minion, self).prepare() try: if self.config['verify_env']: confd = self.config.get('default_include') if confd: # If 'default_include' is specified in config, then use it if '*' in confd: # Value is of the form "minion.d/*.conf" confd = os.path.dirname(confd) if not os.path.isabs(confd): # If configured 'default_include' is not an absolute # path, consider it relative to folder of 'conf_file' # (/etc/salt by default) confd = os.path.join( os.path.dirname(self.config['conf_file']), confd ) else: confd = os.path.join( os.path.dirname(self.config['conf_file']), 'minion.d' ) v_dirs = [ self.config['pki_dir'], self.config['cachedir'], self.config['sock_dir'], self.config['extension_modules'], confd, ] verify_env( v_dirs, self.config['user'], permissive=self.config['permissive_pki_access'], root_dir=self.config['root_dir'], pki_dir=self.config['pki_dir'], ) except OSError as error: self.environment_failure(error) self.setup_logfile_logger() verify_log(self.config) log.info('Setting up the Salt Minion "%s"', self.config['id']) migrations.migrate_paths(self.config) # Bail out if we find a process running and it matches out pidfile if self.check_running(): self.action_log_info('An instance is already running. Exiting') self.shutdown(1) transport = self.config.get('transport').lower() # TODO: AIO core is separate from transport if transport in ('zeromq', 'tcp', 'detect'): # Late import so logging works correctly import salt.minion # If the minion key has not been accepted, then Salt enters a loop # waiting for it, if we daemonize later then the minion could halt # the boot process waiting for a key to be accepted on the master. # This is the latest safe place to daemonize self.daemonize_if_required() self.set_pidfile() if self.config.get('master_type') == 'func': salt.minion.eval_master_func(self.config) self.minion = salt.minion.MinionManager(self.config) else: log.error( 'The transport \'%s\' is not supported. Please use one of ' 'the following: tcp, zeromq, or detect.', transport ) self.shutdown(1)
Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare()
Below is the the instruction that describes the task: ### Input: Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ### Response: def prepare(self): ''' Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Minion, self).prepare() try: if self.config['verify_env']: confd = self.config.get('default_include') if confd: # If 'default_include' is specified in config, then use it if '*' in confd: # Value is of the form "minion.d/*.conf" confd = os.path.dirname(confd) if not os.path.isabs(confd): # If configured 'default_include' is not an absolute # path, consider it relative to folder of 'conf_file' # (/etc/salt by default) confd = os.path.join( os.path.dirname(self.config['conf_file']), confd ) else: confd = os.path.join( os.path.dirname(self.config['conf_file']), 'minion.d' ) v_dirs = [ self.config['pki_dir'], self.config['cachedir'], self.config['sock_dir'], self.config['extension_modules'], confd, ] verify_env( v_dirs, self.config['user'], permissive=self.config['permissive_pki_access'], root_dir=self.config['root_dir'], pki_dir=self.config['pki_dir'], ) except OSError as error: self.environment_failure(error) self.setup_logfile_logger() verify_log(self.config) log.info('Setting up the Salt Minion "%s"', self.config['id']) migrations.migrate_paths(self.config) # Bail out if we find a process running and it matches out pidfile if self.check_running(): self.action_log_info('An instance is already running. Exiting') self.shutdown(1) transport = self.config.get('transport').lower() # TODO: AIO core is separate from transport if transport in ('zeromq', 'tcp', 'detect'): # Late import so logging works correctly import salt.minion # If the minion key has not been accepted, then Salt enters a loop # waiting for it, if we daemonize later then the minion could halt # the boot process waiting for a key to be accepted on the master. # This is the latest safe place to daemonize self.daemonize_if_required() self.set_pidfile() if self.config.get('master_type') == 'func': salt.minion.eval_master_func(self.config) self.minion = salt.minion.MinionManager(self.config) else: log.error( 'The transport \'%s\' is not supported. Please use one of ' 'the following: tcp, zeromq, or detect.', transport ) self.shutdown(1)
def get_proficiency_admin_session(self, proxy): """Gets the ``OsidSession`` associated with the proficiency administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ProficiencyAdminSession) - a ``ProficiencyAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_proficiency_admin()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_proficiency_admin()`` is ``true``.* """ if not self.supports_proficiency_admin(): raise errors.Unimplemented() # pylint: disable=no-member return sessions.ProficiencyAdminSession(proxy=proxy, runtime=self._runtime)
Gets the ``OsidSession`` associated with the proficiency administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ProficiencyAdminSession) - a ``ProficiencyAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_proficiency_admin()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_proficiency_admin()`` is ``true``.*
Below is the the instruction that describes the task: ### Input: Gets the ``OsidSession`` associated with the proficiency administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ProficiencyAdminSession) - a ``ProficiencyAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_proficiency_admin()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_proficiency_admin()`` is ``true``.* ### Response: def get_proficiency_admin_session(self, proxy): """Gets the ``OsidSession`` associated with the proficiency administration service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ProficiencyAdminSession) - a ``ProficiencyAdminSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_proficiency_admin()`` is ``false`` *compliance: optional -- This method must be implemented if ``supports_proficiency_admin()`` is ``true``.* """ if not self.supports_proficiency_admin(): raise errors.Unimplemented() # pylint: disable=no-member return sessions.ProficiencyAdminSession(proxy=proxy, runtime=self._runtime)
def create_config_drive(network_interface_info, os_version): """Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address netmask_v4 - IPV4 netmask :param str os_version: operating system version of the guest """ temp_path = CONF.guest.temp_path if not os.path.exists(temp_path): os.mkdir(temp_path) cfg_dir = os.path.join(temp_path, 'openstack') if os.path.exists(cfg_dir): shutil.rmtree(cfg_dir) content_dir = os.path.join(cfg_dir, 'content') latest_dir = os.path.join(cfg_dir, 'latest') os.mkdir(cfg_dir) os.mkdir(content_dir) os.mkdir(latest_dir) net_file = os.path.join(content_dir, '0000') generate_net_file(network_interface_info, net_file, os_version) znetconfig_file = os.path.join(content_dir, '0001') generate_znetconfig_file(znetconfig_file, os_version) meta_data_path = os.path.join(latest_dir, 'meta_data.json') generate_meta_data(meta_data_path) network_data_path = os.path.join(latest_dir, 'network_data.json') generate_file('{}', network_data_path) vendor_data_path = os.path.join(latest_dir, 'vendor_data.json') generate_file('{}', vendor_data_path) tar_path = os.path.join(temp_path, 'cfgdrive.tgz') tar = tarfile.open(tar_path, "w:gz") os.chdir(temp_path) tar.add('openstack') tar.close() return tar_path
Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address netmask_v4 - IPV4 netmask :param str os_version: operating system version of the guest
Below is the the instruction that describes the task: ### Input: Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address netmask_v4 - IPV4 netmask :param str os_version: operating system version of the guest ### Response: def create_config_drive(network_interface_info, os_version): """Generate config driver for zVM guest vm. :param dict network_interface_info: Required keys: ip_addr - (str) IP address nic_vdev - (str) VDEV of the nic gateway_v4 - IPV4 gateway broadcast_v4 - IPV4 broadcast address netmask_v4 - IPV4 netmask :param str os_version: operating system version of the guest """ temp_path = CONF.guest.temp_path if not os.path.exists(temp_path): os.mkdir(temp_path) cfg_dir = os.path.join(temp_path, 'openstack') if os.path.exists(cfg_dir): shutil.rmtree(cfg_dir) content_dir = os.path.join(cfg_dir, 'content') latest_dir = os.path.join(cfg_dir, 'latest') os.mkdir(cfg_dir) os.mkdir(content_dir) os.mkdir(latest_dir) net_file = os.path.join(content_dir, '0000') generate_net_file(network_interface_info, net_file, os_version) znetconfig_file = os.path.join(content_dir, '0001') generate_znetconfig_file(znetconfig_file, os_version) meta_data_path = os.path.join(latest_dir, 'meta_data.json') generate_meta_data(meta_data_path) network_data_path = os.path.join(latest_dir, 'network_data.json') generate_file('{}', network_data_path) vendor_data_path = os.path.join(latest_dir, 'vendor_data.json') generate_file('{}', vendor_data_path) tar_path = os.path.join(temp_path, 'cfgdrive.tgz') tar = tarfile.open(tar_path, "w:gz") os.chdir(temp_path) tar.add('openstack') tar.close() return tar_path
def forward(*args, **kwargs): """Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. """ self, cmd = args[:2] # It's also possible to invoke another command which might or # might not have a callback. if not isinstance(cmd, Command): raise TypeError('Callback is not a command.') for param in self.params: if param not in kwargs: kwargs[param] = self.params[param] return self.invoke(cmd, **kwargs)
Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands.
Below is the the instruction that describes the task: ### Input: Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. ### Response: def forward(*args, **kwargs): """Similar to :meth:`invoke` but fills in default keyword arguments from the current context if the other command expects it. This cannot invoke callbacks directly, only other commands. """ self, cmd = args[:2] # It's also possible to invoke another command which might or # might not have a callback. if not isinstance(cmd, Command): raise TypeError('Callback is not a command.') for param in self.params: if param not in kwargs: kwargs[param] = self.params[param] return self.invoke(cmd, **kwargs)
def imagetransformer_cifar_tpu_range(rhp): """Range of hyperparameters for vizier.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.01, 1.0, scale=rhp.LOG_SCALE) rhp.set_discrete("num_decoder_layers", [8, 10, 12, 14, 16]) rhp.set_discrete("hidden_size", [256, 512, 1024]) rhp.set_discrete("block_length", [128, 256, 512]) rhp.set_categorical("dec_attention_type", [ cia.AttentionType.RELATIVE_LOCAL_1D, cia.AttentionType.LOCAL_1D])
Range of hyperparameters for vizier.
Below is the the instruction that describes the task: ### Input: Range of hyperparameters for vizier. ### Response: def imagetransformer_cifar_tpu_range(rhp): """Range of hyperparameters for vizier.""" # After starting from base, set intervals for some parameters. rhp.set_float("learning_rate", 0.01, 1.0, scale=rhp.LOG_SCALE) rhp.set_discrete("num_decoder_layers", [8, 10, 12, 14, 16]) rhp.set_discrete("hidden_size", [256, 512, 1024]) rhp.set_discrete("block_length", [128, 256, 512]) rhp.set_categorical("dec_attention_type", [ cia.AttentionType.RELATIVE_LOCAL_1D, cia.AttentionType.LOCAL_1D])
def authorize(self, username, arguments=[], authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Authorize with a TACACS+ server. :param username: :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: Minimal Required priv_lvl. :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAuthenticationReply :raises: socket.timeout, socket.error """ with self.closing(): packet = self.send( TACACSAuthorizationStart(username, TAC_PLUS_AUTHEN_METH_TACACSPLUS, priv_lvl, authen_type, arguments, rem_addr=rem_addr, port=port), TAC_PLUS_AUTHOR ) reply = TACACSAuthorizationReply.unpacked(packet.body) logger.debug('\n'.join([ reply.__class__.__name__, 'recv header <%s>' % packet.header, 'recv body <%s>' % reply ])) reply_arguments = dict([ arg.split(six.b('='), 1) for arg in reply.arguments or [] if arg.find(six.b('=')) > -1] ) user_priv_lvl = int(reply_arguments.get( six.b('priv-lvl'), TAC_PLUS_PRIV_LVL_MAX)) if user_priv_lvl < priv_lvl: reply.status = TAC_PLUS_AUTHOR_STATUS_FAIL return reply
Authorize with a TACACS+ server. :param username: :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: Minimal Required priv_lvl. :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAuthenticationReply :raises: socket.timeout, socket.error
Below is the the instruction that describes the task: ### Input: Authorize with a TACACS+ server. :param username: :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: Minimal Required priv_lvl. :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAuthenticationReply :raises: socket.timeout, socket.error ### Response: def authorize(self, username, arguments=[], authen_type=TAC_PLUS_AUTHEN_TYPE_ASCII, priv_lvl=TAC_PLUS_PRIV_LVL_MIN, rem_addr=TAC_PLUS_VIRTUAL_REM_ADDR, port=TAC_PLUS_VIRTUAL_PORT): """ Authorize with a TACACS+ server. :param username: :param arguments: The authorization arguments :param authen_type: TAC_PLUS_AUTHEN_TYPE_ASCII, TAC_PLUS_AUTHEN_TYPE_PAP, TAC_PLUS_AUTHEN_TYPE_CHAP :param priv_lvl: Minimal Required priv_lvl. :param rem_addr: AAA request source, default to TAC_PLUS_VIRTUAL_REM_ADDR :param port: AAA port, default to TAC_PLUS_VIRTUAL_PORT :return: TACACSAuthenticationReply :raises: socket.timeout, socket.error """ with self.closing(): packet = self.send( TACACSAuthorizationStart(username, TAC_PLUS_AUTHEN_METH_TACACSPLUS, priv_lvl, authen_type, arguments, rem_addr=rem_addr, port=port), TAC_PLUS_AUTHOR ) reply = TACACSAuthorizationReply.unpacked(packet.body) logger.debug('\n'.join([ reply.__class__.__name__, 'recv header <%s>' % packet.header, 'recv body <%s>' % reply ])) reply_arguments = dict([ arg.split(six.b('='), 1) for arg in reply.arguments or [] if arg.find(six.b('=')) > -1] ) user_priv_lvl = int(reply_arguments.get( six.b('priv-lvl'), TAC_PLUS_PRIV_LVL_MAX)) if user_priv_lvl < priv_lvl: reply.status = TAC_PLUS_AUTHOR_STATUS_FAIL return reply
def for_branch(self, branch): """ Return a UsageLocator for the same block in a different branch of the library. """ return self.replace(library_key=self.library_key.for_branch(branch))
Return a UsageLocator for the same block in a different branch of the library.
Below is the the instruction that describes the task: ### Input: Return a UsageLocator for the same block in a different branch of the library. ### Response: def for_branch(self, branch): """ Return a UsageLocator for the same block in a different branch of the library. """ return self.replace(library_key=self.library_key.for_branch(branch))
def _isint(string): """ >>> _isint("123") True >>> _isint("123.45") False """ return type(string) is int or \ (isinstance(string, _binary_type) or isinstance(string, string_types)) and \ _isconvertible(int, string)
>>> _isint("123") True >>> _isint("123.45") False
Below is the the instruction that describes the task: ### Input: >>> _isint("123") True >>> _isint("123.45") False ### Response: def _isint(string): """ >>> _isint("123") True >>> _isint("123.45") False """ return type(string) is int or \ (isinstance(string, _binary_type) or isinstance(string, string_types)) and \ _isconvertible(int, string)
def bbox_transpose(bbox, axis, rows, cols): """Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols. """ x_min, y_min, x_max, y_max = bbox if axis != 0 and axis != 1: raise ValueError('Axis must be either 0 or 1.') if axis == 0: bbox = [y_min, x_min, y_max, x_max] if axis == 1: bbox = [1 - y_max, 1 - x_max, 1 - y_min, 1 - x_min] return bbox
Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols.
Below is the the instruction that describes the task: ### Input: Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols. ### Response: def bbox_transpose(bbox, axis, rows, cols): """Transposes a bounding box along given axis. Args: bbox (tuple): A tuple (x_min, y_min, x_max, y_max). axis (int): 0 - main axis, 1 - secondary axis. rows (int): Image rows. cols (int): Image cols. """ x_min, y_min, x_max, y_max = bbox if axis != 0 and axis != 1: raise ValueError('Axis must be either 0 or 1.') if axis == 0: bbox = [y_min, x_min, y_max, x_max] if axis == 1: bbox = [1 - y_max, 1 - x_max, 1 - y_min, 1 - x_min] return bbox
def _set_interface_auth_key(self, v, load=False): """ Setter method for interface_auth_key, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_auth_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_interface_auth_key is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_auth_key() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("interface_auth_key_level",interface_auth_key.interface_auth_key, yang_name="interface-auth-key", rest_name="auth-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='interface-auth-key-level', extensions={u'tailf-common': {u'info': u'Define authentication key', u'cli-suppress-mode': None, u'callpoint': u'IsisVeInterfaceAuthKey', u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'alt-name': u'auth-key'}}), is_container='list', yang_name="interface-auth-key", rest_name="auth-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Define authentication key', u'cli-suppress-mode': None, u'callpoint': u'IsisVeInterfaceAuthKey', u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'alt-name': u'auth-key'}}, namespace='urn:brocade.com:mgmt:brocade-isis', defining_module='brocade-isis', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interface_auth_key must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("interface_auth_key_level",interface_auth_key.interface_auth_key, yang_name="interface-auth-key", rest_name="auth-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='interface-auth-key-level', extensions={u'tailf-common': {u'info': u'Define authentication key', u'cli-suppress-mode': None, u'callpoint': u'IsisVeInterfaceAuthKey', u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'alt-name': u'auth-key'}}), is_container='list', yang_name="interface-auth-key", rest_name="auth-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Define authentication key', u'cli-suppress-mode': None, u'callpoint': u'IsisVeInterfaceAuthKey', u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'alt-name': u'auth-key'}}, namespace='urn:brocade.com:mgmt:brocade-isis', defining_module='brocade-isis', yang_type='list', is_config=True)""", }) self.__interface_auth_key = t if hasattr(self, '_set'): self._set()
Setter method for interface_auth_key, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_auth_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_interface_auth_key is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_auth_key() directly.
Below is the the instruction that describes the task: ### Input: Setter method for interface_auth_key, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_auth_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_interface_auth_key is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_auth_key() directly. ### Response: def _set_interface_auth_key(self, v, load=False): """ Setter method for interface_auth_key, mapped from YANG variable /routing_system/interface/ve/intf_isis/interface_isis/interface_auth_key (list) If this variable is read-only (config: false) in the source YANG file, then _set_interface_auth_key is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_interface_auth_key() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGListType("interface_auth_key_level",interface_auth_key.interface_auth_key, yang_name="interface-auth-key", rest_name="auth-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='interface-auth-key-level', extensions={u'tailf-common': {u'info': u'Define authentication key', u'cli-suppress-mode': None, u'callpoint': u'IsisVeInterfaceAuthKey', u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'alt-name': u'auth-key'}}), is_container='list', yang_name="interface-auth-key", rest_name="auth-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Define authentication key', u'cli-suppress-mode': None, u'callpoint': u'IsisVeInterfaceAuthKey', u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'alt-name': u'auth-key'}}, namespace='urn:brocade.com:mgmt:brocade-isis', defining_module='brocade-isis', yang_type='list', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """interface_auth_key must be of a type compatible with list""", 'defined-type': "list", 'generated-type': """YANGDynClass(base=YANGListType("interface_auth_key_level",interface_auth_key.interface_auth_key, yang_name="interface-auth-key", rest_name="auth-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='interface-auth-key-level', extensions={u'tailf-common': {u'info': u'Define authentication key', u'cli-suppress-mode': None, u'callpoint': u'IsisVeInterfaceAuthKey', u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'alt-name': u'auth-key'}}), is_container='list', yang_name="interface-auth-key", rest_name="auth-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Define authentication key', u'cli-suppress-mode': None, u'callpoint': u'IsisVeInterfaceAuthKey', u'cli-compact-syntax': None, u'cli-sequence-commands': None, u'cli-suppress-key-abbreviation': None, u'cli-incomplete-command': None, u'alt-name': u'auth-key'}}, namespace='urn:brocade.com:mgmt:brocade-isis', defining_module='brocade-isis', yang_type='list', is_config=True)""", }) self.__interface_auth_key = t if hasattr(self, '_set'): self._set()
def _osd_pct_used(self, health): """Take a single health check string, return (OSD name, percentage used)""" # Full string looks like: osd.2 is full at 95% # Near full string: osd.1 is near full at 94% pct = re.compile(r'\d+%').findall(health) osd = re.compile(r'osd.\d+').findall(health) if len(pct) > 0 and len(osd) > 0: return osd[0], int(pct[0][:-1]) else: return None, None
Take a single health check string, return (OSD name, percentage used)
Below is the the instruction that describes the task: ### Input: Take a single health check string, return (OSD name, percentage used) ### Response: def _osd_pct_used(self, health): """Take a single health check string, return (OSD name, percentage used)""" # Full string looks like: osd.2 is full at 95% # Near full string: osd.1 is near full at 94% pct = re.compile(r'\d+%').findall(health) osd = re.compile(r'osd.\d+').findall(health) if len(pct) > 0 and len(osd) > 0: return osd[0], int(pct[0][:-1]) else: return None, None
def markdown(value, extensions=MARKDOWN_EXTENSIONS): """ Markdown processing with optionally using various extensions that python-markdown supports. `extensions` is an iterable of either markdown.Extension instances or extension paths. """ try: import markdown except ImportError: warnings.warn("The Python markdown library isn't installed.", RuntimeWarning) return value return markdown.markdown(force_text(value), extensions=extensions)
Markdown processing with optionally using various extensions that python-markdown supports. `extensions` is an iterable of either markdown.Extension instances or extension paths.
Below is the the instruction that describes the task: ### Input: Markdown processing with optionally using various extensions that python-markdown supports. `extensions` is an iterable of either markdown.Extension instances or extension paths. ### Response: def markdown(value, extensions=MARKDOWN_EXTENSIONS): """ Markdown processing with optionally using various extensions that python-markdown supports. `extensions` is an iterable of either markdown.Extension instances or extension paths. """ try: import markdown except ImportError: warnings.warn("The Python markdown library isn't installed.", RuntimeWarning) return value return markdown.markdown(force_text(value), extensions=extensions)
def plugin(module, *args, **kwargs): """ Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): return {} return MyExtension # Your view.py @plugin(my_ext) class Index(View): pass :param module: object :param args: :param kwargs: :return: """ def wrap(f): m = module(f, *args, **kwargs) if inspect.isclass(m): for k, v in m.__dict__.items(): if not k.startswith("__"): setattr(f, k, v) elif inspect.isfunction(m): setattr(f, kls.__name__, m) return f return wrap
Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): return {} return MyExtension # Your view.py @plugin(my_ext) class Index(View): pass :param module: object :param args: :param kwargs: :return:
Below is the the instruction that describes the task: ### Input: Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): return {} return MyExtension # Your view.py @plugin(my_ext) class Index(View): pass :param module: object :param args: :param kwargs: :return: ### Response: def plugin(module, *args, **kwargs): """ Decorator to extend a package to a view. The module can be a class or function. It will copy all the methods to the class ie: # Your module.py my_ext(view, **kwargs): class MyExtension(object): def my_view(self): return {} return MyExtension # Your view.py @plugin(my_ext) class Index(View): pass :param module: object :param args: :param kwargs: :return: """ def wrap(f): m = module(f, *args, **kwargs) if inspect.isclass(m): for k, v in m.__dict__.items(): if not k.startswith("__"): setattr(f, k, v) elif inspect.isfunction(m): setattr(f, kls.__name__, m) return f return wrap
def get_profile_dir (): """Return path where all profiles of current user are stored.""" if os.name == 'nt': basedir = unicode(os.environ["APPDATA"], nt_filename_encoding) dirpath = os.path.join(basedir, u"Mozilla", u"Firefox", u"Profiles") elif os.name == 'posix': basedir = unicode(os.environ["HOME"]) dirpath = os.path.join(basedir, u".mozilla", u"firefox") return dirpath
Return path where all profiles of current user are stored.
Below is the the instruction that describes the task: ### Input: Return path where all profiles of current user are stored. ### Response: def get_profile_dir (): """Return path where all profiles of current user are stored.""" if os.name == 'nt': basedir = unicode(os.environ["APPDATA"], nt_filename_encoding) dirpath = os.path.join(basedir, u"Mozilla", u"Firefox", u"Profiles") elif os.name == 'posix': basedir = unicode(os.environ["HOME"]) dirpath = os.path.join(basedir, u".mozilla", u"firefox") return dirpath
def mousePressEvent( self, event ): """ Sets the value for the slider at the event position. :param event | <QMouseEvent> """ self.setValue(self.valueAt(event.pos().x()))
Sets the value for the slider at the event position. :param event | <QMouseEvent>
Below is the the instruction that describes the task: ### Input: Sets the value for the slider at the event position. :param event | <QMouseEvent> ### Response: def mousePressEvent( self, event ): """ Sets the value for the slider at the event position. :param event | <QMouseEvent> """ self.setValue(self.valueAt(event.pos().x()))
def scan(TableName=None, IndexName=None, AttributesToGet=None, Limit=None, Select=None, ScanFilter=None, ConditionalOperator=None, ExclusiveStartKey=None, ReturnConsumedCapacity=None, TotalSegments=None, Segment=None, ProjectionExpression=None, FilterExpression=None, ExpressionAttributeNames=None, ExpressionAttributeValues=None, ConsistentRead=None): """ The Scan operation returns one or more items and item attributes by accessing every item in a table or a secondary index. To have DynamoDB return fewer items, you can provide a FilterExpression operation. If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and results are returned to the user as a LastEvaluatedKey value to continue the scan in a subsequent operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria. By default, Scan operations proceed sequentially; however, for faster performance on a large table or secondary index, applications can request a parallel Scan operation by providing the Segment and TotalSegments parameters. For more information, see Parallel Scan in the Amazon DynamoDB Developer Guide . By default, Scan uses eventually consistent reads when accessing the data in a table; therefore, the result set might not include the changes to data in the table immediately before the operation began. If you need a consistent copy of the data, as of the time that the Scan begins, you can set the ConsistentRead parameter to true . See also: AWS API Documentation Examples This example scans the entire Music table, and then narrows the results to songs by the artist "No One You Know". For each item, only the album title and song title are returned. Expected Output: :example: response = client.scan( TableName='string', IndexName='string', AttributesToGet=[ 'string', ], Limit=123, Select='ALL_ATTRIBUTES'|'ALL_PROJECTED_ATTRIBUTES'|'SPECIFIC_ATTRIBUTES'|'COUNT', ScanFilter={ 'string': { 'AttributeValueList': [ { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False }, ], 'ComparisonOperator': 'EQ'|'NE'|'IN'|'LE'|'LT'|'GE'|'GT'|'BETWEEN'|'NOT_NULL'|'NULL'|'CONTAINS'|'NOT_CONTAINS'|'BEGINS_WITH' } }, ConditionalOperator='AND'|'OR', ExclusiveStartKey={ 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ReturnConsumedCapacity='INDEXES'|'TOTAL'|'NONE', TotalSegments=123, Segment=123, ProjectionExpression='string', FilterExpression='string', ExpressionAttributeNames={ 'string': 'string' }, ExpressionAttributeValues={ 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ConsistentRead=True|False ) :type TableName: string :param TableName: [REQUIRED] The name of the table containing the requested items; or, if you provide IndexName , the name of the table to which that index belongs. :type IndexName: string :param IndexName: The name of a secondary index to scan. This index can be any local secondary index or global secondary index. Note that if you use the IndexName parameter, you must also provide TableName . :type AttributesToGet: list :param AttributesToGet: This is a legacy parameter. Use ProjectionExpression instead. For more information, see AttributesToGet in the Amazon DynamoDB Developer Guide . (string) -- :type Limit: integer :param Limit: The maximum number of items to evaluate (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a key in LastEvaluatedKey to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size exceeds 1 MB before DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a key in LastEvaluatedKey to apply in a subsequent operation to continue the operation. For more information, see Query and Scan in the Amazon DynamoDB Developer Guide . :type Select: string :param Select: The attributes to be returned in the result. You can retrieve all item attributes, specific item attributes, the count of matching items, or in the case of an index, some or all of the attributes projected into the index. ALL_ATTRIBUTES - Returns all of the item attributes from the specified table or index. If you query a local secondary index, then for each matching item in the index DynamoDB will fetch the entire item from the parent table. If the index is configured to project all item attributes, then all of the data can be obtained from the local secondary index, and no fetching is required. ALL_PROJECTED_ATTRIBUTES - Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying ALL_ATTRIBUTES . COUNT - Returns the number of matching items, rather than the matching items themselves. SPECIFIC_ATTRIBUTES - Returns only the attributes listed in AttributesToGet . This return value is equivalent to specifying AttributesToGet without specifying any value for Select . If you query or scan a local secondary index and request only attributes that are projected into that index, the operation will read only the index and not the table. If any of the requested attributes are not projected into the local secondary index, DynamoDB will fetch each of these attributes from the parent table. This extra fetching incurs additional throughput cost and latency. If you query or scan a global secondary index, you can only request attributes that are projected into the index. Global secondary index queries cannot fetch attributes from the parent table. If neither Select nor AttributesToGet are specified, DynamoDB defaults to ALL_ATTRIBUTES when accessing a table, and ALL_PROJECTED_ATTRIBUTES when accessing an index. You cannot use both Select and AttributesToGet together in a single request, unless the value for Select is SPECIFIC_ATTRIBUTES . (This usage is equivalent to specifying AttributesToGet without any value for Select .) Note If you use the ProjectionExpression parameter, then the value for Select can only be SPECIFIC_ATTRIBUTES . Any other value for Select will return an error. :type ScanFilter: dict :param ScanFilter: This is a legacy parameter. Use FilterExpression instead. For more information, see ScanFilter in the Amazon DynamoDB Developer Guide . (string) -- (dict) --Represents the selection criteria for a Query or Scan operation: For a Query operation, Condition is used for specifying the KeyConditions to use when querying a table or an index. For KeyConditions , only the following comparison operators are supported: EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN Condition is also used in a QueryFilter , which evaluates the query results and returns only the desired values. For a Scan operation, Condition is used in a ScanFilter , which evaluates the scan results and returns only the desired values. AttributeValueList (list) --One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used. For type Number, value comparisons are numeric. String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, a is greater than A , and a is greater than B . For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters . For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values. (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true ComparisonOperator (string) -- [REQUIRED]A comparator for evaluating attributes. For example, equals, greater than, less than, etc. The following comparison operators are available: EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN The following are descriptions of each comparison operator. EQ : Equal. EQ is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} . NE : Not equal. NE is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} . LE : Less than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . LT : Less than. AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . GE : Greater than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . GT : Greater than. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . NOT_NULL : The attribute exists. NOT_NULL is supported for all data types, including lists and maps. Note This operator tests for the existence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NOT_NULL , the result is a Boolean true . This result is because the attribute 'a ' exists; its data type is not relevant to the NOT_NULL comparison operator. NULL : The attribute does not exist. NULL is supported for all data types, including lists and maps. Note This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NULL , the result is a Boolean false . This is because the attribute 'a ' exists; its data type is not relevant to the NULL comparison operator. CONTAINS : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating 'a CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list. NOT_CONTAINS : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating 'a NOT CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list. BEGINS_WITH : Checks for a prefix. AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type). IN : Checks for matching elements in a list. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary. These attributes are compared against an existing attribute of an item. If any elements of the input are equal to the item attribute, the expression evaluates to true. BETWEEN : Greater than or equal to the first value, and less than or equal to the second value. AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not compare to {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} For usage examples of AttributeValueList and ComparisonOperator , see Legacy Conditional Parameters in the Amazon DynamoDB Developer Guide . :type ConditionalOperator: string :param ConditionalOperator: This is a legacy parameter. Use FilterExpression instead. For more information, see ConditionalOperator in the Amazon DynamoDB Developer Guide . :type ExclusiveStartKey: dict :param ExclusiveStartKey: The primary key of the first item that this operation will evaluate. Use the value that was returned for LastEvaluatedKey in the previous operation. The data type for ExclusiveStartKey must be String, Number or Binary. No set data types are allowed. In a parallel scan, a Scan request that includes ExclusiveStartKey must specify the same segment whose previous Scan returned the corresponding value of LastEvaluatedKey . (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true :type ReturnConsumedCapacity: string :param ReturnConsumedCapacity: Determines the level of detail about provisioned throughput consumption that is returned in the response: INDEXES - The response includes the aggregate ConsumedCapacity for the operation, together with ConsumedCapacity for each table and secondary index that was accessed. Note that some operations, such as GetItem and BatchGetItem , do not access any indexes at all. In these cases, specifying INDEXES will only return ConsumedCapacity information for table(s). TOTAL - The response includes only the aggregate ConsumedCapacity for the operation. NONE - No ConsumedCapacity details are included in the response. :type TotalSegments: integer :param TotalSegments: For a parallel Scan request, TotalSegments represents the total number of segments into which the Scan operation will be divided. The value of TotalSegments corresponds to the number of application workers that will perform the parallel scan. For example, if you want to use four application threads to scan a table or an index, specify a TotalSegments value of 4. The value for TotalSegments must be greater than or equal to 1, and less than or equal to 1000000. If you specify a TotalSegments value of 1, the Scan operation will be sequential rather than parallel. If you specify TotalSegments , you must also specify Segment . :type Segment: integer :param Segment: For a parallel Scan request, Segment identifies an individual segment to be scanned by an application worker. Segment IDs are zero-based, so the first segment is always 0. For example, if you want to use four application threads to scan a table or an index, then the first thread specifies a Segment value of 0, the second thread specifies 1, and so on. The value of LastEvaluatedKey returned from a parallel Scan request must be used as ExclusiveStartKey with the same segment ID in a subsequent Scan operation. The value for Segment must be greater than or equal to 0, and less than the value provided for TotalSegments . If you provide Segment , you must also provide TotalSegments . :type ProjectionExpression: string :param ProjectionExpression: A string that identifies one or more attributes to retrieve from the specified table or index. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas. If no attribute names are specified, then all attributes will be returned. If any of the requested attributes are not found, they will not appear in the result. For more information, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide . :type FilterExpression: string :param FilterExpression: A string that contains conditions that DynamoDB applies after the Scan operation, but before the data is returned to you. Items that do not satisfy the FilterExpression criteria are not returned. Note A FilterExpression is applied after the items have already been read; the process of filtering does not consume any additional read capacity units. For more information, see Filter Expressions in the Amazon DynamoDB Developer Guide . :type ExpressionAttributeNames: dict :param ExpressionAttributeNames: One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames : To access an attribute whose name conflicts with a DynamoDB reserved word. To create a placeholder for repeating occurrences of an attribute name in an expression. To prevent special characters in an attribute name from being misinterpreted in an expression. Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name: Percentile The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide ). To work around this, you could specify the following for ExpressionAttributeNames : {'#P':'Percentile'} You could then use this substitution in an expression, as in this example: #P = :val Note Tokens that begin with the : character are expression attribute values , which are placeholders for the actual value at runtime. For more information on expression attribute names, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide . (string) -- (string) -- :type ExpressionAttributeValues: dict :param ExpressionAttributeValues: One or more values that can be substituted in an expression. Use the : (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following: Available | Backordered | Discontinued You would first need to specify ExpressionAttributeValues as follows: { ':avail':{'S':'Available'}, ':back':{'S':'Backordered'}, ':disc':{'S':'Discontinued'} } You could then use these values in an expression, such as this: ProductStatus IN (:avail, :back, :disc) For more information on expression attribute values, see Specifying Conditions in the Amazon DynamoDB Developer Guide . (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true :type ConsistentRead: boolean :param ConsistentRead: A Boolean value that determines the read consistency model during the scan: If ConsistentRead is false , then the data returned from Scan might not contain the results from other recently completed write operations (PutItem, UpdateItem or DeleteItem). If ConsistentRead is true , then all of the write operations that completed before the Scan began are guaranteed to be contained in the Scan response. The default setting for ConsistentRead is false . The ConsistentRead parameter is not supported on global secondary indexes. If you scan a global secondary index with ConsistentRead set to true, you will receive a ValidationException . :rtype: dict :return: { 'Items': [ { 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ], 'Count': 123, 'ScannedCount': 123, 'LastEvaluatedKey': { 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, 'ConsumedCapacity': { 'TableName': 'string', 'CapacityUnits': 123.0, 'Table': { 'CapacityUnits': 123.0 }, 'LocalSecondaryIndexes': { 'string': { 'CapacityUnits': 123.0 } }, 'GlobalSecondaryIndexes': { 'string': { 'CapacityUnits': 123.0 } } } } :returns: (string) -- """ pass
The Scan operation returns one or more items and item attributes by accessing every item in a table or a secondary index. To have DynamoDB return fewer items, you can provide a FilterExpression operation. If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and results are returned to the user as a LastEvaluatedKey value to continue the scan in a subsequent operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria. By default, Scan operations proceed sequentially; however, for faster performance on a large table or secondary index, applications can request a parallel Scan operation by providing the Segment and TotalSegments parameters. For more information, see Parallel Scan in the Amazon DynamoDB Developer Guide . By default, Scan uses eventually consistent reads when accessing the data in a table; therefore, the result set might not include the changes to data in the table immediately before the operation began. If you need a consistent copy of the data, as of the time that the Scan begins, you can set the ConsistentRead parameter to true . See also: AWS API Documentation Examples This example scans the entire Music table, and then narrows the results to songs by the artist "No One You Know". For each item, only the album title and song title are returned. Expected Output: :example: response = client.scan( TableName='string', IndexName='string', AttributesToGet=[ 'string', ], Limit=123, Select='ALL_ATTRIBUTES'|'ALL_PROJECTED_ATTRIBUTES'|'SPECIFIC_ATTRIBUTES'|'COUNT', ScanFilter={ 'string': { 'AttributeValueList': [ { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False }, ], 'ComparisonOperator': 'EQ'|'NE'|'IN'|'LE'|'LT'|'GE'|'GT'|'BETWEEN'|'NOT_NULL'|'NULL'|'CONTAINS'|'NOT_CONTAINS'|'BEGINS_WITH' } }, ConditionalOperator='AND'|'OR', ExclusiveStartKey={ 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ReturnConsumedCapacity='INDEXES'|'TOTAL'|'NONE', TotalSegments=123, Segment=123, ProjectionExpression='string', FilterExpression='string', ExpressionAttributeNames={ 'string': 'string' }, ExpressionAttributeValues={ 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ConsistentRead=True|False ) :type TableName: string :param TableName: [REQUIRED] The name of the table containing the requested items; or, if you provide IndexName , the name of the table to which that index belongs. :type IndexName: string :param IndexName: The name of a secondary index to scan. This index can be any local secondary index or global secondary index. Note that if you use the IndexName parameter, you must also provide TableName . :type AttributesToGet: list :param AttributesToGet: This is a legacy parameter. Use ProjectionExpression instead. For more information, see AttributesToGet in the Amazon DynamoDB Developer Guide . (string) -- :type Limit: integer :param Limit: The maximum number of items to evaluate (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a key in LastEvaluatedKey to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size exceeds 1 MB before DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a key in LastEvaluatedKey to apply in a subsequent operation to continue the operation. For more information, see Query and Scan in the Amazon DynamoDB Developer Guide . :type Select: string :param Select: The attributes to be returned in the result. You can retrieve all item attributes, specific item attributes, the count of matching items, or in the case of an index, some or all of the attributes projected into the index. ALL_ATTRIBUTES - Returns all of the item attributes from the specified table or index. If you query a local secondary index, then for each matching item in the index DynamoDB will fetch the entire item from the parent table. If the index is configured to project all item attributes, then all of the data can be obtained from the local secondary index, and no fetching is required. ALL_PROJECTED_ATTRIBUTES - Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying ALL_ATTRIBUTES . COUNT - Returns the number of matching items, rather than the matching items themselves. SPECIFIC_ATTRIBUTES - Returns only the attributes listed in AttributesToGet . This return value is equivalent to specifying AttributesToGet without specifying any value for Select . If you query or scan a local secondary index and request only attributes that are projected into that index, the operation will read only the index and not the table. If any of the requested attributes are not projected into the local secondary index, DynamoDB will fetch each of these attributes from the parent table. This extra fetching incurs additional throughput cost and latency. If you query or scan a global secondary index, you can only request attributes that are projected into the index. Global secondary index queries cannot fetch attributes from the parent table. If neither Select nor AttributesToGet are specified, DynamoDB defaults to ALL_ATTRIBUTES when accessing a table, and ALL_PROJECTED_ATTRIBUTES when accessing an index. You cannot use both Select and AttributesToGet together in a single request, unless the value for Select is SPECIFIC_ATTRIBUTES . (This usage is equivalent to specifying AttributesToGet without any value for Select .) Note If you use the ProjectionExpression parameter, then the value for Select can only be SPECIFIC_ATTRIBUTES . Any other value for Select will return an error. :type ScanFilter: dict :param ScanFilter: This is a legacy parameter. Use FilterExpression instead. For more information, see ScanFilter in the Amazon DynamoDB Developer Guide . (string) -- (dict) --Represents the selection criteria for a Query or Scan operation: For a Query operation, Condition is used for specifying the KeyConditions to use when querying a table or an index. For KeyConditions , only the following comparison operators are supported: EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN Condition is also used in a QueryFilter , which evaluates the query results and returns only the desired values. For a Scan operation, Condition is used in a ScanFilter , which evaluates the scan results and returns only the desired values. AttributeValueList (list) --One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used. For type Number, value comparisons are numeric. String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, a is greater than A , and a is greater than B . For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters . For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values. (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true ComparisonOperator (string) -- [REQUIRED]A comparator for evaluating attributes. For example, equals, greater than, less than, etc. The following comparison operators are available: EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN The following are descriptions of each comparison operator. EQ : Equal. EQ is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} . NE : Not equal. NE is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} . LE : Less than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . LT : Less than. AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . GE : Greater than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . GT : Greater than. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . NOT_NULL : The attribute exists. NOT_NULL is supported for all data types, including lists and maps. Note This operator tests for the existence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NOT_NULL , the result is a Boolean true . This result is because the attribute 'a ' exists; its data type is not relevant to the NOT_NULL comparison operator. NULL : The attribute does not exist. NULL is supported for all data types, including lists and maps. Note This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NULL , the result is a Boolean false . This is because the attribute 'a ' exists; its data type is not relevant to the NULL comparison operator. CONTAINS : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating 'a CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list. NOT_CONTAINS : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating 'a NOT CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list. BEGINS_WITH : Checks for a prefix. AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type). IN : Checks for matching elements in a list. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary. These attributes are compared against an existing attribute of an item. If any elements of the input are equal to the item attribute, the expression evaluates to true. BETWEEN : Greater than or equal to the first value, and less than or equal to the second value. AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not compare to {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} For usage examples of AttributeValueList and ComparisonOperator , see Legacy Conditional Parameters in the Amazon DynamoDB Developer Guide . :type ConditionalOperator: string :param ConditionalOperator: This is a legacy parameter. Use FilterExpression instead. For more information, see ConditionalOperator in the Amazon DynamoDB Developer Guide . :type ExclusiveStartKey: dict :param ExclusiveStartKey: The primary key of the first item that this operation will evaluate. Use the value that was returned for LastEvaluatedKey in the previous operation. The data type for ExclusiveStartKey must be String, Number or Binary. No set data types are allowed. In a parallel scan, a Scan request that includes ExclusiveStartKey must specify the same segment whose previous Scan returned the corresponding value of LastEvaluatedKey . (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true :type ReturnConsumedCapacity: string :param ReturnConsumedCapacity: Determines the level of detail about provisioned throughput consumption that is returned in the response: INDEXES - The response includes the aggregate ConsumedCapacity for the operation, together with ConsumedCapacity for each table and secondary index that was accessed. Note that some operations, such as GetItem and BatchGetItem , do not access any indexes at all. In these cases, specifying INDEXES will only return ConsumedCapacity information for table(s). TOTAL - The response includes only the aggregate ConsumedCapacity for the operation. NONE - No ConsumedCapacity details are included in the response. :type TotalSegments: integer :param TotalSegments: For a parallel Scan request, TotalSegments represents the total number of segments into which the Scan operation will be divided. The value of TotalSegments corresponds to the number of application workers that will perform the parallel scan. For example, if you want to use four application threads to scan a table or an index, specify a TotalSegments value of 4. The value for TotalSegments must be greater than or equal to 1, and less than or equal to 1000000. If you specify a TotalSegments value of 1, the Scan operation will be sequential rather than parallel. If you specify TotalSegments , you must also specify Segment . :type Segment: integer :param Segment: For a parallel Scan request, Segment identifies an individual segment to be scanned by an application worker. Segment IDs are zero-based, so the first segment is always 0. For example, if you want to use four application threads to scan a table or an index, then the first thread specifies a Segment value of 0, the second thread specifies 1, and so on. The value of LastEvaluatedKey returned from a parallel Scan request must be used as ExclusiveStartKey with the same segment ID in a subsequent Scan operation. The value for Segment must be greater than or equal to 0, and less than the value provided for TotalSegments . If you provide Segment , you must also provide TotalSegments . :type ProjectionExpression: string :param ProjectionExpression: A string that identifies one or more attributes to retrieve from the specified table or index. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas. If no attribute names are specified, then all attributes will be returned. If any of the requested attributes are not found, they will not appear in the result. For more information, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide . :type FilterExpression: string :param FilterExpression: A string that contains conditions that DynamoDB applies after the Scan operation, but before the data is returned to you. Items that do not satisfy the FilterExpression criteria are not returned. Note A FilterExpression is applied after the items have already been read; the process of filtering does not consume any additional read capacity units. For more information, see Filter Expressions in the Amazon DynamoDB Developer Guide . :type ExpressionAttributeNames: dict :param ExpressionAttributeNames: One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames : To access an attribute whose name conflicts with a DynamoDB reserved word. To create a placeholder for repeating occurrences of an attribute name in an expression. To prevent special characters in an attribute name from being misinterpreted in an expression. Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name: Percentile The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide ). To work around this, you could specify the following for ExpressionAttributeNames : {'#P':'Percentile'} You could then use this substitution in an expression, as in this example: #P = :val Note Tokens that begin with the : character are expression attribute values , which are placeholders for the actual value at runtime. For more information on expression attribute names, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide . (string) -- (string) -- :type ExpressionAttributeValues: dict :param ExpressionAttributeValues: One or more values that can be substituted in an expression. Use the : (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following: Available | Backordered | Discontinued You would first need to specify ExpressionAttributeValues as follows: { ':avail':{'S':'Available'}, ':back':{'S':'Backordered'}, ':disc':{'S':'Discontinued'} } You could then use these values in an expression, such as this: ProductStatus IN (:avail, :back, :disc) For more information on expression attribute values, see Specifying Conditions in the Amazon DynamoDB Developer Guide . (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true :type ConsistentRead: boolean :param ConsistentRead: A Boolean value that determines the read consistency model during the scan: If ConsistentRead is false , then the data returned from Scan might not contain the results from other recently completed write operations (PutItem, UpdateItem or DeleteItem). If ConsistentRead is true , then all of the write operations that completed before the Scan began are guaranteed to be contained in the Scan response. The default setting for ConsistentRead is false . The ConsistentRead parameter is not supported on global secondary indexes. If you scan a global secondary index with ConsistentRead set to true, you will receive a ValidationException . :rtype: dict :return: { 'Items': [ { 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ], 'Count': 123, 'ScannedCount': 123, 'LastEvaluatedKey': { 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, 'ConsumedCapacity': { 'TableName': 'string', 'CapacityUnits': 123.0, 'Table': { 'CapacityUnits': 123.0 }, 'LocalSecondaryIndexes': { 'string': { 'CapacityUnits': 123.0 } }, 'GlobalSecondaryIndexes': { 'string': { 'CapacityUnits': 123.0 } } } } :returns: (string) --
Below is the the instruction that describes the task: ### Input: The Scan operation returns one or more items and item attributes by accessing every item in a table or a secondary index. To have DynamoDB return fewer items, you can provide a FilterExpression operation. If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and results are returned to the user as a LastEvaluatedKey value to continue the scan in a subsequent operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria. By default, Scan operations proceed sequentially; however, for faster performance on a large table or secondary index, applications can request a parallel Scan operation by providing the Segment and TotalSegments parameters. For more information, see Parallel Scan in the Amazon DynamoDB Developer Guide . By default, Scan uses eventually consistent reads when accessing the data in a table; therefore, the result set might not include the changes to data in the table immediately before the operation began. If you need a consistent copy of the data, as of the time that the Scan begins, you can set the ConsistentRead parameter to true . See also: AWS API Documentation Examples This example scans the entire Music table, and then narrows the results to songs by the artist "No One You Know". For each item, only the album title and song title are returned. Expected Output: :example: response = client.scan( TableName='string', IndexName='string', AttributesToGet=[ 'string', ], Limit=123, Select='ALL_ATTRIBUTES'|'ALL_PROJECTED_ATTRIBUTES'|'SPECIFIC_ATTRIBUTES'|'COUNT', ScanFilter={ 'string': { 'AttributeValueList': [ { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False }, ], 'ComparisonOperator': 'EQ'|'NE'|'IN'|'LE'|'LT'|'GE'|'GT'|'BETWEEN'|'NOT_NULL'|'NULL'|'CONTAINS'|'NOT_CONTAINS'|'BEGINS_WITH' } }, ConditionalOperator='AND'|'OR', ExclusiveStartKey={ 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ReturnConsumedCapacity='INDEXES'|'TOTAL'|'NONE', TotalSegments=123, Segment=123, ProjectionExpression='string', FilterExpression='string', ExpressionAttributeNames={ 'string': 'string' }, ExpressionAttributeValues={ 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ConsistentRead=True|False ) :type TableName: string :param TableName: [REQUIRED] The name of the table containing the requested items; or, if you provide IndexName , the name of the table to which that index belongs. :type IndexName: string :param IndexName: The name of a secondary index to scan. This index can be any local secondary index or global secondary index. Note that if you use the IndexName parameter, you must also provide TableName . :type AttributesToGet: list :param AttributesToGet: This is a legacy parameter. Use ProjectionExpression instead. For more information, see AttributesToGet in the Amazon DynamoDB Developer Guide . (string) -- :type Limit: integer :param Limit: The maximum number of items to evaluate (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a key in LastEvaluatedKey to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size exceeds 1 MB before DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a key in LastEvaluatedKey to apply in a subsequent operation to continue the operation. For more information, see Query and Scan in the Amazon DynamoDB Developer Guide . :type Select: string :param Select: The attributes to be returned in the result. You can retrieve all item attributes, specific item attributes, the count of matching items, or in the case of an index, some or all of the attributes projected into the index. ALL_ATTRIBUTES - Returns all of the item attributes from the specified table or index. If you query a local secondary index, then for each matching item in the index DynamoDB will fetch the entire item from the parent table. If the index is configured to project all item attributes, then all of the data can be obtained from the local secondary index, and no fetching is required. ALL_PROJECTED_ATTRIBUTES - Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying ALL_ATTRIBUTES . COUNT - Returns the number of matching items, rather than the matching items themselves. SPECIFIC_ATTRIBUTES - Returns only the attributes listed in AttributesToGet . This return value is equivalent to specifying AttributesToGet without specifying any value for Select . If you query or scan a local secondary index and request only attributes that are projected into that index, the operation will read only the index and not the table. If any of the requested attributes are not projected into the local secondary index, DynamoDB will fetch each of these attributes from the parent table. This extra fetching incurs additional throughput cost and latency. If you query or scan a global secondary index, you can only request attributes that are projected into the index. Global secondary index queries cannot fetch attributes from the parent table. If neither Select nor AttributesToGet are specified, DynamoDB defaults to ALL_ATTRIBUTES when accessing a table, and ALL_PROJECTED_ATTRIBUTES when accessing an index. You cannot use both Select and AttributesToGet together in a single request, unless the value for Select is SPECIFIC_ATTRIBUTES . (This usage is equivalent to specifying AttributesToGet without any value for Select .) Note If you use the ProjectionExpression parameter, then the value for Select can only be SPECIFIC_ATTRIBUTES . Any other value for Select will return an error. :type ScanFilter: dict :param ScanFilter: This is a legacy parameter. Use FilterExpression instead. For more information, see ScanFilter in the Amazon DynamoDB Developer Guide . (string) -- (dict) --Represents the selection criteria for a Query or Scan operation: For a Query operation, Condition is used for specifying the KeyConditions to use when querying a table or an index. For KeyConditions , only the following comparison operators are supported: EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN Condition is also used in a QueryFilter , which evaluates the query results and returns only the desired values. For a Scan operation, Condition is used in a ScanFilter , which evaluates the scan results and returns only the desired values. AttributeValueList (list) --One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used. For type Number, value comparisons are numeric. String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, a is greater than A , and a is greater than B . For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters . For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values. (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true ComparisonOperator (string) -- [REQUIRED]A comparator for evaluating attributes. For example, equals, greater than, less than, etc. The following comparison operators are available: EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN The following are descriptions of each comparison operator. EQ : Equal. EQ is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} . NE : Not equal. NE is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} . LE : Less than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . LT : Less than. AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . GE : Greater than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . GT : Greater than. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . NOT_NULL : The attribute exists. NOT_NULL is supported for all data types, including lists and maps. Note This operator tests for the existence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NOT_NULL , the result is a Boolean true . This result is because the attribute 'a ' exists; its data type is not relevant to the NOT_NULL comparison operator. NULL : The attribute does not exist. NULL is supported for all data types, including lists and maps. Note This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NULL , the result is a Boolean false . This is because the attribute 'a ' exists; its data type is not relevant to the NULL comparison operator. CONTAINS : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating 'a CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list. NOT_CONTAINS : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating 'a NOT CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list. BEGINS_WITH : Checks for a prefix. AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type). IN : Checks for matching elements in a list. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary. These attributes are compared against an existing attribute of an item. If any elements of the input are equal to the item attribute, the expression evaluates to true. BETWEEN : Greater than or equal to the first value, and less than or equal to the second value. AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not compare to {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} For usage examples of AttributeValueList and ComparisonOperator , see Legacy Conditional Parameters in the Amazon DynamoDB Developer Guide . :type ConditionalOperator: string :param ConditionalOperator: This is a legacy parameter. Use FilterExpression instead. For more information, see ConditionalOperator in the Amazon DynamoDB Developer Guide . :type ExclusiveStartKey: dict :param ExclusiveStartKey: The primary key of the first item that this operation will evaluate. Use the value that was returned for LastEvaluatedKey in the previous operation. The data type for ExclusiveStartKey must be String, Number or Binary. No set data types are allowed. In a parallel scan, a Scan request that includes ExclusiveStartKey must specify the same segment whose previous Scan returned the corresponding value of LastEvaluatedKey . (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true :type ReturnConsumedCapacity: string :param ReturnConsumedCapacity: Determines the level of detail about provisioned throughput consumption that is returned in the response: INDEXES - The response includes the aggregate ConsumedCapacity for the operation, together with ConsumedCapacity for each table and secondary index that was accessed. Note that some operations, such as GetItem and BatchGetItem , do not access any indexes at all. In these cases, specifying INDEXES will only return ConsumedCapacity information for table(s). TOTAL - The response includes only the aggregate ConsumedCapacity for the operation. NONE - No ConsumedCapacity details are included in the response. :type TotalSegments: integer :param TotalSegments: For a parallel Scan request, TotalSegments represents the total number of segments into which the Scan operation will be divided. The value of TotalSegments corresponds to the number of application workers that will perform the parallel scan. For example, if you want to use four application threads to scan a table or an index, specify a TotalSegments value of 4. The value for TotalSegments must be greater than or equal to 1, and less than or equal to 1000000. If you specify a TotalSegments value of 1, the Scan operation will be sequential rather than parallel. If you specify TotalSegments , you must also specify Segment . :type Segment: integer :param Segment: For a parallel Scan request, Segment identifies an individual segment to be scanned by an application worker. Segment IDs are zero-based, so the first segment is always 0. For example, if you want to use four application threads to scan a table or an index, then the first thread specifies a Segment value of 0, the second thread specifies 1, and so on. The value of LastEvaluatedKey returned from a parallel Scan request must be used as ExclusiveStartKey with the same segment ID in a subsequent Scan operation. The value for Segment must be greater than or equal to 0, and less than the value provided for TotalSegments . If you provide Segment , you must also provide TotalSegments . :type ProjectionExpression: string :param ProjectionExpression: A string that identifies one or more attributes to retrieve from the specified table or index. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas. If no attribute names are specified, then all attributes will be returned. If any of the requested attributes are not found, they will not appear in the result. For more information, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide . :type FilterExpression: string :param FilterExpression: A string that contains conditions that DynamoDB applies after the Scan operation, but before the data is returned to you. Items that do not satisfy the FilterExpression criteria are not returned. Note A FilterExpression is applied after the items have already been read; the process of filtering does not consume any additional read capacity units. For more information, see Filter Expressions in the Amazon DynamoDB Developer Guide . :type ExpressionAttributeNames: dict :param ExpressionAttributeNames: One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames : To access an attribute whose name conflicts with a DynamoDB reserved word. To create a placeholder for repeating occurrences of an attribute name in an expression. To prevent special characters in an attribute name from being misinterpreted in an expression. Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name: Percentile The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide ). To work around this, you could specify the following for ExpressionAttributeNames : {'#P':'Percentile'} You could then use this substitution in an expression, as in this example: #P = :val Note Tokens that begin with the : character are expression attribute values , which are placeholders for the actual value at runtime. For more information on expression attribute names, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide . (string) -- (string) -- :type ExpressionAttributeValues: dict :param ExpressionAttributeValues: One or more values that can be substituted in an expression. Use the : (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following: Available | Backordered | Discontinued You would first need to specify ExpressionAttributeValues as follows: { ':avail':{'S':'Available'}, ':back':{'S':'Backordered'}, ':disc':{'S':'Discontinued'} } You could then use these values in an expression, such as this: ProductStatus IN (:avail, :back, :disc) For more information on expression attribute values, see Specifying Conditions in the Amazon DynamoDB Developer Guide . (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true :type ConsistentRead: boolean :param ConsistentRead: A Boolean value that determines the read consistency model during the scan: If ConsistentRead is false , then the data returned from Scan might not contain the results from other recently completed write operations (PutItem, UpdateItem or DeleteItem). If ConsistentRead is true , then all of the write operations that completed before the Scan began are guaranteed to be contained in the Scan response. The default setting for ConsistentRead is false . The ConsistentRead parameter is not supported on global secondary indexes. If you scan a global secondary index with ConsistentRead set to true, you will receive a ValidationException . :rtype: dict :return: { 'Items': [ { 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ], 'Count': 123, 'ScannedCount': 123, 'LastEvaluatedKey': { 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, 'ConsumedCapacity': { 'TableName': 'string', 'CapacityUnits': 123.0, 'Table': { 'CapacityUnits': 123.0 }, 'LocalSecondaryIndexes': { 'string': { 'CapacityUnits': 123.0 } }, 'GlobalSecondaryIndexes': { 'string': { 'CapacityUnits': 123.0 } } } } :returns: (string) -- ### Response: def scan(TableName=None, IndexName=None, AttributesToGet=None, Limit=None, Select=None, ScanFilter=None, ConditionalOperator=None, ExclusiveStartKey=None, ReturnConsumedCapacity=None, TotalSegments=None, Segment=None, ProjectionExpression=None, FilterExpression=None, ExpressionAttributeNames=None, ExpressionAttributeValues=None, ConsistentRead=None): """ The Scan operation returns one or more items and item attributes by accessing every item in a table or a secondary index. To have DynamoDB return fewer items, you can provide a FilterExpression operation. If the total number of scanned items exceeds the maximum data set size limit of 1 MB, the scan stops and results are returned to the user as a LastEvaluatedKey value to continue the scan in a subsequent operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria. By default, Scan operations proceed sequentially; however, for faster performance on a large table or secondary index, applications can request a parallel Scan operation by providing the Segment and TotalSegments parameters. For more information, see Parallel Scan in the Amazon DynamoDB Developer Guide . By default, Scan uses eventually consistent reads when accessing the data in a table; therefore, the result set might not include the changes to data in the table immediately before the operation began. If you need a consistent copy of the data, as of the time that the Scan begins, you can set the ConsistentRead parameter to true . See also: AWS API Documentation Examples This example scans the entire Music table, and then narrows the results to songs by the artist "No One You Know". For each item, only the album title and song title are returned. Expected Output: :example: response = client.scan( TableName='string', IndexName='string', AttributesToGet=[ 'string', ], Limit=123, Select='ALL_ATTRIBUTES'|'ALL_PROJECTED_ATTRIBUTES'|'SPECIFIC_ATTRIBUTES'|'COUNT', ScanFilter={ 'string': { 'AttributeValueList': [ { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False }, ], 'ComparisonOperator': 'EQ'|'NE'|'IN'|'LE'|'LT'|'GE'|'GT'|'BETWEEN'|'NOT_NULL'|'NULL'|'CONTAINS'|'NOT_CONTAINS'|'BEGINS_WITH' } }, ConditionalOperator='AND'|'OR', ExclusiveStartKey={ 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ReturnConsumedCapacity='INDEXES'|'TOTAL'|'NONE', TotalSegments=123, Segment=123, ProjectionExpression='string', FilterExpression='string', ExpressionAttributeNames={ 'string': 'string' }, ExpressionAttributeValues={ 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ConsistentRead=True|False ) :type TableName: string :param TableName: [REQUIRED] The name of the table containing the requested items; or, if you provide IndexName , the name of the table to which that index belongs. :type IndexName: string :param IndexName: The name of a secondary index to scan. This index can be any local secondary index or global secondary index. Note that if you use the IndexName parameter, you must also provide TableName . :type AttributesToGet: list :param AttributesToGet: This is a legacy parameter. Use ProjectionExpression instead. For more information, see AttributesToGet in the Amazon DynamoDB Developer Guide . (string) -- :type Limit: integer :param Limit: The maximum number of items to evaluate (not necessarily the number of matching items). If DynamoDB processes the number of items up to the limit while processing the results, it stops the operation and returns the matching values up to that point, and a key in LastEvaluatedKey to apply in a subsequent operation, so that you can pick up where you left off. Also, if the processed data set size exceeds 1 MB before DynamoDB reaches this limit, it stops the operation and returns the matching values up to the limit, and a key in LastEvaluatedKey to apply in a subsequent operation to continue the operation. For more information, see Query and Scan in the Amazon DynamoDB Developer Guide . :type Select: string :param Select: The attributes to be returned in the result. You can retrieve all item attributes, specific item attributes, the count of matching items, or in the case of an index, some or all of the attributes projected into the index. ALL_ATTRIBUTES - Returns all of the item attributes from the specified table or index. If you query a local secondary index, then for each matching item in the index DynamoDB will fetch the entire item from the parent table. If the index is configured to project all item attributes, then all of the data can be obtained from the local secondary index, and no fetching is required. ALL_PROJECTED_ATTRIBUTES - Allowed only when querying an index. Retrieves all attributes that have been projected into the index. If the index is configured to project all attributes, this return value is equivalent to specifying ALL_ATTRIBUTES . COUNT - Returns the number of matching items, rather than the matching items themselves. SPECIFIC_ATTRIBUTES - Returns only the attributes listed in AttributesToGet . This return value is equivalent to specifying AttributesToGet without specifying any value for Select . If you query or scan a local secondary index and request only attributes that are projected into that index, the operation will read only the index and not the table. If any of the requested attributes are not projected into the local secondary index, DynamoDB will fetch each of these attributes from the parent table. This extra fetching incurs additional throughput cost and latency. If you query or scan a global secondary index, you can only request attributes that are projected into the index. Global secondary index queries cannot fetch attributes from the parent table. If neither Select nor AttributesToGet are specified, DynamoDB defaults to ALL_ATTRIBUTES when accessing a table, and ALL_PROJECTED_ATTRIBUTES when accessing an index. You cannot use both Select and AttributesToGet together in a single request, unless the value for Select is SPECIFIC_ATTRIBUTES . (This usage is equivalent to specifying AttributesToGet without any value for Select .) Note If you use the ProjectionExpression parameter, then the value for Select can only be SPECIFIC_ATTRIBUTES . Any other value for Select will return an error. :type ScanFilter: dict :param ScanFilter: This is a legacy parameter. Use FilterExpression instead. For more information, see ScanFilter in the Amazon DynamoDB Developer Guide . (string) -- (dict) --Represents the selection criteria for a Query or Scan operation: For a Query operation, Condition is used for specifying the KeyConditions to use when querying a table or an index. For KeyConditions , only the following comparison operators are supported: EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN Condition is also used in a QueryFilter , which evaluates the query results and returns only the desired values. For a Scan operation, Condition is used in a ScanFilter , which evaluates the scan results and returns only the desired values. AttributeValueList (list) --One or more values to evaluate against the supplied attribute. The number of values in the list depends on the ComparisonOperator being used. For type Number, value comparisons are numeric. String value comparisons for greater than, equals, or less than are based on ASCII character code values. For example, a is greater than A , and a is greater than B . For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters . For Binary, DynamoDB treats each byte of the binary data as unsigned when it compares binary values. (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true ComparisonOperator (string) -- [REQUIRED]A comparator for evaluating attributes. For example, equals, greater than, less than, etc. The following comparison operators are available: EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | BEGINS_WITH | IN | BETWEEN The following are descriptions of each comparison operator. EQ : Equal. EQ is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue element of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} . NE : Not equal. NE is supported for all data types, including lists and maps. AttributeValueList can contain only one AttributeValue of type String, Number, Binary, String Set, Number Set, or Binary Set. If an item contains an AttributeValue of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not equal {'NS':['6', '2', '1']} . LE : Less than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . LT : Less than. AttributeValueList can contain only one AttributeValue of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . GE : Greater than or equal. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . GT : Greater than. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not equal {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} . NOT_NULL : The attribute exists. NOT_NULL is supported for all data types, including lists and maps. Note This operator tests for the existence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NOT_NULL , the result is a Boolean true . This result is because the attribute 'a ' exists; its data type is not relevant to the NOT_NULL comparison operator. NULL : The attribute does not exist. NULL is supported for all data types, including lists and maps. Note This operator tests for the nonexistence of an attribute, not its data type. If the data type of attribute 'a ' is null, and you evaluate it using NULL , the result is a Boolean false . This is because the attribute 'a ' exists; its data type is not relevant to the NULL comparison operator. CONTAINS : Checks for a subsequence, or value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is of type String, then the operator checks for a substring match. If the target attribute of the comparison is of type Binary, then the operator looks for a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it finds an exact match with any member of the set. CONTAINS is supported for lists: When evaluating 'a CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list. NOT_CONTAINS : Checks for absence of a subsequence, or absence of a value in a set. AttributeValueList can contain only one AttributeValue element of type String, Number, or Binary (not a set type). If the target attribute of the comparison is a String, then the operator checks for the absence of a substring match. If the target attribute of the comparison is Binary, then the operator checks for the absence of a subsequence of the target that matches the input. If the target attribute of the comparison is a set ('SS ', 'NS ', or 'BS '), then the operator evaluates to true if it does not find an exact match with any member of the set. NOT_CONTAINS is supported for lists: When evaluating 'a NOT CONTAINS b ', 'a ' can be a list; however, 'b ' cannot be a set, a map, or a list. BEGINS_WITH : Checks for a prefix. AttributeValueList can contain only one AttributeValue of type String or Binary (not a Number or a set type). The target attribute of the comparison must be of type String or Binary (not a Number or a set type). IN : Checks for matching elements in a list. AttributeValueList can contain one or more AttributeValue elements of type String, Number, or Binary. These attributes are compared against an existing attribute of an item. If any elements of the input are equal to the item attribute, the expression evaluates to true. BETWEEN : Greater than or equal to the first value, and less than or equal to the second value. AttributeValueList must contain two AttributeValue elements of the same type, either String, Number, or Binary (not a set type). A target attribute matches if the target value is greater than, or equal to, the first element and less than, or equal to, the second element. If an item contains an AttributeValue element of a different type than the one provided in the request, the value does not match. For example, {'S':'6'} does not compare to {'N':'6'} . Also, {'N':'6'} does not compare to {'NS':['6', '2', '1']} For usage examples of AttributeValueList and ComparisonOperator , see Legacy Conditional Parameters in the Amazon DynamoDB Developer Guide . :type ConditionalOperator: string :param ConditionalOperator: This is a legacy parameter. Use FilterExpression instead. For more information, see ConditionalOperator in the Amazon DynamoDB Developer Guide . :type ExclusiveStartKey: dict :param ExclusiveStartKey: The primary key of the first item that this operation will evaluate. Use the value that was returned for LastEvaluatedKey in the previous operation. The data type for ExclusiveStartKey must be String, Number or Binary. No set data types are allowed. In a parallel scan, a Scan request that includes ExclusiveStartKey must specify the same segment whose previous Scan returned the corresponding value of LastEvaluatedKey . (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true :type ReturnConsumedCapacity: string :param ReturnConsumedCapacity: Determines the level of detail about provisioned throughput consumption that is returned in the response: INDEXES - The response includes the aggregate ConsumedCapacity for the operation, together with ConsumedCapacity for each table and secondary index that was accessed. Note that some operations, such as GetItem and BatchGetItem , do not access any indexes at all. In these cases, specifying INDEXES will only return ConsumedCapacity information for table(s). TOTAL - The response includes only the aggregate ConsumedCapacity for the operation. NONE - No ConsumedCapacity details are included in the response. :type TotalSegments: integer :param TotalSegments: For a parallel Scan request, TotalSegments represents the total number of segments into which the Scan operation will be divided. The value of TotalSegments corresponds to the number of application workers that will perform the parallel scan. For example, if you want to use four application threads to scan a table or an index, specify a TotalSegments value of 4. The value for TotalSegments must be greater than or equal to 1, and less than or equal to 1000000. If you specify a TotalSegments value of 1, the Scan operation will be sequential rather than parallel. If you specify TotalSegments , you must also specify Segment . :type Segment: integer :param Segment: For a parallel Scan request, Segment identifies an individual segment to be scanned by an application worker. Segment IDs are zero-based, so the first segment is always 0. For example, if you want to use four application threads to scan a table or an index, then the first thread specifies a Segment value of 0, the second thread specifies 1, and so on. The value of LastEvaluatedKey returned from a parallel Scan request must be used as ExclusiveStartKey with the same segment ID in a subsequent Scan operation. The value for Segment must be greater than or equal to 0, and less than the value provided for TotalSegments . If you provide Segment , you must also provide TotalSegments . :type ProjectionExpression: string :param ProjectionExpression: A string that identifies one or more attributes to retrieve from the specified table or index. These attributes can include scalars, sets, or elements of a JSON document. The attributes in the expression must be separated by commas. If no attribute names are specified, then all attributes will be returned. If any of the requested attributes are not found, they will not appear in the result. For more information, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide . :type FilterExpression: string :param FilterExpression: A string that contains conditions that DynamoDB applies after the Scan operation, but before the data is returned to you. Items that do not satisfy the FilterExpression criteria are not returned. Note A FilterExpression is applied after the items have already been read; the process of filtering does not consume any additional read capacity units. For more information, see Filter Expressions in the Amazon DynamoDB Developer Guide . :type ExpressionAttributeNames: dict :param ExpressionAttributeNames: One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames : To access an attribute whose name conflicts with a DynamoDB reserved word. To create a placeholder for repeating occurrences of an attribute name in an expression. To prevent special characters in an attribute name from being misinterpreted in an expression. Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name: Percentile The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide ). To work around this, you could specify the following for ExpressionAttributeNames : {'#P':'Percentile'} You could then use this substitution in an expression, as in this example: #P = :val Note Tokens that begin with the : character are expression attribute values , which are placeholders for the actual value at runtime. For more information on expression attribute names, see Accessing Item Attributes in the Amazon DynamoDB Developer Guide . (string) -- (string) -- :type ExpressionAttributeValues: dict :param ExpressionAttributeValues: One or more values that can be substituted in an expression. Use the : (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following: Available | Backordered | Discontinued You would first need to specify ExpressionAttributeValues as follows: { ':avail':{'S':'Available'}, ':back':{'S':'Backordered'}, ':disc':{'S':'Discontinued'} } You could then use these values in an expression, such as this: ProductStatus IN (:avail, :back, :disc) For more information on expression attribute values, see Specifying Conditions in the Amazon DynamoDB Developer Guide . (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . S (string) --An attribute of type String. For example: 'S': 'Hello' N (string) --An attribute of type Number. For example: 'N': '123.45' Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. B (bytes) --An attribute of type Binary. For example: 'B': 'dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk' SS (list) --An attribute of type String Set. For example: 'SS': ['Giraffe', 'Hippo' ,'Zebra'] (string) -- NS (list) --An attribute of type Number Set. For example: 'NS': ['42.2', '-19', '7.5', '3.14'] Numbers are sent across the network to DynamoDB as strings, to maximize compatibility across languages and libraries. However, DynamoDB treats them as number type attributes for mathematical operations. (string) -- BS (list) --An attribute of type Binary Set. For example: 'BS': ['U3Vubnk=', 'UmFpbnk=', 'U25vd3k='] (bytes) -- M (dict) --An attribute of type Map. For example: 'M': {'Name': {'S': 'Joe'}, 'Age': {'N': '35'}} (string) -- (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . L (list) --An attribute of type List. For example: 'L': ['Cookies', 'Coffee', 3.14159] (dict) --Represents the data for an attribute. Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself. For more information, see Data Types in the Amazon DynamoDB Developer Guide . NULL (boolean) --An attribute of type Null. For example: 'NULL': true BOOL (boolean) --An attribute of type Boolean. For example: 'BOOL': true :type ConsistentRead: boolean :param ConsistentRead: A Boolean value that determines the read consistency model during the scan: If ConsistentRead is false , then the data returned from Scan might not contain the results from other recently completed write operations (PutItem, UpdateItem or DeleteItem). If ConsistentRead is true , then all of the write operations that completed before the Scan began are guaranteed to be contained in the Scan response. The default setting for ConsistentRead is false . The ConsistentRead parameter is not supported on global secondary indexes. If you scan a global secondary index with ConsistentRead set to true, you will receive a ValidationException . :rtype: dict :return: { 'Items': [ { 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, ], 'Count': 123, 'ScannedCount': 123, 'LastEvaluatedKey': { 'string': { 'S': 'string', 'N': 'string', 'B': b'bytes', 'SS': [ 'string', ], 'NS': [ 'string', ], 'BS': [ b'bytes', ], 'M': { 'string': {'... recursive ...'} }, 'L': [ {'... recursive ...'}, ], 'NULL': True|False, 'BOOL': True|False } }, 'ConsumedCapacity': { 'TableName': 'string', 'CapacityUnits': 123.0, 'Table': { 'CapacityUnits': 123.0 }, 'LocalSecondaryIndexes': { 'string': { 'CapacityUnits': 123.0 } }, 'GlobalSecondaryIndexes': { 'string': { 'CapacityUnits': 123.0 } } } } :returns: (string) -- """ pass
def reset(self): """Reset internal state """ self.overall = { 'Nref': 0.0, 'Nsys': 0.0, 'Nsubs': 0.0, 'Ntp': 0.0, 'Nfp': 0.0, 'Nfn': 0.0, } self.class_wise = {} for class_label in self.event_label_list: self.class_wise[class_label] = { 'Nref': 0.0, 'Nsys': 0.0, 'Ntp': 0.0, 'Ntn': 0.0, 'Nfp': 0.0, 'Nfn': 0.0, } return self
Reset internal state
Below is the the instruction that describes the task: ### Input: Reset internal state ### Response: def reset(self): """Reset internal state """ self.overall = { 'Nref': 0.0, 'Nsys': 0.0, 'Nsubs': 0.0, 'Ntp': 0.0, 'Nfp': 0.0, 'Nfn': 0.0, } self.class_wise = {} for class_label in self.event_label_list: self.class_wise[class_label] = { 'Nref': 0.0, 'Nsys': 0.0, 'Ntp': 0.0, 'Ntn': 0.0, 'Nfp': 0.0, 'Nfn': 0.0, } return self
def wngram2idngram(input_file, vocab_file, output_file, buffersize=100, hashtablesize=2000000, files=20, compress=False, verbosity=2, n=3, write_ascii=False, fof_size=10): """ Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format. Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this should not be an issue, as they will already be alphabetically sorted. """ cmd = ['wngram2idngram', '-vocab', os.path.abspath(vocab_file), '-idngram', os.path.abspath(output_file)] if buffersize: cmd.extend(['-buffer', buffersize]) if hashtablesize: cmd.extend(['-hash', hashtablesize]) if files: cmd.extend(['-files', files]) if verbosity: cmd.extend(['-verbosity', verbosity]) if n: cmd.extend(['-n', n]) if fof_size: cmd.extend(['-fof_size', fof_size]) if compress: cmd.append('-compress') if write_ascii: cmd.append('-write_ascii') # Ensure that every parameter is of type 'str' cmd = [str(x) for x in cmd] with tempfile.SpooledTemporaryFile() as output_f: with tempfile.SpooledTemporaryFile() as input_f: input_f.write(text.encode('utf-8') if sys.version_info >= (3,) and type(text) is str else text) input_f.seek(0) with output_to_debuglogger() as err_f: with do_in_tempdir(): exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f) output = output_f.read() logger = logging.getLogger(__name__) logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode)) if exitcode != 0: raise ConversionError("'%r' returned with non-zero exit status '%s'" % (cmd, exitcode)) if sys.version_info >= (3,) and type(output) is bytes: output = output.decode('utf-8') return output.strip()
Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format. Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this should not be an issue, as they will already be alphabetically sorted.
Below is the the instruction that describes the task: ### Input: Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format. Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this should not be an issue, as they will already be alphabetically sorted. ### Response: def wngram2idngram(input_file, vocab_file, output_file, buffersize=100, hashtablesize=2000000, files=20, compress=False, verbosity=2, n=3, write_ascii=False, fof_size=10): """ Takes a word N-gram file and a vocabulary file and lists every id n-gram which occurred in the text, along with its number of occurrences, in either ASCII or binary format. Note : It is important that the vocabulary file is in alphabetical order. If you are using vocabularies generated by wfreq2vocab then this should not be an issue, as they will already be alphabetically sorted. """ cmd = ['wngram2idngram', '-vocab', os.path.abspath(vocab_file), '-idngram', os.path.abspath(output_file)] if buffersize: cmd.extend(['-buffer', buffersize]) if hashtablesize: cmd.extend(['-hash', hashtablesize]) if files: cmd.extend(['-files', files]) if verbosity: cmd.extend(['-verbosity', verbosity]) if n: cmd.extend(['-n', n]) if fof_size: cmd.extend(['-fof_size', fof_size]) if compress: cmd.append('-compress') if write_ascii: cmd.append('-write_ascii') # Ensure that every parameter is of type 'str' cmd = [str(x) for x in cmd] with tempfile.SpooledTemporaryFile() as output_f: with tempfile.SpooledTemporaryFile() as input_f: input_f.write(text.encode('utf-8') if sys.version_info >= (3,) and type(text) is str else text) input_f.seek(0) with output_to_debuglogger() as err_f: with do_in_tempdir(): exitcode = subprocess.call(cmd, stdin=input_f, stdout=output_f, stderr=err_f) output = output_f.read() logger = logging.getLogger(__name__) logger.debug("Command '%s' returned with exit code '%d'." % (' '.join(cmd), exitcode)) if exitcode != 0: raise ConversionError("'%r' returned with non-zero exit status '%s'" % (cmd, exitcode)) if sys.version_info >= (3,) and type(output) is bytes: output = output.decode('utf-8') return output.strip()
def get_registered_services(self): # type: () -> List[ServiceReference] """ Returns this bundle's ServiceReference list for all services it has registered or an empty list The list is valid at the time of the call to this method, however, as the Framework is a very dynamic environment, services can be modified or unregistered at any time. :return: An array of ServiceReference objects :raise BundleException: If the bundle has been uninstalled """ if self._state == Bundle.UNINSTALLED: raise BundleException( "Can't call 'get_registered_services' on an " "uninstalled bundle" ) return self.__framework._registry.get_bundle_registered_services(self)
Returns this bundle's ServiceReference list for all services it has registered or an empty list The list is valid at the time of the call to this method, however, as the Framework is a very dynamic environment, services can be modified or unregistered at any time. :return: An array of ServiceReference objects :raise BundleException: If the bundle has been uninstalled
Below is the the instruction that describes the task: ### Input: Returns this bundle's ServiceReference list for all services it has registered or an empty list The list is valid at the time of the call to this method, however, as the Framework is a very dynamic environment, services can be modified or unregistered at any time. :return: An array of ServiceReference objects :raise BundleException: If the bundle has been uninstalled ### Response: def get_registered_services(self): # type: () -> List[ServiceReference] """ Returns this bundle's ServiceReference list for all services it has registered or an empty list The list is valid at the time of the call to this method, however, as the Framework is a very dynamic environment, services can be modified or unregistered at any time. :return: An array of ServiceReference objects :raise BundleException: If the bundle has been uninstalled """ if self._state == Bundle.UNINSTALLED: raise BundleException( "Can't call 'get_registered_services' on an " "uninstalled bundle" ) return self.__framework._registry.get_bundle_registered_services(self)
def Nu_vertical_cylinder_Griffiths_Davis_Morgan(Pr, Gr, turbulent=None): r'''Calculates Nusselt number for natural convection around a vertical isothermal cylinder according to the results of [1]_ correlated by [2]_, as presented in [3]_ and [4]_. .. math:: Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < Ra < 10^{9} Nu_H = 0.0782 Ra_H^{0.357}, \; 10^{9} < Ra < 10^{11} Parameters ---------- Pr : float Prandtl number [-] Gr : float Grashof number [-] turbulent : bool or None, optional Whether or not to force the correlation to return the turbulent result; will return the laminar regime if False; leave as None for automatic selection Returns ------- Nu : float Nusselt number, [-] Notes ----- Cylinder of diameter 17.43 cm, length from 4.65 to 263.5 cm. Air as fluid. Transition between ranges is not smooth. If outside of range, no warning is given. Examples -------- >>> Nu_vertical_cylinder_Griffiths_Davis_Morgan(.7, 2E10) 327.6230596100138 References ---------- .. [1] Griffiths, Ezer, A. H. Davis, and Great Britain. The Transmission of Heat by Radiation and Convection. London: H. M. Stationery off., 1922. .. [2] Morgan, V.T., The Overall Convective Heat Transfer from Smooth Circular Cylinders, in Advances in Heat Transfer, eds. T.F. Irvin and J.P. Hartnett, V 11, 199-264, 1975. .. [3] Popiel, Czeslaw O. "Free Convection Heat Transfer from Vertical Slender Cylinders: A Review." Heat Transfer Engineering 29, no. 6 (June 1, 2008): 521-36. doi:10.1080/01457630801891557. .. [4] Boetcher, Sandra K. S. "Natural Convection Heat Transfer From Vertical Cylinders." In Natural Convection from Circular Cylinders, 23-42. Springer, 2014. ''' Ra = Pr*Gr if turbulent or (Ra > 1E9 and turbulent is None): Nu = 0.0782*Ra**0.357 else: Nu = 0.67*Ra**0.25 return Nu
r'''Calculates Nusselt number for natural convection around a vertical isothermal cylinder according to the results of [1]_ correlated by [2]_, as presented in [3]_ and [4]_. .. math:: Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < Ra < 10^{9} Nu_H = 0.0782 Ra_H^{0.357}, \; 10^{9} < Ra < 10^{11} Parameters ---------- Pr : float Prandtl number [-] Gr : float Grashof number [-] turbulent : bool or None, optional Whether or not to force the correlation to return the turbulent result; will return the laminar regime if False; leave as None for automatic selection Returns ------- Nu : float Nusselt number, [-] Notes ----- Cylinder of diameter 17.43 cm, length from 4.65 to 263.5 cm. Air as fluid. Transition between ranges is not smooth. If outside of range, no warning is given. Examples -------- >>> Nu_vertical_cylinder_Griffiths_Davis_Morgan(.7, 2E10) 327.6230596100138 References ---------- .. [1] Griffiths, Ezer, A. H. Davis, and Great Britain. The Transmission of Heat by Radiation and Convection. London: H. M. Stationery off., 1922. .. [2] Morgan, V.T., The Overall Convective Heat Transfer from Smooth Circular Cylinders, in Advances in Heat Transfer, eds. T.F. Irvin and J.P. Hartnett, V 11, 199-264, 1975. .. [3] Popiel, Czeslaw O. "Free Convection Heat Transfer from Vertical Slender Cylinders: A Review." Heat Transfer Engineering 29, no. 6 (June 1, 2008): 521-36. doi:10.1080/01457630801891557. .. [4] Boetcher, Sandra K. S. "Natural Convection Heat Transfer From Vertical Cylinders." In Natural Convection from Circular Cylinders, 23-42. Springer, 2014.
Below is the the instruction that describes the task: ### Input: r'''Calculates Nusselt number for natural convection around a vertical isothermal cylinder according to the results of [1]_ correlated by [2]_, as presented in [3]_ and [4]_. .. math:: Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < Ra < 10^{9} Nu_H = 0.0782 Ra_H^{0.357}, \; 10^{9} < Ra < 10^{11} Parameters ---------- Pr : float Prandtl number [-] Gr : float Grashof number [-] turbulent : bool or None, optional Whether or not to force the correlation to return the turbulent result; will return the laminar regime if False; leave as None for automatic selection Returns ------- Nu : float Nusselt number, [-] Notes ----- Cylinder of diameter 17.43 cm, length from 4.65 to 263.5 cm. Air as fluid. Transition between ranges is not smooth. If outside of range, no warning is given. Examples -------- >>> Nu_vertical_cylinder_Griffiths_Davis_Morgan(.7, 2E10) 327.6230596100138 References ---------- .. [1] Griffiths, Ezer, A. H. Davis, and Great Britain. The Transmission of Heat by Radiation and Convection. London: H. M. Stationery off., 1922. .. [2] Morgan, V.T., The Overall Convective Heat Transfer from Smooth Circular Cylinders, in Advances in Heat Transfer, eds. T.F. Irvin and J.P. Hartnett, V 11, 199-264, 1975. .. [3] Popiel, Czeslaw O. "Free Convection Heat Transfer from Vertical Slender Cylinders: A Review." Heat Transfer Engineering 29, no. 6 (June 1, 2008): 521-36. doi:10.1080/01457630801891557. .. [4] Boetcher, Sandra K. S. "Natural Convection Heat Transfer From Vertical Cylinders." In Natural Convection from Circular Cylinders, 23-42. Springer, 2014. ### Response: def Nu_vertical_cylinder_Griffiths_Davis_Morgan(Pr, Gr, turbulent=None): r'''Calculates Nusselt number for natural convection around a vertical isothermal cylinder according to the results of [1]_ correlated by [2]_, as presented in [3]_ and [4]_. .. math:: Nu_H = 0.67 Ra_H^{0.25},\; 10^{7} < Ra < 10^{9} Nu_H = 0.0782 Ra_H^{0.357}, \; 10^{9} < Ra < 10^{11} Parameters ---------- Pr : float Prandtl number [-] Gr : float Grashof number [-] turbulent : bool or None, optional Whether or not to force the correlation to return the turbulent result; will return the laminar regime if False; leave as None for automatic selection Returns ------- Nu : float Nusselt number, [-] Notes ----- Cylinder of diameter 17.43 cm, length from 4.65 to 263.5 cm. Air as fluid. Transition between ranges is not smooth. If outside of range, no warning is given. Examples -------- >>> Nu_vertical_cylinder_Griffiths_Davis_Morgan(.7, 2E10) 327.6230596100138 References ---------- .. [1] Griffiths, Ezer, A. H. Davis, and Great Britain. The Transmission of Heat by Radiation and Convection. London: H. M. Stationery off., 1922. .. [2] Morgan, V.T., The Overall Convective Heat Transfer from Smooth Circular Cylinders, in Advances in Heat Transfer, eds. T.F. Irvin and J.P. Hartnett, V 11, 199-264, 1975. .. [3] Popiel, Czeslaw O. "Free Convection Heat Transfer from Vertical Slender Cylinders: A Review." Heat Transfer Engineering 29, no. 6 (June 1, 2008): 521-36. doi:10.1080/01457630801891557. .. [4] Boetcher, Sandra K. S. "Natural Convection Heat Transfer From Vertical Cylinders." In Natural Convection from Circular Cylinders, 23-42. Springer, 2014. ''' Ra = Pr*Gr if turbulent or (Ra > 1E9 and turbulent is None): Nu = 0.0782*Ra**0.357 else: Nu = 0.67*Ra**0.25 return Nu
def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats
Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description)
Below is the the instruction that describes the task: ### Input: Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) ### Response: def get_archive_formats(): """Returns a list of supported formats for archiving and unarchiving. Each element of the returned sequence is a tuple (name, description) """ formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats
def collect_by_type(self, typ): '''A more efficient way to collect nodes of a specified type than collect_nodes. ''' nodes = [] if isinstance(self, typ): nodes.append(self) for c in self: nodes.extend(c.collect_by_type(typ)) return nodes
A more efficient way to collect nodes of a specified type than collect_nodes.
Below is the the instruction that describes the task: ### Input: A more efficient way to collect nodes of a specified type than collect_nodes. ### Response: def collect_by_type(self, typ): '''A more efficient way to collect nodes of a specified type than collect_nodes. ''' nodes = [] if isinstance(self, typ): nodes.append(self) for c in self: nodes.extend(c.collect_by_type(typ)) return nodes
def int_to_gematria(num, gershayim=True): """convert integers between 1 an 999 to Hebrew numerals. - set gershayim flag to False to ommit gershayim """ # 1. Lookup in specials if num in specialnumbers['specials']: retval = specialnumbers['specials'][num] return _add_gershayim(retval) if gershayim else retval # 2. Generate numeral normally parts = [] rest = str(num) while rest: digit = int(rest[0]) rest = rest[1:] if digit == 0: continue power = 10 ** len(rest) parts.append(specialnumbers['numerals'][power * digit]) retval = ''.join(parts) # 3. Add gershayim return _add_gershayim(retval) if gershayim else retval
convert integers between 1 an 999 to Hebrew numerals. - set gershayim flag to False to ommit gershayim
Below is the the instruction that describes the task: ### Input: convert integers between 1 an 999 to Hebrew numerals. - set gershayim flag to False to ommit gershayim ### Response: def int_to_gematria(num, gershayim=True): """convert integers between 1 an 999 to Hebrew numerals. - set gershayim flag to False to ommit gershayim """ # 1. Lookup in specials if num in specialnumbers['specials']: retval = specialnumbers['specials'][num] return _add_gershayim(retval) if gershayim else retval # 2. Generate numeral normally parts = [] rest = str(num) while rest: digit = int(rest[0]) rest = rest[1:] if digit == 0: continue power = 10 ** len(rest) parts.append(specialnumbers['numerals'][power * digit]) retval = ''.join(parts) # 3. Add gershayim return _add_gershayim(retval) if gershayim else retval
def rotate(prefixes, hosts, **kwargs): """ Rotates a set of daily indices by updating a "-current" alias to point to a (newly-created) index for today. This should probably be called from a daily cronjob just after midnight. """ rotator = Rotator(pyes.ES(hosts), **kwargs) for prefix in prefixes: rotator.rotate(prefix)
Rotates a set of daily indices by updating a "-current" alias to point to a (newly-created) index for today. This should probably be called from a daily cronjob just after midnight.
Below is the the instruction that describes the task: ### Input: Rotates a set of daily indices by updating a "-current" alias to point to a (newly-created) index for today. This should probably be called from a daily cronjob just after midnight. ### Response: def rotate(prefixes, hosts, **kwargs): """ Rotates a set of daily indices by updating a "-current" alias to point to a (newly-created) index for today. This should probably be called from a daily cronjob just after midnight. """ rotator = Rotator(pyes.ES(hosts), **kwargs) for prefix in prefixes: rotator.rotate(prefix)
def find_selection(): """Finds the selected ids After the scene has been rendered again in selection mode, this method gathers and returns the ids of the selected object and restores the matrices. :return: The selection stack """ hits = glRenderMode(GL_RENDER) glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) return hits
Finds the selected ids After the scene has been rendered again in selection mode, this method gathers and returns the ids of the selected object and restores the matrices. :return: The selection stack
Below is the the instruction that describes the task: ### Input: Finds the selected ids After the scene has been rendered again in selection mode, this method gathers and returns the ids of the selected object and restores the matrices. :return: The selection stack ### Response: def find_selection(): """Finds the selected ids After the scene has been rendered again in selection mode, this method gathers and returns the ids of the selected object and restores the matrices. :return: The selection stack """ hits = glRenderMode(GL_RENDER) glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) return hits
def _get_mask(X, value_to_mask): """Compute the boolean mask X == missing_values.""" if is_scalar_nan(value_to_mask): if X.dtype.kind == "f": return np.isnan(X) elif X.dtype.kind in ("i", "u"): # can't have NaNs in integer array. return np.zeros(X.shape, dtype=bool) else: # np.isnan does not work on object dtypes. return _object_dtype_isnan(X) else: # X == value_to_mask with object dytpes does not always perform # element-wise for old versions of numpy return np.equal(X, value_to_mask)
Compute the boolean mask X == missing_values.
Below is the the instruction that describes the task: ### Input: Compute the boolean mask X == missing_values. ### Response: def _get_mask(X, value_to_mask): """Compute the boolean mask X == missing_values.""" if is_scalar_nan(value_to_mask): if X.dtype.kind == "f": return np.isnan(X) elif X.dtype.kind in ("i", "u"): # can't have NaNs in integer array. return np.zeros(X.shape, dtype=bool) else: # np.isnan does not work on object dtypes. return _object_dtype_isnan(X) else: # X == value_to_mask with object dytpes does not always perform # element-wise for old versions of numpy return np.equal(X, value_to_mask)
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_low_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 1) self.set_attributes(priority, address, rtr) self.channels = self.byte_to_channels(data[0])
:return: None
Below is the the instruction that describes the task: ### Input: :return: None ### Response: def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_low_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 1) self.set_attributes(priority, address, rtr) self.channels = self.byte_to_channels(data[0])
def assert_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT): """ Similar to wait_for_link_text_visible(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT. """ if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) self.wait_for_link_text_visible(link_text, timeout=timeout) if self.demo_mode: messenger_post = ("ASSERT LINK TEXT {%s}." % link_text) self.__highlight_with_assert_success( messenger_post, link_text, by=By.LINK_TEXT) return True
Similar to wait_for_link_text_visible(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT.
Below is the the instruction that describes the task: ### Input: Similar to wait_for_link_text_visible(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT. ### Response: def assert_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT): """ Similar to wait_for_link_text_visible(), but returns nothing. As above, will raise an exception if nothing can be found. Returns True if successful. Default timeout = SMALL_TIMEOUT. """ if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeout(timeout) self.wait_for_link_text_visible(link_text, timeout=timeout) if self.demo_mode: messenger_post = ("ASSERT LINK TEXT {%s}." % link_text) self.__highlight_with_assert_success( messenger_post, link_text, by=By.LINK_TEXT) return True
def _wrap_lines(self, line_source, point_size): """ Return a sequence of str values representing the text in *line_source* wrapped within this fitter when rendered at *point_size*. """ text, remainder = self._break_line(line_source, point_size) lines = [text] if remainder: lines.extend(self._wrap_lines(remainder, point_size)) return lines
Return a sequence of str values representing the text in *line_source* wrapped within this fitter when rendered at *point_size*.
Below is the the instruction that describes the task: ### Input: Return a sequence of str values representing the text in *line_source* wrapped within this fitter when rendered at *point_size*. ### Response: def _wrap_lines(self, line_source, point_size): """ Return a sequence of str values representing the text in *line_source* wrapped within this fitter when rendered at *point_size*. """ text, remainder = self._break_line(line_source, point_size) lines = [text] if remainder: lines.extend(self._wrap_lines(remainder, point_size)) return lines
def _mlperf_print(key, value=None, benchmark=None, stack_offset=0, tag_set=None, deferred=False, root_dir=None, extra_print=False, prefix=""): ''' Prints out an MLPerf Log Line. key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec. value: The value which contains no newlines. benchmark: The short code for the benchmark being run, see the MLPerf log spec. stack_offset: Increase the value to go deeper into the stack to find the callsite. For example, if this is being called by a wraper/helper you may want to set stack_offset=1 to use the callsite of the wraper/helper itself. tag_set: The set of tags in which key must belong. deferred: The value is not presently known. In that case, a unique ID will be assigned as the value of this call and will be returned. The caller can then include said unique ID when the value is known later. root_dir: Directory prefix which will be trimmed when reporting calling file for compliance logging. extra_print: Print a blank line before logging to clear any text in the line. prefix: String with which to prefix the log message. Useful for differentiating raw lines if stitching will be required. Example output: :::MLP-1537375353 MINGO[17] (eval.py:42) QUALITY: 43.7 ''' return_value = None if (tag_set is None and not PATTERN.match(key)) or key not in tag_set: raise ValueError('Invalid key for MLPerf print: ' + str(key)) if value is not None and deferred: raise ValueError("deferred is set to True, but a value was provided") if deferred: return_value = str(uuid.uuid4()) value = "DEFERRED: {}".format(return_value) if value is None: tag = key else: str_json = json.dumps(value) tag = '{key}: {value}'.format(key=key, value=str_json) callsite = get_caller(2 + stack_offset, root_dir=root_dir) now = time.time() message = '{prefix}:::MLPv0.5.0 {benchmark} {secs:.9f} ({callsite}) {tag}'.format( prefix=prefix, secs=now, benchmark=benchmark, callsite=callsite, tag=tag) if extra_print: print() # There could be prior text on a line if tag in STDOUT_TAG_SET: LOGGER.info(message) else: LOGGER.debug(message) return return_value
Prints out an MLPerf Log Line. key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec. value: The value which contains no newlines. benchmark: The short code for the benchmark being run, see the MLPerf log spec. stack_offset: Increase the value to go deeper into the stack to find the callsite. For example, if this is being called by a wraper/helper you may want to set stack_offset=1 to use the callsite of the wraper/helper itself. tag_set: The set of tags in which key must belong. deferred: The value is not presently known. In that case, a unique ID will be assigned as the value of this call and will be returned. The caller can then include said unique ID when the value is known later. root_dir: Directory prefix which will be trimmed when reporting calling file for compliance logging. extra_print: Print a blank line before logging to clear any text in the line. prefix: String with which to prefix the log message. Useful for differentiating raw lines if stitching will be required. Example output: :::MLP-1537375353 MINGO[17] (eval.py:42) QUALITY: 43.7
Below is the the instruction that describes the task: ### Input: Prints out an MLPerf Log Line. key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec. value: The value which contains no newlines. benchmark: The short code for the benchmark being run, see the MLPerf log spec. stack_offset: Increase the value to go deeper into the stack to find the callsite. For example, if this is being called by a wraper/helper you may want to set stack_offset=1 to use the callsite of the wraper/helper itself. tag_set: The set of tags in which key must belong. deferred: The value is not presently known. In that case, a unique ID will be assigned as the value of this call and will be returned. The caller can then include said unique ID when the value is known later. root_dir: Directory prefix which will be trimmed when reporting calling file for compliance logging. extra_print: Print a blank line before logging to clear any text in the line. prefix: String with which to prefix the log message. Useful for differentiating raw lines if stitching will be required. Example output: :::MLP-1537375353 MINGO[17] (eval.py:42) QUALITY: 43.7 ### Response: def _mlperf_print(key, value=None, benchmark=None, stack_offset=0, tag_set=None, deferred=False, root_dir=None, extra_print=False, prefix=""): ''' Prints out an MLPerf Log Line. key: The MLPerf log key such as 'CLOCK' or 'QUALITY'. See the list of log keys in the spec. value: The value which contains no newlines. benchmark: The short code for the benchmark being run, see the MLPerf log spec. stack_offset: Increase the value to go deeper into the stack to find the callsite. For example, if this is being called by a wraper/helper you may want to set stack_offset=1 to use the callsite of the wraper/helper itself. tag_set: The set of tags in which key must belong. deferred: The value is not presently known. In that case, a unique ID will be assigned as the value of this call and will be returned. The caller can then include said unique ID when the value is known later. root_dir: Directory prefix which will be trimmed when reporting calling file for compliance logging. extra_print: Print a blank line before logging to clear any text in the line. prefix: String with which to prefix the log message. Useful for differentiating raw lines if stitching will be required. Example output: :::MLP-1537375353 MINGO[17] (eval.py:42) QUALITY: 43.7 ''' return_value = None if (tag_set is None and not PATTERN.match(key)) or key not in tag_set: raise ValueError('Invalid key for MLPerf print: ' + str(key)) if value is not None and deferred: raise ValueError("deferred is set to True, but a value was provided") if deferred: return_value = str(uuid.uuid4()) value = "DEFERRED: {}".format(return_value) if value is None: tag = key else: str_json = json.dumps(value) tag = '{key}: {value}'.format(key=key, value=str_json) callsite = get_caller(2 + stack_offset, root_dir=root_dir) now = time.time() message = '{prefix}:::MLPv0.5.0 {benchmark} {secs:.9f} ({callsite}) {tag}'.format( prefix=prefix, secs=now, benchmark=benchmark, callsite=callsite, tag=tag) if extra_print: print() # There could be prior text on a line if tag in STDOUT_TAG_SET: LOGGER.info(message) else: LOGGER.debug(message) return return_value
def generate_confirmation_key(identity_secret, tag, timestamp): """Generate confirmation key for trades. Can only be used once. :param identity_secret: authenticator identity secret :type identity_secret: bytes :param tag: tag identifies what the request, see list below :type tag: str :param timestamp: timestamp to use for generating key :type timestamp: int :return: confirmation key :rtype: bytes Tag choices: * ``conf`` to load the confirmations page * ``details`` to load details about a trade * ``allow`` to confirm a trade * ``cancel`` to cancel a trade """ data = struct.pack('>Q', int(timestamp)) + tag.encode('ascii') # this will NOT stop working in 2038 return hmac_sha1(bytes(identity_secret), data)
Generate confirmation key for trades. Can only be used once. :param identity_secret: authenticator identity secret :type identity_secret: bytes :param tag: tag identifies what the request, see list below :type tag: str :param timestamp: timestamp to use for generating key :type timestamp: int :return: confirmation key :rtype: bytes Tag choices: * ``conf`` to load the confirmations page * ``details`` to load details about a trade * ``allow`` to confirm a trade * ``cancel`` to cancel a trade
Below is the the instruction that describes the task: ### Input: Generate confirmation key for trades. Can only be used once. :param identity_secret: authenticator identity secret :type identity_secret: bytes :param tag: tag identifies what the request, see list below :type tag: str :param timestamp: timestamp to use for generating key :type timestamp: int :return: confirmation key :rtype: bytes Tag choices: * ``conf`` to load the confirmations page * ``details`` to load details about a trade * ``allow`` to confirm a trade * ``cancel`` to cancel a trade ### Response: def generate_confirmation_key(identity_secret, tag, timestamp): """Generate confirmation key for trades. Can only be used once. :param identity_secret: authenticator identity secret :type identity_secret: bytes :param tag: tag identifies what the request, see list below :type tag: str :param timestamp: timestamp to use for generating key :type timestamp: int :return: confirmation key :rtype: bytes Tag choices: * ``conf`` to load the confirmations page * ``details`` to load details about a trade * ``allow`` to confirm a trade * ``cancel`` to cancel a trade """ data = struct.pack('>Q', int(timestamp)) + tag.encode('ascii') # this will NOT stop working in 2038 return hmac_sha1(bytes(identity_secret), data)
def get_band_gap(self): """Get the bandgap, either from the EIGENVAL or DOSCAR files""" if self.outcar is not None and self.eignval is not None: bandgap = VaspParser._get_bandgap_eigenval(self.eignval, self.outcar) elif self.doscar is not None: bandgap = VaspParser._get_bandgap_doscar(self.doscar) else: return None return Property(scalars=[Scalar(value=round(bandgap, 3))], units='eV')
Get the bandgap, either from the EIGENVAL or DOSCAR files
Below is the the instruction that describes the task: ### Input: Get the bandgap, either from the EIGENVAL or DOSCAR files ### Response: def get_band_gap(self): """Get the bandgap, either from the EIGENVAL or DOSCAR files""" if self.outcar is not None and self.eignval is not None: bandgap = VaspParser._get_bandgap_eigenval(self.eignval, self.outcar) elif self.doscar is not None: bandgap = VaspParser._get_bandgap_doscar(self.doscar) else: return None return Property(scalars=[Scalar(value=round(bandgap, 3))], units='eV')
def parse_parameters(self, parameters, array_class=None): """Parses a parameters arg to figure out what fields need to be loaded. Parameters ---------- parameters : (list of) strings The parameter(s) to retrieve. A parameter can be the name of any field in ``samples_group``, a virtual field or method of ``FieldArray`` (as long as the file contains the necessary fields to derive the virtual field or method), and/or a function of these. array_class : array class, optional The type of array to use to parse the parameters. The class must have a ``parse_parameters`` method. Default is to use a ``FieldArray``. Returns ------- list : A list of strings giving the fields to load from the file. """ # get the type of array class to use if array_class is None: array_class = FieldArray # get the names of fields needed for the given parameters possible_fields = self[self.samples_group].keys() return array_class.parse_parameters(parameters, possible_fields)
Parses a parameters arg to figure out what fields need to be loaded. Parameters ---------- parameters : (list of) strings The parameter(s) to retrieve. A parameter can be the name of any field in ``samples_group``, a virtual field or method of ``FieldArray`` (as long as the file contains the necessary fields to derive the virtual field or method), and/or a function of these. array_class : array class, optional The type of array to use to parse the parameters. The class must have a ``parse_parameters`` method. Default is to use a ``FieldArray``. Returns ------- list : A list of strings giving the fields to load from the file.
Below is the the instruction that describes the task: ### Input: Parses a parameters arg to figure out what fields need to be loaded. Parameters ---------- parameters : (list of) strings The parameter(s) to retrieve. A parameter can be the name of any field in ``samples_group``, a virtual field or method of ``FieldArray`` (as long as the file contains the necessary fields to derive the virtual field or method), and/or a function of these. array_class : array class, optional The type of array to use to parse the parameters. The class must have a ``parse_parameters`` method. Default is to use a ``FieldArray``. Returns ------- list : A list of strings giving the fields to load from the file. ### Response: def parse_parameters(self, parameters, array_class=None): """Parses a parameters arg to figure out what fields need to be loaded. Parameters ---------- parameters : (list of) strings The parameter(s) to retrieve. A parameter can be the name of any field in ``samples_group``, a virtual field or method of ``FieldArray`` (as long as the file contains the necessary fields to derive the virtual field or method), and/or a function of these. array_class : array class, optional The type of array to use to parse the parameters. The class must have a ``parse_parameters`` method. Default is to use a ``FieldArray``. Returns ------- list : A list of strings giving the fields to load from the file. """ # get the type of array class to use if array_class is None: array_class = FieldArray # get the names of fields needed for the given parameters possible_fields = self[self.samples_group].keys() return array_class.parse_parameters(parameters, possible_fields)
def MakeOdds(self): """Transforms from probabilities to odds. Values with prob=0 are removed. """ for hypo, prob in self.Items(): if prob: self.Set(hypo, Odds(prob)) else: self.Remove(hypo)
Transforms from probabilities to odds. Values with prob=0 are removed.
Below is the the instruction that describes the task: ### Input: Transforms from probabilities to odds. Values with prob=0 are removed. ### Response: def MakeOdds(self): """Transforms from probabilities to odds. Values with prob=0 are removed. """ for hypo, prob in self.Items(): if prob: self.Set(hypo, Odds(prob)) else: self.Remove(hypo)
def _create_worker(self, method, *args, **kwargs): """Create a new worker instance.""" thread = QThread() worker = RequestsDownloadWorker(method, args, kwargs) worker.moveToThread(thread) worker.sig_finished.connect(self._start) self._sig_download_finished.connect(worker.sig_download_finished) self._sig_download_progress.connect(worker.sig_download_progress) worker.sig_finished.connect(thread.quit) thread.started.connect(worker.start) self._queue.append(thread) self._threads.append(thread) self._workers.append(worker) self._start() return worker
Create a new worker instance.
Below is the the instruction that describes the task: ### Input: Create a new worker instance. ### Response: def _create_worker(self, method, *args, **kwargs): """Create a new worker instance.""" thread = QThread() worker = RequestsDownloadWorker(method, args, kwargs) worker.moveToThread(thread) worker.sig_finished.connect(self._start) self._sig_download_finished.connect(worker.sig_download_finished) self._sig_download_progress.connect(worker.sig_download_progress) worker.sig_finished.connect(thread.quit) thread.started.connect(worker.start) self._queue.append(thread) self._threads.append(thread) self._workers.append(worker) self._start() return worker
def dockerCall(*args, **kwargs): """ Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'. Provided for backwards compatibility with a previous implementation that used 'subprocess.check_call()'. This has since been supplanted and apiDockerCall() is recommended. """ logger.warn("WARNING: dockerCall() using subprocess.check_output() " "is deprecated, please switch to apiDockerCall().") return subprocessDockerCall(*args, checkOutput=False, **kwargs)
Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'. Provided for backwards compatibility with a previous implementation that used 'subprocess.check_call()'. This has since been supplanted and apiDockerCall() is recommended.
Below is the the instruction that describes the task: ### Input: Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'. Provided for backwards compatibility with a previous implementation that used 'subprocess.check_call()'. This has since been supplanted and apiDockerCall() is recommended. ### Response: def dockerCall(*args, **kwargs): """ Deprecated. Runs subprocessDockerCall() using 'subprocess.check_output()'. Provided for backwards compatibility with a previous implementation that used 'subprocess.check_call()'. This has since been supplanted and apiDockerCall() is recommended. """ logger.warn("WARNING: dockerCall() using subprocess.check_output() " "is deprecated, please switch to apiDockerCall().") return subprocessDockerCall(*args, checkOutput=False, **kwargs)
def add_review_comment(self, doc, comment): """Sets the review comment. Raises CardinalityError if already set. OrderError if no reviewer defined before. Raises SPDXValueError if comment is not free form text. """ if len(doc.reviews) != 0: if not self.review_comment_set: self.review_comment_set = True if validations.validate_review_comment(comment): doc.reviews[-1].comment = str_from_text(comment) return True else: raise SPDXValueError('ReviewComment::Comment') else: raise CardinalityError('ReviewComment') else: raise OrderError('ReviewComment')
Sets the review comment. Raises CardinalityError if already set. OrderError if no reviewer defined before. Raises SPDXValueError if comment is not free form text.
Below is the the instruction that describes the task: ### Input: Sets the review comment. Raises CardinalityError if already set. OrderError if no reviewer defined before. Raises SPDXValueError if comment is not free form text. ### Response: def add_review_comment(self, doc, comment): """Sets the review comment. Raises CardinalityError if already set. OrderError if no reviewer defined before. Raises SPDXValueError if comment is not free form text. """ if len(doc.reviews) != 0: if not self.review_comment_set: self.review_comment_set = True if validations.validate_review_comment(comment): doc.reviews[-1].comment = str_from_text(comment) return True else: raise SPDXValueError('ReviewComment::Comment') else: raise CardinalityError('ReviewComment') else: raise OrderError('ReviewComment')
def update_password(self, password: str) -> bool: """ 修改登入密碼 """ try: # 操作所需資訊 payload = { 'pass': password, 'submit': 'sumit' } # 修改密碼 response = self.__session.post( self.__url + '/changePasswd', data=payload, timeout=0.5, verify=False) soup = BeautifulSoup(response.text, 'html.parser') # 回傳結果 return str(soup.find('body')).split()[-2].strip() == 'Success' except requests.exceptions.Timeout: return None
修改登入密碼
Below is the the instruction that describes the task: ### Input: 修改登入密碼 ### Response: def update_password(self, password: str) -> bool: """ 修改登入密碼 """ try: # 操作所需資訊 payload = { 'pass': password, 'submit': 'sumit' } # 修改密碼 response = self.__session.post( self.__url + '/changePasswd', data=payload, timeout=0.5, verify=False) soup = BeautifulSoup(response.text, 'html.parser') # 回傳結果 return str(soup.find('body')).split()[-2].strip() == 'Success' except requests.exceptions.Timeout: return None
def _load_yml_config(self, config_file): """ loads a yaml str, creates a few constructs for pyaml, serializes and normalized the config data. Then assigns the config data to self._data. :param config_file: A :string: loaded from a yaml file. """ if not isinstance(config_file, six.string_types): raise TypeError('config_file must be a str.') try: def construct_yaml_int(self, node): obj = SafeConstructor.construct_yaml_int(self, node) data = ConfigInt( obj, node.start_mark, node.end_mark ) return data def construct_yaml_float(self, node): obj, = SafeConstructor.construct_yaml_float(self, node) data = ConfigFloat( obj, node.start_mark, node.end_mark ) return data def construct_yaml_str(self, node): # Override the default string handling function # to always return unicode objects obj = SafeConstructor.construct_scalar(self, node) assert isinstance(obj, six.string_types) data = ConfigUnicode( obj, node.start_mark, node.end_mark ) return data def construct_yaml_mapping(self, node): obj, = SafeConstructor.construct_yaml_map(self, node) data = ConfigDict( obj, node.start_mark, node.end_mark ) return data def construct_yaml_seq(self, node): obj, = SafeConstructor.construct_yaml_seq(self, node) data = ConfigSeq( obj, node.start_mark, node.end_mark ) return data # SafeConstructor.add_constructor(u'tag:yaml.org,2002:bool', construct_yaml_bool) SafeConstructor.add_constructor(u'tag:yaml.org,2002:float', construct_yaml_float) SafeConstructor.add_constructor(u'tag:yaml.org,2002:int', construct_yaml_int) SafeConstructor.add_constructor(u'tag:yaml.org,2002:map', construct_yaml_mapping) SafeConstructor.add_constructor(u'tag:yaml.org,2002:seq', construct_yaml_seq) SafeConstructor.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str) data = SafeLoader(config_file).get_data() if data is None: raise AttributeError('The configuration file needs to have data in it.') self._data = normalize_keys(data, snake_case=False) except YAMLError as e: if hasattr(e, 'problem_mark'): mark = e.problem_mark raise SyntaxError( "There is a syntax error in your freight-forwarder config file line: {0} column: {1}".format( mark.line + 1, mark.column + 1 ) ) else: raise SyntaxError("There is a syntax error in your freight-forwarder config.")
loads a yaml str, creates a few constructs for pyaml, serializes and normalized the config data. Then assigns the config data to self._data. :param config_file: A :string: loaded from a yaml file.
Below is the the instruction that describes the task: ### Input: loads a yaml str, creates a few constructs for pyaml, serializes and normalized the config data. Then assigns the config data to self._data. :param config_file: A :string: loaded from a yaml file. ### Response: def _load_yml_config(self, config_file): """ loads a yaml str, creates a few constructs for pyaml, serializes and normalized the config data. Then assigns the config data to self._data. :param config_file: A :string: loaded from a yaml file. """ if not isinstance(config_file, six.string_types): raise TypeError('config_file must be a str.') try: def construct_yaml_int(self, node): obj = SafeConstructor.construct_yaml_int(self, node) data = ConfigInt( obj, node.start_mark, node.end_mark ) return data def construct_yaml_float(self, node): obj, = SafeConstructor.construct_yaml_float(self, node) data = ConfigFloat( obj, node.start_mark, node.end_mark ) return data def construct_yaml_str(self, node): # Override the default string handling function # to always return unicode objects obj = SafeConstructor.construct_scalar(self, node) assert isinstance(obj, six.string_types) data = ConfigUnicode( obj, node.start_mark, node.end_mark ) return data def construct_yaml_mapping(self, node): obj, = SafeConstructor.construct_yaml_map(self, node) data = ConfigDict( obj, node.start_mark, node.end_mark ) return data def construct_yaml_seq(self, node): obj, = SafeConstructor.construct_yaml_seq(self, node) data = ConfigSeq( obj, node.start_mark, node.end_mark ) return data # SafeConstructor.add_constructor(u'tag:yaml.org,2002:bool', construct_yaml_bool) SafeConstructor.add_constructor(u'tag:yaml.org,2002:float', construct_yaml_float) SafeConstructor.add_constructor(u'tag:yaml.org,2002:int', construct_yaml_int) SafeConstructor.add_constructor(u'tag:yaml.org,2002:map', construct_yaml_mapping) SafeConstructor.add_constructor(u'tag:yaml.org,2002:seq', construct_yaml_seq) SafeConstructor.add_constructor(u'tag:yaml.org,2002:str', construct_yaml_str) data = SafeLoader(config_file).get_data() if data is None: raise AttributeError('The configuration file needs to have data in it.') self._data = normalize_keys(data, snake_case=False) except YAMLError as e: if hasattr(e, 'problem_mark'): mark = e.problem_mark raise SyntaxError( "There is a syntax error in your freight-forwarder config file line: {0} column: {1}".format( mark.line + 1, mark.column + 1 ) ) else: raise SyntaxError("There is a syntax error in your freight-forwarder config.")
def to_real_keras_layer(layer): ''' real keras layer. ''' from keras import layers if is_layer(layer, "Dense"): return layers.Dense(layer.units, input_shape=(layer.input_units,)) if is_layer(layer, "Conv"): return layers.Conv2D( layer.filters, layer.kernel_size, input_shape=layer.input.shape, padding="same", ) # padding if is_layer(layer, "Pooling"): return layers.MaxPool2D(2) if is_layer(layer, "BatchNormalization"): return layers.BatchNormalization(input_shape=layer.input.shape) if is_layer(layer, "Concatenate"): return layers.Concatenate() if is_layer(layer, "Add"): return layers.Add() if is_layer(layer, "Dropout"): return keras_dropout(layer, layer.rate) if is_layer(layer, "ReLU"): return layers.Activation("relu") if is_layer(layer, "Softmax"): return layers.Activation("softmax") if is_layer(layer, "Flatten"): return layers.Flatten() if is_layer(layer, "GlobalAveragePooling"): return layers.GlobalAveragePooling2D()
real keras layer.
Below is the the instruction that describes the task: ### Input: real keras layer. ### Response: def to_real_keras_layer(layer): ''' real keras layer. ''' from keras import layers if is_layer(layer, "Dense"): return layers.Dense(layer.units, input_shape=(layer.input_units,)) if is_layer(layer, "Conv"): return layers.Conv2D( layer.filters, layer.kernel_size, input_shape=layer.input.shape, padding="same", ) # padding if is_layer(layer, "Pooling"): return layers.MaxPool2D(2) if is_layer(layer, "BatchNormalization"): return layers.BatchNormalization(input_shape=layer.input.shape) if is_layer(layer, "Concatenate"): return layers.Concatenate() if is_layer(layer, "Add"): return layers.Add() if is_layer(layer, "Dropout"): return keras_dropout(layer, layer.rate) if is_layer(layer, "ReLU"): return layers.Activation("relu") if is_layer(layer, "Softmax"): return layers.Activation("softmax") if is_layer(layer, "Flatten"): return layers.Flatten() if is_layer(layer, "GlobalAveragePooling"): return layers.GlobalAveragePooling2D()
def x_lower_limit(self, limit=None): """Returns or sets (if a value is provided) the value at which the x-axis should start. By default this is zero (unless there are negative values). :param limit: If given, the chart's x_lower_limit will be set to this. :raises ValueError: if you try to make the lower limit larger than the\ upper limit.""" if limit is None: if self._x_lower_limit is None: if self.smallest_x() < 0: if self.smallest_x() == self.largest_x(): return int(self.smallest_x() - 1) else: return self.smallest_x() else: return 0 else: return self._x_lower_limit else: if not is_numeric(limit): raise TypeError( "lower x limit must be numeric, not '%s'" % str(limit) ) if limit >= self.largest_x(): raise ValueError( "lower x limit must be less than upper limit (%s), not %s" % ( str(self.largest_x()), str(limit) ) ) self._x_lower_limit = limit
Returns or sets (if a value is provided) the value at which the x-axis should start. By default this is zero (unless there are negative values). :param limit: If given, the chart's x_lower_limit will be set to this. :raises ValueError: if you try to make the lower limit larger than the\ upper limit.
Below is the the instruction that describes the task: ### Input: Returns or sets (if a value is provided) the value at which the x-axis should start. By default this is zero (unless there are negative values). :param limit: If given, the chart's x_lower_limit will be set to this. :raises ValueError: if you try to make the lower limit larger than the\ upper limit. ### Response: def x_lower_limit(self, limit=None): """Returns or sets (if a value is provided) the value at which the x-axis should start. By default this is zero (unless there are negative values). :param limit: If given, the chart's x_lower_limit will be set to this. :raises ValueError: if you try to make the lower limit larger than the\ upper limit.""" if limit is None: if self._x_lower_limit is None: if self.smallest_x() < 0: if self.smallest_x() == self.largest_x(): return int(self.smallest_x() - 1) else: return self.smallest_x() else: return 0 else: return self._x_lower_limit else: if not is_numeric(limit): raise TypeError( "lower x limit must be numeric, not '%s'" % str(limit) ) if limit >= self.largest_x(): raise ValueError( "lower x limit must be less than upper limit (%s), not %s" % ( str(self.largest_x()), str(limit) ) ) self._x_lower_limit = limit
def register_endpoints(self): """ See super class method satosa.backends.base.BackendModule#register_endpoints :rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))] """ url_map = [] sp_endpoints = self.sp.config.getattr("endpoints", "sp") for endp, binding in sp_endpoints["assertion_consumer_service"]: parsed_endp = urlparse(endp) url_map.append(("^%s$" % parsed_endp.path[1:], functools.partial(self.authn_response, binding=binding))) if self.discosrv: for endp, binding in sp_endpoints["discovery_response"]: parsed_endp = urlparse(endp) url_map.append( ("^%s$" % parsed_endp.path[1:], self.disco_response)) if self.expose_entityid_endpoint(): parsed_entity_id = urlparse(self.sp.config.entityid) url_map.append(("^{0}".format(parsed_entity_id.path[1:]), self._metadata_endpoint)) return url_map
See super class method satosa.backends.base.BackendModule#register_endpoints :rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))]
Below is the the instruction that describes the task: ### Input: See super class method satosa.backends.base.BackendModule#register_endpoints :rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))] ### Response: def register_endpoints(self): """ See super class method satosa.backends.base.BackendModule#register_endpoints :rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))] """ url_map = [] sp_endpoints = self.sp.config.getattr("endpoints", "sp") for endp, binding in sp_endpoints["assertion_consumer_service"]: parsed_endp = urlparse(endp) url_map.append(("^%s$" % parsed_endp.path[1:], functools.partial(self.authn_response, binding=binding))) if self.discosrv: for endp, binding in sp_endpoints["discovery_response"]: parsed_endp = urlparse(endp) url_map.append( ("^%s$" % parsed_endp.path[1:], self.disco_response)) if self.expose_entityid_endpoint(): parsed_entity_id = urlparse(self.sp.config.entityid) url_map.append(("^{0}".format(parsed_entity_id.path[1:]), self._metadata_endpoint)) return url_map
def api_info(self, headers=None): """Retrieves information provided by the API root endpoint ``'/api/v1'``. Args: headers (dict): Optional headers to pass to the request. Returns: dict: Details of the HTTP API provided by the BigchainDB server. """ return self.transport.forward_request( method='GET', path=self.api_prefix, headers=headers, )
Retrieves information provided by the API root endpoint ``'/api/v1'``. Args: headers (dict): Optional headers to pass to the request. Returns: dict: Details of the HTTP API provided by the BigchainDB server.
Below is the the instruction that describes the task: ### Input: Retrieves information provided by the API root endpoint ``'/api/v1'``. Args: headers (dict): Optional headers to pass to the request. Returns: dict: Details of the HTTP API provided by the BigchainDB server. ### Response: def api_info(self, headers=None): """Retrieves information provided by the API root endpoint ``'/api/v1'``. Args: headers (dict): Optional headers to pass to the request. Returns: dict: Details of the HTTP API provided by the BigchainDB server. """ return self.transport.forward_request( method='GET', path=self.api_prefix, headers=headers, )
def _get_parser(extra_args): """Return ArgumentParser with any extra arguments.""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) dirs = appdirs.AppDirs('hangups', 'hangups') default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt') parser.add_argument( '--token-path', default=default_token_path, help='path used to store OAuth refresh token' ) parser.add_argument( '-d', '--debug', action='store_true', help='log detailed debugging messages' ) for extra_arg in extra_args: parser.add_argument(extra_arg, required=True) return parser
Return ArgumentParser with any extra arguments.
Below is the the instruction that describes the task: ### Input: Return ArgumentParser with any extra arguments. ### Response: def _get_parser(extra_args): """Return ArgumentParser with any extra arguments.""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) dirs = appdirs.AppDirs('hangups', 'hangups') default_token_path = os.path.join(dirs.user_cache_dir, 'refresh_token.txt') parser.add_argument( '--token-path', default=default_token_path, help='path used to store OAuth refresh token' ) parser.add_argument( '-d', '--debug', action='store_true', help='log detailed debugging messages' ) for extra_arg in extra_args: parser.add_argument(extra_arg, required=True) return parser
def connect_get_namespaced_service_proxy(self, name, namespace, **kwargs): """ connect GET requests to proxy of Service This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_get_namespaced_service_proxy(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the ServiceProxyOptions (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.connect_get_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) else: (data) = self.connect_get_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) return data
connect GET requests to proxy of Service This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_get_namespaced_service_proxy(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the ServiceProxyOptions (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. :return: str If the method is called asynchronously, returns the request thread.
Below is the the instruction that describes the task: ### Input: connect GET requests to proxy of Service This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_get_namespaced_service_proxy(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the ServiceProxyOptions (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. :return: str If the method is called asynchronously, returns the request thread. ### Response: def connect_get_namespaced_service_proxy(self, name, namespace, **kwargs): """ connect GET requests to proxy of Service This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.connect_get_namespaced_service_proxy(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the ServiceProxyOptions (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str path: Path is the part of URLs that include service endpoints, suffixes, and parameters to use for the current proxy request to service. For example, the whole request URL is http://localhost/api/v1/namespaces/kube-system/services/elasticsearch-logging/_search?q=user:kimchy. Path is _search?q=user:kimchy. :return: str If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.connect_get_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) else: (data) = self.connect_get_namespaced_service_proxy_with_http_info(name, namespace, **kwargs) return data
def get_num_names_owned( state_engine, checked_ops, sender ): """ Find out how many preorders a given sender (i.e. a script) actually owns, as of this transaction. """ count = 0 registers = find_by_opcode( checked_ops, "NAME_REGISTRATION" ) for reg in registers: if reg['sender'] == sender: count += 1 count += len( state_engine.get_names_owned_by_sender( sender ) ) log.debug("Sender '%s' owns %s names" % (sender, count)) return count
Find out how many preorders a given sender (i.e. a script) actually owns, as of this transaction.
Below is the the instruction that describes the task: ### Input: Find out how many preorders a given sender (i.e. a script) actually owns, as of this transaction. ### Response: def get_num_names_owned( state_engine, checked_ops, sender ): """ Find out how many preorders a given sender (i.e. a script) actually owns, as of this transaction. """ count = 0 registers = find_by_opcode( checked_ops, "NAME_REGISTRATION" ) for reg in registers: if reg['sender'] == sender: count += 1 count += len( state_engine.get_names_owned_by_sender( sender ) ) log.debug("Sender '%s' owns %s names" % (sender, count)) return count
def _generate_tree_log_file(self, tree, alignment, output_tree_file_path, output_log_file_path, residue_type, fasttree): '''Generate the FastTree log file given a tree and the alignment that made that tree Returns ------- Nothing. The log file as parameter is written as the log file. ''' if residue_type==Create._NUCLEOTIDE_PACKAGE_TYPE: cmd = "%s -quiet -gtr -nt -nome -mllen -intree '%s' -log %s -out %s %s" %\ (fasttree, tree, output_log_file_path, output_tree_file_path, alignment) elif residue_type==Create._PROTEIN_PACKAGE_TYPE: cmd = "%s -quiet -nome -mllen -intree '%s' -log %s -out %s %s" %\ (fasttree, tree, output_log_file_path, output_tree_file_path, alignment) extern.run(cmd)
Generate the FastTree log file given a tree and the alignment that made that tree Returns ------- Nothing. The log file as parameter is written as the log file.
Below is the the instruction that describes the task: ### Input: Generate the FastTree log file given a tree and the alignment that made that tree Returns ------- Nothing. The log file as parameter is written as the log file. ### Response: def _generate_tree_log_file(self, tree, alignment, output_tree_file_path, output_log_file_path, residue_type, fasttree): '''Generate the FastTree log file given a tree and the alignment that made that tree Returns ------- Nothing. The log file as parameter is written as the log file. ''' if residue_type==Create._NUCLEOTIDE_PACKAGE_TYPE: cmd = "%s -quiet -gtr -nt -nome -mllen -intree '%s' -log %s -out %s %s" %\ (fasttree, tree, output_log_file_path, output_tree_file_path, alignment) elif residue_type==Create._PROTEIN_PACKAGE_TYPE: cmd = "%s -quiet -nome -mllen -intree '%s' -log %s -out %s %s" %\ (fasttree, tree, output_log_file_path, output_tree_file_path, alignment) extern.run(cmd)
def log_error(msg=None, exc_info=None, logger=None, **kwargs): """ log an exception and its traceback on the logger defined Parameters ---------- msg : str, optional A message to add to the error exc_info : tuple Information about the current exception logger : logging.Logger logger to use """ if logger is None: logger = _logger if not exc_info: exc_info = sys.exc_info() if msg is None: msg = "" exc_class, exc_msg, _ = exc_info if all(info is not None for info in exc_info): logger.error(msg, exc_info=exc_info)
log an exception and its traceback on the logger defined Parameters ---------- msg : str, optional A message to add to the error exc_info : tuple Information about the current exception logger : logging.Logger logger to use
Below is the the instruction that describes the task: ### Input: log an exception and its traceback on the logger defined Parameters ---------- msg : str, optional A message to add to the error exc_info : tuple Information about the current exception logger : logging.Logger logger to use ### Response: def log_error(msg=None, exc_info=None, logger=None, **kwargs): """ log an exception and its traceback on the logger defined Parameters ---------- msg : str, optional A message to add to the error exc_info : tuple Information about the current exception logger : logging.Logger logger to use """ if logger is None: logger = _logger if not exc_info: exc_info = sys.exc_info() if msg is None: msg = "" exc_class, exc_msg, _ = exc_info if all(info is not None for info in exc_info): logger.error(msg, exc_info=exc_info)
def drop(self, n): """ Drop the first n elements of the sequence. >>> seq([1, 2, 3, 4, 5]).drop(2) [3, 4, 5] :param n: number of elements to drop :return: sequence without first n elements """ if n <= 0: return self._transform(transformations.drop_t(0)) else: return self._transform(transformations.drop_t(n))
Drop the first n elements of the sequence. >>> seq([1, 2, 3, 4, 5]).drop(2) [3, 4, 5] :param n: number of elements to drop :return: sequence without first n elements
Below is the the instruction that describes the task: ### Input: Drop the first n elements of the sequence. >>> seq([1, 2, 3, 4, 5]).drop(2) [3, 4, 5] :param n: number of elements to drop :return: sequence without first n elements ### Response: def drop(self, n): """ Drop the first n elements of the sequence. >>> seq([1, 2, 3, 4, 5]).drop(2) [3, 4, 5] :param n: number of elements to drop :return: sequence without first n elements """ if n <= 0: return self._transform(transformations.drop_t(0)) else: return self._transform(transformations.drop_t(n))
def scorable_block_completion(sender, **kwargs): # pylint: disable=unused-argument """ When a problem is scored, submit a new BlockCompletion for that block. """ if not waffle.waffle().is_enabled(waffle.ENABLE_COMPLETION_TRACKING): return course_key = CourseKey.from_string(kwargs['course_id']) block_key = UsageKey.from_string(kwargs['usage_id']) block_cls = XBlock.load_class(block_key.block_type) if XBlockCompletionMode.get_mode(block_cls) != XBlockCompletionMode.COMPLETABLE: return if getattr(block_cls, 'has_custom_completion', False): return user = User.objects.get(id=kwargs['user_id']) if kwargs.get('score_deleted'): completion = 0.0 else: completion = 1.0 if not kwargs.get('grader_response'): BlockCompletion.objects.submit_completion( user=user, course_key=course_key, block_key=block_key, completion=completion, )
When a problem is scored, submit a new BlockCompletion for that block.
Below is the the instruction that describes the task: ### Input: When a problem is scored, submit a new BlockCompletion for that block. ### Response: def scorable_block_completion(sender, **kwargs): # pylint: disable=unused-argument """ When a problem is scored, submit a new BlockCompletion for that block. """ if not waffle.waffle().is_enabled(waffle.ENABLE_COMPLETION_TRACKING): return course_key = CourseKey.from_string(kwargs['course_id']) block_key = UsageKey.from_string(kwargs['usage_id']) block_cls = XBlock.load_class(block_key.block_type) if XBlockCompletionMode.get_mode(block_cls) != XBlockCompletionMode.COMPLETABLE: return if getattr(block_cls, 'has_custom_completion', False): return user = User.objects.get(id=kwargs['user_id']) if kwargs.get('score_deleted'): completion = 0.0 else: completion = 1.0 if not kwargs.get('grader_response'): BlockCompletion.objects.submit_completion( user=user, course_key=course_key, block_key=block_key, completion=completion, )
def optimize(self, loss, num_async_replicas=1, use_tpu=False): """Return a training op minimizing loss.""" lr = learning_rate.learning_rate_schedule(self.hparams) if num_async_replicas > 1: log_info("Dividing learning rate by num_async_replicas: %d", num_async_replicas) lr /= math.sqrt(float(num_async_replicas)) train_op = optimize.optimize(loss, lr, self.hparams, use_tpu=use_tpu) return train_op
Return a training op minimizing loss.
Below is the the instruction that describes the task: ### Input: Return a training op minimizing loss. ### Response: def optimize(self, loss, num_async_replicas=1, use_tpu=False): """Return a training op minimizing loss.""" lr = learning_rate.learning_rate_schedule(self.hparams) if num_async_replicas > 1: log_info("Dividing learning rate by num_async_replicas: %d", num_async_replicas) lr /= math.sqrt(float(num_async_replicas)) train_op = optimize.optimize(loss, lr, self.hparams, use_tpu=use_tpu) return train_op
def exons(context, build): """Delete all exons in the database""" LOG.info("Running scout delete exons") adapter = context.obj['adapter'] adapter.drop_exons(build)
Delete all exons in the database
Below is the the instruction that describes the task: ### Input: Delete all exons in the database ### Response: def exons(context, build): """Delete all exons in the database""" LOG.info("Running scout delete exons") adapter = context.obj['adapter'] adapter.drop_exons(build)
def get_default_language(language_code=None): """ Returns default language depending on settings.LANGUAGE_CODE merged with best match from settings.LANGUAGES Returns: language_code Raises ImproperlyConfigured if no match found """ if not language_code: language_code = settings.LANGUAGE_CODE languages = dict(settings.LANGUAGES).keys() # first try if there is an exact language if language_code in languages: return language_code # otherwise split the language code if possible, so iso3 language_code = language_code.split("-")[0] if language_code not in languages: raise ImproperlyConfigured("No match in LANGUAGES for LANGUAGE_CODE %s" % settings.LANGUAGE_CODE) return language_code
Returns default language depending on settings.LANGUAGE_CODE merged with best match from settings.LANGUAGES Returns: language_code Raises ImproperlyConfigured if no match found
Below is the the instruction that describes the task: ### Input: Returns default language depending on settings.LANGUAGE_CODE merged with best match from settings.LANGUAGES Returns: language_code Raises ImproperlyConfigured if no match found ### Response: def get_default_language(language_code=None): """ Returns default language depending on settings.LANGUAGE_CODE merged with best match from settings.LANGUAGES Returns: language_code Raises ImproperlyConfigured if no match found """ if not language_code: language_code = settings.LANGUAGE_CODE languages = dict(settings.LANGUAGES).keys() # first try if there is an exact language if language_code in languages: return language_code # otherwise split the language code if possible, so iso3 language_code = language_code.split("-")[0] if language_code not in languages: raise ImproperlyConfigured("No match in LANGUAGES for LANGUAGE_CODE %s" % settings.LANGUAGE_CODE) return language_code
def handle_emphasis(self, start, tag_style, parent_style): """handles various text emphases""" tag_emphasis = google_text_emphasis(tag_style) parent_emphasis = google_text_emphasis(parent_style) # handle Google's text emphasis strikethrough = 'line-through' in tag_emphasis and self.hide_strikethrough bold = 'bold' in tag_emphasis and not 'bold' in parent_emphasis italic = 'italic' in tag_emphasis and not 'italic' in parent_emphasis fixed = google_fixed_width_font(tag_style) and not \ google_fixed_width_font(parent_style) and not self.pre if start: # crossed-out text must be handled before other attributes # in order not to output qualifiers unnecessarily if bold or italic or fixed: self.emphasis += 1 if strikethrough: self.quiet += 1 if italic: self.o(self.emphasis_mark) self.drop_white_space += 1 if bold: self.o(self.strong_mark) self.drop_white_space += 1 if fixed: self.o('`') self.drop_white_space += 1 self.code = True else: if bold or italic or fixed: # there must not be whitespace before closing emphasis mark self.emphasis -= 1 self.space = 0 self.outtext = self.outtext.rstrip() if fixed: if self.drop_white_space: # empty emphasis, drop it self.drop_last(1) self.drop_white_space -= 1 else: self.o('`') self.code = False if bold: if self.drop_white_space: # empty emphasis, drop it self.drop_last(2) self.drop_white_space -= 1 else: self.o(self.strong_mark) if italic: if self.drop_white_space: # empty emphasis, drop it self.drop_last(1) self.drop_white_space -= 1 else: self.o(self.emphasis_mark) # space is only allowed after *all* emphasis marks if (bold or italic) and not self.emphasis: self.o(" ") if strikethrough: self.quiet -= 1
handles various text emphases
Below is the the instruction that describes the task: ### Input: handles various text emphases ### Response: def handle_emphasis(self, start, tag_style, parent_style): """handles various text emphases""" tag_emphasis = google_text_emphasis(tag_style) parent_emphasis = google_text_emphasis(parent_style) # handle Google's text emphasis strikethrough = 'line-through' in tag_emphasis and self.hide_strikethrough bold = 'bold' in tag_emphasis and not 'bold' in parent_emphasis italic = 'italic' in tag_emphasis and not 'italic' in parent_emphasis fixed = google_fixed_width_font(tag_style) and not \ google_fixed_width_font(parent_style) and not self.pre if start: # crossed-out text must be handled before other attributes # in order not to output qualifiers unnecessarily if bold or italic or fixed: self.emphasis += 1 if strikethrough: self.quiet += 1 if italic: self.o(self.emphasis_mark) self.drop_white_space += 1 if bold: self.o(self.strong_mark) self.drop_white_space += 1 if fixed: self.o('`') self.drop_white_space += 1 self.code = True else: if bold or italic or fixed: # there must not be whitespace before closing emphasis mark self.emphasis -= 1 self.space = 0 self.outtext = self.outtext.rstrip() if fixed: if self.drop_white_space: # empty emphasis, drop it self.drop_last(1) self.drop_white_space -= 1 else: self.o('`') self.code = False if bold: if self.drop_white_space: # empty emphasis, drop it self.drop_last(2) self.drop_white_space -= 1 else: self.o(self.strong_mark) if italic: if self.drop_white_space: # empty emphasis, drop it self.drop_last(1) self.drop_white_space -= 1 else: self.o(self.emphasis_mark) # space is only allowed after *all* emphasis marks if (bold or italic) and not self.emphasis: self.o(" ") if strikethrough: self.quiet -= 1
def from_api_repr(cls, api_repr): """Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath`) An instance parsed from ``api_repr``. Raises: ValueError if the parsing fails """ api_repr = api_repr.strip() if not api_repr: raise ValueError("Field path API representation cannot be empty.") return cls(*parse_field_path(api_repr))
Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath`) An instance parsed from ``api_repr``. Raises: ValueError if the parsing fails
Below is the the instruction that describes the task: ### Input: Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath`) An instance parsed from ``api_repr``. Raises: ValueError if the parsing fails ### Response: def from_api_repr(cls, api_repr): """Factory: create a FieldPath from the string formatted per the API. Args: api_repr (str): a string path, with non-identifier elements quoted It cannot exceed 1500 characters, and cannot be empty. Returns: (:class:`FieldPath`) An instance parsed from ``api_repr``. Raises: ValueError if the parsing fails """ api_repr = api_repr.strip() if not api_repr: raise ValueError("Field path API representation cannot be empty.") return cls(*parse_field_path(api_repr))
def get_sdk_download_stream(self, rest_api_id, api_gateway_stage=DEFAULT_STAGE_NAME, sdk_type='javascript'): # type: (str, str, str) -> file """Generate an SDK for a given SDK. Returns a file like object that streams a zip contents for the generated SDK. """ response = self._client('apigateway').get_sdk( restApiId=rest_api_id, stageName=api_gateway_stage, sdkType=sdk_type) return response['body']
Generate an SDK for a given SDK. Returns a file like object that streams a zip contents for the generated SDK.
Below is the the instruction that describes the task: ### Input: Generate an SDK for a given SDK. Returns a file like object that streams a zip contents for the generated SDK. ### Response: def get_sdk_download_stream(self, rest_api_id, api_gateway_stage=DEFAULT_STAGE_NAME, sdk_type='javascript'): # type: (str, str, str) -> file """Generate an SDK for a given SDK. Returns a file like object that streams a zip contents for the generated SDK. """ response = self._client('apigateway').get_sdk( restApiId=rest_api_id, stageName=api_gateway_stage, sdkType=sdk_type) return response['body']
def _format_param_value(key, value): """Wraps string values in quotes, and returns as 'key=value'. """ if isinstance(value, str): value = "'{}'".format(value) return "{}={}".format(key, value)
Wraps string values in quotes, and returns as 'key=value'.
Below is the the instruction that describes the task: ### Input: Wraps string values in quotes, and returns as 'key=value'. ### Response: def _format_param_value(key, value): """Wraps string values in quotes, and returns as 'key=value'. """ if isinstance(value, str): value = "'{}'".format(value) return "{}={}".format(key, value)
def _generate_numpy_doc(self, func_info): """Generate a docstring of numpy type.""" numpy_doc = '' arg_names = func_info.arg_name_list arg_types = func_info.arg_type_list arg_values = func_info.arg_value_list if len(arg_names) > 0 and arg_names[0] == 'self': del arg_names[0] del arg_types[0] del arg_values[0] indent1 = func_info.func_indent + self.code_editor.indent_chars indent2 = func_info.func_indent + self.code_editor.indent_chars * 2 numpy_doc += '\n{}\n'.format(indent1) if len(arg_names) > 0: numpy_doc += '\n{}Parameters'.format(indent1) numpy_doc += '\n{}----------\n'.format(indent1) arg_text = '' for arg_name, arg_type, arg_value in zip(arg_names, arg_types, arg_values): arg_text += '{}{} : '.format(indent1, arg_name) if arg_type: arg_text += '{}'.format(arg_type) else: arg_text += 'TYPE' if arg_value: arg_text += ', optional' arg_text += '\n{}DESCRIPTION.'.format(indent2) if arg_value: arg_value = arg_value.replace(self.quote3, self.quote3_other) arg_text += ' The default is {}.'.format(arg_value) arg_text += '\n' numpy_doc += arg_text if func_info.raise_list: numpy_doc += '\n{}Raises'.format(indent1) numpy_doc += '\n{}------'.format(indent1) for raise_type in func_info.raise_list: numpy_doc += '\n{}{}'.format(indent1, raise_type) numpy_doc += '\n{}DESCRIPTION.'.format(indent2) numpy_doc += '\n' numpy_doc += '\n' if func_info.has_yield: header = '{0}Yields\n{0}------\n'.format(indent1) else: header = '{0}Returns\n{0}-------\n'.format(indent1) return_type_annotated = func_info.return_type_annotated if return_type_annotated: return_section = '{}{}{}'.format(header, indent1, return_type_annotated) return_section += '\n{}DESCRIPTION.'.format(indent2) else: return_element_type = indent1 + '{return_type}\n' + indent2 + \ 'DESCRIPTION.' placeholder = return_element_type.format(return_type='TYPE') return_element_name = indent1 + '{return_name} : ' + \ placeholder.lstrip() try: return_section = self._generate_docstring_return_section( func_info.return_value_in_body, header, return_element_name, return_element_type, placeholder, indent1) except (ValueError, IndexError): return_section = '{}{}None.'.format(header, indent1) numpy_doc += return_section numpy_doc += '\n\n{}{}'.format(indent1, self.quote3) return numpy_doc
Generate a docstring of numpy type.
Below is the the instruction that describes the task: ### Input: Generate a docstring of numpy type. ### Response: def _generate_numpy_doc(self, func_info): """Generate a docstring of numpy type.""" numpy_doc = '' arg_names = func_info.arg_name_list arg_types = func_info.arg_type_list arg_values = func_info.arg_value_list if len(arg_names) > 0 and arg_names[0] == 'self': del arg_names[0] del arg_types[0] del arg_values[0] indent1 = func_info.func_indent + self.code_editor.indent_chars indent2 = func_info.func_indent + self.code_editor.indent_chars * 2 numpy_doc += '\n{}\n'.format(indent1) if len(arg_names) > 0: numpy_doc += '\n{}Parameters'.format(indent1) numpy_doc += '\n{}----------\n'.format(indent1) arg_text = '' for arg_name, arg_type, arg_value in zip(arg_names, arg_types, arg_values): arg_text += '{}{} : '.format(indent1, arg_name) if arg_type: arg_text += '{}'.format(arg_type) else: arg_text += 'TYPE' if arg_value: arg_text += ', optional' arg_text += '\n{}DESCRIPTION.'.format(indent2) if arg_value: arg_value = arg_value.replace(self.quote3, self.quote3_other) arg_text += ' The default is {}.'.format(arg_value) arg_text += '\n' numpy_doc += arg_text if func_info.raise_list: numpy_doc += '\n{}Raises'.format(indent1) numpy_doc += '\n{}------'.format(indent1) for raise_type in func_info.raise_list: numpy_doc += '\n{}{}'.format(indent1, raise_type) numpy_doc += '\n{}DESCRIPTION.'.format(indent2) numpy_doc += '\n' numpy_doc += '\n' if func_info.has_yield: header = '{0}Yields\n{0}------\n'.format(indent1) else: header = '{0}Returns\n{0}-------\n'.format(indent1) return_type_annotated = func_info.return_type_annotated if return_type_annotated: return_section = '{}{}{}'.format(header, indent1, return_type_annotated) return_section += '\n{}DESCRIPTION.'.format(indent2) else: return_element_type = indent1 + '{return_type}\n' + indent2 + \ 'DESCRIPTION.' placeholder = return_element_type.format(return_type='TYPE') return_element_name = indent1 + '{return_name} : ' + \ placeholder.lstrip() try: return_section = self._generate_docstring_return_section( func_info.return_value_in_body, header, return_element_name, return_element_type, placeholder, indent1) except (ValueError, IndexError): return_section = '{}{}None.'.format(header, indent1) numpy_doc += return_section numpy_doc += '\n\n{}{}'.format(indent1, self.quote3) return numpy_doc
def _create(cls, name, node_type, physical_interfaces, nodes=1, loopback_ndi=None, log_server_ref=None, domain_server_address=None, enable_antivirus=False, enable_gti=False, sidewinder_proxy_enabled=False, default_nat=False, location_ref=None, enable_ospf=None, ospf_profile=None, snmp_agent=None, comment=None): """ Create will return the engine configuration as a dict that is a representation of the engine. The creating class will also add engine specific requirements before constructing the request and sending to SMC (which will serialize the dict to json). :param name: name of engine :param str node_type: comes from class attribute of engine type :param dict physical_interfaces: physical interface list of dict :param int nodes: number of nodes for engine :param str log_server_ref: href of log server :param list domain_server_address: dns addresses """ node_list = [] for nodeid in range(1, nodes + 1): # start at nodeid=1 node_list.append(Node._create( name, node_type, nodeid, loopback_ndi)) domain_server_list = [] if domain_server_address: for num, server in enumerate(domain_server_address): try: domain_server = {'rank': num, 'ne_ref' : server.href} except AttributeError: domain_server = {'rank': num, 'value': server} domain_server_list.append(domain_server) # Set log server reference, if not explicitly provided if not log_server_ref and node_type is not 'virtual_fw_node': log_server_ref = LogServer.objects.first().href base_cfg = { 'name': name, 'nodes': node_list, 'domain_server_address': domain_server_list, 'log_server_ref': log_server_ref, 'physicalInterfaces': physical_interfaces} if enable_antivirus: antivirus = { 'antivirus': { 'antivirus_enabled': True, 'antivirus_update': 'daily', 'virus_log_level': 'stored', 'virus_mirror': 'update.nai.com/Products/CommonUpdater'}} base_cfg.update(antivirus) if enable_gti: gti = {'gti_settings': { 'file_reputation_context': 'gti_cloud_only'}} base_cfg.update(gti) if sidewinder_proxy_enabled: base_cfg.update(sidewinder_proxy_enabled=True) if default_nat: base_cfg.update(default_nat=True) if location_ref: base_cfg.update(location_ref=location_helper(location_ref) \ if location_ref else None) if snmp_agent: snmp_agent_ref = SNMPAgent(snmp_agent.pop('snmp_agent_ref')).href base_cfg.update( snmp_agent_ref=snmp_agent_ref, **snmp_agent) if enable_ospf: if not ospf_profile: # get default profile ospf_profile = OSPFProfile('Default OSPFv2 Profile').href ospf = {'dynamic_routing': { 'ospfv2': { 'enabled': True, 'ospfv2_profile_ref': ospf_profile} }} base_cfg.update(ospf) base_cfg.update(comment=comment) return base_cfg
Create will return the engine configuration as a dict that is a representation of the engine. The creating class will also add engine specific requirements before constructing the request and sending to SMC (which will serialize the dict to json). :param name: name of engine :param str node_type: comes from class attribute of engine type :param dict physical_interfaces: physical interface list of dict :param int nodes: number of nodes for engine :param str log_server_ref: href of log server :param list domain_server_address: dns addresses
Below is the the instruction that describes the task: ### Input: Create will return the engine configuration as a dict that is a representation of the engine. The creating class will also add engine specific requirements before constructing the request and sending to SMC (which will serialize the dict to json). :param name: name of engine :param str node_type: comes from class attribute of engine type :param dict physical_interfaces: physical interface list of dict :param int nodes: number of nodes for engine :param str log_server_ref: href of log server :param list domain_server_address: dns addresses ### Response: def _create(cls, name, node_type, physical_interfaces, nodes=1, loopback_ndi=None, log_server_ref=None, domain_server_address=None, enable_antivirus=False, enable_gti=False, sidewinder_proxy_enabled=False, default_nat=False, location_ref=None, enable_ospf=None, ospf_profile=None, snmp_agent=None, comment=None): """ Create will return the engine configuration as a dict that is a representation of the engine. The creating class will also add engine specific requirements before constructing the request and sending to SMC (which will serialize the dict to json). :param name: name of engine :param str node_type: comes from class attribute of engine type :param dict physical_interfaces: physical interface list of dict :param int nodes: number of nodes for engine :param str log_server_ref: href of log server :param list domain_server_address: dns addresses """ node_list = [] for nodeid in range(1, nodes + 1): # start at nodeid=1 node_list.append(Node._create( name, node_type, nodeid, loopback_ndi)) domain_server_list = [] if domain_server_address: for num, server in enumerate(domain_server_address): try: domain_server = {'rank': num, 'ne_ref' : server.href} except AttributeError: domain_server = {'rank': num, 'value': server} domain_server_list.append(domain_server) # Set log server reference, if not explicitly provided if not log_server_ref and node_type is not 'virtual_fw_node': log_server_ref = LogServer.objects.first().href base_cfg = { 'name': name, 'nodes': node_list, 'domain_server_address': domain_server_list, 'log_server_ref': log_server_ref, 'physicalInterfaces': physical_interfaces} if enable_antivirus: antivirus = { 'antivirus': { 'antivirus_enabled': True, 'antivirus_update': 'daily', 'virus_log_level': 'stored', 'virus_mirror': 'update.nai.com/Products/CommonUpdater'}} base_cfg.update(antivirus) if enable_gti: gti = {'gti_settings': { 'file_reputation_context': 'gti_cloud_only'}} base_cfg.update(gti) if sidewinder_proxy_enabled: base_cfg.update(sidewinder_proxy_enabled=True) if default_nat: base_cfg.update(default_nat=True) if location_ref: base_cfg.update(location_ref=location_helper(location_ref) \ if location_ref else None) if snmp_agent: snmp_agent_ref = SNMPAgent(snmp_agent.pop('snmp_agent_ref')).href base_cfg.update( snmp_agent_ref=snmp_agent_ref, **snmp_agent) if enable_ospf: if not ospf_profile: # get default profile ospf_profile = OSPFProfile('Default OSPFv2 Profile').href ospf = {'dynamic_routing': { 'ospfv2': { 'enabled': True, 'ospfv2_profile_ref': ospf_profile} }} base_cfg.update(ospf) base_cfg.update(comment=comment) return base_cfg
def authorize_download(dataset_name=None): """Check with the user that the are happy with terms and conditions for the data set.""" print(('Acquiring resource: ' + dataset_name)) # TODO, check resource is in dictionary! print('') dr = data_resources[dataset_name] print('Details of data: ') print((dr['details'])) print('') if dr['citation']: print('Please cite:') print((dr['citation'])) print('') if dr['size']: print(('After downloading the data will take up ' + str(dr['size']) + ' bytes of space.')) print('') print(('Data will be stored in ' + os.path.join(data_path, dataset_name) + '.')) print('') if overide_manual_authorize: if dr['license']: print('You have agreed to the following license:') print((dr['license'])) print('') return True else: if dr['license']: print('You must also agree to the following license:') print((dr['license'])) print('') return prompt_user('Do you wish to proceed with the download? [yes/no]')
Check with the user that the are happy with terms and conditions for the data set.
Below is the the instruction that describes the task: ### Input: Check with the user that the are happy with terms and conditions for the data set. ### Response: def authorize_download(dataset_name=None): """Check with the user that the are happy with terms and conditions for the data set.""" print(('Acquiring resource: ' + dataset_name)) # TODO, check resource is in dictionary! print('') dr = data_resources[dataset_name] print('Details of data: ') print((dr['details'])) print('') if dr['citation']: print('Please cite:') print((dr['citation'])) print('') if dr['size']: print(('After downloading the data will take up ' + str(dr['size']) + ' bytes of space.')) print('') print(('Data will be stored in ' + os.path.join(data_path, dataset_name) + '.')) print('') if overide_manual_authorize: if dr['license']: print('You have agreed to the following license:') print((dr['license'])) print('') return True else: if dr['license']: print('You must also agree to the following license:') print((dr['license'])) print('') return prompt_user('Do you wish to proceed with the download? [yes/no]')
def verify_path(self, courseid, taskid, path, new_path=False): """ Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed """ task_fs = self.task_factory.get_task_fs(courseid, taskid) # verify that the dir exists if not task_fs.exists(): return None # all path given to this part of the application must start with a "/", let's remove it if not path.startswith("/"): return None path = path[1:len(path)] if ".." in path: return None if task_fs.exists(path) == new_path: return None # do not allow touching the task.* file if os.path.splitext(path)[0] == "task" and os.path.splitext(path)[1][1:] in \ self.task_factory.get_available_task_file_extensions(): return None # do not allow hidden dir/files if path != ".": for i in path.split(os.path.sep): if i.startswith("."): return None return path
Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed
Below is the the instruction that describes the task: ### Input: Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed ### Response: def verify_path(self, courseid, taskid, path, new_path=False): """ Return the real wanted path (relative to the INGInious root) or None if the path is not valid/allowed """ task_fs = self.task_factory.get_task_fs(courseid, taskid) # verify that the dir exists if not task_fs.exists(): return None # all path given to this part of the application must start with a "/", let's remove it if not path.startswith("/"): return None path = path[1:len(path)] if ".." in path: return None if task_fs.exists(path) == new_path: return None # do not allow touching the task.* file if os.path.splitext(path)[0] == "task" and os.path.splitext(path)[1][1:] in \ self.task_factory.get_available_task_file_extensions(): return None # do not allow hidden dir/files if path != ".": for i in path.split(os.path.sep): if i.startswith("."): return None return path
async def _window_open(self, stream_id: int): """Wait until the identified stream's flow control window is open. """ stream = self._get_stream(stream_id) return await stream.window_open.wait()
Wait until the identified stream's flow control window is open.
Below is the the instruction that describes the task: ### Input: Wait until the identified stream's flow control window is open. ### Response: async def _window_open(self, stream_id: int): """Wait until the identified stream's flow control window is open. """ stream = self._get_stream(stream_id) return await stream.window_open.wait()
def df2list(df): """ Convert a MultiIndex df to list Parameters ---------- df : pandas.DataFrame A MultiIndex DataFrame where the first level is subjects and the second level is lists (e.g. egg.pres) Returns ---------- lst : a list of lists of lists of values The input df reformatted as a list """ subjects = df.index.levels[0].values.tolist() lists = df.index.levels[1].values.tolist() idx = pd.IndexSlice df = df.loc[idx[subjects,lists],df.columns] lst = [df.loc[sub,:].values.tolist() for sub in subjects] return lst
Convert a MultiIndex df to list Parameters ---------- df : pandas.DataFrame A MultiIndex DataFrame where the first level is subjects and the second level is lists (e.g. egg.pres) Returns ---------- lst : a list of lists of lists of values The input df reformatted as a list
Below is the the instruction that describes the task: ### Input: Convert a MultiIndex df to list Parameters ---------- df : pandas.DataFrame A MultiIndex DataFrame where the first level is subjects and the second level is lists (e.g. egg.pres) Returns ---------- lst : a list of lists of lists of values The input df reformatted as a list ### Response: def df2list(df): """ Convert a MultiIndex df to list Parameters ---------- df : pandas.DataFrame A MultiIndex DataFrame where the first level is subjects and the second level is lists (e.g. egg.pres) Returns ---------- lst : a list of lists of lists of values The input df reformatted as a list """ subjects = df.index.levels[0].values.tolist() lists = df.index.levels[1].values.tolist() idx = pd.IndexSlice df = df.loc[idx[subjects,lists],df.columns] lst = [df.loc[sub,:].values.tolist() for sub in subjects] return lst
def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs): """Return optimised pore diameter and it's COM.""" args = elements, coordinates if com is not None: pass else: com = center_of_mass(elements, coordinates) if bounds is None: pore_r = pore_diameter(elements, coordinates, com=com)[0] / 2 bounds = ( (com[0]-pore_r, com[0]+pore_r), (com[1]-pore_r, com[1]+pore_r), (com[2]-pore_r, com[2]+pore_r) ) minimisation = minimize( correct_pore_diameter, x0=com, args=args, bounds=bounds) pored = pore_diameter(elements, coordinates, com=minimisation.x) return (pored[0], pored[1], minimisation.x)
Return optimised pore diameter and it's COM.
Below is the the instruction that describes the task: ### Input: Return optimised pore diameter and it's COM. ### Response: def opt_pore_diameter(elements, coordinates, bounds=None, com=None, **kwargs): """Return optimised pore diameter and it's COM.""" args = elements, coordinates if com is not None: pass else: com = center_of_mass(elements, coordinates) if bounds is None: pore_r = pore_diameter(elements, coordinates, com=com)[0] / 2 bounds = ( (com[0]-pore_r, com[0]+pore_r), (com[1]-pore_r, com[1]+pore_r), (com[2]-pore_r, com[2]+pore_r) ) minimisation = minimize( correct_pore_diameter, x0=com, args=args, bounds=bounds) pored = pore_diameter(elements, coordinates, com=minimisation.x) return (pored[0], pored[1], minimisation.x)
def mul(self, T): r'''Computes liquid viscosity at a specified temperature of an organic compound using the Joback method as a function of chemical structure only. .. math:: \mu_{liq} = \text{MW} \exp\left( \frac{ \sum_i \mu_a - 597.82}{T} + \sum_i \mu_b - 11.202 \right) Parameters ---------- T : float Temperature, [K] Returns ------- mul : float Liquid viscosity, [Pa*s] Examples -------- >>> J = Joback('CC(=O)C') >>> J.mul(300) 0.0002940378347162687 ''' if self.calculated_mul_coeffs is None: self.calculated_mul_coeffs = Joback.mul_coeffs(self.counts) a, b = self.calculated_mul_coeffs return self.MW*exp(a/T + b)
r'''Computes liquid viscosity at a specified temperature of an organic compound using the Joback method as a function of chemical structure only. .. math:: \mu_{liq} = \text{MW} \exp\left( \frac{ \sum_i \mu_a - 597.82}{T} + \sum_i \mu_b - 11.202 \right) Parameters ---------- T : float Temperature, [K] Returns ------- mul : float Liquid viscosity, [Pa*s] Examples -------- >>> J = Joback('CC(=O)C') >>> J.mul(300) 0.0002940378347162687
Below is the the instruction that describes the task: ### Input: r'''Computes liquid viscosity at a specified temperature of an organic compound using the Joback method as a function of chemical structure only. .. math:: \mu_{liq} = \text{MW} \exp\left( \frac{ \sum_i \mu_a - 597.82}{T} + \sum_i \mu_b - 11.202 \right) Parameters ---------- T : float Temperature, [K] Returns ------- mul : float Liquid viscosity, [Pa*s] Examples -------- >>> J = Joback('CC(=O)C') >>> J.mul(300) 0.0002940378347162687 ### Response: def mul(self, T): r'''Computes liquid viscosity at a specified temperature of an organic compound using the Joback method as a function of chemical structure only. .. math:: \mu_{liq} = \text{MW} \exp\left( \frac{ \sum_i \mu_a - 597.82}{T} + \sum_i \mu_b - 11.202 \right) Parameters ---------- T : float Temperature, [K] Returns ------- mul : float Liquid viscosity, [Pa*s] Examples -------- >>> J = Joback('CC(=O)C') >>> J.mul(300) 0.0002940378347162687 ''' if self.calculated_mul_coeffs is None: self.calculated_mul_coeffs = Joback.mul_coeffs(self.counts) a, b = self.calculated_mul_coeffs return self.MW*exp(a/T + b)
def find_chunks(self, tokens, **kwargs): """ Annotates the given list of tokens with chunk tags. Several tags can be added, for example chunk + preposition tags. """ # [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] => # [["The", "DT", "B-NP"], ["cat", "NN", "I-NP"], ["purs", "VB", "B-VP"]] return find_prepositions( find_chunks(tokens, language = kwargs.get("language", self.language)))
Annotates the given list of tokens with chunk tags. Several tags can be added, for example chunk + preposition tags.
Below is the the instruction that describes the task: ### Input: Annotates the given list of tokens with chunk tags. Several tags can be added, for example chunk + preposition tags. ### Response: def find_chunks(self, tokens, **kwargs): """ Annotates the given list of tokens with chunk tags. Several tags can be added, for example chunk + preposition tags. """ # [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] => # [["The", "DT", "B-NP"], ["cat", "NN", "I-NP"], ["purs", "VB", "B-VP"]] return find_prepositions( find_chunks(tokens, language = kwargs.get("language", self.language)))
def _minion_event(self, load): ''' Receive an event from the minion and fire it on the master event interface ''' if 'id' not in load: return False if 'events' not in load and ('tag' not in load or 'data' not in load): return False if 'events' in load: for event in load['events']: if 'data' in event: event_data = event['data'] else: event_data = event self.event.fire_event(event_data, event['tag']) # old dup event if load.get('pretag') is not None: self.event.fire_event(event_data, salt.utils.event.tagify(event['tag'], base=load['pretag'])) else: tag = load['tag'] self.event.fire_event(load, tag) return True
Receive an event from the minion and fire it on the master event interface
Below is the the instruction that describes the task: ### Input: Receive an event from the minion and fire it on the master event interface ### Response: def _minion_event(self, load): ''' Receive an event from the minion and fire it on the master event interface ''' if 'id' not in load: return False if 'events' not in load and ('tag' not in load or 'data' not in load): return False if 'events' in load: for event in load['events']: if 'data' in event: event_data = event['data'] else: event_data = event self.event.fire_event(event_data, event['tag']) # old dup event if load.get('pretag') is not None: self.event.fire_event(event_data, salt.utils.event.tagify(event['tag'], base=load['pretag'])) else: tag = load['tag'] self.event.fire_event(load, tag) return True
def readXML(self): """ Reads an xml object from the stream. @return: An etree interface compatible object @see: L{xml.set_default_interface} """ ref = self.readInteger(False) if ref & REFERENCE_BIT == 0: return self.context.getObject(ref >> 1) xmlstring = self.stream.read(ref >> 1) x = xml.fromstring(xmlstring) self.context.addObject(x) return x
Reads an xml object from the stream. @return: An etree interface compatible object @see: L{xml.set_default_interface}
Below is the the instruction that describes the task: ### Input: Reads an xml object from the stream. @return: An etree interface compatible object @see: L{xml.set_default_interface} ### Response: def readXML(self): """ Reads an xml object from the stream. @return: An etree interface compatible object @see: L{xml.set_default_interface} """ ref = self.readInteger(False) if ref & REFERENCE_BIT == 0: return self.context.getObject(ref >> 1) xmlstring = self.stream.read(ref >> 1) x = xml.fromstring(xmlstring) self.context.addObject(x) return x
def pause(self, queue_name, kw_in=None, kw_out=None, kw_all=None, kw_none=None, kw_state=None, kw_bcast=None): """ Pause a queue. Unfortunately, the PAUSE keywords are mostly reserved words in Python, so I've been a little creative in the function variable names. Open to suggestions to change it (canardleteer) :param queue_name: The job queue we are modifying. :param kw_in: pause the queue in input. :param kw_out: pause the queue in output. :param kw_all: pause the queue in input and output (same as specifying both the in and out options). :param kw_none: clear the paused state in input and output. :param kw_state: just report the current queue state. :param kw_bcast: send a PAUSE command to all the reachable nodes of the cluster to set the same queue in the other nodes to the same state. """ command = ["PAUSE", queue_name] if kw_in: command += ["in"] if kw_out: command += ["out"] if kw_all: command += ["all"] if kw_none: command += ["none"] if kw_state: command += ["state"] if kw_bcast: command += ["bcast"] return self.execute_command(*command)
Pause a queue. Unfortunately, the PAUSE keywords are mostly reserved words in Python, so I've been a little creative in the function variable names. Open to suggestions to change it (canardleteer) :param queue_name: The job queue we are modifying. :param kw_in: pause the queue in input. :param kw_out: pause the queue in output. :param kw_all: pause the queue in input and output (same as specifying both the in and out options). :param kw_none: clear the paused state in input and output. :param kw_state: just report the current queue state. :param kw_bcast: send a PAUSE command to all the reachable nodes of the cluster to set the same queue in the other nodes to the same state.
Below is the the instruction that describes the task: ### Input: Pause a queue. Unfortunately, the PAUSE keywords are mostly reserved words in Python, so I've been a little creative in the function variable names. Open to suggestions to change it (canardleteer) :param queue_name: The job queue we are modifying. :param kw_in: pause the queue in input. :param kw_out: pause the queue in output. :param kw_all: pause the queue in input and output (same as specifying both the in and out options). :param kw_none: clear the paused state in input and output. :param kw_state: just report the current queue state. :param kw_bcast: send a PAUSE command to all the reachable nodes of the cluster to set the same queue in the other nodes to the same state. ### Response: def pause(self, queue_name, kw_in=None, kw_out=None, kw_all=None, kw_none=None, kw_state=None, kw_bcast=None): """ Pause a queue. Unfortunately, the PAUSE keywords are mostly reserved words in Python, so I've been a little creative in the function variable names. Open to suggestions to change it (canardleteer) :param queue_name: The job queue we are modifying. :param kw_in: pause the queue in input. :param kw_out: pause the queue in output. :param kw_all: pause the queue in input and output (same as specifying both the in and out options). :param kw_none: clear the paused state in input and output. :param kw_state: just report the current queue state. :param kw_bcast: send a PAUSE command to all the reachable nodes of the cluster to set the same queue in the other nodes to the same state. """ command = ["PAUSE", queue_name] if kw_in: command += ["in"] if kw_out: command += ["out"] if kw_all: command += ["all"] if kw_none: command += ["none"] if kw_state: command += ["state"] if kw_bcast: command += ["bcast"] return self.execute_command(*command)
def update(self, **kwargs): """ Update the project :param kwargs: Project properties """ old_json = self.__json__() for prop in kwargs: setattr(self, prop, kwargs[prop]) # We send notif only if object has changed if old_json != self.__json__(): self.controller.notification.emit("project.updated", self.__json__()) self.dump()
Update the project :param kwargs: Project properties
Below is the the instruction that describes the task: ### Input: Update the project :param kwargs: Project properties ### Response: def update(self, **kwargs): """ Update the project :param kwargs: Project properties """ old_json = self.__json__() for prop in kwargs: setattr(self, prop, kwargs[prop]) # We send notif only if object has changed if old_json != self.__json__(): self.controller.notification.emit("project.updated", self.__json__()) self.dump()
def find_build_id(each_line,temp_func_list): """ Find the build id of a jenkins job. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again. Parameters ---------- each_line : str contains a line read in from jenkins console temp_func_list : list of Python function handles contains a list of functions that we want to invoke to extract information from the Jenkins console text. :return: bool to determine if text mining should continue on the jenkins console text """ global g_before_java_file global g_java_filenames global g_build_id_text global g_jenkins_url global g_output_filename global g_output_pickle_filename if g_build_id_text in each_line: [startStr,found,endStr] = each_line.partition(g_build_id_text) g_failed_test_info_dict["2.build_id"] = endStr.strip() temp_func_list.remove(find_build_id) g_jenkins_url = os.path.join('http://',g_jenkins_url,'view',g_view_name,'job',g_failed_test_info_dict["1.jobName"],g_failed_test_info_dict["2.build_id"],'artifact') return True
Find the build id of a jenkins job. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again. Parameters ---------- each_line : str contains a line read in from jenkins console temp_func_list : list of Python function handles contains a list of functions that we want to invoke to extract information from the Jenkins console text. :return: bool to determine if text mining should continue on the jenkins console text
Below is the the instruction that describes the task: ### Input: Find the build id of a jenkins job. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again. Parameters ---------- each_line : str contains a line read in from jenkins console temp_func_list : list of Python function handles contains a list of functions that we want to invoke to extract information from the Jenkins console text. :return: bool to determine if text mining should continue on the jenkins console text ### Response: def find_build_id(each_line,temp_func_list): """ Find the build id of a jenkins job. It will save this information in g_failed_test_info_dict. In addition, it will delete this particular function handle off the temp_func_list as we do not need to perform this action again. Parameters ---------- each_line : str contains a line read in from jenkins console temp_func_list : list of Python function handles contains a list of functions that we want to invoke to extract information from the Jenkins console text. :return: bool to determine if text mining should continue on the jenkins console text """ global g_before_java_file global g_java_filenames global g_build_id_text global g_jenkins_url global g_output_filename global g_output_pickle_filename if g_build_id_text in each_line: [startStr,found,endStr] = each_line.partition(g_build_id_text) g_failed_test_info_dict["2.build_id"] = endStr.strip() temp_func_list.remove(find_build_id) g_jenkins_url = os.path.join('http://',g_jenkins_url,'view',g_view_name,'job',g_failed_test_info_dict["1.jobName"],g_failed_test_info_dict["2.build_id"],'artifact') return True
def inverse_transform(self, X, copy=None): """ Scale back the data to the original representation. :param X: Scaled data matrix. :type X: numpy.ndarray, shape [n_samples, n_features] :param bool copy: Copy the X data matrix. :return: X data matrix with the scaling operation reverted. :rtype: numpy.ndarray, shape [n_samples, n_features] """ check_is_fitted(self, 'scale_') copy = copy if copy is not None else self.copy if sparse.issparse(X): if self.with_mean: raise ValueError( "Cannot uncenter sparse matrices: pass `with_mean=False` " "instead See docstring for motivation and alternatives.") if not sparse.isspmatrix_csr(X): X = X.tocsr() copy = False if copy: X = X.copy() if self.scale_ is not None: inplace_column_scale(X, self.scale_) else: X = numpy.asarray(X) if copy: X = X.copy() if self.with_std: X *= self.scale_ if self.with_mean: X += self.mean_ return X
Scale back the data to the original representation. :param X: Scaled data matrix. :type X: numpy.ndarray, shape [n_samples, n_features] :param bool copy: Copy the X data matrix. :return: X data matrix with the scaling operation reverted. :rtype: numpy.ndarray, shape [n_samples, n_features]
Below is the the instruction that describes the task: ### Input: Scale back the data to the original representation. :param X: Scaled data matrix. :type X: numpy.ndarray, shape [n_samples, n_features] :param bool copy: Copy the X data matrix. :return: X data matrix with the scaling operation reverted. :rtype: numpy.ndarray, shape [n_samples, n_features] ### Response: def inverse_transform(self, X, copy=None): """ Scale back the data to the original representation. :param X: Scaled data matrix. :type X: numpy.ndarray, shape [n_samples, n_features] :param bool copy: Copy the X data matrix. :return: X data matrix with the scaling operation reverted. :rtype: numpy.ndarray, shape [n_samples, n_features] """ check_is_fitted(self, 'scale_') copy = copy if copy is not None else self.copy if sparse.issparse(X): if self.with_mean: raise ValueError( "Cannot uncenter sparse matrices: pass `with_mean=False` " "instead See docstring for motivation and alternatives.") if not sparse.isspmatrix_csr(X): X = X.tocsr() copy = False if copy: X = X.copy() if self.scale_ is not None: inplace_column_scale(X, self.scale_) else: X = numpy.asarray(X) if copy: X = X.copy() if self.with_std: X *= self.scale_ if self.with_mean: X += self.mean_ return X
def assess_car_t_validity(job, gene_expression, univ_options, reports_options): """ This function creates a report on the available clinical trials and scientific literature available for the overexpressed genes in the specified tumor type. It also gives a list of clinical trials available for other types of cancer with the same overexpressed gene. :param toil.fileStore.FileID gene_expression: The resm gene expression :param dict univ_options: Dict of universal options used by almost all tools :param dict reports_options: Options specific to reporting modules :return: The results of running assess_car_t_validity :rtype: toil.fileStore.FileID """ work_dir = os.getcwd() tumor_type = univ_options['tumor_type'] input_files = { 'rsem_quant.tsv': gene_expression, 'car_t_targets.tsv.tar.gz': reports_options['car_t_targets_file']} input_files = get_files_from_filestore(job, input_files, work_dir, docker=False) input_files['car_t_targets.tsv'] = untargz(input_files['car_t_targets.tsv.tar.gz'], work_dir) target_data = pd.read_table(input_files['car_t_targets.tsv'], index_col=0) patient_df = pd.read_csv('rsem_quant.tsv', sep=' ', delimiter='\t', header='infer', index_col=0) patient_df.index = (patient_df.index).str.replace('\\..*$', '') overexpressed = [] # Check if the tumor has a corresponding normal try: tissue_of_origin = TCGAToGTEx[tumor_type] except KeyError: tissue_of_origin = 'NA' # Write the report with open('car_t_target_report.txt', 'w') as car_t_report: #print(target_data.index, file=car_t_report) if tissue_of_origin in target_data.index: print('Available clinical trials for ' + str.lower(tissue_of_origin) + ' cancer with GTEX and TCGA median values', file=car_t_report) print(('\t{:10}{:<10}{:<10}{:<10}{:<40}{:<12}\n'.format('Gene', 'GTEX', 'TCGA N', 'Observed', 'DOI for gene papers', 'Clinical Trials')), file=car_t_report) collected_values = [] # Get the gene name, GTEX, TCGA, and observed values for index, row in target_data.iterrows(): if index == tissue_of_origin: gene = row['ENSG'] gtex = '{0:.2f}'.format(float(row['GTEX'])) tcga = '{0:.2f}'.format(float(row['TCGA'])) observed = '{0:.2f}'.format( float(patient_df.loc[gene, 'TPM'])) if gene in patient_df.index else 'NA' doi = row['DOI'] target = str.upper(row['TARGET']) clinical_trial = row['Clinical trials'] collection = [target, gtex, tcga, observed, doi, clinical_trial] collected_values.append(collection) if observed != 'NA': if float(gtex) <= float(observed) or float(tcga) <= float(observed): overexpressed.append(gene) collected_values = sorted(collected_values, key=lambda col: float(col[3]), reverse=True) for entry in collected_values: print(('\t{:10}{:<10}{:<10}{:<10}{:<40}{:<12}'.format(entry[0], entry[1], entry[2], str(entry[3]), entry[4], entry[5])), file=car_t_report) print('\nBased on the genes overexpressed in this cancer type, here\'s a list of clinical ' 'trials for other types of cancer', file=car_t_report) if len(overexpressed) != 0: # Check if there are other clinical trials for other cancer types print(('\t{:10}{:<10}{:<10}{:<10}{:<40}{:<17}{:<20}\n'.format('Gene', 'GTEX', 'TCGA N', 'Observed', 'DOI for gene papers', 'Clinical Trials', 'Cancer')), file=car_t_report) other_trials = [] for index, row in target_data.iterrows(): if row['ENSG'] in overexpressed and index != tissue_of_origin: gene = row['ENSG'] gtex = '{0:.2f}'.format(float(row['GTEX'])) tcga = '{0:.2f}'.format(float(row['TCGA'])) doi = row['DOI'] target = str.upper(row['TARGET']) observed = '{0:.2f}'.format( float(patient_df.loc[gene, 'TPM'])) if gene in patient_df.index else 'NA' collected_values = [target, gtex, tcga, observed, doi, row['Clinical trials'], index] other_trials.append(collected_values) other_trials = sorted(other_trials, key=lambda col: col[0]) for entry in other_trials: print(('\t{:10}{:<10}{:<10}{:<10}{:<40}{:<17}{:<20}'.format(entry[0], entry[1], entry[2], entry[3], entry[4], entry[5], entry[6])), file=car_t_report) else: print("Data not available", file=car_t_report) else: print('Data not available for ' + tumor_type, file=car_t_report) output_file = job.fileStore.writeGlobalFile(car_t_report.name) export_results(job, output_file, car_t_report.name, univ_options, subfolder='reports') job.fileStore.logToMaster('Ran car t validity assessment on %s successfully' % univ_options['patient']) return output_file
This function creates a report on the available clinical trials and scientific literature available for the overexpressed genes in the specified tumor type. It also gives a list of clinical trials available for other types of cancer with the same overexpressed gene. :param toil.fileStore.FileID gene_expression: The resm gene expression :param dict univ_options: Dict of universal options used by almost all tools :param dict reports_options: Options specific to reporting modules :return: The results of running assess_car_t_validity :rtype: toil.fileStore.FileID
Below is the the instruction that describes the task: ### Input: This function creates a report on the available clinical trials and scientific literature available for the overexpressed genes in the specified tumor type. It also gives a list of clinical trials available for other types of cancer with the same overexpressed gene. :param toil.fileStore.FileID gene_expression: The resm gene expression :param dict univ_options: Dict of universal options used by almost all tools :param dict reports_options: Options specific to reporting modules :return: The results of running assess_car_t_validity :rtype: toil.fileStore.FileID ### Response: def assess_car_t_validity(job, gene_expression, univ_options, reports_options): """ This function creates a report on the available clinical trials and scientific literature available for the overexpressed genes in the specified tumor type. It also gives a list of clinical trials available for other types of cancer with the same overexpressed gene. :param toil.fileStore.FileID gene_expression: The resm gene expression :param dict univ_options: Dict of universal options used by almost all tools :param dict reports_options: Options specific to reporting modules :return: The results of running assess_car_t_validity :rtype: toil.fileStore.FileID """ work_dir = os.getcwd() tumor_type = univ_options['tumor_type'] input_files = { 'rsem_quant.tsv': gene_expression, 'car_t_targets.tsv.tar.gz': reports_options['car_t_targets_file']} input_files = get_files_from_filestore(job, input_files, work_dir, docker=False) input_files['car_t_targets.tsv'] = untargz(input_files['car_t_targets.tsv.tar.gz'], work_dir) target_data = pd.read_table(input_files['car_t_targets.tsv'], index_col=0) patient_df = pd.read_csv('rsem_quant.tsv', sep=' ', delimiter='\t', header='infer', index_col=0) patient_df.index = (patient_df.index).str.replace('\\..*$', '') overexpressed = [] # Check if the tumor has a corresponding normal try: tissue_of_origin = TCGAToGTEx[tumor_type] except KeyError: tissue_of_origin = 'NA' # Write the report with open('car_t_target_report.txt', 'w') as car_t_report: #print(target_data.index, file=car_t_report) if tissue_of_origin in target_data.index: print('Available clinical trials for ' + str.lower(tissue_of_origin) + ' cancer with GTEX and TCGA median values', file=car_t_report) print(('\t{:10}{:<10}{:<10}{:<10}{:<40}{:<12}\n'.format('Gene', 'GTEX', 'TCGA N', 'Observed', 'DOI for gene papers', 'Clinical Trials')), file=car_t_report) collected_values = [] # Get the gene name, GTEX, TCGA, and observed values for index, row in target_data.iterrows(): if index == tissue_of_origin: gene = row['ENSG'] gtex = '{0:.2f}'.format(float(row['GTEX'])) tcga = '{0:.2f}'.format(float(row['TCGA'])) observed = '{0:.2f}'.format( float(patient_df.loc[gene, 'TPM'])) if gene in patient_df.index else 'NA' doi = row['DOI'] target = str.upper(row['TARGET']) clinical_trial = row['Clinical trials'] collection = [target, gtex, tcga, observed, doi, clinical_trial] collected_values.append(collection) if observed != 'NA': if float(gtex) <= float(observed) or float(tcga) <= float(observed): overexpressed.append(gene) collected_values = sorted(collected_values, key=lambda col: float(col[3]), reverse=True) for entry in collected_values: print(('\t{:10}{:<10}{:<10}{:<10}{:<40}{:<12}'.format(entry[0], entry[1], entry[2], str(entry[3]), entry[4], entry[5])), file=car_t_report) print('\nBased on the genes overexpressed in this cancer type, here\'s a list of clinical ' 'trials for other types of cancer', file=car_t_report) if len(overexpressed) != 0: # Check if there are other clinical trials for other cancer types print(('\t{:10}{:<10}{:<10}{:<10}{:<40}{:<17}{:<20}\n'.format('Gene', 'GTEX', 'TCGA N', 'Observed', 'DOI for gene papers', 'Clinical Trials', 'Cancer')), file=car_t_report) other_trials = [] for index, row in target_data.iterrows(): if row['ENSG'] in overexpressed and index != tissue_of_origin: gene = row['ENSG'] gtex = '{0:.2f}'.format(float(row['GTEX'])) tcga = '{0:.2f}'.format(float(row['TCGA'])) doi = row['DOI'] target = str.upper(row['TARGET']) observed = '{0:.2f}'.format( float(patient_df.loc[gene, 'TPM'])) if gene in patient_df.index else 'NA' collected_values = [target, gtex, tcga, observed, doi, row['Clinical trials'], index] other_trials.append(collected_values) other_trials = sorted(other_trials, key=lambda col: col[0]) for entry in other_trials: print(('\t{:10}{:<10}{:<10}{:<10}{:<40}{:<17}{:<20}'.format(entry[0], entry[1], entry[2], entry[3], entry[4], entry[5], entry[6])), file=car_t_report) else: print("Data not available", file=car_t_report) else: print('Data not available for ' + tumor_type, file=car_t_report) output_file = job.fileStore.writeGlobalFile(car_t_report.name) export_results(job, output_file, car_t_report.name, univ_options, subfolder='reports') job.fileStore.logToMaster('Ran car t validity assessment on %s successfully' % univ_options['patient']) return output_file
def _self_time(self): """Returns the time spent in this workunit outside of any children.""" return self.duration() - sum([child.duration() for child in self.children])
Returns the time spent in this workunit outside of any children.
Below is the the instruction that describes the task: ### Input: Returns the time spent in this workunit outside of any children. ### Response: def _self_time(self): """Returns the time spent in this workunit outside of any children.""" return self.duration() - sum([child.duration() for child in self.children])
def headerData(self, section, orientation, role=Qt.DisplayRole): """ Return the header depending on section, orientation and Qt::ItemDataRole Args: section (int): For horizontal headers, the section number corresponds to the column number. Similarly, for vertical headers, the section number corresponds to the row number. orientation (Qt::Orientations): role (Qt::ItemDataRole): Returns: None if not Qt.DisplayRole _dataFrame.columns.tolist()[section] if orientation == Qt.Horizontal section if orientation == Qt.Vertical None if horizontal orientation and section raises IndexError """ if role != Qt.DisplayRole: return None if orientation == Qt.Horizontal: try: label = self._dataFrame.columns.tolist()[section] if label == section: label = section return label except (IndexError, ): return None elif orientation == Qt.Vertical: return section
Return the header depending on section, orientation and Qt::ItemDataRole Args: section (int): For horizontal headers, the section number corresponds to the column number. Similarly, for vertical headers, the section number corresponds to the row number. orientation (Qt::Orientations): role (Qt::ItemDataRole): Returns: None if not Qt.DisplayRole _dataFrame.columns.tolist()[section] if orientation == Qt.Horizontal section if orientation == Qt.Vertical None if horizontal orientation and section raises IndexError
Below is the the instruction that describes the task: ### Input: Return the header depending on section, orientation and Qt::ItemDataRole Args: section (int): For horizontal headers, the section number corresponds to the column number. Similarly, for vertical headers, the section number corresponds to the row number. orientation (Qt::Orientations): role (Qt::ItemDataRole): Returns: None if not Qt.DisplayRole _dataFrame.columns.tolist()[section] if orientation == Qt.Horizontal section if orientation == Qt.Vertical None if horizontal orientation and section raises IndexError ### Response: def headerData(self, section, orientation, role=Qt.DisplayRole): """ Return the header depending on section, orientation and Qt::ItemDataRole Args: section (int): For horizontal headers, the section number corresponds to the column number. Similarly, for vertical headers, the section number corresponds to the row number. orientation (Qt::Orientations): role (Qt::ItemDataRole): Returns: None if not Qt.DisplayRole _dataFrame.columns.tolist()[section] if orientation == Qt.Horizontal section if orientation == Qt.Vertical None if horizontal orientation and section raises IndexError """ if role != Qt.DisplayRole: return None if orientation == Qt.Horizontal: try: label = self._dataFrame.columns.tolist()[section] if label == section: label = section return label except (IndexError, ): return None elif orientation == Qt.Vertical: return section
def wsgiheader(self): ''' Returns a wsgi conform list of header/value pairs. ''' for c in self.COOKIES.values(): if c.OutputString() not in self.headers.getall('Set-Cookie'): self.headers.append('Set-Cookie', c.OutputString()) # rfc2616 section 10.2.3, 10.3.5 if self.status in (204, 304) and 'content-type' in self.headers: del self.headers['content-type'] if self.status == 304: for h in ('allow', 'content-encoding', 'content-language', 'content-length', 'content-md5', 'content-range', 'content-type', 'last-modified'): # + c-location, expires? if h in self.headers: del self.headers[h] return list(self.headers.iterallitems())
Returns a wsgi conform list of header/value pairs.
Below is the the instruction that describes the task: ### Input: Returns a wsgi conform list of header/value pairs. ### Response: def wsgiheader(self): ''' Returns a wsgi conform list of header/value pairs. ''' for c in self.COOKIES.values(): if c.OutputString() not in self.headers.getall('Set-Cookie'): self.headers.append('Set-Cookie', c.OutputString()) # rfc2616 section 10.2.3, 10.3.5 if self.status in (204, 304) and 'content-type' in self.headers: del self.headers['content-type'] if self.status == 304: for h in ('allow', 'content-encoding', 'content-language', 'content-length', 'content-md5', 'content-range', 'content-type', 'last-modified'): # + c-location, expires? if h in self.headers: del self.headers[h] return list(self.headers.iterallitems())
def read_csv(filepath): """ Read a CSV into a list of dictionarys. The first line of the CSV determines the keys of the dictionary. Parameters ---------- filepath : string Returns ------- list of dictionaries """ symbols = [] with open(filepath, 'rb') as csvfile: spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='"') for row in spamreader: symbols.append(row) return symbols
Read a CSV into a list of dictionarys. The first line of the CSV determines the keys of the dictionary. Parameters ---------- filepath : string Returns ------- list of dictionaries
Below is the the instruction that describes the task: ### Input: Read a CSV into a list of dictionarys. The first line of the CSV determines the keys of the dictionary. Parameters ---------- filepath : string Returns ------- list of dictionaries ### Response: def read_csv(filepath): """ Read a CSV into a list of dictionarys. The first line of the CSV determines the keys of the dictionary. Parameters ---------- filepath : string Returns ------- list of dictionaries """ symbols = [] with open(filepath, 'rb') as csvfile: spamreader = csv.DictReader(csvfile, delimiter=',', quotechar='"') for row in spamreader: symbols.append(row) return symbols
def p_program(p): """ program : line """ if p[1] is not None: [MEMORY.add_instruction(x) for x in p[1] if isinstance(x, Asm)]
program : line
Below is the the instruction that describes the task: ### Input: program : line ### Response: def p_program(p): """ program : line """ if p[1] is not None: [MEMORY.add_instruction(x) for x in p[1] if isinstance(x, Asm)]
def plot_predict(self, h=5, past_values=20, intervals=True, oos_data=None, **kwargs): """ Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) How many past observations to show on the forecast graph? intervals : Boolean Would you like to show 95% prediction intervals for the forecast? oos_data : pd.DataFrame OOS data to use; needs to be same format (columns) as original data Returns ---------- - Plot of the forecast """ import matplotlib.pyplot as plt import seaborn as sns figsize = kwargs.get('figsize',(10,7)) if self.latent_variables.estimated is False: raise Exception("No latent variables estimated!") else: # Retrieve data, dates and (transformed) latent variables scale, shape, skewness = self._get_scale_and_shape(self.latent_variables.get_z_values(transformed=True)) # Retrieve data, dates and (transformed) latent variables date_index = self.shift_dates(h) simulations = 10000 sim_vector = np.zeros([simulations,h]) _, X_oos = dmatrices(self.formula, oos_data) X_oos = np.array([X_oos])[0] full_X = self.X.copy() full_X = np.append(full_X,X_oos,axis=0) Z = full_X a = self.states # Retrieve data, dates and (transformed) latent variables smoothed_series = np.zeros(h) for t in range(h): smoothed_series[t] = self.link(np.dot(Z[self.y.shape[0]+t],a[:,-1])) for n in range(0,simulations): rnd_q = np.zeros((self.state_no,h)) coeff_sim = np.zeros((self.state_no,h)) # TO DO: vectorize this (easy) for state in range(self.state_no): rnd_q[state] = np.random.normal(0,np.sqrt(self.latent_variables.get_z_values(transformed=True)[state]),h) for t in range(0,h): if t == 0: for state in range(self.state_no): coeff_sim[state][t] = a[state][-1] + rnd_q[state][t] else: for state in range(self.state_no): coeff_sim[state][t] = coeff_sim[state][t-1] + rnd_q[state][t] sim_vector[n] = self.family.draw_variable(loc=self.link(np.sum(coeff_sim.T*Z[self.y.shape[0]:self.y.shape[0]+h,:],axis=1)),shape=shape,scale=scale,skewness=skewness,nsims=h) sim_vector = np.transpose(sim_vector) forecasted_values = smoothed_series previous_value = self.data[-1] plt.figure(figsize=figsize) if intervals == True: plt.fill_between(date_index[-h-1:], np.insert([np.percentile(i,5) for i in sim_vector],0,previous_value), np.insert([np.percentile(i,95) for i in sim_vector],0,previous_value), alpha=0.2,label="95 C.I.") plot_values = np.append(self.data[-past_values:],forecasted_values) plot_index = date_index[-h-past_values:] plt.plot(plot_index,plot_values,label=self.data_name) plt.title("Forecast for " + self.data_name) plt.xlabel("Time") plt.ylabel(self.data_name) plt.show()
Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) How many past observations to show on the forecast graph? intervals : Boolean Would you like to show 95% prediction intervals for the forecast? oos_data : pd.DataFrame OOS data to use; needs to be same format (columns) as original data Returns ---------- - Plot of the forecast
Below is the the instruction that describes the task: ### Input: Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) How many past observations to show on the forecast graph? intervals : Boolean Would you like to show 95% prediction intervals for the forecast? oos_data : pd.DataFrame OOS data to use; needs to be same format (columns) as original data Returns ---------- - Plot of the forecast ### Response: def plot_predict(self, h=5, past_values=20, intervals=True, oos_data=None, **kwargs): """ Makes forecast with the estimated model Parameters ---------- h : int (default : 5) How many steps ahead would you like to forecast? past_values : int (default : 20) How many past observations to show on the forecast graph? intervals : Boolean Would you like to show 95% prediction intervals for the forecast? oos_data : pd.DataFrame OOS data to use; needs to be same format (columns) as original data Returns ---------- - Plot of the forecast """ import matplotlib.pyplot as plt import seaborn as sns figsize = kwargs.get('figsize',(10,7)) if self.latent_variables.estimated is False: raise Exception("No latent variables estimated!") else: # Retrieve data, dates and (transformed) latent variables scale, shape, skewness = self._get_scale_and_shape(self.latent_variables.get_z_values(transformed=True)) # Retrieve data, dates and (transformed) latent variables date_index = self.shift_dates(h) simulations = 10000 sim_vector = np.zeros([simulations,h]) _, X_oos = dmatrices(self.formula, oos_data) X_oos = np.array([X_oos])[0] full_X = self.X.copy() full_X = np.append(full_X,X_oos,axis=0) Z = full_X a = self.states # Retrieve data, dates and (transformed) latent variables smoothed_series = np.zeros(h) for t in range(h): smoothed_series[t] = self.link(np.dot(Z[self.y.shape[0]+t],a[:,-1])) for n in range(0,simulations): rnd_q = np.zeros((self.state_no,h)) coeff_sim = np.zeros((self.state_no,h)) # TO DO: vectorize this (easy) for state in range(self.state_no): rnd_q[state] = np.random.normal(0,np.sqrt(self.latent_variables.get_z_values(transformed=True)[state]),h) for t in range(0,h): if t == 0: for state in range(self.state_no): coeff_sim[state][t] = a[state][-1] + rnd_q[state][t] else: for state in range(self.state_no): coeff_sim[state][t] = coeff_sim[state][t-1] + rnd_q[state][t] sim_vector[n] = self.family.draw_variable(loc=self.link(np.sum(coeff_sim.T*Z[self.y.shape[0]:self.y.shape[0]+h,:],axis=1)),shape=shape,scale=scale,skewness=skewness,nsims=h) sim_vector = np.transpose(sim_vector) forecasted_values = smoothed_series previous_value = self.data[-1] plt.figure(figsize=figsize) if intervals == True: plt.fill_between(date_index[-h-1:], np.insert([np.percentile(i,5) for i in sim_vector],0,previous_value), np.insert([np.percentile(i,95) for i in sim_vector],0,previous_value), alpha=0.2,label="95 C.I.") plot_values = np.append(self.data[-past_values:],forecasted_values) plot_index = date_index[-h-past_values:] plt.plot(plot_index,plot_values,label=self.data_name) plt.title("Forecast for " + self.data_name) plt.xlabel("Time") plt.ylabel(self.data_name) plt.show()
def _parse_attr(cls, value, package_dir=None): """Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str """ attr_directive = 'attr:' if not value.startswith(attr_directive): return value attrs_path = value.replace(attr_directive, '').strip().split('.') attr_name = attrs_path.pop() module_name = '.'.join(attrs_path) module_name = module_name or '__init__' parent_path = os.getcwd() if package_dir: if attrs_path[0] in package_dir: # A custom path was specified for the module we want to import custom_path = package_dir[attrs_path[0]] parts = custom_path.rsplit('/', 1) if len(parts) > 1: parent_path = os.path.join(os.getcwd(), parts[0]) module_name = parts[1] else: module_name = custom_path elif '' in package_dir: # A custom parent directory was specified for all root modules parent_path = os.path.join(os.getcwd(), package_dir['']) sys.path.insert(0, parent_path) try: module = import_module(module_name) value = getattr(module, attr_name) finally: sys.path = sys.path[1:] return value
Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str
Below is the the instruction that describes the task: ### Input: Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str ### Response: def _parse_attr(cls, value, package_dir=None): """Represents value as a module attribute. Examples: attr: package.attr attr: package.module.attr :param str value: :rtype: str """ attr_directive = 'attr:' if not value.startswith(attr_directive): return value attrs_path = value.replace(attr_directive, '').strip().split('.') attr_name = attrs_path.pop() module_name = '.'.join(attrs_path) module_name = module_name or '__init__' parent_path = os.getcwd() if package_dir: if attrs_path[0] in package_dir: # A custom path was specified for the module we want to import custom_path = package_dir[attrs_path[0]] parts = custom_path.rsplit('/', 1) if len(parts) > 1: parent_path = os.path.join(os.getcwd(), parts[0]) module_name = parts[1] else: module_name = custom_path elif '' in package_dir: # A custom parent directory was specified for all root modules parent_path = os.path.join(os.getcwd(), package_dir['']) sys.path.insert(0, parent_path) try: module = import_module(module_name) value = getattr(module, attr_name) finally: sys.path = sys.path[1:] return value
def waveform_stack(mediafiles, xy_size, output=None, label_style=None, center_color=None, outer_color=None, bg_color=None): """ Create a stack of waveform images from audio data. Return path to created image file. """ img_files = [] output = output or os.path.abspath(os.path.dirname(os.path.commonprefix(mediafiles))) if os.path.isdir(output): output = os.path.join(output, "waveforms.jpg") cmd = [config.CMD_IM_MONTAGE] + shlex.split(label_style or WAVE_LABEL_STYLE) cmd += ["-tile", "1x%d" % len(mediafiles), "-geometry", "%dx%d" % xy_size, "-label", "%t"] try: tempdir = tempfile.mktemp(__name__) os.makedirs(tempdir) for mediafile in sorted(mediafiles): img_files.append(waveform_image(mediafile, xy_size, tempdir, center_color, outer_color, bg_color)) cmd.extend(img_files) cmd.append(output) subprocess.check_call(cmd, stdout=open(os.devnull, "wb"), stderr=subprocess.STDOUT) finally: if os.path.isdir(tempdir): shutil.rmtree(tempdir, ignore_errors=True) return output
Create a stack of waveform images from audio data. Return path to created image file.
Below is the the instruction that describes the task: ### Input: Create a stack of waveform images from audio data. Return path to created image file. ### Response: def waveform_stack(mediafiles, xy_size, output=None, label_style=None, center_color=None, outer_color=None, bg_color=None): """ Create a stack of waveform images from audio data. Return path to created image file. """ img_files = [] output = output or os.path.abspath(os.path.dirname(os.path.commonprefix(mediafiles))) if os.path.isdir(output): output = os.path.join(output, "waveforms.jpg") cmd = [config.CMD_IM_MONTAGE] + shlex.split(label_style or WAVE_LABEL_STYLE) cmd += ["-tile", "1x%d" % len(mediafiles), "-geometry", "%dx%d" % xy_size, "-label", "%t"] try: tempdir = tempfile.mktemp(__name__) os.makedirs(tempdir) for mediafile in sorted(mediafiles): img_files.append(waveform_image(mediafile, xy_size, tempdir, center_color, outer_color, bg_color)) cmd.extend(img_files) cmd.append(output) subprocess.check_call(cmd, stdout=open(os.devnull, "wb"), stderr=subprocess.STDOUT) finally: if os.path.isdir(tempdir): shutil.rmtree(tempdir, ignore_errors=True) return output
def start_watching(self, cluster, callback): """ Initiates the "watching" of a cluster's associated znode. This is done via kazoo's ChildrenWatch object. When a cluster's znode's child nodes are updated, a callback is fired and we update the cluster's `nodes` attribute based on the existing child znodes and fire a passed-in callback with no arguments once done. If the cluster's znode does not exist we wait for `NO_NODE_INTERVAL` seconds before trying again as long as no ChildrenWatch exists for the given cluster yet and we are not in the process of shutting down. """ logger.debug("starting to watch cluster %s", cluster.name) wait_on_any(self.connected, self.shutdown) logger.debug("done waiting on (connected, shutdown)") znode_path = "/".join([self.base_path, cluster.name]) self.stop_events[znode_path] = threading.Event() def should_stop(): return ( znode_path not in self.stop_events or self.stop_events[znode_path].is_set() or self.shutdown.is_set() ) while not should_stop(): try: if self.client.exists(znode_path): break except exceptions.ConnectionClosedError: break wait_on_any( self.stop_events[znode_path], self.shutdown, timeout=NO_NODE_INTERVAL ) logger.debug("setting up ChildrenWatch for %s", znode_path) @self.client.ChildrenWatch(znode_path) def watch(children): if should_stop(): return False logger.debug("znode children changed! (%s)", znode_path) new_nodes = [] for child in children: child_path = "/".join([znode_path, child]) try: new_nodes.append( Node.deserialize(self.client.get(child_path)[0]) ) except ValueError: logger.exception("Invalid node at path '%s'", child) continue cluster.nodes = new_nodes callback()
Initiates the "watching" of a cluster's associated znode. This is done via kazoo's ChildrenWatch object. When a cluster's znode's child nodes are updated, a callback is fired and we update the cluster's `nodes` attribute based on the existing child znodes and fire a passed-in callback with no arguments once done. If the cluster's znode does not exist we wait for `NO_NODE_INTERVAL` seconds before trying again as long as no ChildrenWatch exists for the given cluster yet and we are not in the process of shutting down.
Below is the the instruction that describes the task: ### Input: Initiates the "watching" of a cluster's associated znode. This is done via kazoo's ChildrenWatch object. When a cluster's znode's child nodes are updated, a callback is fired and we update the cluster's `nodes` attribute based on the existing child znodes and fire a passed-in callback with no arguments once done. If the cluster's znode does not exist we wait for `NO_NODE_INTERVAL` seconds before trying again as long as no ChildrenWatch exists for the given cluster yet and we are not in the process of shutting down. ### Response: def start_watching(self, cluster, callback): """ Initiates the "watching" of a cluster's associated znode. This is done via kazoo's ChildrenWatch object. When a cluster's znode's child nodes are updated, a callback is fired and we update the cluster's `nodes` attribute based on the existing child znodes and fire a passed-in callback with no arguments once done. If the cluster's znode does not exist we wait for `NO_NODE_INTERVAL` seconds before trying again as long as no ChildrenWatch exists for the given cluster yet and we are not in the process of shutting down. """ logger.debug("starting to watch cluster %s", cluster.name) wait_on_any(self.connected, self.shutdown) logger.debug("done waiting on (connected, shutdown)") znode_path = "/".join([self.base_path, cluster.name]) self.stop_events[znode_path] = threading.Event() def should_stop(): return ( znode_path not in self.stop_events or self.stop_events[znode_path].is_set() or self.shutdown.is_set() ) while not should_stop(): try: if self.client.exists(znode_path): break except exceptions.ConnectionClosedError: break wait_on_any( self.stop_events[znode_path], self.shutdown, timeout=NO_NODE_INTERVAL ) logger.debug("setting up ChildrenWatch for %s", znode_path) @self.client.ChildrenWatch(znode_path) def watch(children): if should_stop(): return False logger.debug("znode children changed! (%s)", znode_path) new_nodes = [] for child in children: child_path = "/".join([znode_path, child]) try: new_nodes.append( Node.deserialize(self.client.get(child_path)[0]) ) except ValueError: logger.exception("Invalid node at path '%s'", child) continue cluster.nodes = new_nodes callback()
def get_handler_class(ext): """Get the IOHandler that can handle the extension *ext*.""" if ext in _extensions_map: format = _extensions_map[ext] else: raise ValueError("Unknown format for %s extension." % ext) if format in _handler_map: hc = _handler_map[format] return hc else: matches = difflib.get_close_matches(format, _handler_map.keys()) raise ValueError("Unknown Handler for format %s, close matches: %s" % (format, str(matches)))
Get the IOHandler that can handle the extension *ext*.
Below is the the instruction that describes the task: ### Input: Get the IOHandler that can handle the extension *ext*. ### Response: def get_handler_class(ext): """Get the IOHandler that can handle the extension *ext*.""" if ext in _extensions_map: format = _extensions_map[ext] else: raise ValueError("Unknown format for %s extension." % ext) if format in _handler_map: hc = _handler_map[format] return hc else: matches = difflib.get_close_matches(format, _handler_map.keys()) raise ValueError("Unknown Handler for format %s, close matches: %s" % (format, str(matches)))
def white(self): """ Set color to white. """ self._color = RGB_WHITE cmd = self.command_set.white() self.send(cmd)
Set color to white.
Below is the the instruction that describes the task: ### Input: Set color to white. ### Response: def white(self): """ Set color to white. """ self._color = RGB_WHITE cmd = self.command_set.white() self.send(cmd)
def get_workunit(self, ignore_list=None): """ Gets a new unit of work. Args: ignore_list: list(str) A list of filenames which should be ignored. Defaults to None. Returns: new_workunit: WorkUnit A new unit of work that has not yet been processed. A lock on it has been acquired. Raises: NoAvailableWorkException There is no more work available. """ if ignore_list is None: ignore_list = [] potential_files = self.get_potential_files(ignore_list) while len(potential_files) > 0: potential_file = self.select_potential_file(potential_files) potential_files.remove(potential_file) if self._filter(potential_file): continue if self.directory_context.get_file_size(potential_file) == 0: continue if self.progress_manager.is_done(potential_file): self._done.append(potential_file) continue else: try: self.progress_manager.lock(potential_file) except FileLockedException: continue self._already_fetched.append(potential_file) return self.builder.build_workunit( self.directory_context.get_full_path(potential_file)) logger.info("No eligible workunits remain to be fetched.") raise NoAvailableWorkException()
Gets a new unit of work. Args: ignore_list: list(str) A list of filenames which should be ignored. Defaults to None. Returns: new_workunit: WorkUnit A new unit of work that has not yet been processed. A lock on it has been acquired. Raises: NoAvailableWorkException There is no more work available.
Below is the the instruction that describes the task: ### Input: Gets a new unit of work. Args: ignore_list: list(str) A list of filenames which should be ignored. Defaults to None. Returns: new_workunit: WorkUnit A new unit of work that has not yet been processed. A lock on it has been acquired. Raises: NoAvailableWorkException There is no more work available. ### Response: def get_workunit(self, ignore_list=None): """ Gets a new unit of work. Args: ignore_list: list(str) A list of filenames which should be ignored. Defaults to None. Returns: new_workunit: WorkUnit A new unit of work that has not yet been processed. A lock on it has been acquired. Raises: NoAvailableWorkException There is no more work available. """ if ignore_list is None: ignore_list = [] potential_files = self.get_potential_files(ignore_list) while len(potential_files) > 0: potential_file = self.select_potential_file(potential_files) potential_files.remove(potential_file) if self._filter(potential_file): continue if self.directory_context.get_file_size(potential_file) == 0: continue if self.progress_manager.is_done(potential_file): self._done.append(potential_file) continue else: try: self.progress_manager.lock(potential_file) except FileLockedException: continue self._already_fetched.append(potential_file) return self.builder.build_workunit( self.directory_context.get_full_path(potential_file)) logger.info("No eligible workunits remain to be fetched.") raise NoAvailableWorkException()