code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def lat_bounds(self): """Latitude of grid interfaces (degrees North) :getter: Returns the bounds of axis ``'lat'`` if availible in the process's domains. :type: array :raises: :exc:`ValueError` if no ``'lat'`` axis can be found. "...
Latitude of grid interfaces (degrees North) :getter: Returns the bounds of axis ``'lat'`` if availible in the process's domains. :type: array :raises: :exc:`ValueError` if no ``'lat'`` axis can be found.
Below is the the instruction that describes the task: ### Input: Latitude of grid interfaces (degrees North) :getter: Returns the bounds of axis ``'lat'`` if availible in the process's domains. :type: array :raises: :exc:`ValueError` if no ``'...
def patch_namespaced_cron_job(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_cron_job # noqa: E501 partially update the specified CronJob # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass ...
patch_namespaced_cron_job # noqa: E501 partially update the specified CronJob # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_cron_job(name, namespace, body, async_...
Below is the the instruction that describes the task: ### Input: patch_namespaced_cron_job # noqa: E501 partially update the specified CronJob # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>>...
def current_codes_from_pdb(): """ Get list of all PDB codes currently listed in the PDB. Returns ------- pdb_codes : list(str) List of PDB codes (in lower case). """ url = 'http://www.rcsb.org/pdb/rest/getCurrent' r = requests.get(url) if r.status_code == 200: pdb_codes ...
Get list of all PDB codes currently listed in the PDB. Returns ------- pdb_codes : list(str) List of PDB codes (in lower case).
Below is the the instruction that describes the task: ### Input: Get list of all PDB codes currently listed in the PDB. Returns ------- pdb_codes : list(str) List of PDB codes (in lower case). ### Response: def current_codes_from_pdb(): """ Get list of all PDB codes currently listed in the...
def accepts_admin_roles(func): """ Decorator that accepts only admin roles :param func: :return: """ if inspect.isclass(func): apply_function_to_members(func, accepts_admin_roles) return func else: @functools.wraps(func) def decorator(*args, **kwargs): ...
Decorator that accepts only admin roles :param func: :return:
Below is the the instruction that describes the task: ### Input: Decorator that accepts only admin roles :param func: :return: ### Response: def accepts_admin_roles(func): """ Decorator that accepts only admin roles :param func: :return: """ if inspect.isclass(func): apply_f...
def raw(self, clean=False): """Raw identifier. args: clean (bool): clean name returns: str """ if clean: return ''.join(''.join(p) for p in self.parsed).replace('?', ' ') return '%'.join('%'.join(p) for p in self.parsed).strip().strip('...
Raw identifier. args: clean (bool): clean name returns: str
Below is the the instruction that describes the task: ### Input: Raw identifier. args: clean (bool): clean name returns: str ### Response: def raw(self, clean=False): """Raw identifier. args: clean (bool): clean name returns: s...
async def issueClaims(self, allClaimRequest: Dict[ID, ClaimRequest]) -> \ Dict[ID, Claims]: """ Issue claims for the given users and schemas. :param allClaimRequest: a map of schema ID to a claim request containing prover ID and prover-generated values :return: The c...
Issue claims for the given users and schemas. :param allClaimRequest: a map of schema ID to a claim request containing prover ID and prover-generated values :return: The claims (both primary and non-revocation)
Below is the the instruction that describes the task: ### Input: Issue claims for the given users and schemas. :param allClaimRequest: a map of schema ID to a claim request containing prover ID and prover-generated values :return: The claims (both primary and non-revocation) ### Response: ...
def noise_from_psd(length, delta_t, psd, seed=None): """ Create noise with a given psd. Return noise with a given psd. Note that if unique noise is desired a unique seed should be provided. Parameters ---------- length : int The length of noise to generate in samples. delta_t : flo...
Create noise with a given psd. Return noise with a given psd. Note that if unique noise is desired a unique seed should be provided. Parameters ---------- length : int The length of noise to generate in samples. delta_t : float The time step of the noise. psd : FrequencySer...
Below is the the instruction that describes the task: ### Input: Create noise with a given psd. Return noise with a given psd. Note that if unique noise is desired a unique seed should be provided. Parameters ---------- length : int The length of noise to generate in samples. delta...
def get_host_info_dict_from_describe_dict(self, describe_dict): ''' Parses the dictionary returned by the API call into a flat list of parameters. This method should be used only when 'describe' is used directly because Boto doesn't provide specific classes. ''' # I really don't...
Parses the dictionary returned by the API call into a flat list of parameters. This method should be used only when 'describe' is used directly because Boto doesn't provide specific classes.
Below is the the instruction that describes the task: ### Input: Parses the dictionary returned by the API call into a flat list of parameters. This method should be used only when 'describe' is used directly because Boto doesn't provide specific classes. ### Response: def get_host_info_dic...
def move_to(self, location): """Changes the location of this medium. Some medium types may support changing the storage unit location by simply changing the value of the associated property. In this case the operation is performed immediately, and @a progress is returning a @c null refer...
Changes the location of this medium. Some medium types may support changing the storage unit location by simply changing the value of the associated property. In this case the operation is performed immediately, and @a progress is returning a @c null reference. Otherwise on success there...
Below is the the instruction that describes the task: ### Input: Changes the location of this medium. Some medium types may support changing the storage unit location by simply changing the value of the associated property. In this case the operation is performed immediately, and @a progress...
def _ValidateFSM(self): """Checks state names and destinations for validity. Each destination state must exist, be a valid name and not be a reserved name. There must be a 'Start' state and if 'EOF' or 'End' states are specified, they must be empty. Returns: True if FSM is valid. Ra...
Checks state names and destinations for validity. Each destination state must exist, be a valid name and not be a reserved name. There must be a 'Start' state and if 'EOF' or 'End' states are specified, they must be empty. Returns: True if FSM is valid. Raises: TextFSMTemplateErro...
Below is the the instruction that describes the task: ### Input: Checks state names and destinations for validity. Each destination state must exist, be a valid name and not be a reserved name. There must be a 'Start' state and if 'EOF' or 'End' states are specified, they must be empty. Return...
def display_value(self, value): """Sets `sysparm_display_value` :param value: Bool or 'all' """ if not (isinstance(value, bool) or value == 'all'): raise InvalidUsage("Display value can be of type bool or value 'all'") self._sysparms['sysparm_display_value'] = val...
Sets `sysparm_display_value` :param value: Bool or 'all'
Below is the the instruction that describes the task: ### Input: Sets `sysparm_display_value` :param value: Bool or 'all' ### Response: def display_value(self, value): """Sets `sysparm_display_value` :param value: Bool or 'all' """ if not (isinstance(value, bool) or val...
def startIndyPool(**kwargs): '''Start the indy_pool docker container iff it is not already running. See <indy-sdk>/ci/indy-pool.dockerfile for details. Idempotent. Simply ensures that the indy_pool container is up and running.''' # TODO: Decide if we need a separate docker container for testing and one...
Start the indy_pool docker container iff it is not already running. See <indy-sdk>/ci/indy-pool.dockerfile for details. Idempotent. Simply ensures that the indy_pool container is up and running.
Below is the the instruction that describes the task: ### Input: Start the indy_pool docker container iff it is not already running. See <indy-sdk>/ci/indy-pool.dockerfile for details. Idempotent. Simply ensures that the indy_pool container is up and running. ### Response: def startIndyPool(**kwargs): ...
def get_domain_events(self, originator_id, gt=None, gte=None, lt=None, lte=None, limit=None, is_ascending=True, page_size=None): """ Returns domain events for given entity ID. """
Returns domain events for given entity ID.
Below is the the instruction that describes the task: ### Input: Returns domain events for given entity ID. ### Response: def get_domain_events(self, originator_id, gt=None, gte=None, lt=None, lte=None, limit=None, is_ascending=True, page_size=None): """ Returns domain eve...
def url2fs(url): """ encode a URL to be safe as a filename """ uri, extension = posixpath.splitext(url) return safe64.dir(uri) + extension
encode a URL to be safe as a filename
Below is the the instruction that describes the task: ### Input: encode a URL to be safe as a filename ### Response: def url2fs(url): """ encode a URL to be safe as a filename """ uri, extension = posixpath.splitext(url) return safe64.dir(uri) + extension
def _SetTable(self, table): """Sets table, with column headers and separators.""" if not isinstance(table, TextTable): raise TypeError('Not an instance of TextTable.') self.Reset() self._table = copy.deepcopy(table._table) # pylint: disable=W0212 # Point parent table of each row back ourselv...
Sets table, with column headers and separators.
Below is the the instruction that describes the task: ### Input: Sets table, with column headers and separators. ### Response: def _SetTable(self, table): """Sets table, with column headers and separators.""" if not isinstance(table, TextTable): raise TypeError('Not an instance of TextTable.') se...
def dev_from_name(self, name): """Return the first pcap device name for a given Windows device name. """ try: return next(iface for iface in six.itervalues(self) if (iface.name == name or iface.description == name)) except (StopIteration, Runti...
Return the first pcap device name for a given Windows device name.
Below is the the instruction that describes the task: ### Input: Return the first pcap device name for a given Windows device name. ### Response: def dev_from_name(self, name): """Return the first pcap device name for a given Windows device name. """ try: return ...
def add_mutations_and_flush(self, table, muts): """ Add mutations to a table without the need to create and manage a batch writer. """ if not isinstance(muts, list) and not isinstance(muts, tuple): muts = [muts] cells = {} for mut in muts: cells.se...
Add mutations to a table without the need to create and manage a batch writer.
Below is the the instruction that describes the task: ### Input: Add mutations to a table without the need to create and manage a batch writer. ### Response: def add_mutations_and_flush(self, table, muts): """ Add mutations to a table without the need to create and manage a batch writer. ""...
def sjuncChunk(key, chunk): """ Parse Super Junction (SJUNC) Chunk Method """ schunk = chunk[0].strip().split() result = {'sjuncNumber': schunk[1], 'groundSurfaceElev': schunk[2], 'invertElev': schunk[3], 'manholeSA': schunk[4], 'inletCode': s...
Parse Super Junction (SJUNC) Chunk Method
Below is the the instruction that describes the task: ### Input: Parse Super Junction (SJUNC) Chunk Method ### Response: def sjuncChunk(key, chunk): """ Parse Super Junction (SJUNC) Chunk Method """ schunk = chunk[0].strip().split() result = {'sjuncNumber': schunk[1], 'groundSurf...
def _init(self): """Read the success byte.""" self._api_version = self._file.read(1)[0] self._firmware_version = FirmwareVersion(*self._file.read(2))
Read the success byte.
Below is the the instruction that describes the task: ### Input: Read the success byte. ### Response: def _init(self): """Read the success byte.""" self._api_version = self._file.read(1)[0] self._firmware_version = FirmwareVersion(*self._file.read(2))
def get_instance_by_slug(model, slug, **kwargs): """Get an instance by slug. :param model: a string, model name in rio.models :param slug: a string used to query by `slug`. This requires there is a slug field in model definition. :return: None or a SQLAlchemy Model instance. """ ...
Get an instance by slug. :param model: a string, model name in rio.models :param slug: a string used to query by `slug`. This requires there is a slug field in model definition. :return: None or a SQLAlchemy Model instance.
Below is the the instruction that describes the task: ### Input: Get an instance by slug. :param model: a string, model name in rio.models :param slug: a string used to query by `slug`. This requires there is a slug field in model definition. :return: None or a SQLAlchemy Model instanc...
def getvariable(name): """Get the value of a local variable somewhere in the call stack.""" import inspect fr = inspect.currentframe() try: while fr: fr = fr.f_back vars = fr.f_locals if name in vars: return vars[name] except: pass ...
Get the value of a local variable somewhere in the call stack.
Below is the the instruction that describes the task: ### Input: Get the value of a local variable somewhere in the call stack. ### Response: def getvariable(name): """Get the value of a local variable somewhere in the call stack.""" import inspect fr = inspect.currentframe() try: while fr:...
async def _dump_message_field(self, writer, msg, field, fvalue=None): """ Dumps a message field to the writer. Field is defined by the message field specification. :param writer: :param msg: :param field: :param fvalue: :return: """ fname, ftype, ...
Dumps a message field to the writer. Field is defined by the message field specification. :param writer: :param msg: :param field: :param fvalue: :return:
Below is the the instruction that describes the task: ### Input: Dumps a message field to the writer. Field is defined by the message field specification. :param writer: :param msg: :param field: :param fvalue: :return: ### Response: async def _dump_message_field(self, writ...
def __msg_curse_sum(self, ret, sep_char='_', mmm=None, args=None): """ Build the sum message (only when filter is on) and add it to the ret dict. * ret: list of string where the message is added * sep_char: define the line separation char * mmm: display min, max, mean or current...
Build the sum message (only when filter is on) and add it to the ret dict. * ret: list of string where the message is added * sep_char: define the line separation char * mmm: display min, max, mean or current (if mmm=None) * args: Glances args
Below is the the instruction that describes the task: ### Input: Build the sum message (only when filter is on) and add it to the ret dict. * ret: list of string where the message is added * sep_char: define the line separation char * mmm: display min, max, mean or current (if mmm=None) ...
def _iter_axes_subartists(ax): r"""Yield all child `Artist`\s (*not* `Container`\s) of *ax*.""" yield from ax.collections yield from ax.images yield from ax.lines yield from ax.patches yield from ax.texts
r"""Yield all child `Artist`\s (*not* `Container`\s) of *ax*.
Below is the the instruction that describes the task: ### Input: r"""Yield all child `Artist`\s (*not* `Container`\s) of *ax*. ### Response: def _iter_axes_subartists(ax): r"""Yield all child `Artist`\s (*not* `Container`\s) of *ax*.""" yield from ax.collections yield from ax.images yield from ax.l...
def pkill(): """Kill all of FIO processes""" if env(): return 1 cmd = ["ps -aux | grep fio | grep -v grep"] status, _, _ = cij.ssh.command(cmd, shell=True, echo=False) if not status: status, _, _ = cij.ssh.command(["pkill -f fio"], shell=True) if status: return ...
Kill all of FIO processes
Below is the the instruction that describes the task: ### Input: Kill all of FIO processes ### Response: def pkill(): """Kill all of FIO processes""" if env(): return 1 cmd = ["ps -aux | grep fio | grep -v grep"] status, _, _ = cij.ssh.command(cmd, shell=True, echo=False) if not statu...
def get_size_in_bytes(self, handle): """Return the size in bytes.""" fpath = self._fpath_from_handle(handle) return os.stat(fpath).st_size
Return the size in bytes.
Below is the the instruction that describes the task: ### Input: Return the size in bytes. ### Response: def get_size_in_bytes(self, handle): """Return the size in bytes.""" fpath = self._fpath_from_handle(handle) return os.stat(fpath).st_size
def Runtime_compileScript(self, expression, sourceURL, persistScript, **kwargs ): """ Function path: Runtime.compileScript Domain: Runtime Method name: compileScript Parameters: Required arguments: 'expression' (type: string) -> Expression to compile. 'sourceURL' (type: string) -> Sou...
Function path: Runtime.compileScript Domain: Runtime Method name: compileScript Parameters: Required arguments: 'expression' (type: string) -> Expression to compile. 'sourceURL' (type: string) -> Source url to be set for the script. 'persistScript' (type: boolean) -> Specifies whether the...
Below is the the instruction that describes the task: ### Input: Function path: Runtime.compileScript Domain: Runtime Method name: compileScript Parameters: Required arguments: 'expression' (type: string) -> Expression to compile. 'sourceURL' (type: string) -> Source url to be set for the ...
def get_trigger(self, trigger_id): """ Retrieves the named trigger from the Weather Alert API. :param trigger_id: the ID of the trigger :type trigger_id: str :return: a `pyowm.alertapi30.trigger.Trigger` instance """ assert isinstance(trigger_id, str), "Value mus...
Retrieves the named trigger from the Weather Alert API. :param trigger_id: the ID of the trigger :type trigger_id: str :return: a `pyowm.alertapi30.trigger.Trigger` instance
Below is the the instruction that describes the task: ### Input: Retrieves the named trigger from the Weather Alert API. :param trigger_id: the ID of the trigger :type trigger_id: str :return: a `pyowm.alertapi30.trigger.Trigger` instance ### Response: def get_trigger(self, trigger_id): ...
def _load_config(self): """Read the configuration file and load it into memory.""" self._config = ConfigParser.SafeConfigParser() self._config.read(self.config_path)
Read the configuration file and load it into memory.
Below is the the instruction that describes the task: ### Input: Read the configuration file and load it into memory. ### Response: def _load_config(self): """Read the configuration file and load it into memory.""" self._config = ConfigParser.SafeConfigParser() self._config.read(self.config...
def update_cached_response(self, request, response): """On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response. """ cache_url =...
On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response.
Below is the the instruction that describes the task: ### Input: On a 304 we will get a new set of headers that we want to update our cached value with, assuming we have one. This should only ever be called when we've sent an ETag and gotten a 304 as the response. ### Response: def update_...
def create(session, course_name): """ Create an instance using a session and a course_name. @param session: Requests session. @type session: requests.Session @param course_name: Course name (slug) from course json. @type course_name: str @return: Instance of On...
Create an instance using a session and a course_name. @param session: Requests session. @type session: requests.Session @param course_name: Course name (slug) from course json. @type course_name: str @return: Instance of OnDemandCourseMaterialItems @rtype: OnDemandCour...
Below is the the instruction that describes the task: ### Input: Create an instance using a session and a course_name. @param session: Requests session. @type session: requests.Session @param course_name: Course name (slug) from course json. @type course_name: str @return:...
def set_schedule_enabled(self, state): """ :param state: a boolean True (on) or False (off) :return: nothing """ desired_state = {"schedule_enabled": state} response = self.api_interface.set_device_state(self, { "desired_state": desired_state }) ...
:param state: a boolean True (on) or False (off) :return: nothing
Below is the the instruction that describes the task: ### Input: :param state: a boolean True (on) or False (off) :return: nothing ### Response: def set_schedule_enabled(self, state): """ :param state: a boolean True (on) or False (off) :return: nothing """ desired_s...
def login_in_terminal(self, need_captcha=False, use_getpass=True): """不使用cookies,在终端中根据提示登陆知乎 :param bool need_captcha: 是否要求输入验证码,如果登录失败请设为 True :param bool use_getpass: 是否使用安全模式输入密码,默认为 True, 如果在某些 Windows IDE 中无法正常输入密码,请把此参数设置为 False 试试 :return: 如果成功返回cookies字符串 :r...
不使用cookies,在终端中根据提示登陆知乎 :param bool need_captcha: 是否要求输入验证码,如果登录失败请设为 True :param bool use_getpass: 是否使用安全模式输入密码,默认为 True, 如果在某些 Windows IDE 中无法正常输入密码,请把此参数设置为 False 试试 :return: 如果成功返回cookies字符串 :rtype: str
Below is the the instruction that describes the task: ### Input: 不使用cookies,在终端中根据提示登陆知乎 :param bool need_captcha: 是否要求输入验证码,如果登录失败请设为 True :param bool use_getpass: 是否使用安全模式输入密码,默认为 True, 如果在某些 Windows IDE 中无法正常输入密码,请把此参数设置为 False 试试 :return: 如果成功返回cookies字符串 :rtype: str...
def read_images(img_list, path='', n_threads=10, printable=True): """Returns all images in list by given path and name of each image file. Parameters ------------- img_list : list of str The image file names. path : str The image folder path. n_threads : int The number o...
Returns all images in list by given path and name of each image file. Parameters ------------- img_list : list of str The image file names. path : str The image folder path. n_threads : int The number of threads to read image. printable : boolean Whether to print...
Below is the the instruction that describes the task: ### Input: Returns all images in list by given path and name of each image file. Parameters ------------- img_list : list of str The image file names. path : str The image folder path. n_threads : int The number of th...
def identical_blocks(self): """ :returns: A list of block matches which appear to be identical """ identical_blocks = [] for (block_a, block_b) in self._block_matches: if self.blocks_probably_identical(block_a, block_b): identical_blocks.append((block_...
:returns: A list of block matches which appear to be identical
Below is the the instruction that describes the task: ### Input: :returns: A list of block matches which appear to be identical ### Response: def identical_blocks(self): """ :returns: A list of block matches which appear to be identical """ identical_blocks = [] for (block_a...
def get_fobj(fname, mode='w+'): """Obtain a proper file object. Parameters ---------- fname : string, file object, file descriptor If a string or file descriptor, then we create a file object. If *fname* is a file object, then we do nothing and ignore the specified *mode* parame...
Obtain a proper file object. Parameters ---------- fname : string, file object, file descriptor If a string or file descriptor, then we create a file object. If *fname* is a file object, then we do nothing and ignore the specified *mode* parameter. mode : str The mode of...
Below is the the instruction that describes the task: ### Input: Obtain a proper file object. Parameters ---------- fname : string, file object, file descriptor If a string or file descriptor, then we create a file object. If *fname* is a file object, then we do nothing and ignore the s...
def handle_message(self, msg): """Handle a message from the server. Parameters ---------- msg : Message object The Message to dispatch to the handler methods. """ # log messages received so that no one else has to if self._logger.isEnabledFor(logging...
Handle a message from the server. Parameters ---------- msg : Message object The Message to dispatch to the handler methods.
Below is the the instruction that describes the task: ### Input: Handle a message from the server. Parameters ---------- msg : Message object The Message to dispatch to the handler methods. ### Response: def handle_message(self, msg): """Handle a message from the server...
def get_summary(url, spk=True): ''' simple function to retrieve the header of a BSP file and return SPK object''' # connect to file at URL bspurl = urllib2.urlopen(url) # retrieve the "tip" of a file at URL bsptip = bspurl.read(10**5) # first 100kB # save data in fake file object (in-memory) ...
simple function to retrieve the header of a BSP file and return SPK object
Below is the the instruction that describes the task: ### Input: simple function to retrieve the header of a BSP file and return SPK object ### Response: def get_summary(url, spk=True): ''' simple function to retrieve the header of a BSP file and return SPK object''' # connect to file at URL bspurl = u...
def asset_path(cls, organization, asset): """Return a fully-qualified asset string.""" return google.api_core.path_template.expand( "organizations/{organization}/assets/{asset}", organization=organization, asset=asset, )
Return a fully-qualified asset string.
Below is the the instruction that describes the task: ### Input: Return a fully-qualified asset string. ### Response: def asset_path(cls, organization, asset): """Return a fully-qualified asset string.""" return google.api_core.path_template.expand( "organizations/{organization}/assets/...
def Extra(self): """ Returns any `V`, `P`, `DOI` or `misc` values as a string. These are all the values not returned by [ID()](#metaknowledge.citation.Citation.ID), they are separated by `' ,'`. # Returns `str` > A string containing the data not in the ID of the `Citation`. ...
Returns any `V`, `P`, `DOI` or `misc` values as a string. These are all the values not returned by [ID()](#metaknowledge.citation.Citation.ID), they are separated by `' ,'`. # Returns `str` > A string containing the data not in the ID of the `Citation`.
Below is the the instruction that describes the task: ### Input: Returns any `V`, `P`, `DOI` or `misc` values as a string. These are all the values not returned by [ID()](#metaknowledge.citation.Citation.ID), they are separated by `' ,'`. # Returns `str` > A string containing the data not...
def merge_ddb_files(self, delete_source_ddbs=True, only_dfpt_tasks=True, exclude_tasks=None, include_tasks=None): """ This method is called when all the q-points have been computed. It runs `mrgddb` in sequential on the local machine to produce the final DDB file ...
This method is called when all the q-points have been computed. It runs `mrgddb` in sequential on the local machine to produce the final DDB file in the outdir of the `Work`. Args: delete_source_ddbs: True if input DDB should be removed once final DDB is created. only_df...
Below is the the instruction that describes the task: ### Input: This method is called when all the q-points have been computed. It runs `mrgddb` in sequential on the local machine to produce the final DDB file in the outdir of the `Work`. Args: delete_source_ddbs: True if input...
def write(self, basename='/tmp/sitemap.xml'): """Write one or a set of sitemap files to disk. resources is a ResourceContainer that may be an ResourceList or a ChangeList. This may be a generator so data is read as needed and length is determined at the end. basename is used as...
Write one or a set of sitemap files to disk. resources is a ResourceContainer that may be an ResourceList or a ChangeList. This may be a generator so data is read as needed and length is determined at the end. basename is used as the name of the single sitemap file or the sitem...
Below is the the instruction that describes the task: ### Input: Write one or a set of sitemap files to disk. resources is a ResourceContainer that may be an ResourceList or a ChangeList. This may be a generator so data is read as needed and length is determined at the end. basenam...
def get_function_name(s): """ Get the function name from a C-style function declaration string. :param str s: A C-style function declaration string. :return: The function name. :rtype: str """ s = s.strip() if s.startswith("__attribute__"): # Remove "__attribute__ ((...
Get the function name from a C-style function declaration string. :param str s: A C-style function declaration string. :return: The function name. :rtype: str
Below is the the instruction that describes the task: ### Input: Get the function name from a C-style function declaration string. :param str s: A C-style function declaration string. :return: The function name. :rtype: str ### Response: def get_function_name(s): """ Get the functio...
def cancel_base_units(units, to_remove): """Given a list of units, remove a specified number of each base unit. Arguments: units: an iterable of units to_remove: a mapping of base_unit => count, such as that returned from count_base_units Returns a 2-tuple of (factor, remaining...
Given a list of units, remove a specified number of each base unit. Arguments: units: an iterable of units to_remove: a mapping of base_unit => count, such as that returned from count_base_units Returns a 2-tuple of (factor, remaining_units).
Below is the the instruction that describes the task: ### Input: Given a list of units, remove a specified number of each base unit. Arguments: units: an iterable of units to_remove: a mapping of base_unit => count, such as that returned from count_base_units Returns a 2-tuple ...
def Element(self, elem, **params): """Ensure that the input element is immutable by the transformation. Returns a single element.""" res = self.__call__(deepcopy(elem), **params) if len(res) > 0: return res[0] else: return None
Ensure that the input element is immutable by the transformation. Returns a single element.
Below is the the instruction that describes the task: ### Input: Ensure that the input element is immutable by the transformation. Returns a single element. ### Response: def Element(self, elem, **params): """Ensure that the input element is immutable by the transformation. Returns a single element.""" ...
def re_install_net_ctrl_paths(self, vrf_table): """Re-installs paths from NC with current BGP policy. Iterates over known paths from NC installed in `vrf4_table` and adds new path with path attributes as per current VRF configuration. """ assert vrf_table for dest in vrf...
Re-installs paths from NC with current BGP policy. Iterates over known paths from NC installed in `vrf4_table` and adds new path with path attributes as per current VRF configuration.
Below is the the instruction that describes the task: ### Input: Re-installs paths from NC with current BGP policy. Iterates over known paths from NC installed in `vrf4_table` and adds new path with path attributes as per current VRF configuration. ### Response: def re_install_net_ctrl_paths(self,...
def setComponentByName(self, name, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g....
Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ value: :class:`object` or :py:class:`~pya...
Below is the the instruction that describes the task: ### Input: Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ...
def dataset_suggest(q=None, type=None, keyword=None, owningOrg=None, publishingOrg=None, hostingOrg=None, publishingCountry=None, decade=None, limit = 100, offset = None, **kwargs): ''' Search that returns up to 20 matching datasets. Results are ordered by relevance. :param q: [str] Query term(s) for full text s...
Search that returns up to 20 matching datasets. Results are ordered by relevance. :param q: [str] Query term(s) for full text search. The value for this parameter can be a simple word or a phrase. Wildcards can be added to the simple word parameters only, e.g. ``q=*puma*`` :param type: [str] Type of dataset, optio...
Below is the the instruction that describes the task: ### Input: Search that returns up to 20 matching datasets. Results are ordered by relevance. :param q: [str] Query term(s) for full text search. The value for this parameter can be a simple word or a phrase. Wildcards can be added to the simple word paramete...
def field2type_and_format(self, field): """Return the dictionary of OpenAPI type and format based on the field type :param Field field: A marshmallow field. :rtype: dict """ # If this type isn't directly in the field mapping then check the # hierarchy until we fi...
Return the dictionary of OpenAPI type and format based on the field type :param Field field: A marshmallow field. :rtype: dict
Below is the the instruction that describes the task: ### Input: Return the dictionary of OpenAPI type and format based on the field type :param Field field: A marshmallow field. :rtype: dict ### Response: def field2type_and_format(self, field): """Return the dictionary of OpenAPI ...
def list_privileges(self, principal_name, principal_type, hiveObject): """ Parameters: - principal_name - principal_type - hiveObject """ self.send_list_privileges(principal_name, principal_type, hiveObject) return self.recv_list_privileges()
Parameters: - principal_name - principal_type - hiveObject
Below is the the instruction that describes the task: ### Input: Parameters: - principal_name - principal_type - hiveObject ### Response: def list_privileges(self, principal_name, principal_type, hiveObject): """ Parameters: - principal_name - principal_type - hiveObject "...
def remove_directory(directory, show_warnings=True): """Deletes a directory and its contents. Returns a list of errors in form (function, path, excinfo).""" errors = [] def onerror(function, path, excinfo): if show_warnings: print 'Cannot delete %s: %s' % (os.path.relpath(directory)...
Deletes a directory and its contents. Returns a list of errors in form (function, path, excinfo).
Below is the the instruction that describes the task: ### Input: Deletes a directory and its contents. Returns a list of errors in form (function, path, excinfo). ### Response: def remove_directory(directory, show_warnings=True): """Deletes a directory and its contents. Returns a list of errors in form...
def serialize(obj, **options): ''' Serialize Python data to a Python string representation (via pprint.format) :param obj: the data structure to serialize :param options: options given to pprint.format ''' #round-trip this through JSON to avoid OrderedDict types # there's probably a more p...
Serialize Python data to a Python string representation (via pprint.format) :param obj: the data structure to serialize :param options: options given to pprint.format
Below is the the instruction that describes the task: ### Input: Serialize Python data to a Python string representation (via pprint.format) :param obj: the data structure to serialize :param options: options given to pprint.format ### Response: def serialize(obj, **options): ''' Serialize Python ...
def gte(self, key, value, includeMissing=False): '''Return entries where the key's value is greater or equal (>=). Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": ...
Return entries where the key's value is greater or equal (>=). Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs": [3, 2, 9]}, ... {"name": "Joe", "age": 20, "inc...
Below is the the instruction that describes the task: ### Input: Return entries where the key's value is greater or equal (>=). Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, ...
def sync(self): """基于账户/密码去sync数据库 """ if self.wechat_id is not None: res = self.client.find_one({'wechat_id': self.wechat_id}) else: res = self.client.find_one( { 'username': self.username, 'password': self...
基于账户/密码去sync数据库
Below is the the instruction that describes the task: ### Input: 基于账户/密码去sync数据库 ### Response: def sync(self): """基于账户/密码去sync数据库 """ if self.wechat_id is not None: res = self.client.find_one({'wechat_id': self.wechat_id}) else: res = self.client.find_one( ...
def email(self, name, to, from_addr, subject, body, header, owner=None, **kwargs): """ Create the Email TI object. Args: owner: to: from_addr: name: subject: header: body: **kwargs: Return: ...
Create the Email TI object. Args: owner: to: from_addr: name: subject: header: body: **kwargs: Return:
Below is the the instruction that describes the task: ### Input: Create the Email TI object. Args: owner: to: from_addr: name: subject: header: body: **kwargs: Return: ### Response: def email(self, nam...
def get_client(self, initial_timeout=0.1, next_timeout=30): """ Wait until a client instance is available :param float initial_timeout: how long to wait initially for an existing client to complete :param float next_timeout: if the pool could not obtain a client durin...
Wait until a client instance is available :param float initial_timeout: how long to wait initially for an existing client to complete :param float next_timeout: if the pool could not obtain a client during the initial timeout, and we have allocated the maximum available num...
Below is the the instruction that describes the task: ### Input: Wait until a client instance is available :param float initial_timeout: how long to wait initially for an existing client to complete :param float next_timeout: if the pool could not obtain a client during the initi...
def _output_to_file(self): """ Save to filepath specified on init. (Will throw an error if the document is already open). """ f = open(self.filepath, 'wb') if not f: raise Exception('Unable to create output file: ', self.filepath) f.w...
Save to filepath specified on init. (Will throw an error if the document is already open).
Below is the the instruction that describes the task: ### Input: Save to filepath specified on init. (Will throw an error if the document is already open). ### Response: def _output_to_file(self): """ Save to filepath specified on init. (Will throw an error if ...
def write_info (self, url_data): """Write url_data.info.""" self.write(self.part("info") + self.spaces("info")) self.writeln(self.wrap(url_data.info, 65), color=self.colorinfo)
Write url_data.info.
Below is the the instruction that describes the task: ### Input: Write url_data.info. ### Response: def write_info (self, url_data): """Write url_data.info.""" self.write(self.part("info") + self.spaces("info")) self.writeln(self.wrap(url_data.info, 65), color=self.colorinfo)
def get_components(self): """ Returns all the applications from the store """ components = [] for app_id in self.components: components.append(self.components[app_id]) return components
Returns all the applications from the store
Below is the the instruction that describes the task: ### Input: Returns all the applications from the store ### Response: def get_components(self): """ Returns all the applications from the store """ components = [] for app_id in self.components: components.append(self.componen...
def mle(x1, x2, x1err=[], x2err=[], cerr=[], s_int=True, po=(1,0,0.1), verbose=False, logify=True, full_output=False): """ Maximum Likelihood Estimation of best-fit parameters Parameters ---------- x1, x2 : float arrays the independent and dependent variables. x...
Maximum Likelihood Estimation of best-fit parameters Parameters ---------- x1, x2 : float arrays the independent and dependent variables. x1err, x2err : float arrays (optional) measurement uncertainties on independent and dependent variables....
Below is the the instruction that describes the task: ### Input: Maximum Likelihood Estimation of best-fit parameters Parameters ---------- x1, x2 : float arrays the independent and dependent variables. x1err, x2err : float arrays (optional) measurement un...
def setup(self, app): """ Setup the plugin from an application. """ super().setup(app) if isinstance(self.cfg.template_folders, str): self.cfg.template_folders = [self.cfg.template_folders] else: self.cfg.template_folders = list(self.cfg.template_folders) ...
Setup the plugin from an application.
Below is the the instruction that describes the task: ### Input: Setup the plugin from an application. ### Response: def setup(self, app): """ Setup the plugin from an application. """ super().setup(app) if isinstance(self.cfg.template_folders, str): self.cfg.template_folders =...
def _follow_next(self, url): """Follow the 'next' link on paginated results.""" response = self._json(self._get(url), 200) data = response['data'] next_url = self._get_attribute(response, 'links', 'next') while next_url is not None: response = self._json(self._get(ne...
Follow the 'next' link on paginated results.
Below is the the instruction that describes the task: ### Input: Follow the 'next' link on paginated results. ### Response: def _follow_next(self, url): """Follow the 'next' link on paginated results.""" response = self._json(self._get(url), 200) data = response['data'] next_url = ...
def create_app(client_name, scopes=__DEFAULT_SCOPES, redirect_uris=None, website=None, to_file=None, api_base_url=__DEFAULT_BASE_URL, request_timeout=__DEFAULT_TIMEOUT, session=None): """ Create a new app with given `client_name` and `scopes` (The basic scropse are "read", "write", "f...
Create a new app with given `client_name` and `scopes` (The basic scropse are "read", "write", "follow" and "push" - more granular scopes are available, please refere to Mastodon documentation for which). Specify `redirect_uris` if you want users to be redirected to a certain page after authenticating...
Below is the the instruction that describes the task: ### Input: Create a new app with given `client_name` and `scopes` (The basic scropse are "read", "write", "follow" and "push" - more granular scopes are available, please refere to Mastodon documentation for which). Specify `redirect_uris` if y...
def on(self, image): """ Project bounding boxes from one image to a new one. Parameters ---------- image : ndarray or tuple of int The new image onto which to project. Either an image with shape ``(H,W,[C])`` or a tuple denoting such an image ...
Project bounding boxes from one image to a new one. Parameters ---------- image : ndarray or tuple of int The new image onto which to project. Either an image with shape ``(H,W,[C])`` or a tuple denoting such an image shape. Returns ------- ...
Below is the the instruction that describes the task: ### Input: Project bounding boxes from one image to a new one. Parameters ---------- image : ndarray or tuple of int The new image onto which to project. Either an image with shape ``(H,W,[C])`` or a tuple denotin...
def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortest name based on the given description. for word in desc.split(): c = word[0].lower() if not c.isalnum(): continue ...
Attempts to guess the menu entry name from the function name.
Below is the the instruction that describes the task: ### Input: Attempts to guess the menu entry name from the function name. ### Response: def _guess_name(desc, taken=None): """Attempts to guess the menu entry name from the function name.""" taken = taken or [] name = "" # Try to find the shortes...
def bigger_version(version_string_a, version_string_b): """Returns the bigger version of two version strings.""" major_a, minor_a, patch_a = parse_version_string(version_string_a) major_b, minor_b, patch_b = parse_version_string(version_string_b) if major_a > major_b: return version_string_a ...
Returns the bigger version of two version strings.
Below is the the instruction that describes the task: ### Input: Returns the bigger version of two version strings. ### Response: def bigger_version(version_string_a, version_string_b): """Returns the bigger version of two version strings.""" major_a, minor_a, patch_a = parse_version_string(version_string_...
def update(self): """ Remove items in cart """ subtotal = float(0) total = float(0) for product in self.items: subtotal += float(product["price"]) if subtotal > 0: total = subtotal + self.extra_amount self.subtotal = subtotal self.total = ...
Remove items in cart
Below is the the instruction that describes the task: ### Input: Remove items in cart ### Response: def update(self): """ Remove items in cart """ subtotal = float(0) total = float(0) for product in self.items: subtotal += float(product["price"]) if subtotal > 0...
def flush(self): """Flush changes to record.""" files = self.dumps() # Do not create `_files` when there has not been `_files` field before # and the record still has no files attached. if files or '_files' in self.record: self.record['_files'] = files
Flush changes to record.
Below is the the instruction that describes the task: ### Input: Flush changes to record. ### Response: def flush(self): """Flush changes to record.""" files = self.dumps() # Do not create `_files` when there has not been `_files` field before # and the record still has no files att...
def _add_request_entry(self, entry=()): """This function record the request with netfn, sequence number and command, which will be used in parse_ipmi_payload. :param entry: a set of netfn, sequence number and command. """ if not self._lookup_request_entry(entry): self...
This function record the request with netfn, sequence number and command, which will be used in parse_ipmi_payload. :param entry: a set of netfn, sequence number and command.
Below is the the instruction that describes the task: ### Input: This function record the request with netfn, sequence number and command, which will be used in parse_ipmi_payload. :param entry: a set of netfn, sequence number and command. ### Response: def _add_request_entry(self, entry=()): ...
def register_warning_code(code, exception_type, domain='core'): """Register a new warning code""" Logger._warning_code_to_exception[code] = (exception_type, domain) Logger._domain_codes[domain].add(code)
Register a new warning code
Below is the the instruction that describes the task: ### Input: Register a new warning code ### Response: def register_warning_code(code, exception_type, domain='core'): """Register a new warning code""" Logger._warning_code_to_exception[code] = (exception_type, domain) Logger._domain_code...
def validate(self, value, model=None, context=None): """ Validate Perform value validation and return result :param value: value to check, cast to string :param model: parent model being validated :param context: object or None, validation con...
Validate Perform value validation and return result :param value: value to check, cast to string :param model: parent model being validated :param context: object or None, validation context :return: shiftschema.results.SimpleResult
Below is the the instruction that describes the task: ### Input: Validate Perform value validation and return result :param value: value to check, cast to string :param model: parent model being validated :param context: object or None, validation context...
def register(self, *dependencies, default=False, hidden=False, ignore_return_code=False): """ Decorates a callable to turn it into a task """ def outer(func): task = Task(func, *dependencies, default=default, hidden=hidden, ignore_return_code=ignore_return_code) ...
Decorates a callable to turn it into a task
Below is the the instruction that describes the task: ### Input: Decorates a callable to turn it into a task ### Response: def register(self, *dependencies, default=False, hidden=False, ignore_return_code=False): """ Decorates a callable to turn it into a task """ def outer(func): ...
def check_error(result, func, cargs): "Error checking proper value returns" if result != 0: msg = 'Error in "%s": %s' % (func.__name__, get_errors(result) ) raise RTreeError(msg) return
Error checking proper value returns
Below is the the instruction that describes the task: ### Input: Error checking proper value returns ### Response: def check_error(result, func, cargs): "Error checking proper value returns" if result != 0: msg = 'Error in "%s": %s' % (func.__name__, get_errors(result) ) raise RTreeError(ms...
def handle_link(self, value): """ rdf:link rdf:resource points to the resource described by a record. """ for s, p, o in self.graph.triples((value, None, None)): if p == LINK_ELEM: return unicode(o).replace('file://', '')
rdf:link rdf:resource points to the resource described by a record.
Below is the the instruction that describes the task: ### Input: rdf:link rdf:resource points to the resource described by a record. ### Response: def handle_link(self, value): """ rdf:link rdf:resource points to the resource described by a record. """ for s, p, o in self.graph.trip...
def graph2geoff(graph, edge_rel_name, encoder=None): """ Get the `graph` as Geoff string. The edges between the nodes have relationship name `edge_rel_name`. The code below shows a simple example:: # create a graph import networkx as nx G = nx.Graph() G.add_nodes_from([1, 2,...
Get the `graph` as Geoff string. The edges between the nodes have relationship name `edge_rel_name`. The code below shows a simple example:: # create a graph import networkx as nx G = nx.Graph() G.add_nodes_from([1, 2, 3]) G.add_edge(1, 2) G.add_edge(2, 3) ...
Below is the the instruction that describes the task: ### Input: Get the `graph` as Geoff string. The edges between the nodes have relationship name `edge_rel_name`. The code below shows a simple example:: # create a graph import networkx as nx G = nx.Graph() G.add_nodes_fro...
def _uneven_utility_transform(systematic_utilities, alt_IDs, rows_to_alts, shape_params, intercept_params, intercept_ref_pos=None, *args, **...
Parameters ---------- systematic_utilities : 1D ndarray. All elements should be ints, floats, or longs. Should contain the systematic utilities of each observation per available alternative. Note that this vector is formed by the dot product of the design matrix with the vector o...
Below is the the instruction that describes the task: ### Input: Parameters ---------- systematic_utilities : 1D ndarray. All elements should be ints, floats, or longs. Should contain the systematic utilities of each observation per available alternative. Note that this vector is for...
def stop_cont(self, cont=True): """Send SIGSTOP/SIGCONT to processes called <name> """ for proc in psutil.process_iter(): if proc.name() == self.process_name: sig = psutil.signal.SIGCONT if cont else psutil.signal.SIGSTOP proc.send_signal(sig) ...
Send SIGSTOP/SIGCONT to processes called <name>
Below is the the instruction that describes the task: ### Input: Send SIGSTOP/SIGCONT to processes called <name> ### Response: def stop_cont(self, cont=True): """Send SIGSTOP/SIGCONT to processes called <name> """ for proc in psutil.process_iter(): if proc.name() == self.process...
def load_dict(): """ Load java messages that can be ignored pickle file into a dict structure g_ok_java_messages. :return: none """ global g_load_java_message_filename global g_ok_java_messages if os.path.isfile(g_load_java_message_filename): # only load dict from file if it ex...
Load java messages that can be ignored pickle file into a dict structure g_ok_java_messages. :return: none
Below is the the instruction that describes the task: ### Input: Load java messages that can be ignored pickle file into a dict structure g_ok_java_messages. :return: none ### Response: def load_dict(): """ Load java messages that can be ignored pickle file into a dict structure g_ok_java_messages. ...
def read_git_commit_timestamp_for_file(filepath, repo_path=None, repo=None): """Obtain the timestamp for the most recent commit to a given file in a Git repository. Parameters ---------- filepath : `str` Absolute or repository-relative path for a file. repo_path : `str`, optional ...
Obtain the timestamp for the most recent commit to a given file in a Git repository. Parameters ---------- filepath : `str` Absolute or repository-relative path for a file. repo_path : `str`, optional Path to the Git repository. Leave as `None` to use the current working dir...
Below is the the instruction that describes the task: ### Input: Obtain the timestamp for the most recent commit to a given file in a Git repository. Parameters ---------- filepath : `str` Absolute or repository-relative path for a file. repo_path : `str`, optional Path to the G...
def copy(self, deep=True, data=None): """Returns a copy of this array. If `deep=True`, a deep copy is made of the data array. Otherwise, a shallow copy is made, so each variable in the new array's dataset is also a variable in this array's dataset. Use `data` to create a new ob...
Returns a copy of this array. If `deep=True`, a deep copy is made of the data array. Otherwise, a shallow copy is made, so each variable in the new array's dataset is also a variable in this array's dataset. Use `data` to create a new object with the same structure as original ...
Below is the the instruction that describes the task: ### Input: Returns a copy of this array. If `deep=True`, a deep copy is made of the data array. Otherwise, a shallow copy is made, so each variable in the new array's dataset is also a variable in this array's dataset. Use `data...
def get_source(self, source, clean=False, callback=None): """ Download a file from a URL and return it wrapped in a row-generating acessor object. :param spec: A SourceSpec that describes the source to fetch. :param account_accessor: A callable to return the username and password to us...
Download a file from a URL and return it wrapped in a row-generating acessor object. :param spec: A SourceSpec that describes the source to fetch. :param account_accessor: A callable to return the username and password to use for access FTP and S3 URLs. :param clean: Delete files in cache and r...
Below is the the instruction that describes the task: ### Input: Download a file from a URL and return it wrapped in a row-generating acessor object. :param spec: A SourceSpec that describes the source to fetch. :param account_accessor: A callable to return the username and password to use for acce...
def stop_reactor(): """Stop the reactor and join the reactor thread until it stops. Call this function in teardown at the module or package level to reset the twisted system after your tests. You *must* do this if you mix tests using these tools and tests using twisted.trial. """ global _twisted...
Stop the reactor and join the reactor thread until it stops. Call this function in teardown at the module or package level to reset the twisted system after your tests. You *must* do this if you mix tests using these tools and tests using twisted.trial.
Below is the the instruction that describes the task: ### Input: Stop the reactor and join the reactor thread until it stops. Call this function in teardown at the module or package level to reset the twisted system after your tests. You *must* do this if you mix tests using these tools and tests using ...
def items(self): """D.items() -> a set-like object providing a view on D's items""" keycol = self._keycol for row in self.__iter__(): yield (row[keycol], dict(row))
D.items() -> a set-like object providing a view on D's items
Below is the the instruction that describes the task: ### Input: D.items() -> a set-like object providing a view on D's items ### Response: def items(self): """D.items() -> a set-like object providing a view on D's items""" keycol = self._keycol for row in self.__iter__(): yield...
def yaml_force_unicode(): """ Force pyyaml to return unicode values. """ #/ ## modified from |http://stackoverflow.com/a/2967461| if sys.version_info[0] == 2: def construct_func(self, node): return self.construct_scalar(node) yaml.L...
Force pyyaml to return unicode values.
Below is the the instruction that describes the task: ### Input: Force pyyaml to return unicode values. ### Response: def yaml_force_unicode(): """ Force pyyaml to return unicode values. """ #/ ## modified from |http://stackoverflow.com/a/2967461| if sys.version_info...
def window_blackman(N, alpha=0.16): r"""Blackman window :param N: window length .. math:: a_0 - a_1 \cos(\frac{2\pi n}{N-1}) +a_2 \cos(\frac{4\pi n }{N-1}) with .. math:: a_0 = (1-\alpha)/2, a_1=0.5, a_2=\alpha/2 \rm{\;and\; \alpha}=0.16 When :math:`\alpha=0.16`, this is the unqual...
r"""Blackman window :param N: window length .. math:: a_0 - a_1 \cos(\frac{2\pi n}{N-1}) +a_2 \cos(\frac{4\pi n }{N-1}) with .. math:: a_0 = (1-\alpha)/2, a_1=0.5, a_2=\alpha/2 \rm{\;and\; \alpha}=0.16 When :math:`\alpha=0.16`, this is the unqualified Blackman window with :math:`a_...
Below is the the instruction that describes the task: ### Input: r"""Blackman window :param N: window length .. math:: a_0 - a_1 \cos(\frac{2\pi n}{N-1}) +a_2 \cos(\frac{4\pi n }{N-1}) with .. math:: a_0 = (1-\alpha)/2, a_1=0.5, a_2=\alpha/2 \rm{\;and\; \alpha}=0.16 When :math:`\al...
def clean_cache(self, request): """ Remove all MenuItems from Cache. """ treenav.delete_cache() self.message_user(request, _('Cache menuitem cache cleaned successfully.')) info = self.model._meta.app_label, self.model._meta.model_name changelist_url = reverse('adm...
Remove all MenuItems from Cache.
Below is the the instruction that describes the task: ### Input: Remove all MenuItems from Cache. ### Response: def clean_cache(self, request): """ Remove all MenuItems from Cache. """ treenav.delete_cache() self.message_user(request, _('Cache menuitem cache cleaned successf...
def _create_grammar_state(self, world: WikiTablesWorld, possible_actions: List[ProductionRule], linking_scores: torch.Tensor, entity_types: torch.Tensor) -> LambdaGrammarStatelet: """ ...
This method creates the LambdaGrammarStatelet object that's used for decoding. Part of creating that is creating the `valid_actions` dictionary, which contains embedded representations of all of the valid actions. So, we create that here as well. The way we represent the valid expansions is a...
Below is the the instruction that describes the task: ### Input: This method creates the LambdaGrammarStatelet object that's used for decoding. Part of creating that is creating the `valid_actions` dictionary, which contains embedded representations of all of the valid actions. So, we create that ...
def closenessScores(self, expValues, actValues, fractional=True,): """ See the function description in base.py kwargs will have the keyword "fractional", which is ignored by this encoder """ expValue = expValues[0] actValue = actValues[0] if expValue == actValue: closeness = 1.0 els...
See the function description in base.py kwargs will have the keyword "fractional", which is ignored by this encoder
Below is the the instruction that describes the task: ### Input: See the function description in base.py kwargs will have the keyword "fractional", which is ignored by this encoder ### Response: def closenessScores(self, expValues, actValues, fractional=True,): """ See the function description in base.py ...
def log_status(self): '''show download status''' if self.download_filename is None: print("No download") return dt = time.time() - self.download_start speed = os.path.getsize(self.download_filename) / (1000.0 * dt) m = self.entries.get(self.download_lognum...
show download status
Below is the the instruction that describes the task: ### Input: show download status ### Response: def log_status(self): '''show download status''' if self.download_filename is None: print("No download") return dt = time.time() - self.download_start speed = ...
def metric(self, measurement_name, values, tags=None, timestamp=None): """ Append global tags configured for the client to the tags given then converts the data into InfluxDB Line protocol and sends to to socket """ if not measurement_name or values in (None, {}): # D...
Append global tags configured for the client to the tags given then converts the data into InfluxDB Line protocol and sends to to socket
Below is the the instruction that describes the task: ### Input: Append global tags configured for the client to the tags given then converts the data into InfluxDB Line protocol and sends to to socket ### Response: def metric(self, measurement_name, values, tags=None, timestamp=None): """ ...
def shutdown_server(self): """Shut down server if it is alive.""" self.log.debug('shutdown_server: in') if self.ensime and self.toggle_teardown: self.ensime.stop()
Shut down server if it is alive.
Below is the the instruction that describes the task: ### Input: Shut down server if it is alive. ### Response: def shutdown_server(self): """Shut down server if it is alive.""" self.log.debug('shutdown_server: in') if self.ensime and self.toggle_teardown: self.ensime.stop()
def make_sequence(content, error=None, version=None, mode=None, mask=None, encoding=None, boost_error=True, symbol_count=None): """\ Creates a sequence of QR Codes. If the content fits into one QR Code and neither ``version`` nor ``symbol_count`` is provided, this function may return ...
\ Creates a sequence of QR Codes. If the content fits into one QR Code and neither ``version`` nor ``symbol_count`` is provided, this function may return a sequence with one QR Code which does not use the Structured Append mode. Otherwise a sequence of 2 .. n (max. n = 16) QR Codes is returned whi...
Below is the the instruction that describes the task: ### Input: \ Creates a sequence of QR Codes. If the content fits into one QR Code and neither ``version`` nor ``symbol_count`` is provided, this function may return a sequence with one QR Code which does not use the Structured Append mode. Other...
def adsSyncWriteReqEx(port, address, index_group, index_offset, value, plc_data_type): # type: (int, AmsAddr, int, int, Any, Type) -> None """Send data synchronous to an ADS-device. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsA...
Send data synchronous to an ADS-device. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr :param int indexGroup: PLC storage area, according to the INDEXGROUP constants :param int index_offset: PLC storage address :p...
Below is the the instruction that describes the task: ### Input: Send data synchronous to an ADS-device. :param int port: local AMS port as returned by adsPortOpenEx() :param pyads.structs.AmsAddr address: local or remote AmsAddr :param int indexGroup: PLC storage area, according to the INDEXGROUP ...
def format_usage(program_name, description, commands=None, options=()): """ Construct the usage text. Parameters ---------- program_name : str Usually the name of the python file that contains the experiment. description : str description of this experiment (usua...
Construct the usage text. Parameters ---------- program_name : str Usually the name of the python file that contains the experiment. description : str description of this experiment (usually the docstring). commands : dict[str, func] Dictionary of sup...
Below is the the instruction that describes the task: ### Input: Construct the usage text. Parameters ---------- program_name : str Usually the name of the python file that contains the experiment. description : str description of this experiment (usually the docstri...
def Copy(self, old_urn, new_urn, age=NEWEST_TIME, limit=None, update_timestamps=False): """Make a copy of one AFF4 object to a different URN.""" new_urn = rdfvalue.RDFURN(new_urn) if update_timestamps and age != NEWEST_TIME: raise ValueError( ...
Make a copy of one AFF4 object to a different URN.
Below is the the instruction that describes the task: ### Input: Make a copy of one AFF4 object to a different URN. ### Response: def Copy(self, old_urn, new_urn, age=NEWEST_TIME, limit=None, update_timestamps=False): """Make a copy of one AFF4 object to a...
def uploader(func): """This method only used for CKEditor under version 4.5, in newer version, you should use ``upload_success()`` and ``upload_fail()`` instead. Decorated the view function that handle the file upload. The upload view must return the uploaded image's url. For example:: ...
This method only used for CKEditor under version 4.5, in newer version, you should use ``upload_success()`` and ``upload_fail()`` instead. Decorated the view function that handle the file upload. The upload view must return the uploaded image's url. For example:: from flask import ...
Below is the the instruction that describes the task: ### Input: This method only used for CKEditor under version 4.5, in newer version, you should use ``upload_success()`` and ``upload_fail()`` instead. Decorated the view function that handle the file upload. The upload view must return th...
def params(self): """ A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`. """ params = FormsDict() for key, value in self.query.iterallitems(): params[key] = value for key, value in self.forms...
A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`.
Below is the the instruction that describes the task: ### Input: A :class:`FormsDict` with the combined values of :attr:`query` and :attr:`forms`. File uploads are stored in :attr:`files`. ### Response: def params(self): """ A :class:`FormsDict` with the combined values of :attr:`query` and ...
def source_to_unicode(txt, errors='replace', skip_encoding_cookie=True): """Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buffe...
Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buffer or a string containing the source code.
Below is the the instruction that describes the task: ### Input: Converts a bytes string with python source code to unicode. Unicode strings are passed through unchanged. Byte strings are checked for the python source file encoding cookie to determine encoding. txt can be either a bytes buffer or a stri...
def _parse_mode(self, mode, allowed=None, single=False): r""" This private method is for checking the \'mode\' used in the calling method. Parameters ---------- mode : string or list of strings The mode(s) to be parsed allowed : list of strings ...
r""" This private method is for checking the \'mode\' used in the calling method. Parameters ---------- mode : string or list of strings The mode(s) to be parsed allowed : list of strings A list containing the allowed modes. This list is defined...
Below is the the instruction that describes the task: ### Input: r""" This private method is for checking the \'mode\' used in the calling method. Parameters ---------- mode : string or list of strings The mode(s) to be parsed allowed : list of strings ...
def _get_response(self, url, **params): """ Giving a service path and optional specific arguments, returns the response string. """ data = urlencode(params) url = "%s?%s" % (url, data) headers = {'User-Agent': self.get_random_agent()} request = Request(url, header...
Giving a service path and optional specific arguments, returns the response string.
Below is the the instruction that describes the task: ### Input: Giving a service path and optional specific arguments, returns the response string. ### Response: def _get_response(self, url, **params): """ Giving a service path and optional specific arguments, returns the response string. ...