code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def compute_displays( self, program: Union[circuits.Circuit, schedules.Schedule], param_resolver: study.ParamResolver = study.ParamResolver({}), qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT, initial_state: Union[int, np.ndarray] = 0, ) -> study.ComputeDisplaysRe...
Computes displays in the supplied Circuit or Schedule. Args: program: The circuit or schedule to simulate. param_resolver: Parameters to run with the program. qubit_order: Determines the canonical ordering of the qubits used to define the order of amplitudes ...
Below is the the instruction that describes the task: ### Input: Computes displays in the supplied Circuit or Schedule. Args: program: The circuit or schedule to simulate. param_resolver: Parameters to run with the program. qubit_order: Determines the canonical ordering ...
def get_interval_timedelta(self): """ Spits out the timedelta in days. """ now_datetime = timezone.now() current_month_days = monthrange(now_datetime.year, now_datetime.month)[1] # Two weeks if self.interval == reminders_choices.INTERVAL_2_WEEKS: interval_timedelta ...
Spits out the timedelta in days.
Below is the the instruction that describes the task: ### Input: Spits out the timedelta in days. ### Response: def get_interval_timedelta(self): """ Spits out the timedelta in days. """ now_datetime = timezone.now() current_month_days = monthrange(now_datetime.year, now_datetime.month)[1]...
def document_did_save_notification(self, params): """ Handle the textDocument/didSave message received from an LSP server. """ text = None if 'text' in params: text = params['text'] params = { 'textDocument': { 'uri': path_as_uri(pa...
Handle the textDocument/didSave message received from an LSP server.
Below is the the instruction that describes the task: ### Input: Handle the textDocument/didSave message received from an LSP server. ### Response: def document_did_save_notification(self, params): """ Handle the textDocument/didSave message received from an LSP server. """ text = N...
def max_speed(self): """ Returns the maximum value that is accepted by the `speed_sp` attribute. This may be slightly different than the maximum speed that a particular motor can reach - it's the maximum theoretical speed. """ (self._max_speed, value) = self.get_cached_at...
Returns the maximum value that is accepted by the `speed_sp` attribute. This may be slightly different than the maximum speed that a particular motor can reach - it's the maximum theoretical speed.
Below is the the instruction that describes the task: ### Input: Returns the maximum value that is accepted by the `speed_sp` attribute. This may be slightly different than the maximum speed that a particular motor can reach - it's the maximum theoretical speed. ### Response: def max_speed(self): ...
def remove_all(self, token): """Removes all occurrences of token :param token: string to remove :return: input without token """ out = self.string.replace(" ", token) # replace tokens while out.find(token + token) >= 0: # while there are tokens out = out.r...
Removes all occurrences of token :param token: string to remove :return: input without token
Below is the the instruction that describes the task: ### Input: Removes all occurrences of token :param token: string to remove :return: input without token ### Response: def remove_all(self, token): """Removes all occurrences of token :param token: string to remove :retu...
def no_company_with_insufficient_companies_house_data(value): """ Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError """ for p...
Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError
Below is the the instruction that describes the task: ### Input: Confirms that the company number is not for for a company that Companies House does not hold information on. Args: value (string): The company number to check. Raises: django.forms.ValidationError ### Response: def no_co...
def _ctype_key_value(keys, vals): """ Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only. """ if isinstance(keys, (tuple, list)): assert(len(keys) == len(vals)) c_keys = [] c_vals = [] use_str_keys = None f...
Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only.
Below is the the instruction that describes the task: ### Input: Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only. ### Response: def _ctype_key_value(keys, vals): """ Returns ctype arrays for the key-value args, and the whether string keys are use...
def generate_query_batches( self, sql, params=None, param_types=None, partition_size_bytes=None, max_partitions=None, ): """Start a partitioned query operation. Uses the ``PartitionQuery`` API request to start a partitioned query operation. R...
Start a partitioned query operation. Uses the ``PartitionQuery`` API request to start a partitioned query operation. Returns a list of batch information needed to peform the actual queries. :type sql: str :param sql: SQL query statement :type params: dict, {str -> col...
Below is the the instruction that describes the task: ### Input: Start a partitioned query operation. Uses the ``PartitionQuery`` API request to start a partitioned query operation. Returns a list of batch information needed to peform the actual queries. :type sql: str :pa...
def parse(self, xml_data): """ Parse XML data """ # parse tree if isinstance(xml_data, string_types): # Presumably, this is textual xml data. try: root = ET.fromstring(xml_data) except StdlibParseError as e: raise ParseError(st...
Parse XML data
Below is the the instruction that describes the task: ### Input: Parse XML data ### Response: def parse(self, xml_data): """ Parse XML data """ # parse tree if isinstance(xml_data, string_types): # Presumably, this is textual xml data. try: root = ET...
def wrap_get_channel(cls, response): """Wrap the response from getting a channel into an instance and return it :param response: The response from getting a channel :type response: :class:`requests.Response` :returns: the new channel instance :rtype: :class:`list` of :cl...
Wrap the response from getting a channel into an instance and return it :param response: The response from getting a channel :type response: :class:`requests.Response` :returns: the new channel instance :rtype: :class:`list` of :class:`channel` :raises: None
Below is the the instruction that describes the task: ### Input: Wrap the response from getting a channel into an instance and return it :param response: The response from getting a channel :type response: :class:`requests.Response` :returns: the new channel instance :rtype:...
def get_segment_token_offsets(segment_token_list, token_map): """ given a list of token node IDs, returns the index of its first and last elements. this actually calculates the int indices, as there are weird formats like RS3, which use unordered / wrongly ordered IDs. Parameters ---------- ...
given a list of token node IDs, returns the index of its first and last elements. this actually calculates the int indices, as there are weird formats like RS3, which use unordered / wrongly ordered IDs. Parameters ---------- segment_token_list : list of str sorted list of token IDs (i.e. t...
Below is the the instruction that describes the task: ### Input: given a list of token node IDs, returns the index of its first and last elements. this actually calculates the int indices, as there are weird formats like RS3, which use unordered / wrongly ordered IDs. Parameters ---------- segm...
def register(self, type, parser, composer, **meta): """Registers a parser and composer of a format. You can use this method to overwrite existing formats. :param type: The unique name of the format :param parser: The method to parse data as the format :param composer: The metho...
Registers a parser and composer of a format. You can use this method to overwrite existing formats. :param type: The unique name of the format :param parser: The method to parse data as the format :param composer: The method to compose data as the format :param meta: The extra ...
Below is the the instruction that describes the task: ### Input: Registers a parser and composer of a format. You can use this method to overwrite existing formats. :param type: The unique name of the format :param parser: The method to parse data as the format :param composer: The...
def computeSmartIndent(self, block, ch): """special rules: ;;; -> indent 0 ;; -> align with next line, if possible ; -> usually on the same line as code -> ignore """ if re.search(r'^\s*;;;', block.text()): return '' elif...
special rules: ;;; -> indent 0 ;; -> align with next line, if possible ; -> usually on the same line as code -> ignore
Below is the the instruction that describes the task: ### Input: special rules: ;;; -> indent 0 ;; -> align with next line, if possible ; -> usually on the same line as code -> ignore ### Response: def computeSmartIndent(self, block, ch): """special ru...
def next(self): """ Sends a "next" command to the player. """ msg = cr.Message() msg.type = cr.NEXT self.send_message(msg)
Sends a "next" command to the player.
Below is the the instruction that describes the task: ### Input: Sends a "next" command to the player. ### Response: def next(self): """ Sends a "next" command to the player. """ msg = cr.Message() msg.type = cr.NEXT self.send_message(msg)
def phantomjs_get(url): """ Perform the request via PhantomJS. """ from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities dcap = dict(DesiredCapabilities.PHANTOMJS) dcap["phantomjs.page.settings.userAgent"] = config.USER_AGENT dcap[...
Perform the request via PhantomJS.
Below is the the instruction that describes the task: ### Input: Perform the request via PhantomJS. ### Response: def phantomjs_get(url): """ Perform the request via PhantomJS. """ from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities ...
def create_many(self, statements): """ Creates multiple statement entries. """ Statement = self.get_model('statement') Tag = self.get_model('tag') tag_cache = {} for statement in statements: statement_data = statement.serialize() tag_dat...
Creates multiple statement entries.
Below is the the instruction that describes the task: ### Input: Creates multiple statement entries. ### Response: def create_many(self, statements): """ Creates multiple statement entries. """ Statement = self.get_model('statement') Tag = self.get_model('tag') tag_...
def previous_sibling(self): """The previous sibling statement. :returns: The previous sibling statement node. :rtype: NodeNG or None """ stmts = self.parent.child_sequence(self) index = stmts.index(self) if index >= 1: return stmts[index - 1] ...
The previous sibling statement. :returns: The previous sibling statement node. :rtype: NodeNG or None
Below is the the instruction that describes the task: ### Input: The previous sibling statement. :returns: The previous sibling statement node. :rtype: NodeNG or None ### Response: def previous_sibling(self): """The previous sibling statement. :returns: The previous sibling statem...
def get_forecast(self) -> List[SmhiForecast]: """ Returns a list of forecasts. The first in list are the current one """ json_data = self._api.get_forecast_api(self._longitude, self._latitude) return _get_forecast(json_data)
Returns a list of forecasts. The first in list are the current one
Below is the the instruction that describes the task: ### Input: Returns a list of forecasts. The first in list are the current one ### Response: def get_forecast(self) -> List[SmhiForecast]: """ Returns a list of forecasts. The first in list are the current one """ json_data = ...
def getNextEyeLocation(self, currentEyeLoc): """ Generate next eye location based on current eye location. @param currentEyeLoc (numpy.array) Current coordinate describing the eye location in the world. @return (tuple) Contains: nextEyeLoc (numpy.array) Coordinate ...
Generate next eye location based on current eye location. @param currentEyeLoc (numpy.array) Current coordinate describing the eye location in the world. @return (tuple) Contains: nextEyeLoc (numpy.array) Coordinate of the next eye location. eyeDiff (numpy...
Below is the the instruction that describes the task: ### Input: Generate next eye location based on current eye location. @param currentEyeLoc (numpy.array) Current coordinate describing the eye location in the world. @return (tuple) Contains: nextEyeLoc (numpy.array) ...
def comment(self, format, *args): """ Add a comment to hash table before saving to disk. You can add as many comment lines as you like. These comment lines are discarded when loading the file. If you use a null format, all comments are deleted. """ return lib.zhash_comment(self._as_param...
Add a comment to hash table before saving to disk. You can add as many comment lines as you like. These comment lines are discarded when loading the file. If you use a null format, all comments are deleted.
Below is the the instruction that describes the task: ### Input: Add a comment to hash table before saving to disk. You can add as many comment lines as you like. These comment lines are discarded when loading the file. If you use a null format, all comments are deleted. ### Response: def comment(self, format, *ar...
def load_schema(name): """ Load a schema from ./schemas/``name``.json and return it. """ data = pkgutil.get_data('jsonschema', "schemas/{0}.json".format(name)) return json.loads(data.decode("utf-8"))
Load a schema from ./schemas/``name``.json and return it.
Below is the the instruction that describes the task: ### Input: Load a schema from ./schemas/``name``.json and return it. ### Response: def load_schema(name): """ Load a schema from ./schemas/``name``.json and return it. """ data = pkgutil.get_data('jsonschema', "schemas/{0}.json".format(name)) ...
def find_output_with_ifo(self, ifo): """ Find all files who have ifo = ifo """ # Enforce upper case ifo = ifo.upper() return FileList([i for i in self if ifo in i.ifo_list])
Find all files who have ifo = ifo
Below is the the instruction that describes the task: ### Input: Find all files who have ifo = ifo ### Response: def find_output_with_ifo(self, ifo): """ Find all files who have ifo = ifo """ # Enforce upper case ifo = ifo.upper() return FileList([i for i in self if ...
def union(self, second_iterable, selector=identity): '''Returns those elements which are either in the source sequence or in the second_iterable, or in both. Note: This method uses deferred execution. Args: second_iterable: Elements from this sequence are returns if they ...
Returns those elements which are either in the source sequence or in the second_iterable, or in both. Note: This method uses deferred execution. Args: second_iterable: Elements from this sequence are returns if they are not also in the source sequence. ...
Below is the the instruction that describes the task: ### Input: Returns those elements which are either in the source sequence or in the second_iterable, or in both. Note: This method uses deferred execution. Args: second_iterable: Elements from this sequence are returns if th...
def devices(self): """ Returns a list of all :class:`~plexapi.myplex.MyPlexDevice` objects connected to the server. """ data = self.query(MyPlexDevice.key) return [MyPlexDevice(self, elem) for elem in data]
Returns a list of all :class:`~plexapi.myplex.MyPlexDevice` objects connected to the server.
Below is the the instruction that describes the task: ### Input: Returns a list of all :class:`~plexapi.myplex.MyPlexDevice` objects connected to the server. ### Response: def devices(self): """ Returns a list of all :class:`~plexapi.myplex.MyPlexDevice` objects connected to the server. """ data = ...
def CaptureNamedVariable(self, name, value, depth, limits): """Appends name to the product of CaptureVariable. Args: name: name of the variable. value: data to capture depth: nested depth of dictionaries and vectors so far. limits: Per-object limits for capturing variable data. Ret...
Appends name to the product of CaptureVariable. Args: name: name of the variable. value: data to capture depth: nested depth of dictionaries and vectors so far. limits: Per-object limits for capturing variable data. Returns: Formatted captured data as per Variable proto with name...
Below is the the instruction that describes the task: ### Input: Appends name to the product of CaptureVariable. Args: name: name of the variable. value: data to capture depth: nested depth of dictionaries and vectors so far. limits: Per-object limits for capturing variable data. R...
def ctypes2numpy(cptr, length, dtype): """Convert a ctypes pointer array to a numpy array. """ NUMPY_TO_CTYPES_MAPPING = { np.float32: ctypes.c_float, np.uint32: ctypes.c_uint, } if dtype not in NUMPY_TO_CTYPES_MAPPING: raise RuntimeError('Supported types: {}'.format(NUMPY_TO...
Convert a ctypes pointer array to a numpy array.
Below is the the instruction that describes the task: ### Input: Convert a ctypes pointer array to a numpy array. ### Response: def ctypes2numpy(cptr, length, dtype): """Convert a ctypes pointer array to a numpy array. """ NUMPY_TO_CTYPES_MAPPING = { np.float32: ctypes.c_float, np.uint3...
def _match_error_to_data_set(x, ex): """ Inflates ex to match the dimensionality of x, "intelligently". x is assumed to be a 2D array. """ # Simplest case, ex is None or a number if not _fun.is_iterable(ex): # Just make a matched list of Nones if ex is None: ex = [ex]*l...
Inflates ex to match the dimensionality of x, "intelligently". x is assumed to be a 2D array.
Below is the the instruction that describes the task: ### Input: Inflates ex to match the dimensionality of x, "intelligently". x is assumed to be a 2D array. ### Response: def _match_error_to_data_set(x, ex): """ Inflates ex to match the dimensionality of x, "intelligently". x is assumed to be a...
def _estimate_strains(self): """Compute an estimate of the strains.""" # Estimate the strain based on the PGV and shear-wave velocity for l in self._profile: l.reset() l.strain = self._motion.pgv / l.initial_shear_vel
Compute an estimate of the strains.
Below is the the instruction that describes the task: ### Input: Compute an estimate of the strains. ### Response: def _estimate_strains(self): """Compute an estimate of the strains.""" # Estimate the strain based on the PGV and shear-wave velocity for l in self._profile: l.rese...
def get_resource_type_from_included_serializer(self): """ Check to see it this resource has a different resource_name when included and return that name, or None """ field_name = self.field_name or self.parent.field_name parent = self.get_parent_serializer() if p...
Check to see it this resource has a different resource_name when included and return that name, or None
Below is the the instruction that describes the task: ### Input: Check to see it this resource has a different resource_name when included and return that name, or None ### Response: def get_resource_type_from_included_serializer(self): """ Check to see it this resource has a different reso...
def pmll(self,*args,**kwargs): """ NAME: pmll PURPOSE: return proper motion in Galactic longitude (in mas/yr) INPUT: t - (optional) time at which to get pmll (can be Quantity) v obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of ob...
NAME: pmll PURPOSE: return proper motion in Galactic longitude (in mas/yr) INPUT: t - (optional) time at which to get pmll (can be Quantity) v obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer in the Galactocent...
Below is the the instruction that describes the task: ### Input: NAME: pmll PURPOSE: return proper motion in Galactic longitude (in mas/yr) INPUT: t - (optional) time at which to get pmll (can be Quantity) v obs=[X,Y,Z,vx,vy,vz] - (optional) position ...
def Register(self, a, b, migrated_entity): """Registers a merge mapping. If a and b are both not None, this means that entities a and b were merged to produce migrated_entity. If one of a or b are not None, then it means it was not merged but simply migrated. The effect of a call to register is to...
Registers a merge mapping. If a and b are both not None, this means that entities a and b were merged to produce migrated_entity. If one of a or b are not None, then it means it was not merged but simply migrated. The effect of a call to register is to update a_merge_map and b_merge_map according ...
Below is the the instruction that describes the task: ### Input: Registers a merge mapping. If a and b are both not None, this means that entities a and b were merged to produce migrated_entity. If one of a or b are not None, then it means it was not merged but simply migrated. The effect of a cal...
def hill_climbing(problem, iterations_limit=0, viewer=None): ''' Hill climbing search. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Requires: SearchProblem.actions, Search...
Hill climbing search. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Requires: SearchProblem.actions, SearchProblem.result, and SearchProblem.value.
Below is the the instruction that describes the task: ### Input: Hill climbing search. If iterations_limit is specified, the algorithm will end after that number of iterations. Else, it will continue until it can't find a better node than the current one. Requires: SearchProblem.actions, SearchProb...
def Buscar(self, nro_doc, tipo_doc=80): "Devuelve True si fue encontrado y establece atributos con datos" # cuit: codigo único de identificación tributaria del contribuyente # (sin guiones) self.cursor.execute("SELECT * FROM padron WHERE " " tipo_doc=? A...
Devuelve True si fue encontrado y establece atributos con datos
Below is the the instruction that describes the task: ### Input: Devuelve True si fue encontrado y establece atributos con datos ### Response: def Buscar(self, nro_doc, tipo_doc=80): "Devuelve True si fue encontrado y establece atributos con datos" # cuit: codigo único de identificación tributaria ...
def update_port_ip_address(self): """Find the ip address that assinged to a port via DHCP The port database will be updated with the ip address. """ leases = None req = dict(ip='0.0.0.0') instances = self.get_vms_for_this_req(**req) if instances is None: ...
Find the ip address that assinged to a port via DHCP The port database will be updated with the ip address.
Below is the the instruction that describes the task: ### Input: Find the ip address that assinged to a port via DHCP The port database will be updated with the ip address. ### Response: def update_port_ip_address(self): """Find the ip address that assinged to a port via DHCP The port dat...
def set_scanner_alert_threshold(self, scanner_ids, alert_threshold): """Set the alert theshold for the given policies.""" for scanner_id in scanner_ids: self.logger.debug('Setting alert threshold for scanner {0} to {1}'.format(scanner_id, alert_threshold)) result = self.zap.ascan...
Set the alert theshold for the given policies.
Below is the the instruction that describes the task: ### Input: Set the alert theshold for the given policies. ### Response: def set_scanner_alert_threshold(self, scanner_ids, alert_threshold): """Set the alert theshold for the given policies.""" for scanner_id in scanner_ids: self.log...
def connections(self): """Get list of connections.""" self._check_session() status, data = self._rest.get_request('connections') return data
Get list of connections.
Below is the the instruction that describes the task: ### Input: Get list of connections. ### Response: def connections(self): """Get list of connections.""" self._check_session() status, data = self._rest.get_request('connections') return data
def merge(left, right): """ Merge two mappings objects together, combining overlapping Mappings, and favoring right-values left: The left Mapping object. right: The right (favored) Mapping object. NOTE: This is not commutative (merge(a,b) != merge(b,a)). """ merged = {} left_keys ...
Merge two mappings objects together, combining overlapping Mappings, and favoring right-values left: The left Mapping object. right: The right (favored) Mapping object. NOTE: This is not commutative (merge(a,b) != merge(b,a)).
Below is the the instruction that describes the task: ### Input: Merge two mappings objects together, combining overlapping Mappings, and favoring right-values left: The left Mapping object. right: The right (favored) Mapping object. NOTE: This is not commutative (merge(a,b) != merge(b,a)). ### Re...
def serialize_formula(formula): r'''Basic formula serializer to construct a consistently-formatted formula. This is necessary for handling user-supplied formulas, which are not always well formatted. Performs no sanity checking that elements are actually elements. Parameters ---------- ...
r'''Basic formula serializer to construct a consistently-formatted formula. This is necessary for handling user-supplied formulas, which are not always well formatted. Performs no sanity checking that elements are actually elements. Parameters ---------- formula : str Formula strin...
Below is the the instruction that describes the task: ### Input: r'''Basic formula serializer to construct a consistently-formatted formula. This is necessary for handling user-supplied formulas, which are not always well formatted. Performs no sanity checking that elements are actually elements. ...
def append_processor(self, proc, source_proc=None): "Append a new processor to the pipe" if source_proc is None and len(self.processors): source_proc = self.processors[0] if source_proc and not isinstance(source_proc, Processor): raise TypeError('source_proc must be a Pr...
Append a new processor to the pipe
Below is the the instruction that describes the task: ### Input: Append a new processor to the pipe ### Response: def append_processor(self, proc, source_proc=None): "Append a new processor to the pipe" if source_proc is None and len(self.processors): source_proc = self.processors[0] ...
def run_thermal_displacements(self, t_min=0, t_max=1000, t_step=10, temperatures=None, direction=None, freq_min=None...
Prepare thermal displacements calculation Parameters ---------- t_min, t_max, t_step : float, optional Minimum and maximum temperatures and the interval in this temperature range. Default valuues are 0, 1000, and 10. temperatures : array_like, optional ...
Below is the the instruction that describes the task: ### Input: Prepare thermal displacements calculation Parameters ---------- t_min, t_max, t_step : float, optional Minimum and maximum temperatures and the interval in this temperature range. Default valuues are 0,...
async def get_edit(self, message=None, *, timeout=None): """ Awaits for an edit after the last message to arrive. The arguments are the same as those for `get_response`. """ start_time = time.time() target_id = self._get_message_id(message) target_date = self._ed...
Awaits for an edit after the last message to arrive. The arguments are the same as those for `get_response`.
Below is the the instruction that describes the task: ### Input: Awaits for an edit after the last message to arrive. The arguments are the same as those for `get_response`. ### Response: async def get_edit(self, message=None, *, timeout=None): """ Awaits for an edit after the last message ...
def get_handler(self, handler_input, exception): # type: (Input, Exception) -> Union[AbstractExceptionHandler, None] """Get the exception handler that can handle the input and exception. :param handler_input: Generic input passed to the dispatcher. :type handler_inpu...
Get the exception handler that can handle the input and exception. :param handler_input: Generic input passed to the dispatcher. :type handler_input: Input :param exception: Exception thrown by :py:class:`ask_sdk_runtime.dispatch.GenericRequestDispatcher` ...
Below is the the instruction that describes the task: ### Input: Get the exception handler that can handle the input and exception. :param handler_input: Generic input passed to the dispatcher. :type handler_input: Input :param exception: Exception thrown by ...
def get_bucket(bucket_name, include_created=None, flags=FLAGS.ALL ^ FLAGS.CREATED_DATE, **conn): """ Orchestrates all the calls required to fully build out an S3 bucket in the following format: { "Arn": ..., "Name": ..., "Region": ..., "Owner": ..., "Grants": ......
Orchestrates all the calls required to fully build out an S3 bucket in the following format: { "Arn": ..., "Name": ..., "Region": ..., "Owner": ..., "Grants": ..., "GrantReferences": ..., "LifecycleRules": ..., "Logging": ..., "Policy": .....
Below is the the instruction that describes the task: ### Input: Orchestrates all the calls required to fully build out an S3 bucket in the following format: { "Arn": ..., "Name": ..., "Region": ..., "Owner": ..., "Grants": ..., "GrantReferences": ..., ...
def to_bytes(self, frame, state): """ Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. ...
Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``FramerState``. This object may be used to track...
Below is the the instruction that describes the task: ### Input: Convert a single frame into bytes that can be transmitted on the stream. :param frame: The frame to convert. Should be the same type of object returned by ``to_frame()``. :param state: An instance of ``F...
def team_info(): """Returns a list of team information dictionaries""" teams = __get_league_object().find('teams').findall('team') output = [] for team in teams: info = {} for x in team.attrib: info[x] = team.attrib[x] output.append(info) return output
Returns a list of team information dictionaries
Below is the the instruction that describes the task: ### Input: Returns a list of team information dictionaries ### Response: def team_info(): """Returns a list of team information dictionaries""" teams = __get_league_object().find('teams').findall('team') output = [] for team in teams: in...
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ sites.vs30 = 600 * np.ones(len(sites.vs30)) mean, stddevs = ...
See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.
Below is the the instruction that describes the task: ### Input: See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. ### Response: def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :m...
def get(cls, uni_char): """Return the general category code (as Unicode string) for the given Unicode character""" uni_char = unicod(uni_char) # Force to Unicode return unicod(unicodedata.category(uni_char))
Return the general category code (as Unicode string) for the given Unicode character
Below is the the instruction that describes the task: ### Input: Return the general category code (as Unicode string) for the given Unicode character ### Response: def get(cls, uni_char): """Return the general category code (as Unicode string) for the given Unicode character""" uni_char = unicod(un...
def predict(self, y, t=None, return_cov=True, return_var=False): """ Compute the conditional predictive distribution of the model You must call :func:`GP.compute` before this method. Args: y (array[n]): The observations at coordinates ``x`` from :func:`GP.co...
Compute the conditional predictive distribution of the model You must call :func:`GP.compute` before this method. Args: y (array[n]): The observations at coordinates ``x`` from :func:`GP.compute`. t (Optional[array[ntest]]): The independent coordinates where the...
Below is the the instruction that describes the task: ### Input: Compute the conditional predictive distribution of the model You must call :func:`GP.compute` before this method. Args: y (array[n]): The observations at coordinates ``x`` from :func:`GP.compute`. ...
def _top_element(self): """Returns top XML element.""" top = etree.Element("testsuites") comment = etree.Comment("Generated for testrun {}".format(self.testrun_id)) top.append(comment) return top
Returns top XML element.
Below is the the instruction that describes the task: ### Input: Returns top XML element. ### Response: def _top_element(self): """Returns top XML element.""" top = etree.Element("testsuites") comment = etree.Comment("Generated for testrun {}".format(self.testrun_id)) top.append(com...
def do_init(self, fs_settings, global_quota): fs_settings = deepcopy(fs_settings) # because we store some of the info, we need a deep copy ''' If the same restrictions are applied for many destinations, we use the same job to avoid processing files twice ''' for sender_s...
If the same restrictions are applied for many destinations, we use the same job to avoid processing files twice
Below is the the instruction that describes the task: ### Input: If the same restrictions are applied for many destinations, we use the same job to avoid processing files twice ### Response: def do_init(self, fs_settings, global_quota): fs_settings = deepcopy(fs_settings) # because we store some o...
def task_list( limit, filter_task_id, filter_status, filter_type, filter_label, filter_not_label, inexact, filter_requested_after, filter_requested_before, filter_completed_after, filter_completed_before, ): """ Executor for `globus task-list` """ def _proces...
Executor for `globus task-list`
Below is the the instruction that describes the task: ### Input: Executor for `globus task-list` ### Response: def task_list( limit, filter_task_id, filter_status, filter_type, filter_label, filter_not_label, inexact, filter_requested_after, filter_requested_before, filter_c...
def run_powerflow(self, session, method='onthefly', export_pypsa=False, debug=False): """ Performs power flow calculation for all MV grids Args: session : sqlalchemy.orm.session.Session Database session method: str Specify export method ...
Performs power flow calculation for all MV grids Args: session : sqlalchemy.orm.session.Session Database session method: str Specify export method If method='db' grid data will be exported to database If me...
Below is the the instruction that describes the task: ### Input: Performs power flow calculation for all MV grids Args: session : sqlalchemy.orm.session.Session Database session method: str Specify export method If method='db' grid dat...
def join(self): """ Waits until the state finished execution. """ if self.thread: self.thread.join() self.thread = None else: logger.debug("Cannot join {0}, as the state hasn't been started, yet or is already finished!".format(self))
Waits until the state finished execution.
Below is the the instruction that describes the task: ### Input: Waits until the state finished execution. ### Response: def join(self): """ Waits until the state finished execution. """ if self.thread: self.thread.join() self.thread = None else: ...
def stop(ctx, **kwargs): """ stop a vaping process """ update_context(ctx, kwargs) daemon = mk_daemon(ctx) daemon.stop()
stop a vaping process
Below is the the instruction that describes the task: ### Input: stop a vaping process ### Response: def stop(ctx, **kwargs): """ stop a vaping process """ update_context(ctx, kwargs) daemon = mk_daemon(ctx) daemon.stop()
def create_certificate(self, cert_info, request=False, valid_from=0, valid_to=315360000, sn=1, key_length=1024, hash_alg="sha256", write_to_file=False, cert_dir="", cipher_passphrase=None): """ Can create certificate reques...
Can create certificate requests, to be signed later by another certificate with the method create_cert_signed_certificate. If request is True. Can also create self signed root certificates if request is False. This is default behaviour. :param cert_info: Contains inform...
Below is the the instruction that describes the task: ### Input: Can create certificate requests, to be signed later by another certificate with the method create_cert_signed_certificate. If request is True. Can also create self signed root certificates if request is False. This is ...
def _access(self): # pragma: no cover """ Get the HTTP code status. :return: The matched HTTP status code. :rtype: int|None """ try: # We try to get the HTTP status code. if PyFunceble.INTERN["to_test_type"] == "url": # We are g...
Get the HTTP code status. :return: The matched HTTP status code. :rtype: int|None
Below is the the instruction that describes the task: ### Input: Get the HTTP code status. :return: The matched HTTP status code. :rtype: int|None ### Response: def _access(self): # pragma: no cover """ Get the HTTP code status. :return: The matched HTTP status code. ...
def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def auth_filter(app): return Swauth(app, conf) return auth_filter
Returns a WSGI filter app for use with paste.deploy.
Below is the the instruction that describes the task: ### Input: Returns a WSGI filter app for use with paste.deploy. ### Response: def filter_factory(global_conf, **local_conf): """Returns a WSGI filter app for use with paste.deploy.""" conf = global_conf.copy() conf.update(local_conf) def auth_f...
def create_authenticate_message(self, user_name, password, domain_name=None, workstation=None, server_certificate_hash=None): """ Create an NTLM AUTHENTICATE_MESSAGE based on the Ntlm context and the previous messages sent and received :param user_name: The user name of the user we are trying t...
Create an NTLM AUTHENTICATE_MESSAGE based on the Ntlm context and the previous messages sent and received :param user_name: The user name of the user we are trying to authenticate with :param password: The password of the user we are trying to authenticate with :param domain_name: The domain na...
Below is the the instruction that describes the task: ### Input: Create an NTLM AUTHENTICATE_MESSAGE based on the Ntlm context and the previous messages sent and received :param user_name: The user name of the user we are trying to authenticate with :param password: The password of the user we are ...
def fit_mle(self, init_vals, num_draws, seed=None, constrained_pos=None, print_res=True, method="BFGS", loss_tol=1e-06, gradient_tol=1e-06, maxiter=1000, ridge=...
Parameters ---------- init_vals : 1D ndarray. Should contain the initial values to start the optimization process with. There should be one value for each utility coefficient and shape parameter being estimated. num_draws : int. Should be greater t...
Below is the the instruction that describes the task: ### Input: Parameters ---------- init_vals : 1D ndarray. Should contain the initial values to start the optimization process with. There should be one value for each utility coefficient and shape parameter bein...
def get_context_data(self, **kwargs): """ Injects variables necessary for rendering the calendar into the context. Variables added are: `calendar`, `weekdays`, `month`, `next_month` and `previous_month`. """ data = super(BaseCalendarMonthView, self).get_context_data(**kwargs) ...
Injects variables necessary for rendering the calendar into the context. Variables added are: `calendar`, `weekdays`, `month`, `next_month` and `previous_month`.
Below is the the instruction that describes the task: ### Input: Injects variables necessary for rendering the calendar into the context. Variables added are: `calendar`, `weekdays`, `month`, `next_month` and `previous_month`. ### Response: def get_context_data(self, **kwargs): """ Injects...
def readTupleAndExtra(self, stream): """Read symbol and extrabits from stream. Returns symbol length, symbol, extraBits, extra >>> olleke.pos = 6 >>> MetablockLengthAlphabet().readTupleAndExtra(olleke) (2, Symbol(MLEN, 4), 16, 46) """ length, symbol = self.decodeP...
Read symbol and extrabits from stream. Returns symbol length, symbol, extraBits, extra >>> olleke.pos = 6 >>> MetablockLengthAlphabet().readTupleAndExtra(olleke) (2, Symbol(MLEN, 4), 16, 46)
Below is the the instruction that describes the task: ### Input: Read symbol and extrabits from stream. Returns symbol length, symbol, extraBits, extra >>> olleke.pos = 6 >>> MetablockLengthAlphabet().readTupleAndExtra(olleke) (2, Symbol(MLEN, 4), 16, 46) ### Response: def readTuple...
def updatepLvlGrid(self): ''' Update the grid of permanent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1. Identical to version in persistent shocks model, but pLvl=0 is manually a...
Update the grid of permanent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1. Identical to version in persistent shocks model, but pLvl=0 is manually added to the grid (because there is no ...
Below is the the instruction that describes the task: ### Input: Update the grid of permanent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1. Identical to version in persistent shocks model, b...
def save(self): """ Save existing record """ data = { "type": self.type, "data": self.data, "name": self.name, "priority": self.priority, "port": self.port, "ttl": self.ttl, "weight": self.weight, ...
Save existing record
Below is the the instruction that describes the task: ### Input: Save existing record ### Response: def save(self): """ Save existing record """ data = { "type": self.type, "data": self.data, "name": self.name, "priority": self.pri...
def calc_retinotopy(note, error, subject, clean, run_lh, run_rh, invert_rh_angle, max_in_eccen, min_in_eccen, angle_lh_file, theta_lh_file, eccen_lh_file, rho_lh_file, weight_lh_file, radius_lh_file, angle_rh_file, theta...
calc_retinotopy extracts the retinotopy options from the command line, loads the relevant files, and stores them as properties on the subject's lh and rh cortices.
Below is the the instruction that describes the task: ### Input: calc_retinotopy extracts the retinotopy options from the command line, loads the relevant files, and stores them as properties on the subject's lh and rh cortices. ### Response: def calc_retinotopy(note, error, subject, clean, run_lh, run_rh, ...
def linear(self, **paircoords): """ Linearize bin indices. This function is called by subclasses. Refer to the source code of :py:class:`RBinning` for an example. Parameters ---------- args : list a list of bin index, (xi, yi, zi, ..) Ret...
Linearize bin indices. This function is called by subclasses. Refer to the source code of :py:class:`RBinning` for an example. Parameters ---------- args : list a list of bin index, (xi, yi, zi, ..) Returns ------- linearlized bin index
Below is the the instruction that describes the task: ### Input: Linearize bin indices. This function is called by subclasses. Refer to the source code of :py:class:`RBinning` for an example. Parameters ---------- args : list a list of bin index, (xi, yi, zi,...
def set_hook(self, phase, action): """Allows setting hooks (attaching actions) for various uWSGI phases. :param str|unicode phase: See constants in ``.phases``. :param str|unicode|list|HookAction|list[HookAction] action: """ self._set('hook-%s' % phase, action, multi=True) ...
Allows setting hooks (attaching actions) for various uWSGI phases. :param str|unicode phase: See constants in ``.phases``. :param str|unicode|list|HookAction|list[HookAction] action:
Below is the the instruction that describes the task: ### Input: Allows setting hooks (attaching actions) for various uWSGI phases. :param str|unicode phase: See constants in ``.phases``. :param str|unicode|list|HookAction|list[HookAction] action: ### Response: def set_hook(self, phase, action): ...
def select_token(request, scopes='', new=False): """ Presents the user with a selection of applicable tokens for the requested view. """ @tokens_required(scopes=scopes, new=new) def _token_list(r, tokens): context = { 'tokens': tokens, 'base_template': app_settings.E...
Presents the user with a selection of applicable tokens for the requested view.
Below is the the instruction that describes the task: ### Input: Presents the user with a selection of applicable tokens for the requested view. ### Response: def select_token(request, scopes='', new=False): """ Presents the user with a selection of applicable tokens for the requested view. """ @t...
def session_preparation(self): """Prepare the session after the connection has been established.""" self.ansi_escape_codes = True self._test_channel_read() self.set_base_prompt() self.disable_paging() self.set_terminal_width(command="terminal width 511") # Clear t...
Prepare the session after the connection has been established.
Below is the the instruction that describes the task: ### Input: Prepare the session after the connection has been established. ### Response: def session_preparation(self): """Prepare the session after the connection has been established.""" self.ansi_escape_codes = True self._test_channel_...
def appendMissingSignatures(self): """ Store which accounts/keys are supposed to sign the transaction This method is used for an offline-signer! """ missing_signatures = self.get("missing_signatures", []) for pub in missing_signatures: wif = self.blockchain.walle...
Store which accounts/keys are supposed to sign the transaction This method is used for an offline-signer!
Below is the the instruction that describes the task: ### Input: Store which accounts/keys are supposed to sign the transaction This method is used for an offline-signer! ### Response: def appendMissingSignatures(self): """ Store which accounts/keys are supposed to sign the transaction ...
def confd_state_internal_cdb_client_subscription_twophase(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") internal = ET.SubElement(confd_state, "internal"...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def confd_state_internal_cdb_client_subscription_twophase(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", x...
def add_comment(self, page_id, text): """ Add comment into page :param page_id :param text """ data = {'type': 'comment', 'container': {'id': page_id, 'type': 'page', 'status': 'current'}, 'body': {'storage': {'value': text, 'representation...
Add comment into page :param page_id :param text
Below is the the instruction that describes the task: ### Input: Add comment into page :param page_id :param text ### Response: def add_comment(self, page_id, text): """ Add comment into page :param page_id :param text """ data = {'type': 'comment', ...
def sys_version(version_tuple): """ Set a temporary sys.version_info tuple :param version_tuple: a fake sys.version_info tuple """ old_version = sys.version_info sys.version_info = version_tuple yield sys.version_info = old_version
Set a temporary sys.version_info tuple :param version_tuple: a fake sys.version_info tuple
Below is the the instruction that describes the task: ### Input: Set a temporary sys.version_info tuple :param version_tuple: a fake sys.version_info tuple ### Response: def sys_version(version_tuple): """ Set a temporary sys.version_info tuple :param version_tuple: a fake sys.version_info tuple ...
def set_permission(self, username, virtual_host, configure_regex='.*', write_regex='.*', read_regex='.*'): """Set User permissions for the configured virtual host. :param str username: Username :param str virtual_host: Virtual host name :param str configure_regex:...
Set User permissions for the configured virtual host. :param str username: Username :param str virtual_host: Virtual host name :param str configure_regex: Permission pattern for configuration operations for this user. :param str write_regex: Permissio...
Below is the the instruction that describes the task: ### Input: Set User permissions for the configured virtual host. :param str username: Username :param str virtual_host: Virtual host name :param str configure_regex: Permission pattern for configuration ...
def make_node_dict(outer_list, sort="zone"): """Convert node data from nested-list to sorted dict.""" raw_dict = {} x = 1 for inner_list in outer_list: for node in inner_list: raw_dict[x] = node x += 1 if sort == "name": # sort by provider - name srt_dict = O...
Convert node data from nested-list to sorted dict.
Below is the the instruction that describes the task: ### Input: Convert node data from nested-list to sorted dict. ### Response: def make_node_dict(outer_list, sort="zone"): """Convert node data from nested-list to sorted dict.""" raw_dict = {} x = 1 for inner_list in outer_list: for node ...
def get_assessment_parts(self): """Gets all ``AssessmentParts``. return: (osid.assessment.authoring.AssessmentPartList) - a list of ``AssessmentParts`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *complian...
Gets all ``AssessmentParts``. return: (osid.assessment.authoring.AssessmentPartList) - a list of ``AssessmentParts`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implem...
Below is the the instruction that describes the task: ### Input: Gets all ``AssessmentParts``. return: (osid.assessment.authoring.AssessmentPartList) - a list of ``AssessmentParts`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization...
def correct_spurious_inversions(scaffolds, criterion="colinear"): """Invert bins based on orientation neighborhoods. Neighborhoods can be defined by three criteria: -a 'cis' neighborhood is a group of bins belonging to the same initial contig -a 'colinear' neighborhood is a 'cis' neighborhood where...
Invert bins based on orientation neighborhoods. Neighborhoods can be defined by three criteria: -a 'cis' neighborhood is a group of bins belonging to the same initial contig -a 'colinear' neighborhood is a 'cis' neighborhood where bins are ordered the same way they were on the initial contig -a...
Below is the the instruction that describes the task: ### Input: Invert bins based on orientation neighborhoods. Neighborhoods can be defined by three criteria: -a 'cis' neighborhood is a group of bins belonging to the same initial contig -a 'colinear' neighborhood is a 'cis' neighborhood where bin...
def await_socket(self, timeout): """Wait up to a given timeout for a process to write socket info.""" return self.await_metadata_by_name(self._name, 'socket', timeout, self._socket_type)
Wait up to a given timeout for a process to write socket info.
Below is the the instruction that describes the task: ### Input: Wait up to a given timeout for a process to write socket info. ### Response: def await_socket(self, timeout): """Wait up to a given timeout for a process to write socket info.""" return self.await_metadata_by_name(self._name, 'socket', timeou...
def find_pids(self, name, search_string, exact_match, ignore_ad=True): """ Create a set of pids of selected processes. Search for search_string """ if not self.should_refresh_pid_cache(name): return self.pid_cache[name] ad_error_logger = self.log.debug ...
Create a set of pids of selected processes. Search for search_string
Below is the the instruction that describes the task: ### Input: Create a set of pids of selected processes. Search for search_string ### Response: def find_pids(self, name, search_string, exact_match, ignore_ad=True): """ Create a set of pids of selected processes. Search for searc...
def kernel(self, spread=1): """ This will return whatever kind of kernel we want to use. Must have signature (ndarray size NxM, ndarray size 1xM) -> ndarray size Nx1 """ # TODO: use self.kernel_type to choose function def gaussian(data, pixel): return mvn.pdf(dat...
This will return whatever kind of kernel we want to use. Must have signature (ndarray size NxM, ndarray size 1xM) -> ndarray size Nx1
Below is the the instruction that describes the task: ### Input: This will return whatever kind of kernel we want to use. Must have signature (ndarray size NxM, ndarray size 1xM) -> ndarray size Nx1 ### Response: def kernel(self, spread=1): """ This will return whatever kind of kernel we want t...
def add_attachment(self, issue_key, filename): """ Add attachment to Issue :param issue_key: str :param filename: str, name, if file in current directory or full path to file """ log.warning('Adding attachment...') headers = {'X-Atlassian-Token': 'no-check'} ...
Add attachment to Issue :param issue_key: str :param filename: str, name, if file in current directory or full path to file
Below is the the instruction that describes the task: ### Input: Add attachment to Issue :param issue_key: str :param filename: str, name, if file in current directory or full path to file ### Response: def add_attachment(self, issue_key, filename): """ Add attachment to Issue ...
def _read_undone_shard_from_datastore(self, shard_id=None): """Reads undone worke pieces which are assigned to shard with given id.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) filters = [('is_completed', '=', False)] if sh...
Reads undone worke pieces which are assigned to shard with given id.
Below is the the instruction that describes the task: ### Input: Reads undone worke pieces which are assigned to shard with given id. ### Response: def _read_undone_shard_from_datastore(self, shard_id=None): """Reads undone worke pieces which are assigned to shard with given id.""" self._work = {} clie...
def publish(self, topic, *args, **kwargs): """Publish an event to a topic. Replace :meth:`autobahn.wamp.interface.IApplicationSession.publish` """ return self._async_session.publish(topic, *args, **kwargs)
Publish an event to a topic. Replace :meth:`autobahn.wamp.interface.IApplicationSession.publish`
Below is the the instruction that describes the task: ### Input: Publish an event to a topic. Replace :meth:`autobahn.wamp.interface.IApplicationSession.publish` ### Response: def publish(self, topic, *args, **kwargs): """Publish an event to a topic. Replace :meth:`autobahn.wamp.interface...
def to_yaml(obj): """ This function returns correct YAML representation of a UAVCAN structure (message, request, or response), or a DSDL entity (array or primitive), or a UAVCAN transfer, with comments for human benefit. Args: obj: Object to convert. Returns: Unicode string conta...
This function returns correct YAML representation of a UAVCAN structure (message, request, or response), or a DSDL entity (array or primitive), or a UAVCAN transfer, with comments for human benefit. Args: obj: Object to convert. Returns: Unicode string containing YAML representation of t...
Below is the the instruction that describes the task: ### Input: This function returns correct YAML representation of a UAVCAN structure (message, request, or response), or a DSDL entity (array or primitive), or a UAVCAN transfer, with comments for human benefit. Args: obj: Object to conv...
def _parse_hparams(hparams): """Split hparams, based on key prefixes. Args: hparams: hyperparameters Returns: Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. """ prefixes = ["agent_", "optimizer_", "runner_", "replay_buffer_"] ret = [] for prefix in prefixes: ret_...
Split hparams, based on key prefixes. Args: hparams: hyperparameters Returns: Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer.
Below is the the instruction that describes the task: ### Input: Split hparams, based on key prefixes. Args: hparams: hyperparameters Returns: Tuple of hparams for respectably: agent, optimizer, runner, replay_buffer. ### Response: def _parse_hparams(hparams): """Split hparams, based on key prefixe...
def _getOpenID1SessionType(self, assoc_response): """Given an association response message, extract the OpenID 1.X session type. This function mostly takes care of the 'no-encryption' default behavior in OpenID 1. If the association type is plain-text, this function will ...
Given an association response message, extract the OpenID 1.X session type. This function mostly takes care of the 'no-encryption' default behavior in OpenID 1. If the association type is plain-text, this function will return 'no-encryption' @returns: The association t...
Below is the the instruction that describes the task: ### Input: Given an association response message, extract the OpenID 1.X session type. This function mostly takes care of the 'no-encryption' default behavior in OpenID 1. If the association type is plain-text, this function wil...
def DropTables(self): """Drop all existing tables.""" rows, _ = self.ExecuteQuery( "SELECT table_name FROM information_schema.tables " "WHERE table_schema='%s'" % self.database_name) for row in rows: self.ExecuteQuery("DROP TABLE `%s`" % row["table_name"])
Drop all existing tables.
Below is the the instruction that describes the task: ### Input: Drop all existing tables. ### Response: def DropTables(self): """Drop all existing tables.""" rows, _ = self.ExecuteQuery( "SELECT table_name FROM information_schema.tables " "WHERE table_schema='%s'" % self.database_name) ...
def set_state(self): """ Sets the state required for this vertex region. Currently binds and enables the texture of the material of the region. """ glEnable(self.region.material.target) glBindTexture(self.region.material.target, self.region.material.id) s...
Sets the state required for this vertex region. Currently binds and enables the texture of the material of the region.
Below is the the instruction that describes the task: ### Input: Sets the state required for this vertex region. Currently binds and enables the texture of the material of the region. ### Response: def set_state(self): """ Sets the state required for this vertex region. ...
def set_XY(self, X, Y): """ Set the input / output data of the model This is useful if we wish to change our existing data but maintain the same model :param X: input observations :type X: np.ndarray :param Y: output observations :type Y: np.ndarray or ObsAr ...
Set the input / output data of the model This is useful if we wish to change our existing data but maintain the same model :param X: input observations :type X: np.ndarray :param Y: output observations :type Y: np.ndarray or ObsAr
Below is the the instruction that describes the task: ### Input: Set the input / output data of the model This is useful if we wish to change our existing data but maintain the same model :param X: input observations :type X: np.ndarray :param Y: output observations :type Y:...
def decode(input, output): """Decode a file.""" while True: line = input.readline() if not line: break s = binascii.a2b_base64(line) output.write(s)
Decode a file.
Below is the the instruction that describes the task: ### Input: Decode a file. ### Response: def decode(input, output): """Decode a file.""" while True: line = input.readline() if not line: break s = binascii.a2b_base64(line) output.write(s)
def get_fields(model_class, field_name='', path=''): """ Get fields and meta data from a model :param model_class: A django model class :param field_name: The field name to get sub fields from :param path: path of our field in format field_name__second_field_name__ect__ :returns: Returns fi...
Get fields and meta data from a model :param model_class: A django model class :param field_name: The field name to get sub fields from :param path: path of our field in format field_name__second_field_name__ect__ :returns: Returns fields and meta data about such fields fields: Django m...
Below is the the instruction that describes the task: ### Input: Get fields and meta data from a model :param model_class: A django model class :param field_name: The field name to get sub fields from :param path: path of our field in format field_name__second_field_name__ect__ :returns: Re...
def _parse_qualimap_rnaseq(table): """ Retrieve metrics of interest from globals table. """ out = {} for row in table.find_all("tr"): col, val = [x.text for x in row.find_all("td")] col = col.replace(":", "").strip() val = val.replace(",", "") m = {col: val} i...
Retrieve metrics of interest from globals table.
Below is the the instruction that describes the task: ### Input: Retrieve metrics of interest from globals table. ### Response: def _parse_qualimap_rnaseq(table): """ Retrieve metrics of interest from globals table. """ out = {} for row in table.find_all("tr"): col, val = [x.text for x ...
def button_press(self, terminal, event): """Handles the button press event in the terminal widget. If any match string is caught, another application is open to handle the matched resource uri. """ self.matched_value = '' if (Vte.MAJOR_VERSION, Vte.MINOR_VERSION) >= (0, 4...
Handles the button press event in the terminal widget. If any match string is caught, another application is open to handle the matched resource uri.
Below is the the instruction that describes the task: ### Input: Handles the button press event in the terminal widget. If any match string is caught, another application is open to handle the matched resource uri. ### Response: def button_press(self, terminal, event): """Handles the button...
def average_loss(lc): """ Given a loss curve array with `poe` and `loss` fields, computes the average loss on a period of time. :note: As the loss curve is supposed to be piecewise linear as it is a result of a linear interpolation, we compute an exact integral by using the trapei...
Given a loss curve array with `poe` and `loss` fields, computes the average loss on a period of time. :note: As the loss curve is supposed to be piecewise linear as it is a result of a linear interpolation, we compute an exact integral by using the trapeizodal rule with the width given by...
Below is the the instruction that describes the task: ### Input: Given a loss curve array with `poe` and `loss` fields, computes the average loss on a period of time. :note: As the loss curve is supposed to be piecewise linear as it is a result of a linear interpolation, we compute an exact ...
def flatten(value, prefix=None): """Takes an arbitrary JSON(ish) object and 'flattens' it into a dict with values consisting of either simple types or lists of simple types.""" def issimple(value): # foldr(True, or, value)? for item in value: if isinstance(item, dict) or isins...
Takes an arbitrary JSON(ish) object and 'flattens' it into a dict with values consisting of either simple types or lists of simple types.
Below is the the instruction that describes the task: ### Input: Takes an arbitrary JSON(ish) object and 'flattens' it into a dict with values consisting of either simple types or lists of simple types. ### Response: def flatten(value, prefix=None): """Takes an arbitrary JSON(ish) object and 'fla...
def split(self, N, force=False): """ There are two modes of splitting the records - batch: splitting is sequentially to records/N chunks - cycle: placing each record in the splitted files and cycles use `cycle` if the len of the record is not evenly distributed """ ...
There are two modes of splitting the records - batch: splitting is sequentially to records/N chunks - cycle: placing each record in the splitted files and cycles use `cycle` if the len of the record is not evenly distributed
Below is the the instruction that describes the task: ### Input: There are two modes of splitting the records - batch: splitting is sequentially to records/N chunks - cycle: placing each record in the splitted files and cycles use `cycle` if the len of the record is not evenly distributed #...
def append_item(self, item): """ Add an item to the end of the menu before the exit item :param MenuItem item: The item to be added """ did_remove = self.remove_exit() item.menu = self self.items.append(item) if did_remove: self.add_exit() ...
Add an item to the end of the menu before the exit item :param MenuItem item: The item to be added
Below is the the instruction that describes the task: ### Input: Add an item to the end of the menu before the exit item :param MenuItem item: The item to be added ### Response: def append_item(self, item): """ Add an item to the end of the menu before the exit item :param MenuIte...
def confd_state_internal_callpoints_authorization_callbacks_registration_type_daemon_daemon_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") internal ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def confd_state_internal_callpoints_authorization_callbacks_registration_type_daemon_daemon_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state =...
def next_task(self, item, **kwargs): """Calls import_batch for the next filename in the queue and "archives" the file. The archive folder is typically the folder for the deserializer queue. """ filename = os.path.basename(item) try: self.tx_importer.import_ba...
Calls import_batch for the next filename in the queue and "archives" the file. The archive folder is typically the folder for the deserializer queue.
Below is the the instruction that describes the task: ### Input: Calls import_batch for the next filename in the queue and "archives" the file. The archive folder is typically the folder for the deserializer queue. ### Response: def next_task(self, item, **kwargs): """Calls import_batch fo...
def filter_(predicate, *structures, **kwargs): # pylint: disable=differing-param-doc,missing-param-doc, too-many-branches """Select elements of a nested structure based on a predicate function. If multiple structures are provided as input, their structure must match and the function will be applied to correspo...
Select elements of a nested structure based on a predicate function. If multiple structures are provided as input, their structure must match and the function will be applied to corresponding groups of elements. The nested structure can consist of any combination of lists, tuples, and dicts. Args: predica...
Below is the the instruction that describes the task: ### Input: Select elements of a nested structure based on a predicate function. If multiple structures are provided as input, their structure must match and the function will be applied to corresponding groups of elements. The nested structure can consist...
def _process_docs(self, anexec, docblocks, parent, module, docsearch): """Associates the docstrings from the docblocks with their parameters.""" #The documentation for the parameters is stored outside of the executable #We need to get hold of them from docblocks from the parent text key ...
Associates the docstrings from the docblocks with their parameters.
Below is the the instruction that describes the task: ### Input: Associates the docstrings from the docblocks with their parameters. ### Response: def _process_docs(self, anexec, docblocks, parent, module, docsearch): """Associates the docstrings from the docblocks with their parameters.""" #The do...