code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_appointment_group(self, appointment_group): """ Return single Appointment Group by id :calls: `GET /api/v1/appointment_groups/:id \ <https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.show>`_ :param appointment_group: The ID of the ...
Return single Appointment Group by id :calls: `GET /api/v1/appointment_groups/:id \ <https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.show>`_ :param appointment_group: The ID of the appointment group. :type appointment_group: :class:`canvasapi.ap...
Below is the the instruction that describes the task: ### Input: Return single Appointment Group by id :calls: `GET /api/v1/appointment_groups/:id \ <https://canvas.instructure.com/doc/api/appointment_groups.html#method.appointment_groups.show>`_ :param appointment_group: The ID of the app...
def edge_detect(image, size): """ Applies a Sobel filter to the given image. :param image: An image as a list of (R,G,B) values :param size: The size of the image as a tuple (width, height) :return: An array of the Sobel gradient value of each image pixel This value roughly corresponds to how mu...
Applies a Sobel filter to the given image. :param image: An image as a list of (R,G,B) values :param size: The size of the image as a tuple (width, height) :return: An array of the Sobel gradient value of each image pixel This value roughly corresponds to how much of an "edge" a pixel is.
Below is the the instruction that describes the task: ### Input: Applies a Sobel filter to the given image. :param image: An image as a list of (R,G,B) values :param size: The size of the image as a tuple (width, height) :return: An array of the Sobel gradient value of each image pixel This value ro...
def tag(self): """ Get the string representation of the tag used to annotate the status in VOSpace. @return: str """ return "{}{}_{}{:02d}".format(self.target.prefix, self, self.target.version, ...
Get the string representation of the tag used to annotate the status in VOSpace. @return: str
Below is the the instruction that describes the task: ### Input: Get the string representation of the tag used to annotate the status in VOSpace. @return: str ### Response: def tag(self): """ Get the string representation of the tag used to annotate the status in VOSpace. @return: s...
async def _get_cdn_client(self, cdn_redirect): """Similar to ._borrow_exported_client, but for CDNs""" # TODO Implement raise NotImplementedError session = self._exported_sessions.get(cdn_redirect.dc_id) if not session: dc = await self._get_dc(cdn_redirect.dc_id, cdn=...
Similar to ._borrow_exported_client, but for CDNs
Below is the the instruction that describes the task: ### Input: Similar to ._borrow_exported_client, but for CDNs ### Response: async def _get_cdn_client(self, cdn_redirect): """Similar to ._borrow_exported_client, but for CDNs""" # TODO Implement raise NotImplementedError session ...
def DbDeleteDeviceAttribute(self, argin): """ Delete device attribute properties from database :param argin: Str[0] = Device name Str[1] = Attribute name :type: tango.DevVarStringArray :return: :rtype: tango.DevVoid """ self._log.debug("In DbDeleteDeviceAttribut...
Delete device attribute properties from database :param argin: Str[0] = Device name Str[1] = Attribute name :type: tango.DevVarStringArray :return: :rtype: tango.DevVoid
Below is the the instruction that describes the task: ### Input: Delete device attribute properties from database :param argin: Str[0] = Device name Str[1] = Attribute name :type: tango.DevVarStringArray :return: :rtype: tango.DevVoid ### Response: def DbDeleteDeviceAttrib...
def parse_address(self, address, line_number=-1): """ Return an Address object from the given address. Passes itself to the Address constructor to use all the custom loaded suffixes, cities, etc. """ return Address(address, self, line_number, self.logger)
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom loaded suffixes, cities, etc.
Below is the the instruction that describes the task: ### Input: Return an Address object from the given address. Passes itself to the Address constructor to use all the custom loaded suffixes, cities, etc. ### Response: def parse_address(self, address, line_number=-1): """ Return an Addres...
def _lockfile(self): """Pipfile.lock divided by PyPI and external dependencies.""" pfile = pipfile.load(self.pipfile_location, inject_env=False) lockfile = json.loads(pfile.lock()) for section in ("default", "develop"): lock_section = lockfile.get(section, {}) for...
Pipfile.lock divided by PyPI and external dependencies.
Below is the the instruction that describes the task: ### Input: Pipfile.lock divided by PyPI and external dependencies. ### Response: def _lockfile(self): """Pipfile.lock divided by PyPI and external dependencies.""" pfile = pipfile.load(self.pipfile_location, inject_env=False) lockfile = ...
def vecangle(v1, v2, deg=True): """Calculate the angle between two vectors :param v1: coordinates of vector v1 :param v2: coordinates of vector v2 :returns : angle in degree or rad """ if np.array_equal(v1, v2): return 0.0 dm = np.dot(v1, v2) cm = np.linalg.norm(v1) * np.linalg.n...
Calculate the angle between two vectors :param v1: coordinates of vector v1 :param v2: coordinates of vector v2 :returns : angle in degree or rad
Below is the the instruction that describes the task: ### Input: Calculate the angle between two vectors :param v1: coordinates of vector v1 :param v2: coordinates of vector v2 :returns : angle in degree or rad ### Response: def vecangle(v1, v2, deg=True): """Calculate the angle between two vectors...
def token_generator(tree_path, source_token_vocab, target_token_vocab, eos=None): """Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files at source_path and target_path have the same number of lines and yields dictionaries of "inputs" and "ta...
Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files at source_path and target_path have the same number of lines and yields dictionaries of "inputs" and "targets" where inputs and targets are token ids from source and target lines converted to integers using ...
Below is the the instruction that describes the task: ### Input: Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files at source_path and target_path have the same number of lines and yields dictionaries of "inputs" and "targets" where inputs and targets are ...
def main(): """ Print lines of input along with output. """ source_lines = (line.rstrip() for line in sys.stdin) console = InteractiveInterpreter() console.runsource('import turicreate') source = '' try: while True: source = source_lines.next() more = cons...
Print lines of input along with output.
Below is the the instruction that describes the task: ### Input: Print lines of input along with output. ### Response: def main(): """ Print lines of input along with output. """ source_lines = (line.rstrip() for line in sys.stdin) console = InteractiveInterpreter() console.runsource('impor...
def uuid(dev=None): ''' Return the bcache UUID of a block device. If no device is given, the Cache UUID is returned. CLI example: .. code-block:: bash salt '*' bcache.uuid salt '*' bcache.uuid /dev/sda salt '*' bcache.uuid bcache0 ''' try: if dev is None: ...
Return the bcache UUID of a block device. If no device is given, the Cache UUID is returned. CLI example: .. code-block:: bash salt '*' bcache.uuid salt '*' bcache.uuid /dev/sda salt '*' bcache.uuid bcache0
Below is the the instruction that describes the task: ### Input: Return the bcache UUID of a block device. If no device is given, the Cache UUID is returned. CLI example: .. code-block:: bash salt '*' bcache.uuid salt '*' bcache.uuid /dev/sda salt '*' bcache.uuid bcache0 ### R...
def verify(self, pkt, key): """ Check that the integrity check value (icv) of a packet is valid. @param pkt: a packet that contains a valid encrypted ESP or AH layer @param key: the authentication key, a byte string @raise IPSecIntegrityError: if the integrity check fails...
Check that the integrity check value (icv) of a packet is valid. @param pkt: a packet that contains a valid encrypted ESP or AH layer @param key: the authentication key, a byte string @raise IPSecIntegrityError: if the integrity check fails
Below is the the instruction that describes the task: ### Input: Check that the integrity check value (icv) of a packet is valid. @param pkt: a packet that contains a valid encrypted ESP or AH layer @param key: the authentication key, a byte string @raise IPSecIntegrityError: if the ...
def rectangular_neighbors_from_shape(shape): """Compute the neighbors of every pixel as a list of the pixel index's each pixel shares a vertex with. The uniformity of the rectangular grid's geometry is used to compute this. """ pixels = shape[0]*shape[1] pixel_neighbors = -1 * np.ones(shape=(pix...
Compute the neighbors of every pixel as a list of the pixel index's each pixel shares a vertex with. The uniformity of the rectangular grid's geometry is used to compute this.
Below is the the instruction that describes the task: ### Input: Compute the neighbors of every pixel as a list of the pixel index's each pixel shares a vertex with. The uniformity of the rectangular grid's geometry is used to compute this. ### Response: def rectangular_neighbors_from_shape(shape): """Com...
def euler_matrix(ai, aj, ak, axes='sxyz'): """Return homogeneous rotation matrix from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> R = euler_matrix(1, 2, 3, 'syxz') >>> np.allclose(np.sum(R[0]), -1.34...
Return homogeneous rotation matrix from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> R = euler_matrix(1, 2, 3, 'syxz') >>> np.allclose(np.sum(R[0]), -1.34786452) True >>> R = euler_matrix(1, 2, 3,...
Below is the the instruction that describes the task: ### Input: Return homogeneous rotation matrix from Euler angles and axis sequence. ai, aj, ak : Euler's roll, pitch and yaw angles axes : One of 24 axis sequences as string or encoded tuple >>> R = euler_matrix(1, 2, 3, 'syxz') >>> np.allclose(...
def init(port=None, do_not_exit=False, disable_tls=False, log_level='WARNING'): """Start the Xenon GRPC server on the specified port, or, if a service is already running on that port, connect to that. If no port is given, a random port is selected. This means that, by default, every python instance wil...
Start the Xenon GRPC server on the specified port, or, if a service is already running on that port, connect to that. If no port is given, a random port is selected. This means that, by default, every python instance will start its own instance of a xenon-grpc process. :param port: the port number...
Below is the the instruction that describes the task: ### Input: Start the Xenon GRPC server on the specified port, or, if a service is already running on that port, connect to that. If no port is given, a random port is selected. This means that, by default, every python instance will start its own in...
def _update_exit_code_from_stats(cls, statistics: Statistics, app: Application): '''Set the current exit code based on the Statistics.''' for error_type in statistics.errors: exit_code = app.ERROR_CODE_MAP.get(error_type) if exit_code: ...
Set the current exit code based on the Statistics.
Below is the the instruction that describes the task: ### Input: Set the current exit code based on the Statistics. ### Response: def _update_exit_code_from_stats(cls, statistics: Statistics, app: Application): '''Set the current exit code based on the Statistics.''' ...
def get(self,par_names=None,obs_names=None,astype=None): """method to get a new LinearAnalysis class using a subset of parameters and/or observations Parameters ---------- par_names : list par names for new object obs_names : list obs names for ne...
method to get a new LinearAnalysis class using a subset of parameters and/or observations Parameters ---------- par_names : list par names for new object obs_names : list obs names for new object astype : pyemu.Schur or pyemu.ErrVar ty...
Below is the the instruction that describes the task: ### Input: method to get a new LinearAnalysis class using a subset of parameters and/or observations Parameters ---------- par_names : list par names for new object obs_names : list obs names for n...
def plot(x, y, rows=None, columns=None): """ x, y list of values on x- and y-axis plot those values within canvas size (rows and columns) """ if not rows or not columns: rows, columns = get_terminal_size() # offset for caption rows -= 4 # Scale points such that they fit on canva...
x, y list of values on x- and y-axis plot those values within canvas size (rows and columns)
Below is the the instruction that describes the task: ### Input: x, y list of values on x- and y-axis plot those values within canvas size (rows and columns) ### Response: def plot(x, y, rows=None, columns=None): """ x, y list of values on x- and y-axis plot those values within canvas size (rows an...
def info(name, root=None): ''' Return information about a group name Name of the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.info foo ''' if root is not None: getgrnam = functools.partial(_getgrnam, root=root) ...
Return information about a group name Name of the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.info foo
Below is the the instruction that describes the task: ### Input: Return information about a group name Name of the group root Directory to chroot into CLI Example: .. code-block:: bash salt '*' group.info foo ### Response: def info(name, root=None): ''' Return i...
def get(vm, key='uuid'): ''' Output the JSON object describing a VM vm : string vm to be targeted key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.get 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*'...
Output the JSON object describing a VM vm : string vm to be targeted key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.get 186da9ab-7392-4f55-91a5-b8f1fe770543 salt '*' vmadm.get nacl key=alias
Below is the the instruction that describes the task: ### Input: Output the JSON object describing a VM vm : string vm to be targeted key : string [uuid|alias|hostname] value type of 'vm' parameter CLI Example: .. code-block:: bash salt '*' vmadm.get 186da9ab-7392-4f55-91...
def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): ''' Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profi...
Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id
Below is the the instruction that describes the task: ### Input: Create a display name for a key. CLI example:: salt myminion boto_kms.create_alias 'alias/mykey' key_id ### Response: def create_alias(alias_name, target_key_id, region=None, key=None, keyid=None, profile=None): '''...
def run_sync(self, func: Callable, timeout: float = None) -> Any: """Starts the `IOLoop`, runs the given function, and stops the loop. The function must return either an awaitable object or ``None``. If the function returns an awaitable object, the `IOLoop` will run until the awaitable ...
Starts the `IOLoop`, runs the given function, and stops the loop. The function must return either an awaitable object or ``None``. If the function returns an awaitable object, the `IOLoop` will run until the awaitable is resolved (and `run_sync()` will return the awaitable's result). If...
Below is the the instruction that describes the task: ### Input: Starts the `IOLoop`, runs the given function, and stops the loop. The function must return either an awaitable object or ``None``. If the function returns an awaitable object, the `IOLoop` will run until the awaitable is resol...
def main(): """ Entry point when used via command line. Features are given using the environment variable ``PRODUCT_EQUATION``. If it is not set, ``PRODUCT_EQUATION_FILENAME`` is tried: if it points to an existing equation file that selection is used. (if ``APE_PREPEND_FEATURES`` is given, tho...
Entry point when used via command line. Features are given using the environment variable ``PRODUCT_EQUATION``. If it is not set, ``PRODUCT_EQUATION_FILENAME`` is tried: if it points to an existing equation file that selection is used. (if ``APE_PREPEND_FEATURES`` is given, those features are prepende...
Below is the the instruction that describes the task: ### Input: Entry point when used via command line. Features are given using the environment variable ``PRODUCT_EQUATION``. If it is not set, ``PRODUCT_EQUATION_FILENAME`` is tried: if it points to an existing equation file that selection is used. ...
def _parse_reports_by_type(self): """ Returns a data dictionary Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type. """ data = dict() for file_meta in self.find_log_files('picard/sam_file_validation', filehandles=True): sample = file_meta['s_name'] ...
Returns a data dictionary Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type.
Below is the the instruction that describes the task: ### Input: Returns a data dictionary Goes through logs and parses them based on 'No errors found', VERBOSE or SUMMARY type. ### Response: def _parse_reports_by_type(self): """ Returns a data dictionary Goes through logs and parses them bas...
def can_handle(cls, pkt, rpc): """heuristical guess_payload_class""" # type = 0 => request if rpc.getfieldval("type") == 0 and \ str(rpc.object_uuid).startswith("dea00000-6c97-11d1-8271-"): return True return False
heuristical guess_payload_class
Below is the the instruction that describes the task: ### Input: heuristical guess_payload_class ### Response: def can_handle(cls, pkt, rpc): """heuristical guess_payload_class""" # type = 0 => request if rpc.getfieldval("type") == 0 and \ str(rpc.object_uuid).startswith("de...
def url_params_previous_page(self): """ :rtype: dict[str, str] """ self.assert_has_previous_page() params = {self.PARAM_OLDER_ID: str(self.older_id)} self._add_count_to_params_if_needed(params) return params
:rtype: dict[str, str]
Below is the the instruction that describes the task: ### Input: :rtype: dict[str, str] ### Response: def url_params_previous_page(self): """ :rtype: dict[str, str] """ self.assert_has_previous_page() params = {self.PARAM_OLDER_ID: str(self.older_id)} self._add_cou...
def list_server_certificates(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/serv...
Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server certificates for which the path starts with /company/servercerts . ...
Below is the the instruction that describes the task: ### Input: Lists the server certificates stored in IAM that have the specified path prefix. .. versionadded:: ??? :param path_prefix: The path prefix for filtering the results. For example: /company/servercerts would get all server ce...
def start_process_monitor(self): """ Monitor all processes in processes_to_monitor dict, restarting any if they fail, up to max_runs times. """ # Now wait for any child to die Log.info("Start process monitor") while True: if len(self.processes_to_monitor) > 0: (pid, status) = os.wa...
Monitor all processes in processes_to_monitor dict, restarting any if they fail, up to max_runs times.
Below is the the instruction that describes the task: ### Input: Monitor all processes in processes_to_monitor dict, restarting any if they fail, up to max_runs times. ### Response: def start_process_monitor(self): """ Monitor all processes in processes_to_monitor dict, restarting any if they fail, up ...
def _parseResourceDirectory(self, rva, size, magic = consts.PE32): """ Parses the C{IMAGE_RESOURCE_DIRECTORY} directory. @type rva: int @param rva: The RVA where the C{IMAGE_RESOURCE_DIRECTORY} starts. @type size: int @param size: The size of the C{IMAG...
Parses the C{IMAGE_RESOURCE_DIRECTORY} directory. @type rva: int @param rva: The RVA where the C{IMAGE_RESOURCE_DIRECTORY} starts. @type size: int @param size: The size of the C{IMAGE_RESOURCE_DIRECTORY} directory. @type magic: int @param magic...
Below is the the instruction that describes the task: ### Input: Parses the C{IMAGE_RESOURCE_DIRECTORY} directory. @type rva: int @param rva: The RVA where the C{IMAGE_RESOURCE_DIRECTORY} starts. @type size: int @param size: The size of the C{IMAGE_RESOURCE_DIRECTO...
def await_item_handle(self, original, loc, tokens): """Check for Python 3.5 await expression.""" internal_assert(len(tokens) == 1, "invalid await statement tokens", tokens) if not self.target: self.make_err( CoconutTargetError, "await requires a specif...
Check for Python 3.5 await expression.
Below is the the instruction that describes the task: ### Input: Check for Python 3.5 await expression. ### Response: def await_item_handle(self, original, loc, tokens): """Check for Python 3.5 await expression.""" internal_assert(len(tokens) == 1, "invalid await statement tokens", tokens) ...
def generate_address(self, passphrase): """ Make sure the confirm code is valid for the given password and address. """ inter = Bip38IntermediatePoint.create(passphrase, ownersalt=self.ownersalt) public_key = privtopub(inter.passpoint) # from Bip38EncryptedPrivateKey.c...
Make sure the confirm code is valid for the given password and address.
Below is the the instruction that describes the task: ### Input: Make sure the confirm code is valid for the given password and address. ### Response: def generate_address(self, passphrase): """ Make sure the confirm code is valid for the given password and address. """ inter = Bip...
def offer_random(pool, answer, rationale, student_id, options): """ The random selection algorithm. The same as simple algorithm """ offer_simple(pool, answer, rationale, student_id, options)
The random selection algorithm. The same as simple algorithm
Below is the the instruction that describes the task: ### Input: The random selection algorithm. The same as simple algorithm ### Response: def offer_random(pool, answer, rationale, student_id, options): """ The random selection algorithm. The same as simple algorithm """ offer_simple(pool, answer,...
def get_master_key(password_hash_hash, nt_response): """ GetMasterKey( IN 16-octet PasswordHashHash, IN 24-octet NTResponse, OUT 16-octet MasterKey ) { 20-octet Digest ZeroMemory(Digest, sizeof(Digest)); /* * SHSInit(), SHSUpdate() and SHSFinal() * are an implem...
GetMasterKey( IN 16-octet PasswordHashHash, IN 24-octet NTResponse, OUT 16-octet MasterKey ) { 20-octet Digest ZeroMemory(Digest, sizeof(Digest)); /* * SHSInit(), SHSUpdate() and SHSFinal() * are an implementation of the Secure Hash Standard [7]. */ SHSIn...
Below is the the instruction that describes the task: ### Input: GetMasterKey( IN 16-octet PasswordHashHash, IN 24-octet NTResponse, OUT 16-octet MasterKey ) { 20-octet Digest ZeroMemory(Digest, sizeof(Digest)); /* * SHSInit(), SHSUpdate() and SHSFinal() * are an i...
def write_dfile(self): """ Write the generated d_file to a temporary file. """ f_in = self.tempfiles.get_tempfile(prefix="bmds-", suffix=".(d)") with open(f_in, "w") as f: f.write(self.as_dfile()) return f_in
Write the generated d_file to a temporary file.
Below is the the instruction that describes the task: ### Input: Write the generated d_file to a temporary file. ### Response: def write_dfile(self): """ Write the generated d_file to a temporary file. """ f_in = self.tempfiles.get_tempfile(prefix="bmds-", suffix=".(d)") wit...
def ensure_python(specs): """Given a list of range specifiers for python, ensure compatibility. """ if not isinstance(specs, (list, tuple)): specs = [specs] v = sys.version_info part = '%s.%s' % (v.major, v.minor) for spec in specs: if part == spec: return try...
Given a list of range specifiers for python, ensure compatibility.
Below is the the instruction that describes the task: ### Input: Given a list of range specifiers for python, ensure compatibility. ### Response: def ensure_python(specs): """Given a list of range specifiers for python, ensure compatibility. """ if not isinstance(specs, (list, tuple)): specs = ...
def _set_class_parser(self, init_parser, methods_to_parse, cls): """Creates the complete argument parser for the decorated class. Args: init_parser: argument parser for the __init__ method or None methods_to_parse: dict of method name pointing to their associated arg...
Creates the complete argument parser for the decorated class. Args: init_parser: argument parser for the __init__ method or None methods_to_parse: dict of method name pointing to their associated argument parser cls: the class we are decorating Returns: ...
Below is the the instruction that describes the task: ### Input: Creates the complete argument parser for the decorated class. Args: init_parser: argument parser for the __init__ method or None methods_to_parse: dict of method name pointing to their associated argument p...
def get_names_and_paths(compiler_output: Dict[str, Any]) -> Dict[str, str]: """ Return a mapping of contract name to relative path as defined in compiler output. """ return { contract_name: make_path_relative(path) for path in compiler_output for contract_name in compiler_output[...
Return a mapping of contract name to relative path as defined in compiler output.
Below is the the instruction that describes the task: ### Input: Return a mapping of contract name to relative path as defined in compiler output. ### Response: def get_names_and_paths(compiler_output: Dict[str, Any]) -> Dict[str, str]: """ Return a mapping of contract name to relative path as defined in c...
def create_template(self): """Create template (main function called by Stacker).""" template = self.template variables = self.get_variables() self.template.add_version('2010-09-09') self.template.add_description('Terraform State Resources') # Conditions for i in ...
Create template (main function called by Stacker).
Below is the the instruction that describes the task: ### Input: Create template (main function called by Stacker). ### Response: def create_template(self): """Create template (main function called by Stacker).""" template = self.template variables = self.get_variables() self.templa...
def get_assignees(self): """ :calls: `GET /repos/:owner/:repo/assignees <http://developer.github.com/v3/issues/assignees>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` """ return github.PaginatedList.PaginatedList( github...
:calls: `GET /repos/:owner/:repo/assignees <http://developer.github.com/v3/issues/assignees>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser`
Below is the the instruction that describes the task: ### Input: :calls: `GET /repos/:owner/:repo/assignees <http://developer.github.com/v3/issues/assignees>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` ### Response: def get_assignees(self): """ ...
def write_pagerange(self, pagerange, prefix=''): """ Save the subset of pages specified in `pagerange` (dict) as separate PDF. e.g. pagerange = {'title':'First chapter', 'page_start':0, 'page_end':5} """ writer = PdfFileWriter() slug = "".join([c for c in pagerange['title...
Save the subset of pages specified in `pagerange` (dict) as separate PDF. e.g. pagerange = {'title':'First chapter', 'page_start':0, 'page_end':5}
Below is the the instruction that describes the task: ### Input: Save the subset of pages specified in `pagerange` (dict) as separate PDF. e.g. pagerange = {'title':'First chapter', 'page_start':0, 'page_end':5} ### Response: def write_pagerange(self, pagerange, prefix=''): """ Save the sub...
def register_catchall_controlreq(self, callback, callback_parsed=None): """ Registers a callback that is called for all control requests received by your Thing `Example` #!python def controlreq_callback(data): print(data) ... clie...
Registers a callback that is called for all control requests received by your Thing `Example` #!python def controlreq_callback(data): print(data) ... client.register_catchall_controlreq(controlreq_callback) `callback` (required) the func...
Below is the the instruction that describes the task: ### Input: Registers a callback that is called for all control requests received by your Thing `Example` #!python def controlreq_callback(data): print(data) ... client.register_catchall_co...
def rotate(self, log): """Move the current log to a new file with timestamp and create a new empty log file.""" self.write(log, rotate=True) self.write({})
Move the current log to a new file with timestamp and create a new empty log file.
Below is the the instruction that describes the task: ### Input: Move the current log to a new file with timestamp and create a new empty log file. ### Response: def rotate(self, log): """Move the current log to a new file with timestamp and create a new empty log file.""" self.write(log, rotate=Tr...
def find_duplicates(items, k=2, key=None): """ Find all duplicate items in a list. Search for all items that appear more than `k` times and return a mapping from each (k)-duplicate item to the positions it appeared in. Args: items (Iterable): hashable items possibly containing duplicates ...
Find all duplicate items in a list. Search for all items that appear more than `k` times and return a mapping from each (k)-duplicate item to the positions it appeared in. Args: items (Iterable): hashable items possibly containing duplicates k (int): only return items that appear at least ...
Below is the the instruction that describes the task: ### Input: Find all duplicate items in a list. Search for all items that appear more than `k` times and return a mapping from each (k)-duplicate item to the positions it appeared in. Args: items (Iterable): hashable items possibly containin...
def Copy(self): """Return a copy of the queue manager. Returns: Copy of the QueueManager object. NOTE: pending writes/deletions are not copied. On the other hand, if the original object has a frozen timestamp, a copy will have it as well. """ result = QueueManager(store=self.data_store, tok...
Return a copy of the queue manager. Returns: Copy of the QueueManager object. NOTE: pending writes/deletions are not copied. On the other hand, if the original object has a frozen timestamp, a copy will have it as well.
Below is the the instruction that describes the task: ### Input: Return a copy of the queue manager. Returns: Copy of the QueueManager object. NOTE: pending writes/deletions are not copied. On the other hand, if the original object has a frozen timestamp, a copy will have it as well. ### Response: ...
def op(cls,text,*args,**kwargs): """ This method must be overriden in derived classes """ return cls.fn(text,*args,**kwargs)
This method must be overriden in derived classes
Below is the the instruction that describes the task: ### Input: This method must be overriden in derived classes ### Response: def op(cls,text,*args,**kwargs): """ This method must be overriden in derived classes """ return cls.fn(text,*args,**kwargs)
async def _create_transaction(self, msg, *args, **kwargs): """ Create a transaction with the distant server :param msg: message to be sent :param args: args to be sent to the coroutines given to `register_transaction` :param kwargs: kwargs to be sent to the coroutines given to `r...
Create a transaction with the distant server :param msg: message to be sent :param args: args to be sent to the coroutines given to `register_transaction` :param kwargs: kwargs to be sent to the coroutines given to `register_transaction`
Below is the the instruction that describes the task: ### Input: Create a transaction with the distant server :param msg: message to be sent :param args: args to be sent to the coroutines given to `register_transaction` :param kwargs: kwargs to be sent to the coroutines given to `register_tr...
def print_accuracies(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, base_eps_iter=BASE_EPS_ITER, nb_iter=NB_ITER): """ Load a saved model...
Load a saved model and print out its accuracy on different data distributions This function works by running a single attack on each example. This provides a reasonable estimate of the true failure rate quickly, so long as the model does not suffer from gradient masking. However, this estimate is mostly intend...
Below is the the instruction that describes the task: ### Input: Load a saved model and print out its accuracy on different data distributions This function works by running a single attack on each example. This provides a reasonable estimate of the true failure rate quickly, so long as the model does not su...
def with_blob(self, blob): """ Init Azure Blob Lease with existing blob. """ content = json.loads(blob.content) self.partition_id = content["partition_id"] self.owner = content["owner"] self.token = content["token"] self.epoch = content["epoch"] se...
Init Azure Blob Lease with existing blob.
Below is the the instruction that describes the task: ### Input: Init Azure Blob Lease with existing blob. ### Response: def with_blob(self, blob): """ Init Azure Blob Lease with existing blob. """ content = json.loads(blob.content) self.partition_id = content["partition_id"...
def check_import_stdlib(module): """Check if module is in Python stdlib. Args: module (str): The name of the module to check. Returns: bool: Returns True if the module is in the stdlib or template. """ if ( module in stdlib_list('2.7') # pyl...
Check if module is in Python stdlib. Args: module (str): The name of the module to check. Returns: bool: Returns True if the module is in the stdlib or template.
Below is the the instruction that describes the task: ### Input: Check if module is in Python stdlib. Args: module (str): The name of the module to check. Returns: bool: Returns True if the module is in the stdlib or template. ### Response: def check_import_stdlib(module):...
def upload_document_fileobj(file_obj, file_name, session, documents_resource, log=None): """Uploads a single file-like object to the One Codex server directly to S3. Parameters ---------- file_obj : `FilePassthru`, or a file-like object If a file-like object is given, its mime-type will be sent...
Uploads a single file-like object to the One Codex server directly to S3. Parameters ---------- file_obj : `FilePassthru`, or a file-like object If a file-like object is given, its mime-type will be sent as 'text/plain'. Otherwise, `FilePassthru` will send a compressed type if the file is g...
Below is the the instruction that describes the task: ### Input: Uploads a single file-like object to the One Codex server directly to S3. Parameters ---------- file_obj : `FilePassthru`, or a file-like object If a file-like object is given, its mime-type will be sent as 'text/plain'. Otherwise...
def atleast_1d(*arrs): r"""Convert inputs to arrays with at least one dimension. Scalars are converted to 1-dimensional arrays, whilst other higher-dimensional inputs are preserved. This is a thin wrapper around `numpy.atleast_1d` to preserve units. Parameters ---------- arrs : arbitrary p...
r"""Convert inputs to arrays with at least one dimension. Scalars are converted to 1-dimensional arrays, whilst other higher-dimensional inputs are preserved. This is a thin wrapper around `numpy.atleast_1d` to preserve units. Parameters ---------- arrs : arbitrary positional arguments ...
Below is the the instruction that describes the task: ### Input: r"""Convert inputs to arrays with at least one dimension. Scalars are converted to 1-dimensional arrays, whilst other higher-dimensional inputs are preserved. This is a thin wrapper around `numpy.atleast_1d` to preserve units. Parame...
def dataframe(self, predicate=None, filtered_columns=None, columns=None, df_class=None): """Return the partition as a Pandas dataframe :param predicate: If defined, a callable that is called for each row, and if it returns true, the row is included in the output. :param filtered_column...
Return the partition as a Pandas dataframe :param predicate: If defined, a callable that is called for each row, and if it returns true, the row is included in the output. :param filtered_columns: If defined, the value is a dict of column names and associated values. Only rows where al...
Below is the the instruction that describes the task: ### Input: Return the partition as a Pandas dataframe :param predicate: If defined, a callable that is called for each row, and if it returns true, the row is included in the output. :param filtered_columns: If defined, the value is a d...
def verifySignature(ecPublicSigningKey, message, signature): """ :type ecPublicSigningKey: ECPublicKey :type message: bytearray :type signature: bytearray """ if ecPublicSigningKey.getType() == Curve.DJB_TYPE: result = _curve.verifySignature(ecPublicSigningKe...
:type ecPublicSigningKey: ECPublicKey :type message: bytearray :type signature: bytearray
Below is the the instruction that describes the task: ### Input: :type ecPublicSigningKey: ECPublicKey :type message: bytearray :type signature: bytearray ### Response: def verifySignature(ecPublicSigningKey, message, signature): """ :type ecPublicSigningKey: ECPublicKey :ty...
def QA_fetch_get_stock_info(code, ip=None, port=None): '股票基本信息' ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() market_code = _select_market_code(code) with api.connect(ip, port): return api.to_df(api.get_finance_info(market_code, code))
股票基本信息
Below is the the instruction that describes the task: ### Input: 股票基本信息 ### Response: def QA_fetch_get_stock_info(code, ip=None, port=None): '股票基本信息' ip, port = get_mainmarket_ip(ip, port) api = TdxHq_API() market_code = _select_market_code(code) with api.connect(ip, port): return api.t...
def kmip_version(self, value): """ Set the KMIP version for the client. Args: value (KMIPVersion): A KMIPVersion enumeration Return: None Raises: ValueError: if value is not a KMIPVersion enumeration Example: >>> client....
Set the KMIP version for the client. Args: value (KMIPVersion): A KMIPVersion enumeration Return: None Raises: ValueError: if value is not a KMIPVersion enumeration Example: >>> client.kmip_version = enums.KMIPVersion.KMIP_1_1 ...
Below is the the instruction that describes the task: ### Input: Set the KMIP version for the client. Args: value (KMIPVersion): A KMIPVersion enumeration Return: None Raises: ValueError: if value is not a KMIPVersion enumeration Example: ...
def _set_cluster(self, v, load=False): """ Setter method for cluster, mapped from YANG variable /mgmt_cluster/cluster (container) If this variable is read-only (config: false) in the source YANG file, then _set_cluster is considered as a private method. Backends looking to populate this variable sho...
Setter method for cluster, mapped from YANG variable /mgmt_cluster/cluster (container) If this variable is read-only (config: false) in the source YANG file, then _set_cluster is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_cluster() di...
Below is the the instruction that describes the task: ### Input: Setter method for cluster, mapped from YANG variable /mgmt_cluster/cluster (container) If this variable is read-only (config: false) in the source YANG file, then _set_cluster is considered as a private method. Backends looking to populate...
def window(self, time_interval=None, force_calculation=False): """ Gets a view on this stream for the time interval given :param time_interval: either a TimeInterval object or (start, end) tuple of type str or datetime :param force_calculation: Whether we should force calculation for th...
Gets a view on this stream for the time interval given :param time_interval: either a TimeInterval object or (start, end) tuple of type str or datetime :param force_calculation: Whether we should force calculation for this stream view if data does not exist :type time_interval: None | Iterable ...
Below is the the instruction that describes the task: ### Input: Gets a view on this stream for the time interval given :param time_interval: either a TimeInterval object or (start, end) tuple of type str or datetime :param force_calculation: Whether we should force calculation for this stream view...
def decrypt(self, encrypted_number): """Return the decrypted & decoded plaintext of *encrypted_number*. Args: encrypted_number (EncryptedNumber): encrypted against a known public key, i.e., one for which the private key is on this keyring. Returns: the int or fl...
Return the decrypted & decoded plaintext of *encrypted_number*. Args: encrypted_number (EncryptedNumber): encrypted against a known public key, i.e., one for which the private key is on this keyring. Returns: the int or float that *encrypted_number* was holding. N.B. if...
Below is the the instruction that describes the task: ### Input: Return the decrypted & decoded plaintext of *encrypted_number*. Args: encrypted_number (EncryptedNumber): encrypted against a known public key, i.e., one for which the private key is on this keyring. Returns: ...
def findall(self, title=None): """Fetch and return a list of spreadsheets with the given title. Args: title(str): title/name of the spreadsheets to return, or ``None`` for all Returns: list: list of new SpreadSheet instances (possibly empty) """ if title ...
Fetch and return a list of spreadsheets with the given title. Args: title(str): title/name of the spreadsheets to return, or ``None`` for all Returns: list: list of new SpreadSheet instances (possibly empty)
Below is the the instruction that describes the task: ### Input: Fetch and return a list of spreadsheets with the given title. Args: title(str): title/name of the spreadsheets to return, or ``None`` for all Returns: list: list of new SpreadSheet instances (possibly empty) ##...
def find(model, rid): """ Find a model from the store by resource id """ validate_rid(model, rid) rid_field = model.rid_field model = goldman.sess.store.find(model.RTYPE, rid_field, rid) if not model: abort(exceptions.DocumentNotFound) return model
Find a model from the store by resource id
Below is the the instruction that describes the task: ### Input: Find a model from the store by resource id ### Response: def find(model, rid): """ Find a model from the store by resource id """ validate_rid(model, rid) rid_field = model.rid_field model = goldman.sess.store.find(model.RTYPE, rid_...
def progress_bar(iteration, total, prefix=None, suffix=None, decs=1, length=100): """Creates a console progress bar. This should be called in a loop to create a progress bar. See `StackOverflow <http://stackoverflow.com/q...
Creates a console progress bar. This should be called in a loop to create a progress bar. See `StackOverflow <http://stackoverflow.com/questions/3173320/>`__. Args: iteration (int): current iteration total (int): total iterations prefix (str): prefix string suffix (str): suffix st...
Below is the the instruction that describes the task: ### Input: Creates a console progress bar. This should be called in a loop to create a progress bar. See `StackOverflow <http://stackoverflow.com/questions/3173320/>`__. Args: iteration (int): current iteration total (int): total itera...
def has_pfn(self, url, site=None): """ Wrapper of the pegasus hasPFN function, that allows it to be called outside of specific pegasus functions. """ curr_pfn = dax.PFN(url, site) return self.hasPFN(curr_pfn)
Wrapper of the pegasus hasPFN function, that allows it to be called outside of specific pegasus functions.
Below is the the instruction that describes the task: ### Input: Wrapper of the pegasus hasPFN function, that allows it to be called outside of specific pegasus functions. ### Response: def has_pfn(self, url, site=None): """ Wrapper of the pegasus hasPFN function, that allows it to be called ...
def download(self, path, file): """Download remote file to disk.""" resp = self._sendRequest("GET", path) if resp.status_code == 200: with open(file, "wb") as f: f.write(resp.content) else: raise YaDiskException(resp.status_code, resp.content)
Download remote file to disk.
Below is the the instruction that describes the task: ### Input: Download remote file to disk. ### Response: def download(self, path, file): """Download remote file to disk.""" resp = self._sendRequest("GET", path) if resp.status_code == 200: with open(file, "wb") as f: ...
def service(flavour): r""" Mark a class as implementing a Service Each Service class must have a ``run`` method, which does not take any arguments. This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless * the Service has been garbage collected, or * the ServiceUnit...
r""" Mark a class as implementing a Service Each Service class must have a ``run`` method, which does not take any arguments. This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless * the Service has been garbage collected, or * the ServiceUnit has been :py:meth:`~.Serv...
Below is the the instruction that describes the task: ### Input: r""" Mark a class as implementing a Service Each Service class must have a ``run`` method, which does not take any arguments. This method is :py:meth:`~.ServiceRunner.adopt`\ ed after the daemon starts, unless * the Service has been ...
def load_terminfo(terminal_name=None, fallback='vt100'): """ If the environment variable TERM is unset try with `fallback` if not empty. vt100 is a popular terminal supporting ANSI X3.64. """ terminal_name = os.getenv('TERM') if not terminal_name: if not fallback: raise Term...
If the environment variable TERM is unset try with `fallback` if not empty. vt100 is a popular terminal supporting ANSI X3.64.
Below is the the instruction that describes the task: ### Input: If the environment variable TERM is unset try with `fallback` if not empty. vt100 is a popular terminal supporting ANSI X3.64. ### Response: def load_terminfo(terminal_name=None, fallback='vt100'): """ If the environment variable TERM is ...
def header_size(self): """Total size of `file`'s header (including extended) in bytes. The size of the header is determined from `header`. If this is not possible (i.e., before the header has been read), 0 is returned. If the header contains an ``'nsymbt'`` entry (size of the extra ...
Total size of `file`'s header (including extended) in bytes. The size of the header is determined from `header`. If this is not possible (i.e., before the header has been read), 0 is returned. If the header contains an ``'nsymbt'`` entry (size of the extra header in bytes), its value i...
Below is the the instruction that describes the task: ### Input: Total size of `file`'s header (including extended) in bytes. The size of the header is determined from `header`. If this is not possible (i.e., before the header has been read), 0 is returned. If the header contains an ``'nsy...
def _which(command): """protected""" if isinstance(command, str): command = [command] command = list(command) name = command[0] args = command[1:] if _is_windows(): pathext = _decode_if_not_text(os.environ.get("PATHEXT", "")) path = _find_executable(name, pathext.split(o...
protected
Below is the the instruction that describes the task: ### Input: protected ### Response: def _which(command): """protected""" if isinstance(command, str): command = [command] command = list(command) name = command[0] args = command[1:] if _is_windows(): pathext = _decode_if...
def _to_string(val): """Convert to text.""" if isinstance(val, binary_type): return val.decode('utf-8') assert isinstance(val, text_type) return val
Convert to text.
Below is the the instruction that describes the task: ### Input: Convert to text. ### Response: def _to_string(val): """Convert to text.""" if isinstance(val, binary_type): return val.decode('utf-8') assert isinstance(val, text_type) return val
def root_adb(self): """Change adb to root mode for this device if allowed. If executed on a production build, adb will not be switched to root mode per security restrictions. """ self.adb.root() self.adb.wait_for_device( timeout=DEFAULT_TIMEOUT_BOOT_COMPLETIO...
Change adb to root mode for this device if allowed. If executed on a production build, adb will not be switched to root mode per security restrictions.
Below is the the instruction that describes the task: ### Input: Change adb to root mode for this device if allowed. If executed on a production build, adb will not be switched to root mode per security restrictions. ### Response: def root_adb(self): """Change adb to root mode for this dev...
def libvlc_media_list_new(p_instance): '''Create an empty media list. @param p_instance: libvlc instance. @return: empty media list, or NULL on error. ''' f = _Cfunctions.get('libvlc_media_list_new', None) or \ _Cfunction('libvlc_media_list_new', ((1,),), class_result(MediaList), ...
Create an empty media list. @param p_instance: libvlc instance. @return: empty media list, or NULL on error.
Below is the the instruction that describes the task: ### Input: Create an empty media list. @param p_instance: libvlc instance. @return: empty media list, or NULL on error. ### Response: def libvlc_media_list_new(p_instance): '''Create an empty media list. @param p_instance: libvlc instance. @...
def tag_text(self, text, **kwargs): """Annotates `analysis` entries in `corpus` with a list of lemmas` synsets and queried WordNet data in a 'wordnet' entry. Note ---- Annotates every `analysis` entry with a `wordnet`:{`synsets`:[..]}. Parameters ---------- te...
Annotates `analysis` entries in `corpus` with a list of lemmas` synsets and queried WordNet data in a 'wordnet' entry. Note ---- Annotates every `analysis` entry with a `wordnet`:{`synsets`:[..]}. Parameters ---------- text: estnltk.text.Text Representation ...
Below is the the instruction that describes the task: ### Input: Annotates `analysis` entries in `corpus` with a list of lemmas` synsets and queried WordNet data in a 'wordnet' entry. Note ---- Annotates every `analysis` entry with a `wordnet`:{`synsets`:[..]}. Parameters ...
def read_by(cls, removed=False, **kwargs): """ filter_by query helper that handles soft delete logic. If your query conditions require expressions, use read. :param removed: whether to include soft-deleted rows :param kwargs: where clause mappings to pass to filter_by :return: r...
filter_by query helper that handles soft delete logic. If your query conditions require expressions, use read. :param removed: whether to include soft-deleted rows :param kwargs: where clause mappings to pass to filter_by :return: row object generator
Below is the the instruction that describes the task: ### Input: filter_by query helper that handles soft delete logic. If your query conditions require expressions, use read. :param removed: whether to include soft-deleted rows :param kwargs: where clause mappings to pass to filter_by :ret...
def cli(config, in_file, out_file, verbose): """Main Interface to generate xml documents from custom dictionaries using legal xsd files complying with legal documents in all countires around the world. """ config.out_file = out_file config.verbose = verbose config.in_file = in_file c...
Main Interface to generate xml documents from custom dictionaries using legal xsd files complying with legal documents in all countires around the world.
Below is the the instruction that describes the task: ### Input: Main Interface to generate xml documents from custom dictionaries using legal xsd files complying with legal documents in all countires around the world. ### Response: def cli(config, in_file, out_file, verbose): """Main Interface to ...
def cluster_commit(): ''' Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak-admin', 'cluster commit') if cmd['retcode'] != 0: r...
Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit
Below is the the instruction that describes the task: ### Input: Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit ### Response: def cluster_commit(): ''' Commit Cluster Changes .. versionchanged:: 2015.8.0 C...
def get_subpackages_names(dir_): """Figures out the names of the subpackages of a package Args: dir_: (str) path to package directory Source: http://stackoverflow.com/questions/832004/python-finding-all-packages-inside-a-package """ def is_package(d): d = os.path.join(di...
Figures out the names of the subpackages of a package Args: dir_: (str) path to package directory Source: http://stackoverflow.com/questions/832004/python-finding-all-packages-inside-a-package
Below is the the instruction that describes the task: ### Input: Figures out the names of the subpackages of a package Args: dir_: (str) path to package directory Source: http://stackoverflow.com/questions/832004/python-finding-all-packages-inside-a-package ### Response: def get_subpackages_...
def urlencode_utf8(params): """ UTF-8 safe variant of urllib.urlencode. http://stackoverflow.com/a/8152242 """ if hasattr(params, 'items'): params = params.items() params = ( '='.join(( quote_plus(k.encode('utf8'), safe='/'), quote_plus(v.encode('utf8'), s...
UTF-8 safe variant of urllib.urlencode. http://stackoverflow.com/a/8152242
Below is the the instruction that describes the task: ### Input: UTF-8 safe variant of urllib.urlencode. http://stackoverflow.com/a/8152242 ### Response: def urlencode_utf8(params): """ UTF-8 safe variant of urllib.urlencode. http://stackoverflow.com/a/8152242 """ if hasattr(params, 'items'...
def var(self, values, axis=0, weights=None, dtype=None): """compute the variance over each group Parameters ---------- values : array_like, [keys, ...] values to take variance of per group axis : int, optional alternative reduction axis for values ...
compute the variance over each group Parameters ---------- values : array_like, [keys, ...] values to take variance of per group axis : int, optional alternative reduction axis for values Returns ------- unique: ndarray, [groups] ...
Below is the the instruction that describes the task: ### Input: compute the variance over each group Parameters ---------- values : array_like, [keys, ...] values to take variance of per group axis : int, optional alternative reduction axis for values ...
def xtime(b, n): """Repeated polynomial multiplication in GF(2^8).""" b = b.reshape(8) for _ in range(n): b = exprzeros(1) + b[:7] ^ uint2exprs(0x1b, 8) & b[7]*8 return b
Repeated polynomial multiplication in GF(2^8).
Below is the the instruction that describes the task: ### Input: Repeated polynomial multiplication in GF(2^8). ### Response: def xtime(b, n): """Repeated polynomial multiplication in GF(2^8).""" b = b.reshape(8) for _ in range(n): b = exprzeros(1) + b[:7] ^ uint2exprs(0x1b, 8) & b[7]*8 ret...
def get_sort_field(model=None, sort_field='sort', order_name='asc'): """ Get sort column info according request, the data format just likes: ?sort=fieldA.asc&sort=fieldB.desc or: ?sort=fieldA&sort=fieldB&order=asc&order=desc default order is 'asc'. `field` can be just l...
Get sort column info according request, the data format just likes: ?sort=fieldA.asc&sort=fieldB.desc or: ?sort=fieldA&sort=fieldB&order=asc&order=desc default order is 'asc'. `field` can be just like `model.field` :param model: default model, if no model existed in field ...
Below is the the instruction that describes the task: ### Input: Get sort column info according request, the data format just likes: ?sort=fieldA.asc&sort=fieldB.desc or: ?sort=fieldA&sort=fieldB&order=asc&order=desc default order is 'asc'. `field` can be just like `model.fie...
def configure(self, cnf=None, **kw): """ Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~Table.keys`. See :meth:`~Table.__init__` for a description of the widget specific option. """ if cnf == 'drag_cols': ...
Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~Table.keys`. See :meth:`~Table.__init__` for a description of the widget specific option.
Below is the the instruction that describes the task: ### Input: Configure resources of the widget. To get the list of options for this widget, call the method :meth:`~Table.keys`. See :meth:`~Table.__init__` for a description of the widget specific option. ### Response: def configure(self, cnf=No...
def open_url(url, retries=0, sleep=0.5): ''' Open a mysql connection to a url. Note that if your password has punctuation characters, it might break the parsing of url. url: A string in the form "mysql://username:password@host.domain/database" ''' return open_conn(retries=retries, sleep=sleep,...
Open a mysql connection to a url. Note that if your password has punctuation characters, it might break the parsing of url. url: A string in the form "mysql://username:password@host.domain/database"
Below is the the instruction that describes the task: ### Input: Open a mysql connection to a url. Note that if your password has punctuation characters, it might break the parsing of url. url: A string in the form "mysql://username:password@host.domain/database" ### Response: def open_url(url, retries=0...
def get_value(self,column=None,keyValue=None,table=None,verbose=None): """ Returns the value from a cell as specified by row and column ids. :param column (string, optional): Specifies the name of a column in the tab le :param keyValue (string, optional): Specifies a row of ...
Returns the value from a cell as specified by row and column ids. :param column (string, optional): Specifies the name of a column in the tab le :param keyValue (string, optional): Specifies a row of a table using the pr imary key as the indentifier :param table (string,...
Below is the the instruction that describes the task: ### Input: Returns the value from a cell as specified by row and column ids. :param column (string, optional): Specifies the name of a column in the tab le :param keyValue (string, optional): Specifies a row of a table using the pr ...
def convert_numpy_type(cls, dtype): """Convert a numpy dtype into a Column datatype. Only handles common types. Implemented as a function to decouple from numpy """ m = { 'int64': cls.DATATYPE_INTEGER64, 'float64': cls.DATATYPE_FLOAT, 'objec...
Convert a numpy dtype into a Column datatype. Only handles common types. Implemented as a function to decouple from numpy
Below is the the instruction that describes the task: ### Input: Convert a numpy dtype into a Column datatype. Only handles common types. Implemented as a function to decouple from numpy ### Response: def convert_numpy_type(cls, dtype): """Convert a numpy dtype into a Column datatype. Only...
def clean_value(self, value): ''' Additional clean action to preprocess value before :meth:`to_python` method. Subclasses may define own clean_value method to allow additional clean actions like html cleanup, etc. ''' # We have to clean before checking min/max le...
Additional clean action to preprocess value before :meth:`to_python` method. Subclasses may define own clean_value method to allow additional clean actions like html cleanup, etc.
Below is the the instruction that describes the task: ### Input: Additional clean action to preprocess value before :meth:`to_python` method. Subclasses may define own clean_value method to allow additional clean actions like html cleanup, etc. ### Response: def clean_value(self, value): ...
def getComponentButtonMask(self, pchRenderModelName, pchComponentName): """ Get the button mask for all buttons associated with this component If no buttons (or axes) are associated with this component, return 0 Note: multiple components may be associated with the same button. Ex: tw...
Get the button mask for all buttons associated with this component If no buttons (or axes) are associated with this component, return 0 Note: multiple components may be associated with the same button. Ex: two grip buttons on a single controller. Note: A single component may be associated ...
Below is the the instruction that describes the task: ### Input: Get the button mask for all buttons associated with this component If no buttons (or axes) are associated with this component, return 0 Note: multiple components may be associated with the same button. Ex: two grip buttons on a sin...
def circumcenter(self): ''' The intersection of the median perpendicular bisectors, Point. The center of the circumscribed circle, which is the circle that passes through all vertices of the triangle. https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2 ...
The intersection of the median perpendicular bisectors, Point. The center of the circumscribed circle, which is the circle that passes through all vertices of the triangle. https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2 BUG: only finds the circumcenter in t...
Below is the the instruction that describes the task: ### Input: The intersection of the median perpendicular bisectors, Point. The center of the circumscribed circle, which is the circle that passes through all vertices of the triangle. https://en.wikipedia.org/wiki/Circumscribed_circle#C...
def get_tagged_sections(book_dir=BOOK_PATH, include_tags=None): """ Get list of (adoc_file_path, (adoc_syntax_tag, raw_line_str)) >>> get_tagged_sections() [('...src/nlpia/data/book/Appendix F -- Glossary.asc', <generator object filter_tagged_lines at ...>)] """ return [(filepath, tag_lines(lines, ...
Get list of (adoc_file_path, (adoc_syntax_tag, raw_line_str)) >>> get_tagged_sections() [('...src/nlpia/data/book/Appendix F -- Glossary.asc', <generator object filter_tagged_lines at ...>)]
Below is the the instruction that describes the task: ### Input: Get list of (adoc_file_path, (adoc_syntax_tag, raw_line_str)) >>> get_tagged_sections() [('...src/nlpia/data/book/Appendix F -- Glossary.asc', <generator object filter_tagged_lines at ...>)] ### Response: def get_tagged_sections(book_dir=BOO...
def splitSong(songToSplit, start1, start2): """Split a song into two parts, one starting at start1, the other at start2""" print "start1 " + str(start1) print "start2 " + str(start2) # songs = [songToSplit[:start1+2000], songToSplit[start2-2000:]] songs = [songToSplit[:start1], songToSplit[start2:]]...
Split a song into two parts, one starting at start1, the other at start2
Below is the the instruction that describes the task: ### Input: Split a song into two parts, one starting at start1, the other at start2 ### Response: def splitSong(songToSplit, start1, start2): """Split a song into two parts, one starting at start1, the other at start2""" print "start1 " + str(start1) ...
def add_series(self, name, values=(), number_format=None): """ Add a series to this data set entitled *name* and having the data points specified by *values*, an iterable of numeric values. *number_format* specifies how the series values will be displayed, and may be a string, e....
Add a series to this data set entitled *name* and having the data points specified by *values*, an iterable of numeric values. *number_format* specifies how the series values will be displayed, and may be a string, e.g. '#,##0' corresponding to an Excel number format.
Below is the the instruction that describes the task: ### Input: Add a series to this data set entitled *name* and having the data points specified by *values*, an iterable of numeric values. *number_format* specifies how the series values will be displayed, and may be a string, e.g. '#,##0'...
def write_base (self, url_data): """Write url_data.base_ref.""" self.writeln(u"<tr><td>"+self.part("base")+u"</td><td>"+ cgi.escape(url_data.base_ref)+u"</td></tr>")
Write url_data.base_ref.
Below is the the instruction that describes the task: ### Input: Write url_data.base_ref. ### Response: def write_base (self, url_data): """Write url_data.base_ref.""" self.writeln(u"<tr><td>"+self.part("base")+u"</td><td>"+ cgi.escape(url_data.base_ref)+u"</td></tr>")
def update_ssl_termination(self, loadbalancer, securePort=None, enabled=None, secureTrafficOnly=None): """ Updates existing SSL termination information for the load balancer without affecting the existing certificates/keys. """ ssl_info = self.get_ssl_termination(load...
Updates existing SSL termination information for the load balancer without affecting the existing certificates/keys.
Below is the the instruction that describes the task: ### Input: Updates existing SSL termination information for the load balancer without affecting the existing certificates/keys. ### Response: def update_ssl_termination(self, loadbalancer, securePort=None, enabled=None, secureTrafficOnly=Non...
def get_block(block_id, api_code=None): """Get a single block based on a block hash. :param str block_id: block hash to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Block` class """ resource = 'rawblock/' + block_id if api_code is not Non...
Get a single block based on a block hash. :param str block_id: block hash to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Block` class
Below is the the instruction that describes the task: ### Input: Get a single block based on a block hash. :param str block_id: block hash to look up :param str api_code: Blockchain.info API code (optional) :return: an instance of :class:`Block` class ### Response: def get_block(block_id, api_code=Non...
def to_dict(self, model): """Create a dictionary serialization for a model. Parameters ---------- model : ModelHandle Returns ------- dict Dictionary serialization for a model """ # Get the basic Json object from the super class ...
Create a dictionary serialization for a model. Parameters ---------- model : ModelHandle Returns ------- dict Dictionary serialization for a model
Below is the the instruction that describes the task: ### Input: Create a dictionary serialization for a model. Parameters ---------- model : ModelHandle Returns ------- dict Dictionary serialization for a model ### Response: def to_dict(self, model): ...
def create(cls, spec_path, address_maps): """Creates an address family from the given set of address maps. :param spec_path: The directory prefix shared by all address_maps. :param address_maps: The family of maps that form this namespace. :type address_maps: :class:`collections.Iterable` of :class:`Ad...
Creates an address family from the given set of address maps. :param spec_path: The directory prefix shared by all address_maps. :param address_maps: The family of maps that form this namespace. :type address_maps: :class:`collections.Iterable` of :class:`AddressMap` :returns: a new address family. ...
Below is the the instruction that describes the task: ### Input: Creates an address family from the given set of address maps. :param spec_path: The directory prefix shared by all address_maps. :param address_maps: The family of maps that form this namespace. :type address_maps: :class:`collections.Ite...
def save(self, calc, session): ''' Saves tilde_obj into the database NB: this is the PUBLIC method @returns checksum, error ''' checksum = calc.get_checksum() try: existing_calc = session.query(model.Calculation).filter(model.Calculation.checksum == c...
Saves tilde_obj into the database NB: this is the PUBLIC method @returns checksum, error
Below is the the instruction that describes the task: ### Input: Saves tilde_obj into the database NB: this is the PUBLIC method @returns checksum, error ### Response: def save(self, calc, session): ''' Saves tilde_obj into the database NB: this is the PUBLIC method ...
def try_enqueue(conn, queue_name, msg): """ Try to enqueue a message. If it succeeds, return the message ID. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param queue_name: name of queue to put message in :type queue_name: str :param msg: JSON-serialized messa...
Try to enqueue a message. If it succeeds, return the message ID. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param queue_name: name of queue to put message in :type queue_name: str :param msg: JSON-serialized message body :type msg: str :return: message ID ...
Below is the the instruction that describes the task: ### Input: Try to enqueue a message. If it succeeds, return the message ID. :param conn: SQS API connection :type conn: :py:class:`botocore:SQS.Client` :param queue_name: name of queue to put message in :type queue_name: str :param msg: JSON...
def serve_record(self, environ, coll='$root', url=''): """Serve a URL's content from a WARC/ARC record in replay mode or from the live web in live, proxy, and record mode. :param dict environ: The WSGI environment dictionary for the request :param str coll: The name of the collection th...
Serve a URL's content from a WARC/ARC record in replay mode or from the live web in live, proxy, and record mode. :param dict environ: The WSGI environment dictionary for the request :param str coll: The name of the collection the record is to be served from :param str url: The URL for ...
Below is the the instruction that describes the task: ### Input: Serve a URL's content from a WARC/ARC record in replay mode or from the live web in live, proxy, and record mode. :param dict environ: The WSGI environment dictionary for the request :param str coll: The name of the collection...
def by_leb(blocks): """Sort blocks by Logical Erase Block number. Arguments: List:blocks -- List of block objects to sort. Returns: List -- Indexes of blocks sorted by LEB. """ slist_len = len(blocks) slist = ['x'] * slist_len for block in blocks: if ...
Sort blocks by Logical Erase Block number. Arguments: List:blocks -- List of block objects to sort. Returns: List -- Indexes of blocks sorted by LEB.
Below is the the instruction that describes the task: ### Input: Sort blocks by Logical Erase Block number. Arguments: List:blocks -- List of block objects to sort. Returns: List -- Indexes of blocks sorted by LEB. ### Response: def by_leb(blocks): """Sort blocks by Logic...
def drop_it(title, filters, blacklist): """ The found torrents should be in filters list and shouldn't be in blacklist. """ title = title.lower() matched = False for f in filters: if re.match(f, title): matched = True if not matched: return True for b in black...
The found torrents should be in filters list and shouldn't be in blacklist.
Below is the the instruction that describes the task: ### Input: The found torrents should be in filters list and shouldn't be in blacklist. ### Response: def drop_it(title, filters, blacklist): """ The found torrents should be in filters list and shouldn't be in blacklist. """ title = title.lower(...
def read_dalton(basis_lines, fname): '''Reads Dalton-formatted file data and converts it to a dictionary with the usual BSE fields Note that the nwchem format does not store all the fields we have, so some fields are left blank ''' skipchars = '$' basis_lines = [l for l in basis_l...
Reads Dalton-formatted file data and converts it to a dictionary with the usual BSE fields Note that the nwchem format does not store all the fields we have, so some fields are left blank
Below is the the instruction that describes the task: ### Input: Reads Dalton-formatted file data and converts it to a dictionary with the usual BSE fields Note that the nwchem format does not store all the fields we have, so some fields are left blank ### Response: def read_dalton(basis_line...