code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def create_contentkey_authorization_policy_options(access_token, key_delivery_type="2", \ name="HLS Open Authorization Policy", key_restriction_type="0"): '''Create Media Service Content Key Authorization Policy Options. Args: access_token (str): A valid Azure authentication token. key_delivery...
Create Media Service Content Key Authorization Policy Options. Args: access_token (str): A valid Azure authentication token. key_delivery_type (str): A Media Service Content Key Authorization Policy Delivery Type. name (str): A Media Service Contenty Key Authorization Policy Name. k...
Below is the the instruction that describes the task: ### Input: Create Media Service Content Key Authorization Policy Options. Args: access_token (str): A valid Azure authentication token. key_delivery_type (str): A Media Service Content Key Authorization Policy Delivery Type. name (st...
def getChild(self, name, ns=None, default=None): """ Get a child by (optional) name and/or (optional) namespace. @param name: The name of a child element (may contain prefix). @type name: basestring @param ns: An optional namespace used to match the child. @type ns: (I{pr...
Get a child by (optional) name and/or (optional) namespace. @param name: The name of a child element (may contain prefix). @type name: basestring @param ns: An optional namespace used to match the child. @type ns: (I{prefix}, I{name}) @param default: Returned when child not-found...
Below is the the instruction that describes the task: ### Input: Get a child by (optional) name and/or (optional) namespace. @param name: The name of a child element (may contain prefix). @type name: basestring @param ns: An optional namespace used to match the child. @type ns: (I{pr...
def children_and_parameters(m:nn.Module): "Return the children of `m` and its direct parameters not registered in modules." children = list(m.children()) children_p = sum([[id(p) for p in c.parameters()] for c in m.children()],[]) for p in m.parameters(): if id(p) not in children_p: children.app...
Return the children of `m` and its direct parameters not registered in modules.
Below is the the instruction that describes the task: ### Input: Return the children of `m` and its direct parameters not registered in modules. ### Response: def children_and_parameters(m:nn.Module): "Return the children of `m` and its direct parameters not registered in modules." children = list(m.childr...
def get_metadata(feature_name, etextno): """Looks up the value of a meta-data feature for a given text. Arguments: feature_name (str): The name of the meta-data to look up. etextno (int): The identifier of the Gutenberg text for which to look up the meta-data. Returns: ...
Looks up the value of a meta-data feature for a given text. Arguments: feature_name (str): The name of the meta-data to look up. etextno (int): The identifier of the Gutenberg text for which to look up the meta-data. Returns: frozenset: The values of the meta-data for the t...
Below is the the instruction that describes the task: ### Input: Looks up the value of a meta-data feature for a given text. Arguments: feature_name (str): The name of the meta-data to look up. etextno (int): The identifier of the Gutenberg text for which to look up the meta-data. ...
def intersection(self, *others): r"""Return a new multiset with elements common to the multiset and all others. >>> ms = Multiset('aab') >>> sorted(ms.intersection('abc')) ['a', 'b'] You can also use the ``&`` operator for the same effect. However, the operator version ...
r"""Return a new multiset with elements common to the multiset and all others. >>> ms = Multiset('aab') >>> sorted(ms.intersection('abc')) ['a', 'b'] You can also use the ``&`` operator for the same effect. However, the operator version will only accept a set as other operator,...
Below is the the instruction that describes the task: ### Input: r"""Return a new multiset with elements common to the multiset and all others. >>> ms = Multiset('aab') >>> sorted(ms.intersection('abc')) ['a', 'b'] You can also use the ``&`` operator for the same effect. However, t...
def _condition_as_text(lambda_inspection: icontract._represent.ConditionLambdaInspection) -> str: """Format condition lambda function as reST.""" lambda_ast_node = lambda_inspection.node assert isinstance(lambda_ast_node, ast.Lambda) body_node = lambda_ast_node.body text = None # type: Optional[s...
Format condition lambda function as reST.
Below is the the instruction that describes the task: ### Input: Format condition lambda function as reST. ### Response: def _condition_as_text(lambda_inspection: icontract._represent.ConditionLambdaInspection) -> str: """Format condition lambda function as reST.""" lambda_ast_node = lambda_inspection.node...
async def send_cluster_commands(self, stack, raise_on_error=True, allow_redirections=True): """ Send a bunch of cluster commands to the redis cluster. `allow_redirections` If the pipeline should follow `ASK` & `MOVED` responses automatically. If set to false it will raise RedisClusterEx...
Send a bunch of cluster commands to the redis cluster. `allow_redirections` If the pipeline should follow `ASK` & `MOVED` responses automatically. If set to false it will raise RedisClusterException.
Below is the the instruction that describes the task: ### Input: Send a bunch of cluster commands to the redis cluster. `allow_redirections` If the pipeline should follow `ASK` & `MOVED` responses automatically. If set to false it will raise RedisClusterException. ### Response: async def send_clus...
def build_channel(namespace, name, user_ids): """ Creates complete channel information as described here https://fzambia.gitbooks.io/centrifugal/content/server/channels.html. """ ids = ','.join(map(str, user_ids)) return "{0}:{1}#{2}".format(namespace, name, ids)
Creates complete channel information as described here https://fzambia.gitbooks.io/centrifugal/content/server/channels.html.
Below is the the instruction that describes the task: ### Input: Creates complete channel information as described here https://fzambia.gitbooks.io/centrifugal/content/server/channels.html. ### Response: def build_channel(namespace, name, user_ids): """ Creates complete channel information as described here ht...
def pack(self, grads): """ Args: grads (list): list of gradient tensors Returns: packed list of gradient tensors to be aggregated. """ for i, g in enumerate(grads): assert g.shape == self._shapes[i] with cached_name_scope("GradientPac...
Args: grads (list): list of gradient tensors Returns: packed list of gradient tensors to be aggregated.
Below is the the instruction that describes the task: ### Input: Args: grads (list): list of gradient tensors Returns: packed list of gradient tensors to be aggregated. ### Response: def pack(self, grads): """ Args: grads (list): list of gradient tensors...
def page_guiref(arg_s=None): """Show a basic reference about the GUI Console.""" from IPython.core import page page.page(gui_reference, auto_html=True)
Show a basic reference about the GUI Console.
Below is the the instruction that describes the task: ### Input: Show a basic reference about the GUI Console. ### Response: def page_guiref(arg_s=None): """Show a basic reference about the GUI Console.""" from IPython.core import page page.page(gui_reference, auto_html=True)
def crypto_hash_sha256(message): """ Hashes and returns the message ``message``. :param message: bytes :rtype: bytes """ digest = ffi.new("unsigned char[]", crypto_hash_sha256_BYTES) rc = lib.crypto_hash_sha256(digest, message, len(message)) ensure(rc == 0, 'Unexpected librar...
Hashes and returns the message ``message``. :param message: bytes :rtype: bytes
Below is the the instruction that describes the task: ### Input: Hashes and returns the message ``message``. :param message: bytes :rtype: bytes ### Response: def crypto_hash_sha256(message): """ Hashes and returns the message ``message``. :param message: bytes :rtype: bytes """ d...
def read(self, obj): """ Returns object: fragment """ path, frag = [], obj for part in self.parts: path.append(part) if isinstance(frag, dict): try: frag = frag[part] except KeyError as error:...
Returns object: fragment
Below is the the instruction that describes the task: ### Input: Returns object: fragment ### Response: def read(self, obj): """ Returns object: fragment """ path, frag = [], obj for part in self.parts: path.append(part) if isi...
def _real_time_thread(self): """Handles real-time updates to the order book.""" while self.ws_client.connected(): if self.die: break if self.pause: sleep(5) continue message = self.ws_client.receive() if message is None: break message_type ...
Handles real-time updates to the order book.
Below is the the instruction that describes the task: ### Input: Handles real-time updates to the order book. ### Response: def _real_time_thread(self): """Handles real-time updates to the order book.""" while self.ws_client.connected(): if self.die: break if self.pause: ...
def _handle_array(toks): """ Generate the correct function for an array signature. :param toks: the list of parsed tokens :returns: function that returns an Array or Dictionary value :rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str """ if len(toks...
Generate the correct function for an array signature. :param toks: the list of parsed tokens :returns: function that returns an Array or Dictionary value :rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str
Below is the the instruction that describes the task: ### Input: Generate the correct function for an array signature. :param toks: the list of parsed tokens :returns: function that returns an Array or Dictionary value :rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str ### Resp...
def set_write_buffer_limits(self, high=None, low=None): """Set the low and high watermark for the write buffer.""" if high is None: high = self.write_buffer_size if low is None: low = high // 2 if low > high: low = high self._write_buffer_high ...
Set the low and high watermark for the write buffer.
Below is the the instruction that describes the task: ### Input: Set the low and high watermark for the write buffer. ### Response: def set_write_buffer_limits(self, high=None, low=None): """Set the low and high watermark for the write buffer.""" if high is None: high = self.write_buffe...
def check_encoding(proof_req: dict, proof: dict) -> bool: """ Return whether the proof's raw values correspond to their encodings as cross-referenced against proof request. :param proof request: proof request :param proof: corresponding proof to check :return: True if OK...
Return whether the proof's raw values correspond to their encodings as cross-referenced against proof request. :param proof request: proof request :param proof: corresponding proof to check :return: True if OK, False for encoding mismatch
Below is the the instruction that describes the task: ### Input: Return whether the proof's raw values correspond to their encodings as cross-referenced against proof request. :param proof request: proof request :param proof: corresponding proof to check :return: True if OK, False f...
def _GetRecordValue(self, record, value_entry): """Retrieves a specific value from the record. Args: record (pyesedb.record): ESE record. value_entry (int): value entry. Returns: object: value. Raises: ValueError: if the value is not supported. """ column_type = record...
Retrieves a specific value from the record. Args: record (pyesedb.record): ESE record. value_entry (int): value entry. Returns: object: value. Raises: ValueError: if the value is not supported.
Below is the the instruction that describes the task: ### Input: Retrieves a specific value from the record. Args: record (pyesedb.record): ESE record. value_entry (int): value entry. Returns: object: value. Raises: ValueError: if the value is not supported. ### Response: def...
def securitygroupid(vm_): ''' Returns the SecurityGroupId ''' securitygroupid_set = set() securitygroupid_list = config.get_cloud_config_value( 'securitygroupid', vm_, __opts__, search_global=False ) # If the list is None, then the set will remain empty # ...
Returns the SecurityGroupId
Below is the the instruction that describes the task: ### Input: Returns the SecurityGroupId ### Response: def securitygroupid(vm_): ''' Returns the SecurityGroupId ''' securitygroupid_set = set() securitygroupid_list = config.get_cloud_config_value( 'securitygroupid', vm_, ...
def observe(M, C, obs_mesh, obs_vals, obs_V=0, lintrans=None, cross_validate=True): """ (M, C, obs_mesh, obs_vals[, obs_V = 0, lintrans = None, cross_validate = True]) Imposes observation of the value of obs_vals on M and C, where obs_vals ~ N(lintrans * f(obs_mesh), V) f ~ GP(M,C) ...
(M, C, obs_mesh, obs_vals[, obs_V = 0, lintrans = None, cross_validate = True]) Imposes observation of the value of obs_vals on M and C, where obs_vals ~ N(lintrans * f(obs_mesh), V) f ~ GP(M,C) :Arguments: - `M`: The mean function - `C`: The covariance function - `...
Below is the the instruction that describes the task: ### Input: (M, C, obs_mesh, obs_vals[, obs_V = 0, lintrans = None, cross_validate = True]) Imposes observation of the value of obs_vals on M and C, where obs_vals ~ N(lintrans * f(obs_mesh), V) f ~ GP(M,C) :Arguments: - `M`: The m...
def list_all_geo_zones(cls, **kwargs): """List GeoZones Return a list of GeoZones This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_geo_zones(async=True) >>> result = thread.get...
List GeoZones Return a list of GeoZones This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_geo_zones(async=True) >>> result = thread.get() :param async bool :param int p...
Below is the the instruction that describes the task: ### Input: List GeoZones Return a list of GeoZones This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_geo_zones(async=True) >>> ...
def getBool(t): """If t is of type bool, return it, otherwise raise InvalidTypeError. """ b = c_int() if PL_get_long(t, byref(b)): return bool(b.value) else: raise InvalidTypeError("bool")
If t is of type bool, return it, otherwise raise InvalidTypeError.
Below is the the instruction that describes the task: ### Input: If t is of type bool, return it, otherwise raise InvalidTypeError. ### Response: def getBool(t): """If t is of type bool, return it, otherwise raise InvalidTypeError. """ b = c_int() if PL_get_long(t, byref(b)): return bool(b....
def make_decoder(num_topics, num_words): """Create the decoder function. Args: num_topics: The number of topics. num_words: The number of words. Returns: decoder: A `callable` mapping a `Tensor` of encodings to a `tfd.Distribution` instance over words. """ topics_words_logits = tf.compat.v...
Create the decoder function. Args: num_topics: The number of topics. num_words: The number of words. Returns: decoder: A `callable` mapping a `Tensor` of encodings to a `tfd.Distribution` instance over words.
Below is the the instruction that describes the task: ### Input: Create the decoder function. Args: num_topics: The number of topics. num_words: The number of words. Returns: decoder: A `callable` mapping a `Tensor` of encodings to a `tfd.Distribution` instance over words. ### Response: def...
def _import_next_layer(self, proto, length): """Import next layer extractor. Positional arguments: * proto -- str, next layer protocol name * length -- int, valid (not padding) length Returns: * bool -- flag if extraction of next layer succeeded ...
Import next layer extractor. Positional arguments: * proto -- str, next layer protocol name * length -- int, valid (not padding) length Returns: * bool -- flag if extraction of next layer succeeded * Info -- info of next layer * ProtoChain --...
Below is the the instruction that describes the task: ### Input: Import next layer extractor. Positional arguments: * proto -- str, next layer protocol name * length -- int, valid (not padding) length Returns: * bool -- flag if extraction of next layer succeeded...
def minimum_sys(cls, inherit_path): """Return the minimum sys necessary to run this interpreter, a la python -S. :returns: (sys.path, sys.path_importer_cache, sys.modules) tuple of a bare python installation. """ site_libs = set(cls.site_libs()) for site_lib in site_libs: TRACER.log('Fo...
Return the minimum sys necessary to run this interpreter, a la python -S. :returns: (sys.path, sys.path_importer_cache, sys.modules) tuple of a bare python installation.
Below is the the instruction that describes the task: ### Input: Return the minimum sys necessary to run this interpreter, a la python -S. :returns: (sys.path, sys.path_importer_cache, sys.modules) tuple of a bare python installation. ### Response: def minimum_sys(cls, inherit_path): """Return the m...
def force_horizontal_padding_after( self, index: int, padding: Union[int, float]) -> None: """Change the padding after the given column.""" self.horizontal_padding[index] = padding
Change the padding after the given column.
Below is the the instruction that describes the task: ### Input: Change the padding after the given column. ### Response: def force_horizontal_padding_after( self, index: int, padding: Union[int, float]) -> None: """Change the padding after the given column.""" self.horizontal_padding[i...
def timeseries(self, dataframe=False): """Get the date histogram aggregations. :param dataframe: if true, return a pandas.DataFrame object """ self.query.get_cardinality("author_uuid").by_period() return super().timeseries(dataframe)
Get the date histogram aggregations. :param dataframe: if true, return a pandas.DataFrame object
Below is the the instruction that describes the task: ### Input: Get the date histogram aggregations. :param dataframe: if true, return a pandas.DataFrame object ### Response: def timeseries(self, dataframe=False): """Get the date histogram aggregations. :param dataframe: if true, return ...
def check(self, batch_size): """Returns True if the logging frequency has been met.""" self.increment(batch_size) return self.unit_count >= self.config["log_train_every"]
Returns True if the logging frequency has been met.
Below is the the instruction that describes the task: ### Input: Returns True if the logging frequency has been met. ### Response: def check(self, batch_size): """Returns True if the logging frequency has been met.""" self.increment(batch_size) return self.unit_count >= self.config["log_tra...
def _threaded(self, *args, **kwargs): """Call the target and put the result in the Queue.""" for target in self.targets: result = target(*args, **kwargs) self.queue.put(result)
Call the target and put the result in the Queue.
Below is the the instruction that describes the task: ### Input: Call the target and put the result in the Queue. ### Response: def _threaded(self, *args, **kwargs): """Call the target and put the result in the Queue.""" for target in self.targets: result = target(*args, **kwargs) ...
def register_view(self, view): """Called when the View was registered""" super(TopToolBarController, self).register_view(view) view['maximize_button'].connect('clicked', self.on_maximize_button_clicked) self.update_maximize_button()
Called when the View was registered
Below is the the instruction that describes the task: ### Input: Called when the View was registered ### Response: def register_view(self, view): """Called when the View was registered""" super(TopToolBarController, self).register_view(view) view['maximize_button'].connect('clicked', self.o...
def check(dependency=None, timeout=60): """Mark function as a check. :param dependency: the check that this check depends on :type dependency: function :param timeout: maximum number of seconds the check can run :type timeout: int When a check depends on another, the former will only run if th...
Mark function as a check. :param dependency: the check that this check depends on :type dependency: function :param timeout: maximum number of seconds the check can run :type timeout: int When a check depends on another, the former will only run if the latter passes. Additionally, the dependen...
Below is the the instruction that describes the task: ### Input: Mark function as a check. :param dependency: the check that this check depends on :type dependency: function :param timeout: maximum number of seconds the check can run :type timeout: int When a check depends on another, the form...
def read(self): """Read the default, additional, system, and user config files. :raises DefaultConfigValidationError: There was a validation error with the *default* file. """ if self.default_file: self.read_default_config() ...
Read the default, additional, system, and user config files. :raises DefaultConfigValidationError: There was a validation error with the *default* file.
Below is the the instruction that describes the task: ### Input: Read the default, additional, system, and user config files. :raises DefaultConfigValidationError: There was a validation error with the *default* file. ### Response: def read(self): """R...
def index(index, length): """Generates an index. :param index: The index, can be positive or negative. :param length: The length of the sequence to index. :raises: IndexError Negative indices are typically used to index a sequence in reverse order. But to use them, the indexed object must con...
Generates an index. :param index: The index, can be positive or negative. :param length: The length of the sequence to index. :raises: IndexError Negative indices are typically used to index a sequence in reverse order. But to use them, the indexed object must convert them to the correct, pos...
Below is the the instruction that describes the task: ### Input: Generates an index. :param index: The index, can be positive or negative. :param length: The length of the sequence to index. :raises: IndexError Negative indices are typically used to index a sequence in reverse order. But to u...
def type_list(signature, doc, header): """ Construct a list of types, preferring type annotations to docstrings if they are available. Parameters ---------- signature : Signature Signature of thing doc : list of tuple Numpydoc's type list section Returns ------- ...
Construct a list of types, preferring type annotations to docstrings if they are available. Parameters ---------- signature : Signature Signature of thing doc : list of tuple Numpydoc's type list section Returns ------- list of str Markdown formatted type list
Below is the the instruction that describes the task: ### Input: Construct a list of types, preferring type annotations to docstrings if they are available. Parameters ---------- signature : Signature Signature of thing doc : list of tuple Numpydoc's type list section Retur...
def _execute_single_level_task(self): """ Execute a single-level task """ self.log(u"Executing single level task...") try: # load audio file, extract MFCCs from real wave, clear audio file self._step_begin(u"extract MFCC real wave") real_wave_mfcc = self._extr...
Execute a single-level task
Below is the the instruction that describes the task: ### Input: Execute a single-level task ### Response: def _execute_single_level_task(self): """ Execute a single-level task """ self.log(u"Executing single level task...") try: # load audio file, extract MFCCs from real wave, ...
def update_alias(FunctionName, Name, FunctionVersion=None, Description=None, region=None, key=None, keyid=None, profile=None): ''' Update the named alias to the configuration. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. ...
Update the named alias to the configuration. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_alias my_lambda my_alias $LATEST
Below is the the instruction that describes the task: ### Input: Update the named alias to the configuration. Returns {updated: true} if the alias was updated and returns {updated: False} if the alias was not updated. CLI Example: .. code-block:: bash salt myminion boto_lamba.update_alia...
def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.describe_stack_events(stackname, next) event_list.append(events) if events.next_token is None: break next = ev...
Get the events in batches and return in chronological order
Below is the the instruction that describes the task: ### Input: Get the events in batches and return in chronological order ### Response: def get_events(conn, stackname): """Get the events in batches and return in chronological order""" next = None event_list = [] while 1: events = conn.de...
def nsx_controller_connection_addr_method(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") nsx_controller = ET.SubElement(config, "nsx-controller", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(nsx_controller, "name") name...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def nsx_controller_connection_addr_method(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") nsx_controller = ET.SubElement(config, "nsx-controller", xmlns="urn:...
def valid_token(token): """Asserts a provided string is a valid duration token representation :param token: duration representation token :type token: string """ is_scale = False # Check if the token represents a scale # If it doesn't set a flag accordingly try: Scale(token)...
Asserts a provided string is a valid duration token representation :param token: duration representation token :type token: string
Below is the the instruction that describes the task: ### Input: Asserts a provided string is a valid duration token representation :param token: duration representation token :type token: string ### Response: def valid_token(token): """Asserts a provided string is a valid duration token representa...
def find_node(self, node, path): """Finds a node by the given path from the given node.""" for hash_value in path: if isinstance(node, LeafStatisticsNode): break for stats in node.get_child_keys(): if hash(stats) == hash_value: ...
Finds a node by the given path from the given node.
Below is the the instruction that describes the task: ### Input: Finds a node by the given path from the given node. ### Response: def find_node(self, node, path): """Finds a node by the given path from the given node.""" for hash_value in path: if isinstance(node, LeafStatisticsNode): ...
def make_shift_function(alphabet): """Construct a shift function from an alphabet. Examples: Shift cases independently >>> make_shift_function([string.ascii_uppercase, string.ascii_lowercase]) <function make_shift_function.<locals>.shift_case_sensitive> Additionally shift punc...
Construct a shift function from an alphabet. Examples: Shift cases independently >>> make_shift_function([string.ascii_uppercase, string.ascii_lowercase]) <function make_shift_function.<locals>.shift_case_sensitive> Additionally shift punctuation characters >>> make_shift...
Below is the the instruction that describes the task: ### Input: Construct a shift function from an alphabet. Examples: Shift cases independently >>> make_shift_function([string.ascii_uppercase, string.ascii_lowercase]) <function make_shift_function.<locals>.shift_case_sensitive> ...
def execute_command_with_connection(self, context, command, *args): """ Note: session & vcenter_data_model & reservation id objects will be injected dynamically to the command :param command: :param context: instance of ResourceCommandContext or AutoLoadCommandContext :type conte...
Note: session & vcenter_data_model & reservation id objects will be injected dynamically to the command :param command: :param context: instance of ResourceCommandContext or AutoLoadCommandContext :type context: cloudshell.shell.core.context.ResourceCommandContext :param args:
Below is the the instruction that describes the task: ### Input: Note: session & vcenter_data_model & reservation id objects will be injected dynamically to the command :param command: :param context: instance of ResourceCommandContext or AutoLoadCommandContext :type context: cloudshell.shel...
def wait_for_servers(session, servers): """Wait for the servers to be ready. Note(msimonin): we don't garantee the SSH connection to be ready. """ nclient = nova.Client(NOVA_VERSION, session=session, region_name=os.environ['OS_REGION_NAME']) while True: deployed = ...
Wait for the servers to be ready. Note(msimonin): we don't garantee the SSH connection to be ready.
Below is the the instruction that describes the task: ### Input: Wait for the servers to be ready. Note(msimonin): we don't garantee the SSH connection to be ready. ### Response: def wait_for_servers(session, servers): """Wait for the servers to be ready. Note(msimonin): we don't garantee the SSH con...
def get_group_dict(user=None, include_default=True): ''' Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ''' if HAS_GRP is False or HAS_PWD is False: return {} group_dict = {} group_names...
Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27}
Below is the the instruction that describes the task: ### Input: Returns a dict of all of the system groups as keys, and group ids as values, of which the user is a member. E.g.: {'staff': 501, 'sudo': 27} ### Response: def get_group_dict(user=None, include_default=True): ''' Returns a dict of all ...
def add(self, node): """Add one node as descendant """ self.sons.append(node) node.parent = self
Add one node as descendant
Below is the the instruction that describes the task: ### Input: Add one node as descendant ### Response: def add(self, node): """Add one node as descendant """ self.sons.append(node) node.parent = self
def nan_empty(self, col: str): """ Fill empty values with NaN values :param col: name of the colum :type col: str :example: ``ds.nan_empty("mycol")`` """ try: self.df[col] = self.df[col].replace('', nan) self.ok("Filled empty values with ...
Fill empty values with NaN values :param col: name of the colum :type col: str :example: ``ds.nan_empty("mycol")``
Below is the the instruction that describes the task: ### Input: Fill empty values with NaN values :param col: name of the colum :type col: str :example: ``ds.nan_empty("mycol")`` ### Response: def nan_empty(self, col: str): """ Fill empty values with NaN values :...
def widget_from_single_value(o): """Make widgets from single values, which can be used as parameter defaults.""" if isinstance(o, string_types): return Text(value=unicode_type(o)) elif isinstance(o, bool): return Checkbox(value=o) elif isinstance(o, Integral): ...
Make widgets from single values, which can be used as parameter defaults.
Below is the the instruction that describes the task: ### Input: Make widgets from single values, which can be used as parameter defaults. ### Response: def widget_from_single_value(o): """Make widgets from single values, which can be used as parameter defaults.""" if isinstance(o, string_types): ...
def nfa_union(nfa_1: dict, nfa_2: dict) -> dict: """ Returns a NFA that reads the union of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. here is a NFA :math:`A_∨` that nondeterministically chooses :math:`A_1` or :math:`A_2` and runs ...
Returns a NFA that reads the union of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. here is a NFA :math:`A_∨` that nondeterministically chooses :math:`A_1` or :math:`A_2` and runs it on the input word. It is defined as: :math:`A...
Below is the the instruction that describes the task: ### Input: Returns a NFA that reads the union of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. here is a NFA :math:`A_∨` that nondeterministically chooses :math:`A_1` or :math:`A_...
def with_run_kwargs(self, **kwargs: Dict[str, Any]) -> 'Optimization': """ Replace Tensorflow session run kwargs. Check Tensorflow session run [documentation](https://www.tensorflow.org/api_docs/python/tf/Session). :param kwargs: Dictionary of tensors as keys and numpy arrays or ...
Replace Tensorflow session run kwargs. Check Tensorflow session run [documentation](https://www.tensorflow.org/api_docs/python/tf/Session). :param kwargs: Dictionary of tensors as keys and numpy arrays or primitive python types as values. :return: Optimization instance s...
Below is the the instruction that describes the task: ### Input: Replace Tensorflow session run kwargs. Check Tensorflow session run [documentation](https://www.tensorflow.org/api_docs/python/tf/Session). :param kwargs: Dictionary of tensors as keys and numpy arrays or primitive...
def plot_pc_scatter(self, pc1, pc2, v=True, subset=None, ax=None, color=None, s=None, marker=None, color_name=None, s_name=None, marker_name=None): """ Make a scatter plot of two principal components. You can create differently colored, sized, or m...
Make a scatter plot of two principal components. You can create differently colored, sized, or marked scatter points. Parameters ---------- pc1 : str String of form PCX where X is the number of the principal component you want to plot on the x-axis. ...
Below is the the instruction that describes the task: ### Input: Make a scatter plot of two principal components. You can create differently colored, sized, or marked scatter points. Parameters ---------- pc1 : str String of form PCX where X is the number of the principa...
def heappush(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown(heap, 0, len(heap)-1)
Push item onto heap, maintaining the heap invariant.
Below is the the instruction that describes the task: ### Input: Push item onto heap, maintaining the heap invariant. ### Response: def heappush(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown(heap, 0, len(heap)-1)
def add_update_callback(self, group=None, name=None, cb=None): """ Add a callback for a specific parameter name. This callback will be executed when a new value is read from the Crazyflie. """ if not group and not name: self.all_update_callback.add_callback(cb) ...
Add a callback for a specific parameter name. This callback will be executed when a new value is read from the Crazyflie.
Below is the the instruction that describes the task: ### Input: Add a callback for a specific parameter name. This callback will be executed when a new value is read from the Crazyflie. ### Response: def add_update_callback(self, group=None, name=None, cb=None): """ Add a callback for a sp...
def make_sentence(self, init_state=None, **kwargs): """ Attempts `tries` (default: 10) times to generate a valid sentence, based on the model and `test_sentence_output`. Passes `max_overlap_ratio` and `max_overlap_total` to `test_sentence_output`. If successful, returns the sent...
Attempts `tries` (default: 10) times to generate a valid sentence, based on the model and `test_sentence_output`. Passes `max_overlap_ratio` and `max_overlap_total` to `test_sentence_output`. If successful, returns the sentence as a string. If not, returns None. If `init_state` (a tupl...
Below is the the instruction that describes the task: ### Input: Attempts `tries` (default: 10) times to generate a valid sentence, based on the model and `test_sentence_output`. Passes `max_overlap_ratio` and `max_overlap_total` to `test_sentence_output`. If successful, returns the sentenc...
def __load_parcov(self): """private method to set the parcov attribute from: a pest control file (parameter bounds) a pst object a matrix object an uncert file an ascii matrix file """ # if the parcov arg was not pas...
private method to set the parcov attribute from: a pest control file (parameter bounds) a pst object a matrix object an uncert file an ascii matrix file
Below is the the instruction that describes the task: ### Input: private method to set the parcov attribute from: a pest control file (parameter bounds) a pst object a matrix object an uncert file an ascii matrix file ### Response: def...
def write_ioc_to_file(self, output_dir=None, force=False): """ Serialize the IOC to a .ioc file. :param output_dir: Directory to write the ioc out to. default is the current working directory. :param force: If specified, will not validate the root node of the IOC is 'OpenIOC'. ...
Serialize the IOC to a .ioc file. :param output_dir: Directory to write the ioc out to. default is the current working directory. :param force: If specified, will not validate the root node of the IOC is 'OpenIOC'. :return:
Below is the the instruction that describes the task: ### Input: Serialize the IOC to a .ioc file. :param output_dir: Directory to write the ioc out to. default is the current working directory. :param force: If specified, will not validate the root node of the IOC is 'OpenIOC'. :return: #...
def get_dates_file(path): """ parse dates file of dates and probability of choosing""" with open(path) as f: dates = f.readlines() return [(convert_time_string(date_string.split(" ")[0]), float(date_string.split(" ")[1])) for date_string in dates]
parse dates file of dates and probability of choosing
Below is the the instruction that describes the task: ### Input: parse dates file of dates and probability of choosing ### Response: def get_dates_file(path): """ parse dates file of dates and probability of choosing""" with open(path) as f: dates = f.readlines() return [(convert_time_string(da...
def set_tag(self, tag): ''' Sets the tag. If the Entity belongs to the world it will check for tag conflicts. ''' if self._world: if self._world.get_entity_by_tag(tag): raise NonUniqueTagError(tag) self._tag = tag
Sets the tag. If the Entity belongs to the world it will check for tag conflicts.
Below is the the instruction that describes the task: ### Input: Sets the tag. If the Entity belongs to the world it will check for tag conflicts. ### Response: def set_tag(self, tag): ''' Sets the tag. If the Entity belongs to the world it will check for tag conflicts. ''' ...
def is_restricted(self, assets, dt): """ An asset is restricted for all dts if it is in the static list. """ if isinstance(assets, Asset): return assets in self._restricted_set return pd.Series( index=pd.Index(assets), data=vectorized_is_elemen...
An asset is restricted for all dts if it is in the static list.
Below is the the instruction that describes the task: ### Input: An asset is restricted for all dts if it is in the static list. ### Response: def is_restricted(self, assets, dt): """ An asset is restricted for all dts if it is in the static list. """ if isinstance(assets, Asset): ...
def inverse(self, z): """ Inverse of the logit transform Parameters ---------- z : array-like The value of the logit transform at `p` Returns ------- p : array Probabilities Notes ----- g^(-1)(z) = exp(z)/...
Inverse of the logit transform Parameters ---------- z : array-like The value of the logit transform at `p` Returns ------- p : array Probabilities Notes ----- g^(-1)(z) = exp(z)/(1+exp(z))
Below is the the instruction that describes the task: ### Input: Inverse of the logit transform Parameters ---------- z : array-like The value of the logit transform at `p` Returns ------- p : array Probabilities Notes ----- ...
def _spill(self): """ dump already partitioned data into disks. """ global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(path) used_memory = get_used_memory() if not self....
dump already partitioned data into disks.
Below is the the instruction that describes the task: ### Input: dump already partitioned data into disks. ### Response: def _spill(self): """ dump already partitioned data into disks. """ global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) ...
def key_to_int(key, base=BASE62): """ Convert the following key to an integer. @param key: a key. @param base: a sequence of characters that was used to encode the integer value. @return: the integer value corresponding to the given key. @raise ValueError: if one character of the s...
Convert the following key to an integer. @param key: a key. @param base: a sequence of characters that was used to encode the integer value. @return: the integer value corresponding to the given key. @raise ValueError: if one character of the specified key doesn't match any char...
Below is the the instruction that describes the task: ### Input: Convert the following key to an integer. @param key: a key. @param base: a sequence of characters that was used to encode the integer value. @return: the integer value corresponding to the given key. @raise ValueError: if...
def indent(txt, spacing=4): """ Indent given text using custom spacing, default is set to 4. """ return prefix(str(txt), ''.join([' ' for _ in range(spacing)]))
Indent given text using custom spacing, default is set to 4.
Below is the the instruction that describes the task: ### Input: Indent given text using custom spacing, default is set to 4. ### Response: def indent(txt, spacing=4): """ Indent given text using custom spacing, default is set to 4. """ return prefix(str(txt), ''.join([' ' for _ in range(spacing)])...
def create_build_context(image, inputs, wdir): """ Creates a tar archive with a dockerfile and a directory called "inputs" The Dockerfile will copy the "inputs" directory to the chosen working directory """ assert os.path.isabs(wdir) dockerlines = ["FROM %s" % image, "RUN mk...
Creates a tar archive with a dockerfile and a directory called "inputs" The Dockerfile will copy the "inputs" directory to the chosen working directory
Below is the the instruction that describes the task: ### Input: Creates a tar archive with a dockerfile and a directory called "inputs" The Dockerfile will copy the "inputs" directory to the chosen working directory ### Response: def create_build_context(image, inputs, wdir): """ Creates a tar archive...
def pick_enclosure_link(post, parameter=''): '''Override URL of the Post to point to url of the first enclosure with href attribute non-empty and type matching specified regexp parameter (empty=any). Missing "type" attribute for enclosure will be matched as an empty string. If none of the enclosures match, link...
Override URL of the Post to point to url of the first enclosure with href attribute non-empty and type matching specified regexp parameter (empty=any). Missing "type" attribute for enclosure will be matched as an empty string. If none of the enclosures match, link won't be updated.
Below is the the instruction that describes the task: ### Input: Override URL of the Post to point to url of the first enclosure with href attribute non-empty and type matching specified regexp parameter (empty=any). Missing "type" attribute for enclosure will be matched as an empty string. If none of the en...
def get_settings(): ''' Get all currently loaded settings. ''' settings = {} for config_file in config_files(): config_contents = load_config(config_file) if config_contents is not None: settings = deep_merge(settings, config_contents) return settings
Get all currently loaded settings.
Below is the the instruction that describes the task: ### Input: Get all currently loaded settings. ### Response: def get_settings(): ''' Get all currently loaded settings. ''' settings = {} for config_file in config_files(): config_contents = load_config(config_file) if config_...
def is_default_port(self): """A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise. """ if self.port is None: return False default = DEFAULT_PORTS.get(self....
A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise.
Below is the the instruction that describes the task: ### Input: A check for default port. Return True if port is default for specified scheme, e.g. 'http://python.org' or 'http://python.org:80', False otherwise. ### Response: def is_default_port(self): """A check for default port....
def bytes(self): """Emit the address in bytes format.""" addrbyte = b'\x00\x00\x00' if self.addr is not None: addrbyte = self.addr return addrbyte
Emit the address in bytes format.
Below is the the instruction that describes the task: ### Input: Emit the address in bytes format. ### Response: def bytes(self): """Emit the address in bytes format.""" addrbyte = b'\x00\x00\x00' if self.addr is not None: addrbyte = self.addr return addrbyte
def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.PY2 \ else self.channel.send(load)
Return a list of available environments
Below is the the instruction that describes the task: ### Input: Return a list of available environments ### Response: def envs(self): ''' Return a list of available environments ''' load = {'cmd': '_file_envs'} return salt.utils.data.decode(self.channel.send(load)) if six.P...
def rm_subtitles(path): """ delete all subtitles in path recursively """ sub_exts = ['ass', 'srt', 'sub'] count = 0 for root, dirs, files in os.walk(path): for f in files: _, ext = os.path.splitext(f) ext = ext[1:] if ext in sub_exts: p = o...
delete all subtitles in path recursively
Below is the the instruction that describes the task: ### Input: delete all subtitles in path recursively ### Response: def rm_subtitles(path): """ delete all subtitles in path recursively """ sub_exts = ['ass', 'srt', 'sub'] count = 0 for root, dirs, files in os.walk(path): for f in fi...
def apply(self, name, foci): """ Apply a named transformation to a set of foci. If the named transformation doesn't exist, return foci untransformed. """ if name in self.transformations: return transform(foci, self.transformations[name]) else: logger.info...
Apply a named transformation to a set of foci. If the named transformation doesn't exist, return foci untransformed.
Below is the the instruction that describes the task: ### Input: Apply a named transformation to a set of foci. If the named transformation doesn't exist, return foci untransformed. ### Response: def apply(self, name, foci): """ Apply a named transformation to a set of foci. If the named ...
def gps_inject_data_send(self, target_system, target_component, len, data, force_mavlink1=False): ''' data for injecting into the onboard GPS (used for DGPS) target_system : System ID (uint8_t) target_component : Component ID (uint8_t...
data for injecting into the onboard GPS (used for DGPS) target_system : System ID (uint8_t) target_component : Component ID (uint8_t) len : data length (uint8_t) data : raw data (110 is enoug...
Below is the the instruction that describes the task: ### Input: data for injecting into the onboard GPS (used for DGPS) target_system : System ID (uint8_t) target_component : Component ID (uint8_t) len : data length (uint8_...
def basic_auth_user(self, realm, user_name, password, environ): """Returns True if this user_name/password pair is valid for the realm, False otherwise. Used for basic authentication.""" user = self._get_realm_entry(realm, user_name) if user is not None and password == user.get("passwor...
Returns True if this user_name/password pair is valid for the realm, False otherwise. Used for basic authentication.
Below is the the instruction that describes the task: ### Input: Returns True if this user_name/password pair is valid for the realm, False otherwise. Used for basic authentication. ### Response: def basic_auth_user(self, realm, user_name, password, environ): """Returns True if this user_name/passw...
def rangecalc(x, y=None, pad=0.05): """ Calculate padded range limits for axes. """ mn = np.nanmin([np.nanmin(x), np.nanmin(y)]) mx = np.nanmax([np.nanmax(x), np.nanmax(y)]) rn = mx - mn return (mn - pad * rn, mx + pad * rn)
Calculate padded range limits for axes.
Below is the the instruction that describes the task: ### Input: Calculate padded range limits for axes. ### Response: def rangecalc(x, y=None, pad=0.05): """ Calculate padded range limits for axes. """ mn = np.nanmin([np.nanmin(x), np.nanmin(y)]) mx = np.nanmax([np.nanmax(x), np.nanmax...
def validate_protocol(protocol): '''Validate a protocol, a string, and return it.''' if not re.match(PROTOCOL_REGEX, protocol): raise ValueError(f'invalid protocol: {protocol}') return protocol.lower()
Validate a protocol, a string, and return it.
Below is the the instruction that describes the task: ### Input: Validate a protocol, a string, and return it. ### Response: def validate_protocol(protocol): '''Validate a protocol, a string, and return it.''' if not re.match(PROTOCOL_REGEX, protocol): raise ValueError(f'invalid protocol: {protocol...
def make_bucket(self, bucket_name, location='us-east-1'): """ Make a new bucket on the server. Optionally include Location. ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'eu-west-1', 'eu-west-2', 'ca-central-1', 'eu-central-1', 'sa-east-1', 'cn-north-1'...
Make a new bucket on the server. Optionally include Location. ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'eu-west-1', 'eu-west-2', 'ca-central-1', 'eu-central-1', 'sa-east-1', 'cn-north-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ap-northe...
Below is the the instruction that describes the task: ### Input: Make a new bucket on the server. Optionally include Location. ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2', 'eu-west-1', 'eu-west-2', 'ca-central-1', 'eu-central-1', 'sa-east-1', 'cn-north-1', 'ap-sou...
def save_list(lst, path): """ Save items from list to the file. """ with open(path, 'wb') as out: lines = [] for item in lst: if isinstance(item, (six.text_type, six.binary_type)): lines.append(make_str(item)) else: lines.append(ma...
Save items from list to the file.
Below is the the instruction that describes the task: ### Input: Save items from list to the file. ### Response: def save_list(lst, path): """ Save items from list to the file. """ with open(path, 'wb') as out: lines = [] for item in lst: if isinstance(item, (six.text_t...
def is_multipart(header_dict): """ Args: header_dict : CaseInsensitiveDict Returns: bool: ``True`` if ``header_dict`` has a Content-Type key (case insensitive) with value that begins with 'multipart'. """ return ( {k.lower(): v for k, v in header_dict.items()} .get('content-ty...
Args: header_dict : CaseInsensitiveDict Returns: bool: ``True`` if ``header_dict`` has a Content-Type key (case insensitive) with value that begins with 'multipart'.
Below is the the instruction that describes the task: ### Input: Args: header_dict : CaseInsensitiveDict Returns: bool: ``True`` if ``header_dict`` has a Content-Type key (case insensitive) with value that begins with 'multipart'. ### Response: def is_multipart(header_dict): """ Args: head...
def nd_sort_samples(samples): """ Sort an N-dimensional list of samples using a KDTree. :param samples: ``(nsamples, ndim)`` The list of samples. This must be a two-dimensional array. :returns i: ``(nsamples,)`` The list of indices into the original array that return the correctly ...
Sort an N-dimensional list of samples using a KDTree. :param samples: ``(nsamples, ndim)`` The list of samples. This must be a two-dimensional array. :returns i: ``(nsamples,)`` The list of indices into the original array that return the correctly sorted version.
Below is the the instruction that describes the task: ### Input: Sort an N-dimensional list of samples using a KDTree. :param samples: ``(nsamples, ndim)`` The list of samples. This must be a two-dimensional array. :returns i: ``(nsamples,)`` The list of indices into the original array tha...
def cbpdnmd_ustep(k): """Do the U step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables. """ mp_Z_U0[k] += mp_DX[k] - mp_Z_Y0[k] - mp_S[k] mp_Z_U1[k] += mp_Z_X[k] - mp_Z_Y1[k]
Do the U step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables.
Below is the the instruction that describes the task: ### Input: Do the U step of the cbpdn stage. The only parameter is the slice index `k` and there are no return values; all inputs and outputs are from and to global variables. ### Response: def cbpdnmd_ustep(k): """Do the U step of the cbpdn stage. ...
def set_ground_width(self, ground_width): '''set ground width of view''' state = self.state state.ground_width = ground_width state.panel.re_center(state.width/2, state.height/2, state.lat, state.lon)
set ground width of view
Below is the the instruction that describes the task: ### Input: set ground width of view ### Response: def set_ground_width(self, ground_width): '''set ground width of view''' state = self.state state.ground_width = ground_width state.panel.re_center(state.width/2, state.height/2, ...
def evaluate(self, sequence, transformations): """ Execute the sequence of transformations in parallel :param sequence: Sequence to evaluation :param transformations: Transformations to apply :return: Resulting sequence or value """ result = sequence paral...
Execute the sequence of transformations in parallel :param sequence: Sequence to evaluation :param transformations: Transformations to apply :return: Resulting sequence or value
Below is the the instruction that describes the task: ### Input: Execute the sequence of transformations in parallel :param sequence: Sequence to evaluation :param transformations: Transformations to apply :return: Resulting sequence or value ### Response: def evaluate(self, sequence, trans...
def _get_autoscaling_min_max(template, parameters, asg_name): """Helper to extract the configured MinSize, MaxSize attributes from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param asg_name: logical resourc...
Helper to extract the configured MinSize, MaxSize attributes from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param asg_name: logical resource name of the autoscaling group :return: MinSize, MaxSize
Below is the the instruction that describes the task: ### Input: Helper to extract the configured MinSize, MaxSize attributes from the template. :param template: cloudformation template (json) :param parameters: list of {'ParameterKey': 'x1', 'ParameterValue': 'y1'} :param asg_name: logical resourc...
def decode(self, encoded_packet): """Decode a transmitted package. The return value indicates how many binary attachment packets are necessary to fully decode the packet. """ ep = encoded_packet try: self.packet_type = int(ep[0:1]) except TypeError: ...
Decode a transmitted package. The return value indicates how many binary attachment packets are necessary to fully decode the packet.
Below is the the instruction that describes the task: ### Input: Decode a transmitted package. The return value indicates how many binary attachment packets are necessary to fully decode the packet. ### Response: def decode(self, encoded_packet): """Decode a transmitted package. T...
def predict(self, X): """Rank samples according to survival times Lower ranks indicate shorter survival, higher ranks longer survival. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y...
Rank samples according to survival times Lower ranks indicate shorter survival, higher ranks longer survival. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : ndarray, shape = (n_samples,) ...
Below is the the instruction that describes the task: ### Input: Rank samples according to survival times Lower ranks indicate shorter survival, higher ranks longer survival. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. ...
def parse_stations(html): """ Strips JS code, loads JSON """ html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '') html = json.loads(html) return html['suggestions']
Strips JS code, loads JSON
Below is the the instruction that describes the task: ### Input: Strips JS code, loads JSON ### Response: def parse_stations(html): """ Strips JS code, loads JSON """ html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '') html = json.loads(html) return html['suggestio...
def get_stations(self): """ Retrieves all of the user's stations registered on the Stations API. :returns: list of *pyowm.stationsapi30.station.Station* objects """ status, data = self.http_client.get_json( STATIONS_URI, params={'appid': self.API_key}, ...
Retrieves all of the user's stations registered on the Stations API. :returns: list of *pyowm.stationsapi30.station.Station* objects
Below is the the instruction that describes the task: ### Input: Retrieves all of the user's stations registered on the Stations API. :returns: list of *pyowm.stationsapi30.station.Station* objects ### Response: def get_stations(self): """ Retrieves all of the user's stations registered on...
def parse(self, limit=None): """ :param limit: :return: """ if limit is not None: LOG.info("Only parsing first %s rows fo each file", str(limit)) LOG.info("Parsing files...") if self.test_only: self.test_mode = True self._proces...
:param limit: :return:
Below is the the instruction that describes the task: ### Input: :param limit: :return: ### Response: def parse(self, limit=None): """ :param limit: :return: """ if limit is not None: LOG.info("Only parsing first %s rows fo each file", str(limit)) ...
def InvalidLineEnd(self, bad_line_end, context=None, type=TYPE_WARNING): """bad_line_end is a human readable string.""" e = InvalidLineEnd(bad_line_end=bad_line_end, context=context, context2=self._context, type=type) self.AddToAccumulator(e)
bad_line_end is a human readable string.
Below is the the instruction that describes the task: ### Input: bad_line_end is a human readable string. ### Response: def InvalidLineEnd(self, bad_line_end, context=None, type=TYPE_WARNING): """bad_line_end is a human readable string.""" e = InvalidLineEnd(bad_line_end=bad_line_end, context=context, ...
def find_egg(self, egg_dist): """Find an egg by name in the given environment""" site_packages = self.libdir[1] search_filename = "{0}.egg-link".format(egg_dist.project_name) try: user_site = site.getusersitepackages() except AttributeError: user_site = si...
Find an egg by name in the given environment
Below is the the instruction that describes the task: ### Input: Find an egg by name in the given environment ### Response: def find_egg(self, egg_dist): """Find an egg by name in the given environment""" site_packages = self.libdir[1] search_filename = "{0}.egg-link".format(egg_dist.projec...
def init_state_from_encoder(self, encoder_outputs, encoder_valid_length=None): """Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list ...
Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list The decoder states, includes: - mem_value : NDArray - me...
Below is the the instruction that describes the task: ### Input: Initialize the state from the encoder outputs. Parameters ---------- encoder_outputs : list encoder_valid_length : NDArray or None Returns ------- decoder_states : list The decoder ...
def comparable(self): """str: comparable representation of the path specification.""" string_parts = [] if self.cipher_mode: string_parts.append('cipher_mode: {0:s}'.format(self.cipher_mode)) if self.encryption_method: string_parts.append('encryption_method: {0:s}'.format( self.e...
str: comparable representation of the path specification.
Below is the the instruction that describes the task: ### Input: str: comparable representation of the path specification. ### Response: def comparable(self): """str: comparable representation of the path specification.""" string_parts = [] if self.cipher_mode: string_parts.append('cipher_mode: ...
def get_config(config_file): """Get configuration from a file.""" def load(fp): try: return yaml.safe_load(fp) except yaml.YAMLError as e: sys.stderr.write(text_type(e)) sys.exit(1) # TODO document exit codes if config_file == '-': return load(sy...
Get configuration from a file.
Below is the the instruction that describes the task: ### Input: Get configuration from a file. ### Response: def get_config(config_file): """Get configuration from a file.""" def load(fp): try: return yaml.safe_load(fp) except yaml.YAMLError as e: sys.stderr.write(t...
def to_table(components, topo_info): """ normalize raw logical plan info to table """ inputs, outputs = defaultdict(list), defaultdict(list) for ctype, component in components.items(): if ctype == 'bolts': for component_name, component_info in component.items(): for input_stream in component_inf...
normalize raw logical plan info to table
Below is the the instruction that describes the task: ### Input: normalize raw logical plan info to table ### Response: def to_table(components, topo_info): """ normalize raw logical plan info to table """ inputs, outputs = defaultdict(list), defaultdict(list) for ctype, component in components.items(): ...
def logpdf_link(self, link_f, y, Y_metadata=None): """ Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = -\\lambda(f_{i}) + y_{i}\\log \\lambda(f_{i}) - \\log y_{i}! :param link_f: latent variables (link(f)) :type link_f: Nx1 array ...
Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = -\\lambda(f_{i}) + y_{i}\\log \\lambda(f_{i}) - \\log y_{i}! :param link_f: latent variables (link(f)) :type link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadata:...
Below is the the instruction that describes the task: ### Input: Log Likelihood Function given link(f) .. math:: \\ln p(y_{i}|\lambda(f_{i})) = -\\lambda(f_{i}) + y_{i}\\log \\lambda(f_{i}) - \\log y_{i}! :param link_f: latent variables (link(f)) :type link_f: Nx1 array ...
def _load_profile(self, profile_name): """Load a profile by name Called by load_user_options """ # find the profile default_profile = self._profile_list[0] for profile in self._profile_list: if profile.get('default', False): # explicit defaul...
Load a profile by name Called by load_user_options
Below is the the instruction that describes the task: ### Input: Load a profile by name Called by load_user_options ### Response: def _load_profile(self, profile_name): """Load a profile by name Called by load_user_options """ # find the profile default_profile = ...
def language_match(self, cpeset, cpel_dom=None): """ Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applic...
Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applicability Language, represented as the XML infoset for the ...
Below is the the instruction that describes the task: ### Input: Accepts a set of known CPE Names and an expression in the CPE language, and delivers the answer True if the expression matches with the set. Otherwise, it returns False. :param CPELanguage self: An expression in the CPE Applic...
def fake2db_logger(): '''creates a logger obj''' # Pull the local ip and username for meaningful logging username = getpass.getuser() # Set the logger FORMAT = '%(asctime)-15s %(user)-8s %(message)s' logging.basicConfig(format=FORMAT) extra_information = {'user': username} logger = ...
creates a logger obj
Below is the the instruction that describes the task: ### Input: creates a logger obj ### Response: def fake2db_logger(): '''creates a logger obj''' # Pull the local ip and username for meaningful logging username = getpass.getuser() # Set the logger FORMAT = '%(asctime)-15s %(user)-8s %(m...
def index(self, axes): """ :param axes: The Axes instance to find the index of. :type axes: Axes :rtype: int """ return None if axes is self._colormap_axes else self._axes.index(axes)
:param axes: The Axes instance to find the index of. :type axes: Axes :rtype: int
Below is the the instruction that describes the task: ### Input: :param axes: The Axes instance to find the index of. :type axes: Axes :rtype: int ### Response: def index(self, axes): """ :param axes: The Axes instance to find the index of. :type axes: Axes :rtype: i...
def yesterday(date=None): """yesterday once more""" if not date: return _date - datetime.timedelta(days=1) else: current_date = parse(date) return current_date - datetime.timedelta(days=1)
yesterday once more
Below is the the instruction that describes the task: ### Input: yesterday once more ### Response: def yesterday(date=None): """yesterday once more""" if not date: return _date - datetime.timedelta(days=1) else: current_date = parse(date) return current_date - datetime.timedelta...
def RootNode(self): """Return our current root node and appropriate adapter for it""" tree = self.loader.get_root( self.viewType ) adapter = self.loader.get_adapter( self.viewType ) rows = self.loader.get_rows( self.viewType ) adapter.SetPercentage(self.percentageView, a...
Return our current root node and appropriate adapter for it
Below is the the instruction that describes the task: ### Input: Return our current root node and appropriate adapter for it ### Response: def RootNode(self): """Return our current root node and appropriate adapter for it""" tree = self.loader.get_root( self.viewType ) adapter = self.loader...
def next_run_in(self, utc_now=None): """ :param utc_now: optional parameter to be used by Unit Tests as a definition of "now" :return: timedelta instance presenting amount of time before the trigger is triggered next time or None if the RepeatTimer instance is not running """ if utc...
:param utc_now: optional parameter to be used by Unit Tests as a definition of "now" :return: timedelta instance presenting amount of time before the trigger is triggered next time or None if the RepeatTimer instance is not running
Below is the the instruction that describes the task: ### Input: :param utc_now: optional parameter to be used by Unit Tests as a definition of "now" :return: timedelta instance presenting amount of time before the trigger is triggered next time or None if the RepeatTimer instance is not runnin...