code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def reciprocal_remove(self): """Removes results rows for which the n-gram is not present in at least one text in each labelled set of texts.""" self._logger.info( 'Removing n-grams that are not attested in all labels') self._matches = self._reciprocal_remove(self._matches)
Removes results rows for which the n-gram is not present in at least one text in each labelled set of texts.
Below is the the instruction that describes the task: ### Input: Removes results rows for which the n-gram is not present in at least one text in each labelled set of texts. ### Response: def reciprocal_remove(self): """Removes results rows for which the n-gram is not present in at least on...
def sharey(axes): """ Shared axes limits without shared locators, ticks, etc. By Joe Kington """ linker = Linker(axes) for ax in axes: ax._linker = linker
Shared axes limits without shared locators, ticks, etc. By Joe Kington
Below is the the instruction that describes the task: ### Input: Shared axes limits without shared locators, ticks, etc. By Joe Kington ### Response: def sharey(axes): """ Shared axes limits without shared locators, ticks, etc. By Joe Kington """ linker = Linker(axes) for ax in axes: ...
def log_post(self, url=None, credentials=None, do_verify_certificate=True): """ Write to a remote host via HTTP POST """ if url is None: url = self.url if credentials is None: credentials = self.credentials if do_verify_certificate is None: ...
Write to a remote host via HTTP POST
Below is the the instruction that describes the task: ### Input: Write to a remote host via HTTP POST ### Response: def log_post(self, url=None, credentials=None, do_verify_certificate=True): """ Write to a remote host via HTTP POST """ if url is None: url = self.url ...
def add_coconut_to_path(): """Adds coconut to sys.path if it isn't there already.""" try: import coconut # NOQA except ImportError: sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
Adds coconut to sys.path if it isn't there already.
Below is the the instruction that describes the task: ### Input: Adds coconut to sys.path if it isn't there already. ### Response: def add_coconut_to_path(): """Adds coconut to sys.path if it isn't there already.""" try: import coconut # NOQA except ImportError: sys.path.insert(0, os.p...
def audio_bottom(x, model_hparams, vocab_size): """Transform input from data space to model space. Args: x: A Tensor with shape [batch, ...] model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: body_input: A Tensor with shape [batch, ?, ?, model_hparams....
Transform input from data space to model space. Args: x: A Tensor with shape [batch, ...] model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: body_input: A Tensor with shape [batch, ?, ?, model_hparams.hidden_size].
Below is the the instruction that describes the task: ### Input: Transform input from data space to model space. Args: x: A Tensor with shape [batch, ...] model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: body_input: A Tensor with shape [batch, ?, ?, ...
def _rollback(self): """Roll back the transaction. Raises: ValueError: If no transaction is in progress. """ if not self.in_progress: raise ValueError(_CANT_ROLLBACK) try: # NOTE: The response is just ``google.protobuf.Empty``. se...
Roll back the transaction. Raises: ValueError: If no transaction is in progress.
Below is the the instruction that describes the task: ### Input: Roll back the transaction. Raises: ValueError: If no transaction is in progress. ### Response: def _rollback(self): """Roll back the transaction. Raises: ValueError: If no transaction is in progress. ...
def create_connection(address): """ Wrapper for socket.create_connection() function. If *address* (a 2-tuple ``(host, port)``) contains a valid IPv4/v6 address, passes *address* to socket.create_connection(). If *host* is valid path to Unix Domain socket, tries to connect to the server listenin...
Wrapper for socket.create_connection() function. If *address* (a 2-tuple ``(host, port)``) contains a valid IPv4/v6 address, passes *address* to socket.create_connection(). If *host* is valid path to Unix Domain socket, tries to connect to the server listening on the given socket. :param address: ...
Below is the the instruction that describes the task: ### Input: Wrapper for socket.create_connection() function. If *address* (a 2-tuple ``(host, port)``) contains a valid IPv4/v6 address, passes *address* to socket.create_connection(). If *host* is valid path to Unix Domain socket, tries to connect t...
def telephone(self, mask: str = '', placeholder: str = '#') -> str: """Generate a random phone number. :param mask: Mask for formatting number. :param placeholder: A placeholder for a mask (default is #). :return: Phone number. :Example: +7-(963)-409-11-22. ...
Generate a random phone number. :param mask: Mask for formatting number. :param placeholder: A placeholder for a mask (default is #). :return: Phone number. :Example: +7-(963)-409-11-22.
Below is the the instruction that describes the task: ### Input: Generate a random phone number. :param mask: Mask for formatting number. :param placeholder: A placeholder for a mask (default is #). :return: Phone number. :Example: +7-(963)-409-11-22. ### Response: def...
def data_filename(fname, pkgdir=""): """Return the path to a data file of ours. The file is searched for on `STATIC_PATH`, and the first place it's found, is returned. Each directory in `STATIC_PATH` is searched as-is, and also, if `pkgdir` is provided, at that subdirectory. """ for stati...
Return the path to a data file of ours. The file is searched for on `STATIC_PATH`, and the first place it's found, is returned. Each directory in `STATIC_PATH` is searched as-is, and also, if `pkgdir` is provided, at that subdirectory.
Below is the the instruction that describes the task: ### Input: Return the path to a data file of ours. The file is searched for on `STATIC_PATH`, and the first place it's found, is returned. Each directory in `STATIC_PATH` is searched as-is, and also, if `pkgdir` is provided, at that subdirector...
def get_prtflds_default(self): """Get default fields.""" return self._fldsdefprt[:-1] + \ ["p_{M}".format(M=m.fieldname) for m in self.method_flds] + \ [self._fldsdefprt[-1]]
Get default fields.
Below is the the instruction that describes the task: ### Input: Get default fields. ### Response: def get_prtflds_default(self): """Get default fields.""" return self._fldsdefprt[:-1] + \ ["p_{M}".format(M=m.fieldname) for m in self.method_flds] + \ [self._fldsdefprt[...
def axesfontsize(ax, fontsize): """ Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*. """ items = ([ax.title, ax.xaxis.label, ax.yaxis.label] + ax.get_xticklabels() + ax.get_yticklabels()) for item in items: item.set_fontsize(fontsize)
Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*.
Below is the the instruction that describes the task: ### Input: Change the font size for the title, x and y labels, and x and y tick labels for axis *ax* to *fontsize*. ### Response: def axesfontsize(ax, fontsize): """ Change the font size for the title, x and y labels, and x and y tick labels for axis *a...
def verify_file_private(filename): """ Raises ValueError the file permissions allow group/other On windows this never raises due to the implementation of stat. """ if platform.system().upper() != 'WINDOWS': filename = os.path.expanduser(filename) if os.path.exists(filename): ...
Raises ValueError the file permissions allow group/other On windows this never raises due to the implementation of stat.
Below is the the instruction that describes the task: ### Input: Raises ValueError the file permissions allow group/other On windows this never raises due to the implementation of stat. ### Response: def verify_file_private(filename): """ Raises ValueError the file permissions allow group/other On ...
def description(self): """A user-friendly description of the handler. Returns: :py:class:`str`: The handler's description. """ if self._description is None: text = '\n'.join(self.__doc__.splitlines()[1:]).strip() lines = [] for line in map(...
A user-friendly description of the handler. Returns: :py:class:`str`: The handler's description.
Below is the the instruction that describes the task: ### Input: A user-friendly description of the handler. Returns: :py:class:`str`: The handler's description. ### Response: def description(self): """A user-friendly description of the handler. Returns: :py:class:`str...
def find_cookies_for_class(cookies_file, class_name): """ Return a RequestsCookieJar containing the cookies for .coursera.org and class.coursera.org found in the given cookies_file. """ path = "/" + class_name def cookies_filter(c): return c.domain == ".coursera.org" \ or (...
Return a RequestsCookieJar containing the cookies for .coursera.org and class.coursera.org found in the given cookies_file.
Below is the the instruction that describes the task: ### Input: Return a RequestsCookieJar containing the cookies for .coursera.org and class.coursera.org found in the given cookies_file. ### Response: def find_cookies_for_class(cookies_file, class_name): """ Return a RequestsCookieJar containing the ...
def capsnet(batch_size, n_class, num_routing, recon_loss_weight): """Create CapsNet""" # data.shape = [batch_size, 1, 28, 28] data = mx.sym.Variable('data') input_shape = (1, 28, 28) # Conv2D layer # net.shape = [batch_size, 256, 20, 20] conv1 = mx.sym.Convolution(data=data, ...
Create CapsNet
Below is the the instruction that describes the task: ### Input: Create CapsNet ### Response: def capsnet(batch_size, n_class, num_routing, recon_loss_weight): """Create CapsNet""" # data.shape = [batch_size, 1, 28, 28] data = mx.sym.Variable('data') input_shape = (1, 28, 28) # Conv2D layer ...
def read_table(self, table_name, index_col=None, coerce_float=True, parse_dates=None, columns=None, schema=None, chunksize=None): """Read SQL database table into a DataFrame. Parameters ---------- table_name : string Name of SQL table in...
Read SQL database table into a DataFrame. Parameters ---------- table_name : string Name of SQL table in database. index_col : string, optional, default: None Column to set as index. coerce_float : boolean, default True Attempts to convert val...
Below is the the instruction that describes the task: ### Input: Read SQL database table into a DataFrame. Parameters ---------- table_name : string Name of SQL table in database. index_col : string, optional, default: None Column to set as index. coe...
def as_live(self): """ Return this call as if it were being assigned in a pyconfig namespace, but load the actual value currently available in pyconfig. """ key = self.get_key() default = pyconfig.get(key) if default: default = repr(default) e...
Return this call as if it were being assigned in a pyconfig namespace, but load the actual value currently available in pyconfig.
Below is the the instruction that describes the task: ### Input: Return this call as if it were being assigned in a pyconfig namespace, but load the actual value currently available in pyconfig. ### Response: def as_live(self): """ Return this call as if it were being assigned in a pyconfig...
def _init_hex(self, hexval: str) -> None: """ Initialize from a hex value string. """ self.hexval = hex2termhex(fix_hex(hexval)) self.code = hex2term(self.hexval) self.rgb = hex2rgb(self.hexval)
Initialize from a hex value string.
Below is the the instruction that describes the task: ### Input: Initialize from a hex value string. ### Response: def _init_hex(self, hexval: str) -> None: """ Initialize from a hex value string. """ self.hexval = hex2termhex(fix_hex(hexval)) self.code = hex2term(self.hexval) self....
def main(input_filename, format): """ Calculate the fingerprint hashses of the referenced audio file and save to disk as a pickle file """ # open the file & convert to wav song_data = AudioSegment.from_file(input_filename, format=format) song_data = song_data.set_channels(1) # convert to m...
Calculate the fingerprint hashses of the referenced audio file and save to disk as a pickle file
Below is the the instruction that describes the task: ### Input: Calculate the fingerprint hashses of the referenced audio file and save to disk as a pickle file ### Response: def main(input_filename, format): """ Calculate the fingerprint hashses of the referenced audio file and save to disk as a ...
def get_wrong_answer_ids(self): """provide this method to return only wrong answer ids""" id_list = [] for answer in self.get_wrong_answers(): id_list.append(answer.get_id()) return IdList(id_list)
provide this method to return only wrong answer ids
Below is the the instruction that describes the task: ### Input: provide this method to return only wrong answer ids ### Response: def get_wrong_answer_ids(self): """provide this method to return only wrong answer ids""" id_list = [] for answer in self.get_wrong_answers(): id_li...
def is_monotonic(a, increasing=True): """ Tests whether a vector a has monotonicity. Parameters ---------- a : array-like Array that should be tested for monotonicity increasing : bool, default: True Test if the array is montonically increasing, otherwise test if the ar...
Tests whether a vector a has monotonicity. Parameters ---------- a : array-like Array that should be tested for monotonicity increasing : bool, default: True Test if the array is montonically increasing, otherwise test if the array is montonically decreasing.
Below is the the instruction that describes the task: ### Input: Tests whether a vector a has monotonicity. Parameters ---------- a : array-like Array that should be tested for monotonicity increasing : bool, default: True Test if the array is montonically increasing, otherwise tes...
def init_epoch(self): """Set up the batch generator for a new epoch.""" if self._restored_from_state: self.random_shuffler.random_state = self._random_state_this_epoch else: self._random_state_this_epoch = self.random_shuffler.random_state self.create_batches() ...
Set up the batch generator for a new epoch.
Below is the the instruction that describes the task: ### Input: Set up the batch generator for a new epoch. ### Response: def init_epoch(self): """Set up the batch generator for a new epoch.""" if self._restored_from_state: self.random_shuffler.random_state = self._random_state_this_e...
def hidden_constraints(self): """ Constraints applied to the population, but temporarily removed. """ try: return self._hidden_constraints except AttributeError: self._hidden_constraints = ConstraintDict() return self._hidden_constraints
Constraints applied to the population, but temporarily removed.
Below is the the instruction that describes the task: ### Input: Constraints applied to the population, but temporarily removed. ### Response: def hidden_constraints(self): """ Constraints applied to the population, but temporarily removed. """ try: return self._hidden_c...
def _Reg2Py(data, size, data_type): """Converts a Windows Registry value to the corresponding Python data type.""" if data_type == winreg.REG_DWORD: if size == 0: return 0 # DWORD is an unsigned 32-bit integer, see: # https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/262627d8-34...
Converts a Windows Registry value to the corresponding Python data type.
Below is the the instruction that describes the task: ### Input: Converts a Windows Registry value to the corresponding Python data type. ### Response: def _Reg2Py(data, size, data_type): """Converts a Windows Registry value to the corresponding Python data type.""" if data_type == winreg.REG_DWORD: if siz...
def lookupjoin(left, right, key=None, lkey=None, rkey=None, missing=None, presorted=False, buffersize=None, tempdir=None, cache=True, lprefix=None, rprefix=None): """ Perform a left join, but where the key is not unique in the right-hand table, arbitrarily choose the first row ...
Perform a left join, but where the key is not unique in the right-hand table, arbitrarily choose the first row and ignore others. E.g.:: >>> import petl as etl >>> table1 = [['id', 'color', 'cost'], ... [1, 'blue', 12], ... [2, 'red', 8], ... [3...
Below is the the instruction that describes the task: ### Input: Perform a left join, but where the key is not unique in the right-hand table, arbitrarily choose the first row and ignore others. E.g.:: >>> import petl as etl >>> table1 = [['id', 'color', 'cost'], ... [1, 'blue...
def _format_final_exc_line(etype, value): """Return a list of a single line -- normal case for format_exception_only""" valuestr = _some_str(value) if value is None or not valuestr: line = "%s\n" % etype else: line = "%s: %s\n" % (etype, valuestr) return line
Return a list of a single line -- normal case for format_exception_only
Below is the the instruction that describes the task: ### Input: Return a list of a single line -- normal case for format_exception_only ### Response: def _format_final_exc_line(etype, value): """Return a list of a single line -- normal case for format_exception_only""" valuestr = _some_str(value) if v...
def async_handler(handler): """ This decorator allows for use of async handlers by automatically running them in an event loop. The loop is added to the context object for if the handler needs it. Usage:: >>> from lambda_decorators import async_handler >>> async def foobar(): ...
This decorator allows for use of async handlers by automatically running them in an event loop. The loop is added to the context object for if the handler needs it. Usage:: >>> from lambda_decorators import async_handler >>> async def foobar(): ... return 'foobar' >>> @...
Below is the the instruction that describes the task: ### Input: This decorator allows for use of async handlers by automatically running them in an event loop. The loop is added to the context object for if the handler needs it. Usage:: >>> from lambda_decorators import async_handler ...
def matches_requirement(self, req): """ Say if this instance matches (fulfills) a requirement. :param req: The requirement to match. :rtype req: str :return: True if it matches, else False. """ # Requirement may contain extras - parse to lose those # from ...
Say if this instance matches (fulfills) a requirement. :param req: The requirement to match. :rtype req: str :return: True if it matches, else False.
Below is the the instruction that describes the task: ### Input: Say if this instance matches (fulfills) a requirement. :param req: The requirement to match. :rtype req: str :return: True if it matches, else False. ### Response: def matches_requirement(self, req): """ Say if...
def allow_client_outgoing(self, application_sid, **kwargs): """ Allow the user of this token to make outgoing connections. Keyword arguments are passed to the application. :param str application_sid: Application to contact """ scope = ScopeURI('client', 'outgoing', {'app...
Allow the user of this token to make outgoing connections. Keyword arguments are passed to the application. :param str application_sid: Application to contact
Below is the the instruction that describes the task: ### Input: Allow the user of this token to make outgoing connections. Keyword arguments are passed to the application. :param str application_sid: Application to contact ### Response: def allow_client_outgoing(self, application_sid, **kwargs): ...
def make_preprocessing_fn(output_dir, features, keep_target): """Makes a preprocessing function. Args: output_dir: folder path that contains the vocab and stats files. features: the features dict Returns: a function that takes a dict of input tensors """ def preprocessing_fn(inputs): """Prep...
Makes a preprocessing function. Args: output_dir: folder path that contains the vocab and stats files. features: the features dict Returns: a function that takes a dict of input tensors
Below is the the instruction that describes the task: ### Input: Makes a preprocessing function. Args: output_dir: folder path that contains the vocab and stats files. features: the features dict Returns: a function that takes a dict of input tensors ### Response: def make_preprocessing_fn(output...
def getPattern(self, idx, sparseBinaryForm=False, cat=None): """Gets a training pattern either by index or category number. :param idx: Index of the training pattern :param sparseBinaryForm: If true, returns a list of the indices of the non-zero bits in the training pattern :param cat: If not...
Gets a training pattern either by index or category number. :param idx: Index of the training pattern :param sparseBinaryForm: If true, returns a list of the indices of the non-zero bits in the training pattern :param cat: If not None, get the first pattern belonging to category cat. If t...
Below is the the instruction that describes the task: ### Input: Gets a training pattern either by index or category number. :param idx: Index of the training pattern :param sparseBinaryForm: If true, returns a list of the indices of the non-zero bits in the training pattern :param cat: If no...
def _init_itemid2name(self): """Print gene symbols instead of gene IDs, if provided.""" if not hasattr(self.args, 'id2sym'): return None fin_id2sym = self.args.id2sym if fin_id2sym is not None and os.path.exists(fin_id2sym): id2sym = {} cmpl = re.compi...
Print gene symbols instead of gene IDs, if provided.
Below is the the instruction that describes the task: ### Input: Print gene symbols instead of gene IDs, if provided. ### Response: def _init_itemid2name(self): """Print gene symbols instead of gene IDs, if provided.""" if not hasattr(self.args, 'id2sym'): return None fin_id2sym...
def normalize_path(path, filetype=None, has_filetype=True): """ Convert dot-separated paths to directory paths Allows non-python files to be placed in the PYTHONPATH and be referenced using dot-notation instead of absolute or relative file-system paths. If a text file, named test.txt was placed in a p...
Convert dot-separated paths to directory paths Allows non-python files to be placed in the PYTHONPATH and be referenced using dot-notation instead of absolute or relative file-system paths. If a text file, named test.txt was placed in a python repo named myprog in the module named util, then: ...
Below is the the instruction that describes the task: ### Input: Convert dot-separated paths to directory paths Allows non-python files to be placed in the PYTHONPATH and be referenced using dot-notation instead of absolute or relative file-system paths. If a text file, named test.txt was placed in a ...
def physical_cpus(): """Get cpus identifiers, for instance set(["0", "1", "2", "3"]) :return Number of physical CPUs available :rtype: int """ if platform.system() == 'Darwin': ncores = subprocess.check_output( ['/usr/sbin/sysctl', '-n', 'hw.ncpu'], shell=False ) ...
Get cpus identifiers, for instance set(["0", "1", "2", "3"]) :return Number of physical CPUs available :rtype: int
Below is the the instruction that describes the task: ### Input: Get cpus identifiers, for instance set(["0", "1", "2", "3"]) :return Number of physical CPUs available :rtype: int ### Response: def physical_cpus(): """Get cpus identifiers, for instance set(["0", "1", "2", "3"]) :return Number of ...
def min_validator(min_value): """Return validator function that ensures lower bound of a number. Result validation function will validate the internal value of resource instance field with the ``value >= min_value`` check Args: min_value: minimal value for new validator """ def valida...
Return validator function that ensures lower bound of a number. Result validation function will validate the internal value of resource instance field with the ``value >= min_value`` check Args: min_value: minimal value for new validator
Below is the the instruction that describes the task: ### Input: Return validator function that ensures lower bound of a number. Result validation function will validate the internal value of resource instance field with the ``value >= min_value`` check Args: min_value: minimal value for new v...
def line_intersects_itself(lons, lats, closed_shape=False): """ Return ``True`` if line of points intersects itself. Line with the last point repeating the first one considered intersecting itself. The line is defined by lists (or numpy arrays) of points' longitudes and latitudes (depth is not ...
Return ``True`` if line of points intersects itself. Line with the last point repeating the first one considered intersecting itself. The line is defined by lists (or numpy arrays) of points' longitudes and latitudes (depth is not taken into account). :param closed_shape: If ``True`` the l...
Below is the the instruction that describes the task: ### Input: Return ``True`` if line of points intersects itself. Line with the last point repeating the first one considered intersecting itself. The line is defined by lists (or numpy arrays) of points' longitudes and latitudes (depth is not tak...
def show(self, value=True, modal=None): "Display or hide the window, optionally disabling all other windows" self.wx_obj.Show(value) if modal: # disable all top level windows of this application (MakeModal) disabler = wx.WindowDisabler(self.wx_obj) # cre...
Display or hide the window, optionally disabling all other windows
Below is the the instruction that describes the task: ### Input: Display or hide the window, optionally disabling all other windows ### Response: def show(self, value=True, modal=None): "Display or hide the window, optionally disabling all other windows" self.wx_obj.Show(value) if modal:...
def nontruncating_zip(*seqs): """Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is as long as the longest argument sequence. Shorter argument sequences will be represented in the output as None paddi...
Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is as long as the longest argument sequence. Shorter argument sequences will be represented in the output as None padding elements: nontruncating_z...
Below is the the instruction that describes the task: ### Input: Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is as long as the longest argument sequence. Shorter argument sequences will be represented in the o...
def parse(self, filelike, filename): """Parse the given file-like object and return its Module object.""" self.log = log self.source = filelike.readlines() src = "".join(self.source) # This may raise a SyntaxError: compile(src, filename, "exec") self.stream = Toke...
Parse the given file-like object and return its Module object.
Below is the the instruction that describes the task: ### Input: Parse the given file-like object and return its Module object. ### Response: def parse(self, filelike, filename): """Parse the given file-like object and return its Module object.""" self.log = log self.source = filelike.readl...
def do_asg(self,args): """Go to the specified auto scaling group. asg -h for detailed help""" parser = CommandArgumentParser("asg") parser.add_argument(dest='asg',help='asg index or name'); args = vars(parser.parse_args(args)) print "loading auto scaling group {}".format(args['a...
Go to the specified auto scaling group. asg -h for detailed help
Below is the the instruction that describes the task: ### Input: Go to the specified auto scaling group. asg -h for detailed help ### Response: def do_asg(self,args): """Go to the specified auto scaling group. asg -h for detailed help""" parser = CommandArgumentParser("asg") parser.add_argu...
def histogram_cluster_table(analyzed_data_file, output_file, chunk_size=10000000): '''Reads in the cluster info table in chunks and histograms the seed pixels into one occupancy array. The 3rd dimension of the occupancy array is the number of different scan parameters used Parameters ---------- ana...
Reads in the cluster info table in chunks and histograms the seed pixels into one occupancy array. The 3rd dimension of the occupancy array is the number of different scan parameters used Parameters ---------- analyzed_data_file : string HDF5 filename of the file containing the cluster table. I...
Below is the the instruction that describes the task: ### Input: Reads in the cluster info table in chunks and histograms the seed pixels into one occupancy array. The 3rd dimension of the occupancy array is the number of different scan parameters used Parameters ---------- analyzed_data_file : str...
def zharkov_panh(v, temp, v0, a0, m, n, z, t_ref=300., three_r=3. * constants.R): """ calculate pressure from anharmonicity for Zharkov equation the equation is from Dorogokupets 2015 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in...
calculate pressure from anharmonicity for Zharkov equation the equation is from Dorogokupets 2015 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param a0: parameter in K-1 for the Zharkov equation :param m: parameter for the Zharkov ...
Below is the the instruction that describes the task: ### Input: calculate pressure from anharmonicity for Zharkov equation the equation is from Dorogokupets 2015 :param v: unit-cell volume in A^3 :param temp: temperature in K :param v0: unit-cell volume in A^3 at 1 bar :param a0: parameter in ...
def set_interval(self, start, end, value, compact=False): """Set the value for the time series on an interval. If compact is True, only set the value if it's different from what it would be anyway. """ # for each interval to render for i, (s, e, v) in enumerate(self.iter...
Set the value for the time series on an interval. If compact is True, only set the value if it's different from what it would be anyway.
Below is the the instruction that describes the task: ### Input: Set the value for the time series on an interval. If compact is True, only set the value if it's different from what it would be anyway. ### Response: def set_interval(self, start, end, value, compact=False): """Set the value ...
def parse_volumes_output(out): """ Parses the output of the Docker CLI 'docker volume ls' and returns it in the format similar to the Docker API. :param out: CLI output. :type out: unicode | str :return: Parsed result. :rtype: list[dict] """ if not out: return [] line_iter =...
Parses the output of the Docker CLI 'docker volume ls' and returns it in the format similar to the Docker API. :param out: CLI output. :type out: unicode | str :return: Parsed result. :rtype: list[dict]
Below is the the instruction that describes the task: ### Input: Parses the output of the Docker CLI 'docker volume ls' and returns it in the format similar to the Docker API. :param out: CLI output. :type out: unicode | str :return: Parsed result. :rtype: list[dict] ### Response: def parse_volume...
def verify_tops(self, tops): ''' Verify the contents of the top file data ''' errors = [] if not isinstance(tops, dict): errors.append('Top data was not formed as a dict') # No further checks will work, bail out return errors for salten...
Verify the contents of the top file data
Below is the the instruction that describes the task: ### Input: Verify the contents of the top file data ### Response: def verify_tops(self, tops): ''' Verify the contents of the top file data ''' errors = [] if not isinstance(tops, dict): errors.append('Top dat...
def __partial_trace_vec(vec, trace_systems, dimensions, reverse=True): """ Partial trace over subsystems of multi-partite vector. Args: vec (vector_like): complex vector N trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. ...
Partial trace over subsystems of multi-partite vector. Args: vec (vector_like): complex vector N trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions (list(int)): a list of the dimensions of the subsystems. ...
Below is the the instruction that describes the task: ### Input: Partial trace over subsystems of multi-partite vector. Args: vec (vector_like): complex vector N trace_systems (list(int)): a list of subsystems (starting from 0) to trace over. dimensions...
def get_by_username(cls, username): """ Return a User by email address """ return cls.query().filter(cls.username == username).first()
Return a User by email address
Below is the the instruction that describes the task: ### Input: Return a User by email address ### Response: def get_by_username(cls, username): """ Return a User by email address """ return cls.query().filter(cls.username == username).first()
def from_points(cls, lons, lats, depths=None, sitemodel=None, req_site_params=()): """ Build the site collection from :param lons: a sequence of longitudes :param lats: a sequence of latitudes :param depths: a sequence of d...
Build the site collection from :param lons: a sequence of longitudes :param lats: a sequence of latitudes :param depths: a sequence of depths (or None) :param sitemodel: None or an object containing site parameters as attributes :p...
Below is the the instruction that describes the task: ### Input: Build the site collection from :param lons: a sequence of longitudes :param lats: a sequence of latitudes :param depths: a sequence of depths (or None) :param sitemodel: ...
def next_frame_savp_gan(): """SAVP - GAN only model.""" hparams = next_frame_savp() hparams.use_gan = True hparams.use_vae = False hparams.gan_loss_multiplier = 0.001 hparams.optimizer_adam_beta1 = 0.5 hparams.learning_rate_constant = 2e-4 hparams.gan_loss = "cross_entropy" hparams.learning_rate_decay...
SAVP - GAN only model.
Below is the the instruction that describes the task: ### Input: SAVP - GAN only model. ### Response: def next_frame_savp_gan(): """SAVP - GAN only model.""" hparams = next_frame_savp() hparams.use_gan = True hparams.use_vae = False hparams.gan_loss_multiplier = 0.001 hparams.optimizer_adam_beta1 = 0.5...
def pypirc_temp(index_url): """ Create a temporary pypirc file for interaction with twine """ pypirc_file = tempfile.NamedTemporaryFile(suffix='.pypirc', delete=False) print(pypirc_file.name) with open(pypirc_file.name, 'w') as fh: fh.write(PYPIRC_TEMPLATE.format(index_name=PYPIRC_TEMP_INDEX_NAM...
Create a temporary pypirc file for interaction with twine
Below is the the instruction that describes the task: ### Input: Create a temporary pypirc file for interaction with twine ### Response: def pypirc_temp(index_url): """ Create a temporary pypirc file for interaction with twine """ pypirc_file = tempfile.NamedTemporaryFile(suffix='.pypirc', delete=False) ...
def _chart(self, x, y, chart_type, opts, style, label, options, **kwargs): """ Initialize chart options """ if opts is not None: self.chart_opts = opts if style is not None: self.chart_style = style if label is not None: self.label = label self.x = x self.y = y if chart_type is None: retur...
Initialize chart options
Below is the the instruction that describes the task: ### Input: Initialize chart options ### Response: def _chart(self, x, y, chart_type, opts, style, label, options, **kwargs): """ Initialize chart options """ if opts is not None: self.chart_opts = opts if style is not None: self.chart_style = st...
def u2opener(self): """ Create a urllib opener. @return: An opener. @rtype: I{OpenerDirector} """ if self.urlopener is None: return urllib2.build_opener(*self.u2handlers()) return self.urlopener
Create a urllib opener. @return: An opener. @rtype: I{OpenerDirector}
Below is the the instruction that describes the task: ### Input: Create a urllib opener. @return: An opener. @rtype: I{OpenerDirector} ### Response: def u2opener(self): """ Create a urllib opener. @return: An opener. @rtype: I{OpenerDirector} """ i...
def _expand_formatting_rule(rule, national_prefix): """Formatting rules can include terms "$NP" and "$FG", These get replaced with: "$NP" => the national prefix "$FG" => the first group, i.e. "$1" """ if rule is None: return None if national_prefix is None: national_prefix ...
Formatting rules can include terms "$NP" and "$FG", These get replaced with: "$NP" => the national prefix "$FG" => the first group, i.e. "$1"
Below is the the instruction that describes the task: ### Input: Formatting rules can include terms "$NP" and "$FG", These get replaced with: "$NP" => the national prefix "$FG" => the first group, i.e. "$1" ### Response: def _expand_formatting_rule(rule, national_prefix): """Formatting rules can ...
def global_fixes(): """Yield multiple (code, function) tuples.""" for function in list(globals().values()): if inspect.isfunction(function): arguments = _get_parameters(function) if arguments[:1] != ['source']: continue code = extract_code_from_functi...
Yield multiple (code, function) tuples.
Below is the the instruction that describes the task: ### Input: Yield multiple (code, function) tuples. ### Response: def global_fixes(): """Yield multiple (code, function) tuples.""" for function in list(globals().values()): if inspect.isfunction(function): arguments = _get_parameters...
def _remove_vars(self): """ Remove hosts/host_vars/group_vars and returns None. :returns: None """ for name in ("hosts", "group_vars", "host_vars"): d = os.path.join(self.inventory_directory, name) if os.path.islink(d) or os.path.isfile(d): ...
Remove hosts/host_vars/group_vars and returns None. :returns: None
Below is the the instruction that describes the task: ### Input: Remove hosts/host_vars/group_vars and returns None. :returns: None ### Response: def _remove_vars(self): """ Remove hosts/host_vars/group_vars and returns None. :returns: None """ for name in ("hosts"...
def _on_del_route(self, msg): """ Respond to :data:`mitogen.core.DEL_ROUTE` by validating the source of the message, updating the local table, propagating the message upwards, and downwards towards any stream that every had a message forwarded from it towards the disconnecting co...
Respond to :data:`mitogen.core.DEL_ROUTE` by validating the source of the message, updating the local table, propagating the message upwards, and downwards towards any stream that every had a message forwarded from it towards the disconnecting context.
Below is the the instruction that describes the task: ### Input: Respond to :data:`mitogen.core.DEL_ROUTE` by validating the source of the message, updating the local table, propagating the message upwards, and downwards towards any stream that every had a message forwarded from it towards t...
def read(self, size=None): """Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all re...
Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all remaining data. Returns: ...
Below is the the instruction that describes the task: ### Input: Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to r...
def __merge_json_values(current, previous): """Merges the values between the current and previous run of the script.""" for value in current: name = value['name'] # Find the previous value previous_value = __find_and_remove_value(previous, value) if previous_value is not None: ...
Merges the values between the current and previous run of the script.
Below is the the instruction that describes the task: ### Input: Merges the values between the current and previous run of the script. ### Response: def __merge_json_values(current, previous): """Merges the values between the current and previous run of the script.""" for value in current: name = v...
def reproduce(self, config, species, pop_size, generation): """ Handles creation of genomes, either from scratch or by sexual or asexual reproduction from parents. """ # TODO: I don't like this modification of the species and stagnation objects, # because it requires inte...
Handles creation of genomes, either from scratch or by sexual or asexual reproduction from parents.
Below is the the instruction that describes the task: ### Input: Handles creation of genomes, either from scratch or by sexual or asexual reproduction from parents. ### Response: def reproduce(self, config, species, pop_size, generation): """ Handles creation of genomes, either from scratch...
def parse(contents, tokens=None): """Parse a string called contents for an AST and return it.""" # Shortcut for users who are interested in tokens if tokens is None: tokens = [t for t in tokenize(contents)] token_index, body = _ast_worker(tokens, len(tokens), 0, None) assert token_index ==...
Parse a string called contents for an AST and return it.
Below is the the instruction that describes the task: ### Input: Parse a string called contents for an AST and return it. ### Response: def parse(contents, tokens=None): """Parse a string called contents for an AST and return it.""" # Shortcut for users who are interested in tokens if tokens is None: ...
def build(package, path=None, dry_run=False, env='default', force=False, build_file=False): """ Compile a Quilt data package, either from a build file or an existing package node. :param package: short package specifier, i.e. 'team:user/pkg' :param path: file path, git url, or existing package node ...
Compile a Quilt data package, either from a build file or an existing package node. :param package: short package specifier, i.e. 'team:user/pkg' :param path: file path, git url, or existing package node
Below is the the instruction that describes the task: ### Input: Compile a Quilt data package, either from a build file or an existing package node. :param package: short package specifier, i.e. 'team:user/pkg' :param path: file path, git url, or existing package node ### Response: def build(package, path...
def json(self, var, default=NOTSET): """ :returns: Json parsed """ return self.get_value(var, cast=json.loads, default=default)
:returns: Json parsed
Below is the the instruction that describes the task: ### Input: :returns: Json parsed ### Response: def json(self, var, default=NOTSET): """ :returns: Json parsed """ return self.get_value(var, cast=json.loads, default=default)
def ionic_strength(mis, zis): r'''Calculate the ionic strength of a solution in one of two ways, depending on the inputs only. For Pitzer and Bromley models, `mis` should be molalities of each component. For eNRTL models, `mis` should be mole fractions of each electrolyte in the solution. This will ...
r'''Calculate the ionic strength of a solution in one of two ways, depending on the inputs only. For Pitzer and Bromley models, `mis` should be molalities of each component. For eNRTL models, `mis` should be mole fractions of each electrolyte in the solution. This will sum to be much less than 1. ....
Below is the the instruction that describes the task: ### Input: r'''Calculate the ionic strength of a solution in one of two ways, depending on the inputs only. For Pitzer and Bromley models, `mis` should be molalities of each component. For eNRTL models, `mis` should be mole fractions of each electrol...
def unpack_4to8(data): """ Promote 2-bit unisgned data into 8-bit unsigned data. Args: data: Numpy array with dtype == uint8 Notes: # The process is this: # ABCDEFGH [Bits of one 4+4-bit value] # 00000000ABCDEFGH [astype(uint16)] # 0000ABCDEFGH0000 [<< 4] # ...
Promote 2-bit unisgned data into 8-bit unsigned data. Args: data: Numpy array with dtype == uint8 Notes: # The process is this: # ABCDEFGH [Bits of one 4+4-bit value] # 00000000ABCDEFGH [astype(uint16)] # 0000ABCDEFGH0000 [<< 4] # 0000ABCDXXXXEFGH [bitwise 'or' ...
Below is the the instruction that describes the task: ### Input: Promote 2-bit unisgned data into 8-bit unsigned data. Args: data: Numpy array with dtype == uint8 Notes: # The process is this: # ABCDEFGH [Bits of one 4+4-bit value] # 00000000ABCDEFGH [astype(uint16)] ...
def update_k8s_model(target, changes, logger=None, target_name=None, changes_name=None): """ Takes a model instance such as V1PodSpec() and updates it with another model, which is allowed to be a dict or another model instance of the same type. The logger is used to warn if any truthy value in the targe...
Takes a model instance such as V1PodSpec() and updates it with another model, which is allowed to be a dict or another model instance of the same type. The logger is used to warn if any truthy value in the target is is overridden. The target_name parameter can for example be "pod.spec", and changes_name...
Below is the the instruction that describes the task: ### Input: Takes a model instance such as V1PodSpec() and updates it with another model, which is allowed to be a dict or another model instance of the same type. The logger is used to warn if any truthy value in the target is is overridden. The targ...
def post(self, request): """Respond to POSTed username/password with token.""" serializer = AuthTokenSerializer(data=request.data) if serializer.is_valid(): token, _ = ExpiringToken.objects.get_or_create( user=serializer.validated_data['user'] ) ...
Respond to POSTed username/password with token.
Below is the the instruction that describes the task: ### Input: Respond to POSTed username/password with token. ### Response: def post(self, request): """Respond to POSTed username/password with token.""" serializer = AuthTokenSerializer(data=request.data) if serializer.is_valid(): ...
def sendDocument(self, chat_id, document, thumb=None, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None): """ See: https://cor...
See: https://core.telegram.org/bots/api#senddocument :param document: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto`
Below is the the instruction that describes the task: ### Input: See: https://core.telegram.org/bots/api#senddocument :param document: Same as ``photo`` in :meth:`amanobot.Bot.sendPhoto` ### Response: def sendDocument(self, chat_id, document, thumb=None, caption=N...
def delete_global_cache(appname='default'): """ Reads cache files to a safe place in each operating system """ #close_global_shelf(appname) shelf_fpath = get_global_shelf_fpath(appname) util_path.remove_file(shelf_fpath, verbose=True, dryrun=False)
Reads cache files to a safe place in each operating system
Below is the the instruction that describes the task: ### Input: Reads cache files to a safe place in each operating system ### Response: def delete_global_cache(appname='default'): """ Reads cache files to a safe place in each operating system """ #close_global_shelf(appname) shelf_fpath = get_global_...
def delete_all_but_self(self): """ DELETE ALL INDEXES WITH GIVEN PREFIX, EXCEPT name """ prefix = self.settings.alias name = self.settings.index if prefix == name: Log.note("{{index_name}} will not be deleted", index_name= prefix) for a in self.clust...
DELETE ALL INDEXES WITH GIVEN PREFIX, EXCEPT name
Below is the the instruction that describes the task: ### Input: DELETE ALL INDEXES WITH GIVEN PREFIX, EXCEPT name ### Response: def delete_all_but_self(self): """ DELETE ALL INDEXES WITH GIVEN PREFIX, EXCEPT name """ prefix = self.settings.alias name = self.settings.index ...
def get_datastreams(self): """ To get list of Datastream """ datastreams = [] response = self.http.get('/Datastream') for datastream in response: datastreams.append(Schemas.Datastream(datastream=datastream)) return datastreams
To get list of Datastream
Below is the the instruction that describes the task: ### Input: To get list of Datastream ### Response: def get_datastreams(self): """ To get list of Datastream """ datastreams = [] response = self.http.get('/Datastream') for datastream in response: data...
def _radix_sort(L, i=0): """ Most significant char radix sort """ if len(L) <= 1: return L done_bucket = [] buckets = [ [] for x in range(255) ] for s in L: if i >= len(s): done_bucket.append(s) else: buckets[ ord(s[i]) ].append(s) buckets = [ _radix_sort(b, i + 1) for b in buck...
Most significant char radix sort
Below is the the instruction that describes the task: ### Input: Most significant char radix sort ### Response: def _radix_sort(L, i=0): """ Most significant char radix sort """ if len(L) <= 1: return L done_bucket = [] buckets = [ [] for x in range(255) ] for s in L: if i >= len(s): d...
def stop(self): """ Stops this VirtualBox VM. """ self._hw_virtualization = False yield from self._stop_ubridge() yield from self._stop_remote_console() vm_state = yield from self._get_vm_state() if vm_state == "running" or vm_state == "paused" or vm_stat...
Stops this VirtualBox VM.
Below is the the instruction that describes the task: ### Input: Stops this VirtualBox VM. ### Response: def stop(self): """ Stops this VirtualBox VM. """ self._hw_virtualization = False yield from self._stop_ubridge() yield from self._stop_remote_console() ...
def sendResult(self, future): """Send a terminated future back to its parent.""" future = copy.copy(future) # Remove the (now) extraneous elements from future class future.callable = future.args = future.kargs = future.greenlet = None if not future.sendResultBack: ...
Send a terminated future back to its parent.
Below is the the instruction that describes the task: ### Input: Send a terminated future back to its parent. ### Response: def sendResult(self, future): """Send a terminated future back to its parent.""" future = copy.copy(future) # Remove the (now) extraneous elements from future cla...
def gen(function, io_loop=None): """Allows using a generator to chain together reversible actions. This function is very similar to :py:func:`reversible.gen` except that it may be used with actions whose ``forwards`` and/or ``backwards`` methods are couroutines. Specifically, if either of those methods...
Allows using a generator to chain together reversible actions. This function is very similar to :py:func:`reversible.gen` except that it may be used with actions whose ``forwards`` and/or ``backwards`` methods are couroutines. Specifically, if either of those methods return futures the generated action...
Below is the the instruction that describes the task: ### Input: Allows using a generator to chain together reversible actions. This function is very similar to :py:func:`reversible.gen` except that it may be used with actions whose ``forwards`` and/or ``backwards`` methods are couroutines. Specificall...
def _retrieve_indices(cols): ''' Retrieve a list of indices corresponding to the provided column specification. ''' if isinstance(cols, int): return [cols] elif isinstance(cols, slice): start = cols.start if cols.start else 0 stop = cols.stop ...
Retrieve a list of indices corresponding to the provided column specification.
Below is the the instruction that describes the task: ### Input: Retrieve a list of indices corresponding to the provided column specification. ### Response: def _retrieve_indices(cols): ''' Retrieve a list of indices corresponding to the provided column specification. ''' if isinst...
def _set_index(self, key, index): """Set a new index array for this series """ axis = key[0] origin = "{}0".format(axis) delta = "d{}".format(axis) if index is None: return delattr(self, key) if not isinstance(index, Index): try: ...
Set a new index array for this series
Below is the the instruction that describes the task: ### Input: Set a new index array for this series ### Response: def _set_index(self, key, index): """Set a new index array for this series """ axis = key[0] origin = "{}0".format(axis) delta = "d{}".format(axis) if...
def _get_function_ptr(self, name): """Get or create a function pointer of the given name.""" func = _make_function_ptr_instance self._function_ptrs.setdefault(name, func(self, name)) return self._function_ptrs[name]
Get or create a function pointer of the given name.
Below is the the instruction that describes the task: ### Input: Get or create a function pointer of the given name. ### Response: def _get_function_ptr(self, name): """Get or create a function pointer of the given name.""" func = _make_function_ptr_instance self._function_ptrs.setdefaul...
def register_as(self, klass, name, callback): """ Register a class with a function. :param klass: The class :type klass: class :param callback: The callable :type callback: callable :param name: The short name :type name: str """ return ...
Register a class with a function. :param klass: The class :type klass: class :param callback: The callable :type callback: callable :param name: The short name :type name: str
Below is the the instruction that describes the task: ### Input: Register a class with a function. :param klass: The class :type klass: class :param callback: The callable :type callback: callable :param name: The short name :type name: str ### Response: def regis...
def aggregate(input, **params): """ Returns aggregate :param input: :param params: :return: """ PARAM_CFG_EXTRACT = 'extract' PARAM_CFG_SUBSTITUTE = 'substitute' PARAM_CFG_AGGREGATE = 'aggregate' AGGR_FIELD = 'field' AGGR_FUNC = 'func' extract_params = params.get(PARAM_C...
Returns aggregate :param input: :param params: :return:
Below is the the instruction that describes the task: ### Input: Returns aggregate :param input: :param params: :return: ### Response: def aggregate(input, **params): """ Returns aggregate :param input: :param params: :return: """ PARAM_CFG_EXTRACT = 'extract' PARAM_CFG_...
def from_web_element(self, web_element): """ Store reference to a WebElement instance representing the element on the DOM. Use it when an instance of WebElement has already been created (e.g. as the result of find_element) and you want to create a UIComponent out of it withou...
Store reference to a WebElement instance representing the element on the DOM. Use it when an instance of WebElement has already been created (e.g. as the result of find_element) and you want to create a UIComponent out of it without evaluating it from the locator again. Returns an in...
Below is the the instruction that describes the task: ### Input: Store reference to a WebElement instance representing the element on the DOM. Use it when an instance of WebElement has already been created (e.g. as the result of find_element) and you want to create a UIComponent out of it wi...
def get_modifications_indirect(self): """Extract indirect Modification INDRA Statements.""" # Get all the specific mod types mod_event_types = list(ont_to_mod_type.keys()) # Add ONT::PTMs as a special case mod_event_types += ['ONT::PTM'] def get_increase_events(mod_event...
Extract indirect Modification INDRA Statements.
Below is the the instruction that describes the task: ### Input: Extract indirect Modification INDRA Statements. ### Response: def get_modifications_indirect(self): """Extract indirect Modification INDRA Statements.""" # Get all the specific mod types mod_event_types = list(ont_to_mod_type....
def set_color( fg=Color.normal, bg=Color.normal, fg_dark=False, bg_dark=False, underlined=False, ): """Set the console color. >>> set_color(Color.red, Color.blue) >>> set_color('red', 'blue') >>> set_color() # returns back to normal """ _set_color(fg, bg, fg_dar...
Set the console color. >>> set_color(Color.red, Color.blue) >>> set_color('red', 'blue') >>> set_color() # returns back to normal
Below is the the instruction that describes the task: ### Input: Set the console color. >>> set_color(Color.red, Color.blue) >>> set_color('red', 'blue') >>> set_color() # returns back to normal ### Response: def set_color( fg=Color.normal, bg=Color.normal, fg_dark=False, bg_da...
def compare_md5(self): """Compare md5 of file on network device to md5 of local file.""" if self.direction == "put": remote_md5 = self.remote_md5() return self.source_md5 == remote_md5 elif self.direction == "get": local_md5 = self.file_md5(self.dest_file) ...
Compare md5 of file on network device to md5 of local file.
Below is the the instruction that describes the task: ### Input: Compare md5 of file on network device to md5 of local file. ### Response: def compare_md5(self): """Compare md5 of file on network device to md5 of local file.""" if self.direction == "put": remote_md5 = self.remote_md5() ...
def is_int(value): """ Check if value is an int :type value: int, str, bytes, float, Decimal >>> is_int(123), is_int('123'), is_int(Decimal('10')) (True, True, True) >>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1')) (False, False, False) >>> is_int(object) Traceback (most rec...
Check if value is an int :type value: int, str, bytes, float, Decimal >>> is_int(123), is_int('123'), is_int(Decimal('10')) (True, True, True) >>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1')) (False, False, False) >>> is_int(object) Traceback (most recent call last): TypeError:
Below is the the instruction that describes the task: ### Input: Check if value is an int :type value: int, str, bytes, float, Decimal >>> is_int(123), is_int('123'), is_int(Decimal('10')) (True, True, True) >>> is_int(1.1), is_int('1.1'), is_int(Decimal('10.1')) (False, False, False) >>> ...
def translate_paths (properties, path): """ Interpret all path properties in 'properties' as relative to 'path' The property values are assumed to be in system-specific form, and will be translated into normalized form. """ assert is_iterable_typed(properties, Property) result = [] ...
Interpret all path properties in 'properties' as relative to 'path' The property values are assumed to be in system-specific form, and will be translated into normalized form.
Below is the the instruction that describes the task: ### Input: Interpret all path properties in 'properties' as relative to 'path' The property values are assumed to be in system-specific form, and will be translated into normalized form. ### Response: def translate_paths (properties, path): ...
def _gwf_channel_segments(path, channel, warn=True): """Yields the segments containing data for ``channel`` in this GWF path """ stream = open_gwf(path) # get segments for frames toc = stream.GetTOC() secs = toc.GetGTimeS() nano = toc.GetGTimeN() dur = toc.GetDt() readers = [getattr...
Yields the segments containing data for ``channel`` in this GWF path
Below is the the instruction that describes the task: ### Input: Yields the segments containing data for ``channel`` in this GWF path ### Response: def _gwf_channel_segments(path, channel, warn=True): """Yields the segments containing data for ``channel`` in this GWF path """ stream = open_gwf(path) ...
def fix_even_row_data_fc(fdata): """When the number of rows in fdata is even, there is a subtlety that must be taken care of if fdata is to satisfy the symmetry required for further processing. For an array length of 6,the data is align as [0 1 2 -3 -2 -1] this routine simply sets the row corresponding...
When the number of rows in fdata is even, there is a subtlety that must be taken care of if fdata is to satisfy the symmetry required for further processing. For an array length of 6,the data is align as [0 1 2 -3 -2 -1] this routine simply sets the row corresponding to the -3 index equal to zero. It ...
Below is the the instruction that describes the task: ### Input: When the number of rows in fdata is even, there is a subtlety that must be taken care of if fdata is to satisfy the symmetry required for further processing. For an array length of 6,the data is align as [0 1 2 -3 -2 -1] this routine simp...
def visualRegionForSelection(self, selection): """Gets the region of all of the components in selection :param selection: a selection model for this view :type selection: :qtdoc:`QItemSelectionModel` :returns: :qtdoc:`QRegion` -- union of rects of the selected components """ ...
Gets the region of all of the components in selection :param selection: a selection model for this view :type selection: :qtdoc:`QItemSelectionModel` :returns: :qtdoc:`QRegion` -- union of rects of the selected components
Below is the the instruction that describes the task: ### Input: Gets the region of all of the components in selection :param selection: a selection model for this view :type selection: :qtdoc:`QItemSelectionModel` :returns: :qtdoc:`QRegion` -- union of rects of the selected components ### ...
def add_to_emails(self, *emails): """ :calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_ :param email: string :rtype: None """ assert all(isinstance(element, (str, unicode)) for element in emails), emails post_parameters = emails he...
:calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_ :param email: string :rtype: None
Below is the the instruction that describes the task: ### Input: :calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_ :param email: string :rtype: None ### Response: def add_to_emails(self, *emails): """ :calls: `POST /user/emails <http://developer.github.com/v...
def vert_attr2tex_2_meshes(script, source_mesh=0, target_mesh=1, attribute=0, max_distance=0.5, tex_name='TEMP3D_texture.png', tex_width=1024, tex_height=1024, overwrite_tex=True, assign_tex=False, fill_tex=True)...
Transfer Vertex Attributes to Texture (between 2 meshes) Args: script: the FilterScript object or script filename to write the filter to. source_mesh (int): The mesh that contains the source data that we want to transfer target_mesh (int): The mesh whose texture will be filled a...
Below is the the instruction that describes the task: ### Input: Transfer Vertex Attributes to Texture (between 2 meshes) Args: script: the FilterScript object or script filename to write the filter to. source_mesh (int): The mesh that contains the source data that we want to transf...
def norm_nuclear(X): r"""Compute the nuclear norm .. math:: \| X \|_* = \sum_i \sigma_i where :math:`\sigma_i` are the singular values of matrix :math:`X`. Parameters ---------- X : array_like Input array :math:`X` Returns ------- nncl : float Nuclear norm of `...
r"""Compute the nuclear norm .. math:: \| X \|_* = \sum_i \sigma_i where :math:`\sigma_i` are the singular values of matrix :math:`X`. Parameters ---------- X : array_like Input array :math:`X` Returns ------- nncl : float Nuclear norm of `X`
Below is the the instruction that describes the task: ### Input: r"""Compute the nuclear norm .. math:: \| X \|_* = \sum_i \sigma_i where :math:`\sigma_i` are the singular values of matrix :math:`X`. Parameters ---------- X : array_like Input array :math:`X` Returns ----...
def Page_deleteCookie(self, cookieName, url): """ Function path: Page.deleteCookie Domain: Page Method name: deleteCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'cookieName' (type: string) -> Name of the cookie to remove. 'url' (type: string)...
Function path: Page.deleteCookie Domain: Page Method name: deleteCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'cookieName' (type: string) -> Name of the cookie to remove. 'url' (type: string) -> URL to match cooke domain and path. No return v...
Below is the the instruction that describes the task: ### Input: Function path: Page.deleteCookie Domain: Page Method name: deleteCookie WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'cookieName' (type: string) -> Name of the cookie to remove. 'url'...
def lal(self): """ Returns a LAL Object that contains this data """ lal_data = None if self._data.dtype == float32: lal_data = _lal.CreateREAL4Vector(len(self)) elif self._data.dtype == float64: lal_data = _lal.CreateREAL8Vector(len(self)) elif self._data...
Returns a LAL Object that contains this data
Below is the the instruction that describes the task: ### Input: Returns a LAL Object that contains this data ### Response: def lal(self): """ Returns a LAL Object that contains this data """ lal_data = None if self._data.dtype == float32: lal_data = _lal.CreateREAL4Vector(len(...
def _parse_metadata(self, metadata): """ Transforms raw HADS metadata into a dictionary (station code -> props) """ retval = {} # these are the first keys, afterwards follows a var-len list of variables/props # first key always blank so skip it field_keys = [ ...
Transforms raw HADS metadata into a dictionary (station code -> props)
Below is the the instruction that describes the task: ### Input: Transforms raw HADS metadata into a dictionary (station code -> props) ### Response: def _parse_metadata(self, metadata): """ Transforms raw HADS metadata into a dictionary (station code -> props) """ retval = {} ...
async def update_firmware(self, filename: str, loop: asyncio.AbstractEventLoop = None, explicit_modeset: bool = True) -> str: """ Program the smoothie board with a given hex file. If explicit_modeset is Tr...
Program the smoothie board with a given hex file. If explicit_modeset is True (default), explicitly place the smoothie in programming mode. If explicit_modeset is False, assume the smoothie is already in programming mode.
Below is the the instruction that describes the task: ### Input: Program the smoothie board with a given hex file. If explicit_modeset is True (default), explicitly place the smoothie in programming mode. If explicit_modeset is False, assume the smoothie is already in programming m...
def open(self, path, mode='r', *args, **kwargs): """Proxy to function `open` with path to the current file.""" return open(os.path.join(os.path.dirname(self.path), path), mode=mode, *args, **kwargs)
Proxy to function `open` with path to the current file.
Below is the the instruction that describes the task: ### Input: Proxy to function `open` with path to the current file. ### Response: def open(self, path, mode='r', *args, **kwargs): """Proxy to function `open` with path to the current file.""" return open(os.path.join(os.path.dirname(self.path), ...
def axes(self): '''A list of axes of rotation for this joint.''' return [np.array(self.ode_obj.getAxis1()), np.array(self.ode_obj.getAxis2())]
A list of axes of rotation for this joint.
Below is the the instruction that describes the task: ### Input: A list of axes of rotation for this joint. ### Response: def axes(self): '''A list of axes of rotation for this joint.''' return [np.array(self.ode_obj.getAxis1()), np.array(self.ode_obj.getAxis2())]
def optimized(fn): """Decorator that will call the optimized c++ version of a pycast function if available rather than theo original pycast function :param function fn: original pycast function :return: return the wrapped function :rtype: function """ def _optimized(self, *args, **kwa...
Decorator that will call the optimized c++ version of a pycast function if available rather than theo original pycast function :param function fn: original pycast function :return: return the wrapped function :rtype: function
Below is the the instruction that describes the task: ### Input: Decorator that will call the optimized c++ version of a pycast function if available rather than theo original pycast function :param function fn: original pycast function :return: return the wrapped function :rtype: function ###...
def log_interp1d(self, xx, yy, kind='linear'): """ Performs a log space 1d interpolation. :param xx: the x values. :param yy: the y values. :param kind: the type of interpolation to apply (as per scipy interp1d) :return: the interpolation function. """ log...
Performs a log space 1d interpolation. :param xx: the x values. :param yy: the y values. :param kind: the type of interpolation to apply (as per scipy interp1d) :return: the interpolation function.
Below is the the instruction that describes the task: ### Input: Performs a log space 1d interpolation. :param xx: the x values. :param yy: the y values. :param kind: the type of interpolation to apply (as per scipy interp1d) :return: the interpolation function. ### Response: def lo...
def load_class(path): """ dynamically load a class given a string of the format package.Class """ package, klass = path.rsplit('.', 1) module = import_module(package) return getattr(module, klass)
dynamically load a class given a string of the format package.Class
Below is the the instruction that describes the task: ### Input: dynamically load a class given a string of the format package.Class ### Response: def load_class(path): """ dynamically load a class given a string of the format package.Class """ package, klass = path.rsplit('.', 1)...