code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def wait(self, **kwargs): """ Block until the container stops, then return its exit code. Similar to the ``docker wait`` command. Args: timeout (int): Request timeout condition (str): Wait until a container state reaches the given condition, eithe...
Block until the container stops, then return its exit code. Similar to the ``docker wait`` command. Args: timeout (int): Request timeout condition (str): Wait until a container state reaches the given condition, either ``not-running`` (default), ``next-exit``, ...
Below is the the instruction that describes the task: ### Input: Block until the container stops, then return its exit code. Similar to the ``docker wait`` command. Args: timeout (int): Request timeout condition (str): Wait until a container state reaches the given ...
def search(lines, pattern): """ return all lines that match the pattern #TODO: we need an example :param lines: :param pattern: :return: """ p = pattern.replace("*", ".*") test = re.compile(p) result = [] for l in lines: if test.search(l): result.a...
return all lines that match the pattern #TODO: we need an example :param lines: :param pattern: :return:
Below is the the instruction that describes the task: ### Input: return all lines that match the pattern #TODO: we need an example :param lines: :param pattern: :return: ### Response: def search(lines, pattern): """ return all lines that match the pattern #TODO: we need an exampl...
def register(adapter): '''Register a search adapter''' # register the class in the catalog if adapter.model and adapter.model not in adapter_catalog: adapter_catalog[adapter.model] = adapter # Automatically (re|un)index objects on save/delete post_save.connect(reindex_model_on_save, ...
Register a search adapter
Below is the the instruction that describes the task: ### Input: Register a search adapter ### Response: def register(adapter): '''Register a search adapter''' # register the class in the catalog if adapter.model and adapter.model not in adapter_catalog: adapter_catalog[adapter.model] = adapter...
def rec_new(self, val): """Recursively add a new value and its children to me. Args: val (LispVal): The value to be added. Returns: LispVal: The added value. """ if val not in self.things: for child in val.children(): self.rec...
Recursively add a new value and its children to me. Args: val (LispVal): The value to be added. Returns: LispVal: The added value.
Below is the the instruction that describes the task: ### Input: Recursively add a new value and its children to me. Args: val (LispVal): The value to be added. Returns: LispVal: The added value. ### Response: def rec_new(self, val): """Recursively add a new value ...
def write_results(self, filename): """Writes samples, model stats, acceptance fraction, and random state to the given file. Parameters ----------- filename : str The file to write to. The file is opened using the ``io`` class in an an append state. ...
Writes samples, model stats, acceptance fraction, and random state to the given file. Parameters ----------- filename : str The file to write to. The file is opened using the ``io`` class in an an append state.
Below is the the instruction that describes the task: ### Input: Writes samples, model stats, acceptance fraction, and random state to the given file. Parameters ----------- filename : str The file to write to. The file is opened using the ``io`` class in an ...
def _wrap_users(users, request): """ Returns a list with the given list of users and/or the currently logged in user, if the list contains the magic item SELF. """ result = set() for u in users: if u is SELF and is_authenticated(request): result.add(request.user.get_username(...
Returns a list with the given list of users and/or the currently logged in user, if the list contains the magic item SELF.
Below is the the instruction that describes the task: ### Input: Returns a list with the given list of users and/or the currently logged in user, if the list contains the magic item SELF. ### Response: def _wrap_users(users, request): """ Returns a list with the given list of users and/or the currently...
def restore(self, filename): """Restore object from mat-file. TODO: determine format specification """ matfile = loadmat(filename) if matfile['dim'] == 1: matfile['solution'] = matfile['solution'][0, :] self.elapsed_time = matfile['elapsed_time'][0, 0] self....
Restore object from mat-file. TODO: determine format specification
Below is the the instruction that describes the task: ### Input: Restore object from mat-file. TODO: determine format specification ### Response: def restore(self, filename): """Restore object from mat-file. TODO: determine format specification """ matfile = loadmat(filename) if ma...
def _compute_H(self, t, index, t2, index2, update_derivatives=False, stationary=False): """Helper function for computing part of the ode1 covariance function. :param t: first time input. :type t: array :param index: Indices of first output. :type index: array of int :par...
Helper function for computing part of the ode1 covariance function. :param t: first time input. :type t: array :param index: Indices of first output. :type index: array of int :param t2: second time input. :type t2: array :param index2: Indices of second output. ...
Below is the the instruction that describes the task: ### Input: Helper function for computing part of the ode1 covariance function. :param t: first time input. :type t: array :param index: Indices of first output. :type index: array of int :param t2: second time input. ...
def load_geo_adwords(filename='AdWords API Location Criteria 2017-06-26.csv.gz'): """ WARN: Not a good source of city names. This table has many errors, even after cleaning""" df = pd.read_csv(filename, header=0, index_col=0, low_memory=False) df.columns = [c.replace(' ', '_').lower() for c in df.columns] ...
WARN: Not a good source of city names. This table has many errors, even after cleaning
Below is the the instruction that describes the task: ### Input: WARN: Not a good source of city names. This table has many errors, even after cleaning ### Response: def load_geo_adwords(filename='AdWords API Location Criteria 2017-06-26.csv.gz'): """ WARN: Not a good source of city names. This table has many ...
def buildIcon(icon): """ Builds an icon from the inputed information. :param icon | <variant> """ if icon is None: return QIcon() if type(icon) == buffer: try: icon = QIcon(projexui.generatePixmap(i...
Builds an icon from the inputed information. :param icon | <variant>
Below is the the instruction that describes the task: ### Input: Builds an icon from the inputed information. :param icon | <variant> ### Response: def buildIcon(icon): """ Builds an icon from the inputed information. :param icon | <variant> ...
def update(self, *data, **kwargs) -> 'Entity': """Update a Record in the repository. Also performs unique validations before creating the entity. Supports both dictionary and keyword argument updates to the entity:: dog.update({'age': 10}) dog.update(age=10) ...
Update a Record in the repository. Also performs unique validations before creating the entity. Supports both dictionary and keyword argument updates to the entity:: dog.update({'age': 10}) dog.update(age=10) :param data: Dictionary of values to be updated for the en...
Below is the the instruction that describes the task: ### Input: Update a Record in the repository. Also performs unique validations before creating the entity. Supports both dictionary and keyword argument updates to the entity:: dog.update({'age': 10}) dog.update(age=10...
def _recursive_bezier(self, x1, y1, x2, y2, x3, y3, attr, row, level=0): 'from http://www.antigrain.com/research/adaptive_bezier/' m_approximation_scale = 10.0 m_distance_tolerance = (0.5 / m_approximation_scale) ** 2 m_angle_tolerance = 1 * 2*math.pi/360 # 15 degrees in rads cu...
from http://www.antigrain.com/research/adaptive_bezier/
Below is the the instruction that describes the task: ### Input: from http://www.antigrain.com/research/adaptive_bezier/ ### Response: def _recursive_bezier(self, x1, y1, x2, y2, x3, y3, attr, row, level=0): 'from http://www.antigrain.com/research/adaptive_bezier/' m_approximation_scale = 10.0 ...
def run_validators(self, value): """ Make sure value is a string so it can run through django validators """ value = self.to_python(value) value = self.value_to_string(value) return super(RegexField, self).run_validators(value)
Make sure value is a string so it can run through django validators
Below is the the instruction that describes the task: ### Input: Make sure value is a string so it can run through django validators ### Response: def run_validators(self, value): """ Make sure value is a string so it can run through django validators """ value = self.to_python(valu...
def _accept_reflected_fn(simplex, objective_values, worst_index, reflected, objective_at_reflected): """Creates the condition function pair for a reflection to be accepted.""" def _replace_worst_with_reflected(): ...
Creates the condition function pair for a reflection to be accepted.
Below is the the instruction that describes the task: ### Input: Creates the condition function pair for a reflection to be accepted. ### Response: def _accept_reflected_fn(simplex, objective_values, worst_index, reflected, ...
def are_equal_or_superset(superset_tree, base_tree): """Return True if ``superset_tree`` is equal to or a superset of ``base_tree`` - Checks that all elements and attributes in ``superset_tree`` are present and contain the same values as in ``base_tree``. For elements, also checks that the order is...
Return True if ``superset_tree`` is equal to or a superset of ``base_tree`` - Checks that all elements and attributes in ``superset_tree`` are present and contain the same values as in ``base_tree``. For elements, also checks that the order is the same. - Can be used for checking if one XML documen...
Below is the the instruction that describes the task: ### Input: Return True if ``superset_tree`` is equal to or a superset of ``base_tree`` - Checks that all elements and attributes in ``superset_tree`` are present and contain the same values as in ``base_tree``. For elements, also checks that the ...
def download(self, download_key, raise_exception_on_failure=False): """Download the file represented by the download_key.""" query = {"output": "json", "user_credentials": self.api_key} resp = requests.get( "%sdownload/%s" % (self._url, download_key), params=query, ...
Download the file represented by the download_key.
Below is the the instruction that describes the task: ### Input: Download the file represented by the download_key. ### Response: def download(self, download_key, raise_exception_on_failure=False): """Download the file represented by the download_key.""" query = {"output": "json", "user_credentials...
def _getTempFile(self, jobStoreID=None): """ :rtype : file-descriptor, string, string is the absolute path to a temporary file within the given job's (referenced by jobStoreID's) temporary file directory. The file-descriptor is integer pointing to open operating system file handle. Shoul...
:rtype : file-descriptor, string, string is the absolute path to a temporary file within the given job's (referenced by jobStoreID's) temporary file directory. The file-descriptor is integer pointing to open operating system file handle. Should be closed using os.close() after writing some mater...
Below is the the instruction that describes the task: ### Input: :rtype : file-descriptor, string, string is the absolute path to a temporary file within the given job's (referenced by jobStoreID's) temporary file directory. The file-descriptor is integer pointing to open operating system file handl...
def parse_blob_snapshot_parameter(url): # type: (str) -> str """Retrieves the blob snapshot parameter from a url :param url str: blob url :rtype: str :return: snapshot parameter """ if blob_is_snapshot(url): tmp = url.split('?snapshot=') if len(tmp) == 2: return t...
Retrieves the blob snapshot parameter from a url :param url str: blob url :rtype: str :return: snapshot parameter
Below is the the instruction that describes the task: ### Input: Retrieves the blob snapshot parameter from a url :param url str: blob url :rtype: str :return: snapshot parameter ### Response: def parse_blob_snapshot_parameter(url): # type: (str) -> str """Retrieves the blob snapshot parameter ...
def show_filetypes(extensions): """ function to show valid file extensions """ for item in extensions.items(): val = item[1] if type(item[1]) == list: val = ", ".join(str(x) for x in item[1]) print("{0:4}: {1}".format(val, item[0]))
function to show valid file extensions
Below is the the instruction that describes the task: ### Input: function to show valid file extensions ### Response: def show_filetypes(extensions): """ function to show valid file extensions """ for item in extensions.items(): val = item[1] if type(item[1]) == list: val = ", ".join(str(x) for x in ite...
def get_pickling_errors(obj, seen=None): """Investigate pickling errors.""" if seen == None: seen = [] if hasattr(obj, "__getstate__"): state = obj.__getstate__() #elif hasattr(obj, "__dict__"): # state = obj.__dict__ else: return None #try: # state = obj.__...
Investigate pickling errors.
Below is the the instruction that describes the task: ### Input: Investigate pickling errors. ### Response: def get_pickling_errors(obj, seen=None): """Investigate pickling errors.""" if seen == None: seen = [] if hasattr(obj, "__getstate__"): state = obj.__getstate__() #elif hasatt...
def destroyTempDir(self, tempDir): """Removes a temporary directory in the temp file dir, checking its in the temp file tree. The dir will be removed regardless of if it is empty. """ #Do basic assertions for goodness of the function assert os.path.isdir(tempDir) assert o...
Removes a temporary directory in the temp file dir, checking its in the temp file tree. The dir will be removed regardless of if it is empty.
Below is the the instruction that describes the task: ### Input: Removes a temporary directory in the temp file dir, checking its in the temp file tree. The dir will be removed regardless of if it is empty. ### Response: def destroyTempDir(self, tempDir): """Removes a temporary directory in the tem...
def difference(self, instrument1, instrument2, bounds, data_labels, cost_function): """ Calculates the difference in signals from multiple instruments within the given bounds. Parameters ---------- instrument1 : Instrument Information must ...
Calculates the difference in signals from multiple instruments within the given bounds. Parameters ---------- instrument1 : Instrument Information must already be loaded into the instrument. instrument2 : Instrument Information must already b...
Below is the the instruction that describes the task: ### Input: Calculates the difference in signals from multiple instruments within the given bounds. Parameters ---------- instrument1 : Instrument Information must already be loaded into the instrument. ...
def chunks(items, chunksize): """Turn generator sequence into sequence of chunks.""" items = iter(items) for first in items: chunk = chain((first,), islice(items, chunksize - 1)) yield chunk deque(chunk, 0)
Turn generator sequence into sequence of chunks.
Below is the the instruction that describes the task: ### Input: Turn generator sequence into sequence of chunks. ### Response: def chunks(items, chunksize): """Turn generator sequence into sequence of chunks.""" items = iter(items) for first in items: chunk = chain((first,), islice(items, chu...
def add(self, item): """ Add a file to the manifest. :param item: The pathname to add. This can be relative to the base. """ if not item.startswith(self.prefix): item = os.path.join(self.base, item) self.files.add(os.path.normpath(item))
Add a file to the manifest. :param item: The pathname to add. This can be relative to the base.
Below is the the instruction that describes the task: ### Input: Add a file to the manifest. :param item: The pathname to add. This can be relative to the base. ### Response: def add(self, item): """ Add a file to the manifest. :param item: The pathname to add. This can be relativ...
def save(self, path): """Save svg as file(.svg) Args: path (str): destination to save file """ with open(path, 'w') as f: f.write(self.contents())
Save svg as file(.svg) Args: path (str): destination to save file
Below is the the instruction that describes the task: ### Input: Save svg as file(.svg) Args: path (str): destination to save file ### Response: def save(self, path): """Save svg as file(.svg) Args: path (str): destination to save file """ with open...
def request(self, send_terminator = False): """Required request() override for v3 and standard method to read meter. Args: send_terminator (bool): Send termination string at end of read. Returns: bool: CRC request flag result from most recent read """ se...
Required request() override for v3 and standard method to read meter. Args: send_terminator (bool): Send termination string at end of read. Returns: bool: CRC request flag result from most recent read
Below is the the instruction that describes the task: ### Input: Required request() override for v3 and standard method to read meter. Args: send_terminator (bool): Send termination string at end of read. Returns: bool: CRC request flag result from most recent read ### Resp...
def get_user(self, login): """ http://confluence.jetbrains.net/display/YTD2/GET+user """ return youtrack.User(self._get("/admin/user/" + urlquote(login.encode('utf8'))), self)
http://confluence.jetbrains.net/display/YTD2/GET+user
Below is the the instruction that describes the task: ### Input: http://confluence.jetbrains.net/display/YTD2/GET+user ### Response: def get_user(self, login): """ http://confluence.jetbrains.net/display/YTD2/GET+user """ return youtrack.User(self._get("/admin/user/" + urlquote(login.encode...
def iterator(self): """ An iterator over the results from applying this QuerySet to the api. """ for item in self.query.results(): obj = self.resource(**item) yield obj
An iterator over the results from applying this QuerySet to the api.
Below is the the instruction that describes the task: ### Input: An iterator over the results from applying this QuerySet to the api. ### Response: def iterator(self): """ An iterator over the results from applying this QuerySet to the api. """ for item in self.query.results(): ...
def load_febrl4(return_links=False): """Load the FEBRL 4 datasets. The Freely Extensible Biomedical Record Linkage (Febrl) package is distributed with a dataset generator and four datasets generated with the generator. This function returns the fourth Febrl dataset as a :class:`pandas.DataFrame`. ...
Load the FEBRL 4 datasets. The Freely Extensible Biomedical Record Linkage (Febrl) package is distributed with a dataset generator and four datasets generated with the generator. This function returns the fourth Febrl dataset as a :class:`pandas.DataFrame`. *"Generated as one data set with...
Below is the the instruction that describes the task: ### Input: Load the FEBRL 4 datasets. The Freely Extensible Biomedical Record Linkage (Febrl) package is distributed with a dataset generator and four datasets generated with the generator. This function returns the fourth Febrl dataset as a :cl...
def GT(classical_reg1, classical_reg2, classical_reg3): """ Produce an GT instruction. :param classical_reg1: Memory address to which to store the comparison result. :param classical_reg2: Left comparison operand. :param classical_reg3: Right comparison operand. :return: A ClassicalGreaterThan ...
Produce an GT instruction. :param classical_reg1: Memory address to which to store the comparison result. :param classical_reg2: Left comparison operand. :param classical_reg3: Right comparison operand. :return: A ClassicalGreaterThan instance.
Below is the the instruction that describes the task: ### Input: Produce an GT instruction. :param classical_reg1: Memory address to which to store the comparison result. :param classical_reg2: Left comparison operand. :param classical_reg3: Right comparison operand. :return: A ClassicalGreaterThan...
def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'], { 'srcPath': srcpath, 'dev': devalias, 'action': _get_libvirt_enum_string('VIR_DOMAIN_EVE...
Domain I/O Error events handler
Below is the the instruction that describes the task: ### Input: Domain I/O Error events handler ### Response: def _domain_event_io_error_cb(conn, domain, srcpath, devalias, action, reason, opaque): ''' Domain I/O Error events handler ''' _salt_send_domain_event(opaque, conn, domain, opaque['event'...
def func_timeout(timeout, func, args=(), kwargs=None): ''' func_timeout - Runs the given function for up to #timeout# seconds. Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut @param timeout <f...
func_timeout - Runs the given function for up to #timeout# seconds. Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut @param timeout <float> - Maximum number of seconds to run #func# before terminating ...
Below is the the instruction that describes the task: ### Input: func_timeout - Runs the given function for up to #timeout# seconds. Raises any exceptions #func# would raise, returns what #func# would return (unless timeout is exceeded), in which case it raises FunctionTimedOut @param timeout <flo...
def register(self, category): """ Usage: @metrics.register('finance') def approved_funds(pronac, data): return metric_from_data_and_pronac_number(data, pronac) """ def decorator(func): name = func.__name__ key = f'{category}...
Usage: @metrics.register('finance') def approved_funds(pronac, data): return metric_from_data_and_pronac_number(data, pronac)
Below is the the instruction that describes the task: ### Input: Usage: @metrics.register('finance') def approved_funds(pronac, data): return metric_from_data_and_pronac_number(data, pronac) ### Response: def register(self, category): """ Usage: @...
def handleError(self, test, err): """ Baseclass override. Called when a test raises an exception. If the test isn't going to be rerun again, then report the error to the nose test result. :param test: The test that has raised an error :type test: ...
Baseclass override. Called when a test raises an exception. If the test isn't going to be rerun again, then report the error to the nose test result. :param test: The test that has raised an error :type test: :class:`nose.case.Test` :param err: ...
Below is the the instruction that describes the task: ### Input: Baseclass override. Called when a test raises an exception. If the test isn't going to be rerun again, then report the error to the nose test result. :param test: The test that has raised an error :type te...
def get_voltage_at_bus_bar(grid, tree): """ Determine voltage level at bus bar of MV-LV substation Parameters ---------- grid : LVGridDing0 Ding0 grid object tree : :networkx:`NetworkX Graph Obj< >` Tree of grid topology: Returns ------- :any:`list` Voltage ...
Determine voltage level at bus bar of MV-LV substation Parameters ---------- grid : LVGridDing0 Ding0 grid object tree : :networkx:`NetworkX Graph Obj< >` Tree of grid topology: Returns ------- :any:`list` Voltage at bus bar. First item refers to load case, second i...
Below is the the instruction that describes the task: ### Input: Determine voltage level at bus bar of MV-LV substation Parameters ---------- grid : LVGridDing0 Ding0 grid object tree : :networkx:`NetworkX Graph Obj< >` Tree of grid topology: Returns ------- :any:`list`...
def _visited_callback(self, state, pc, instr): """ Maintain our own copy of the visited set """ pc = state.platform.current.PC with self.locked_context('visited', dict) as ctx: ctx[pc] = ctx.get(pc, 0) + 1
Maintain our own copy of the visited set
Below is the the instruction that describes the task: ### Input: Maintain our own copy of the visited set ### Response: def _visited_callback(self, state, pc, instr): """ Maintain our own copy of the visited set """ pc = state.platform.current.PC with self.locked_context('visited', ...
def main( gpu:Param("GPU to run on", str)=None ): """Distributed training of Imagenet. Fastest speed is if you run with: python -m fastai.launch""" path = Path('/mnt/fe2_disk/') tot_epochs,size,bs,lr = 60,224,256,3e-1 dirname = 'imagenet' gpu = setup_distrib(gpu) if gpu is None: bs *= torch.cud...
Distributed training of Imagenet. Fastest speed is if you run with: python -m fastai.launch
Below is the the instruction that describes the task: ### Input: Distributed training of Imagenet. Fastest speed is if you run with: python -m fastai.launch ### Response: def main( gpu:Param("GPU to run on", str)=None ): """Distributed training of Imagenet. Fastest speed is if you run with: python -m fastai.la...
def tables_in_schema(self, schema): """Get a listing of all tables in given schema """ sql = """SELECT table_name FROM information_schema.tables WHERE table_schema = %s""" return [t[0] for t in self.query(sql, (schema,)).fetchall()]
Get a listing of all tables in given schema
Below is the the instruction that describes the task: ### Input: Get a listing of all tables in given schema ### Response: def tables_in_schema(self, schema): """Get a listing of all tables in given schema """ sql = """SELECT table_name FROM information_schema.tables ...
def LoadSNPs(self, snps=[]): """Define the SNP inclusions (by RSID). This overrides true boundary \ definition. :param snps: array of RSIDs :return: None This doesn't define RSID ranges, so it throws InvalidBoundarySpec if it encounters what appears to be a range (S...
Define the SNP inclusions (by RSID). This overrides true boundary \ definition. :param snps: array of RSIDs :return: None This doesn't define RSID ranges, so it throws InvalidBoundarySpec if it encounters what appears to be a range (SNP contains a "-")
Below is the the instruction that describes the task: ### Input: Define the SNP inclusions (by RSID). This overrides true boundary \ definition. :param snps: array of RSIDs :return: None This doesn't define RSID ranges, so it throws InvalidBoundarySpec if it encounters ...
def _read_mesafile(filename,data_rows=0,only='all'): """ private routine that is not directly called by the user""" f=open(filename,'r') vv=[] v=[] lines = [] line = '' for i in range(0,6): line = f.readline() lines.extend([line]) hval = lines[2].split() hlist = li...
private routine that is not directly called by the user
Below is the the instruction that describes the task: ### Input: private routine that is not directly called by the user ### Response: def _read_mesafile(filename,data_rows=0,only='all'): """ private routine that is not directly called by the user""" f=open(filename,'r') vv=[] v=[] lines = [] ...
def to_native(self, value): """Return the value as a dict, raising error if conversion to dict is not possible""" if isinstance(value, dict): return value elif isinstance(value, six.string_types): native_value = json.loads(value) if isinstance(native_value, di...
Return the value as a dict, raising error if conversion to dict is not possible
Below is the the instruction that describes the task: ### Input: Return the value as a dict, raising error if conversion to dict is not possible ### Response: def to_native(self, value): """Return the value as a dict, raising error if conversion to dict is not possible""" if isinstance(value, dict)...
def decompose_once_with_qubits(val: Any, qubits: Iterable['cirq.Qid'], default=RaiseTypeErrorIfNotProvided): """Decomposes a value into operations on the given qubits. This method is used when decomposing gates, which don't know which qubits the...
Decomposes a value into operations on the given qubits. This method is used when decomposing gates, which don't know which qubits they are being applied to unless told. It decomposes the gate exactly once, instead of decomposing it and then continuing to decomposing the decomposed operations recursivel...
Below is the the instruction that describes the task: ### Input: Decomposes a value into operations on the given qubits. This method is used when decomposing gates, which don't know which qubits they are being applied to unless told. It decomposes the gate exactly once, instead of decomposing it and th...
def is_imap(self, model): """ Checks whether the given BayesianModel is Imap of JointProbabilityDistribution Parameters ----------- model : An instance of BayesianModel Class, for which you want to check the Imap Returns -------- boolean : Tr...
Checks whether the given BayesianModel is Imap of JointProbabilityDistribution Parameters ----------- model : An instance of BayesianModel Class, for which you want to check the Imap Returns -------- boolean : True if given bayesian model is Imap for Joint P...
Below is the the instruction that describes the task: ### Input: Checks whether the given BayesianModel is Imap of JointProbabilityDistribution Parameters ----------- model : An instance of BayesianModel Class, for which you want to check the Imap Returns ------...
def distance(a, b): """Calculates distance between two latitude-longitude coordinates.""" R = 3963 # radius of Earth (miles) lat1, lon1 = math.radians(a[0]), math.radians(a[1]) lat2, lon2 = math.radians(b[0]), math.radians(b[1]) return math.acos(math.sin(lat1) * math.sin(lat2) + ...
Calculates distance between two latitude-longitude coordinates.
Below is the the instruction that describes the task: ### Input: Calculates distance between two latitude-longitude coordinates. ### Response: def distance(a, b): """Calculates distance between two latitude-longitude coordinates.""" R = 3963 # radius of Earth (miles) lat1, lon1 = math.radians(a[0]), m...
def _parse_json(cls, resources, exactly_one=True): """ Parse display name, latitude, and longitude from a JSON response. """ if not len(resources['features']): # pragma: no cover return None if exactly_one: return cls.parse_resource(resources['features'][...
Parse display name, latitude, and longitude from a JSON response.
Below is the the instruction that describes the task: ### Input: Parse display name, latitude, and longitude from a JSON response. ### Response: def _parse_json(cls, resources, exactly_one=True): """ Parse display name, latitude, and longitude from a JSON response. """ if not len(re...
def get_next_objective(self): """Gets the next Objective in this list. return: (osid.learning.Objective) - the next Objective in this list. The has_next() method should be used to test that a next Objective is available before calling this method. ...
Gets the next Objective in this list. return: (osid.learning.Objective) - the next Objective in this list. The has_next() method should be used to test that a next Objective is available before calling this method. raise: IllegalState - no more elements ...
Below is the the instruction that describes the task: ### Input: Gets the next Objective in this list. return: (osid.learning.Objective) - the next Objective in this list. The has_next() method should be used to test that a next Objective is available before calling this ...
def refweights(self): """A |numpy| |numpy.ndarray| with equal weights for all segment junctions.. >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> states.qjoints.shape = 5 >>> states.qjoints.refweights array([ 0.2, 0.2, 0.2, 0.2, 0.2]) ...
A |numpy| |numpy.ndarray| with equal weights for all segment junctions.. >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> states.qjoints.shape = 5 >>> states.qjoints.refweights array([ 0.2, 0.2, 0.2, 0.2, 0.2])
Below is the the instruction that describes the task: ### Input: A |numpy| |numpy.ndarray| with equal weights for all segment junctions.. >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> states.qjoints.shape = 5 >>> states.qjoints.refweights array([...
def load_file(folder_path, idx, corpus): """ Load speaker, file, utterance, labels for the file with the given id. """ xml_path = os.path.join(folder_path, '{}.xml'.format(idx)) wav_paths = glob.glob(os.path.join(folder_path, '{}_*.wav'.format(idx))) if len(wav_paths) ==...
Load speaker, file, utterance, labels for the file with the given id.
Below is the the instruction that describes the task: ### Input: Load speaker, file, utterance, labels for the file with the given id. ### Response: def load_file(folder_path, idx, corpus): """ Load speaker, file, utterance, labels for the file with the given id. """ xml_path = os.p...
def response(self, response_data): ''' called by the event handler with the result data :param response_data: result data :return: ''' if "address" not in response_data: return None, "address missing from response_data payload" if "function" not in re...
called by the event handler with the result data :param response_data: result data :return:
Below is the the instruction that describes the task: ### Input: called by the event handler with the result data :param response_data: result data :return: ### Response: def response(self, response_data): ''' called by the event handler with the result data :param response_...
def generate_psk(self, security_key): """ Generate and set a psk from the security key. """ if not self._psk: # Backup the real identity. existing_psk_id = self._psk_id # Set the default identity and security key for generation. self._psk_...
Generate and set a psk from the security key.
Below is the the instruction that describes the task: ### Input: Generate and set a psk from the security key. ### Response: def generate_psk(self, security_key): """ Generate and set a psk from the security key. """ if not self._psk: # Backup the real identity. ...
def listTasks(self, opts={}, queryOpts={}): """ Get information about all Koji tasks. Calls "listTasks" XML-RPC. :param dict opts: Eg. {'state': [task_states.OPEN]} :param dict queryOpts: Eg. {'order' : 'priority,create_time'} :returns: deferred that when fired returns ...
Get information about all Koji tasks. Calls "listTasks" XML-RPC. :param dict opts: Eg. {'state': [task_states.OPEN]} :param dict queryOpts: Eg. {'order' : 'priority,create_time'} :returns: deferred that when fired returns a list of Task objects.
Below is the the instruction that describes the task: ### Input: Get information about all Koji tasks. Calls "listTasks" XML-RPC. :param dict opts: Eg. {'state': [task_states.OPEN]} :param dict queryOpts: Eg. {'order' : 'priority,create_time'} :returns: deferred that when fired ret...
def handle(client, request): """ Handle format request request struct: { 'data': 'data_need_format', 'formaters': [ { 'name': 'formater_name', 'config': {} # None or dict }, ... # forma...
Handle format request request struct: { 'data': 'data_need_format', 'formaters': [ { 'name': 'formater_name', 'config': {} # None or dict }, ... # formaters ] } if no f...
Below is the the instruction that describes the task: ### Input: Handle format request request struct: { 'data': 'data_need_format', 'formaters': [ { 'name': 'formater_name', 'config': {} # None or dict },...
def add_element(self, elt): """Helper to add a element to the current section. The Element name will be used as an identifier.""" if not isinstance(elt, Element): raise TypeError("argument should be a subclass of Element") self.elements[elt.get_name()] = elt return el...
Helper to add a element to the current section. The Element name will be used as an identifier.
Below is the the instruction that describes the task: ### Input: Helper to add a element to the current section. The Element name will be used as an identifier. ### Response: def add_element(self, elt): """Helper to add a element to the current section. The Element name will be used as an i...
def sunrise(self, date=None, local=True, use_elevation=True): """Return sunrise time. Calculates the time in the morning when the sun is a 0.833 degrees below the horizon. This is to account for refraction. :param date: The date for which to calculate the sunrise time. ...
Return sunrise time. Calculates the time in the morning when the sun is a 0.833 degrees below the horizon. This is to account for refraction. :param date: The date for which to calculate the sunrise time. If no date is specified then the current date will be used. ...
Below is the the instruction that describes the task: ### Input: Return sunrise time. Calculates the time in the morning when the sun is a 0.833 degrees below the horizon. This is to account for refraction. :param date: The date for which to calculate the sunrise time. ...
def _writable(method): """Check that record is in defined status. :param method: Method to be decorated. :returns: Function decorated. """ @wraps(method) def wrapper(self, *args, **kwargs): """Send record for indexing. :returns: Execution result of the decorated method. ...
Check that record is in defined status. :param method: Method to be decorated. :returns: Function decorated.
Below is the the instruction that describes the task: ### Input: Check that record is in defined status. :param method: Method to be decorated. :returns: Function decorated. ### Response: def _writable(method): """Check that record is in defined status. :param method: Method to be decorated. ...
def type_object_attrgetter(obj, attr, *defargs): """ This implements an improved attrgetter for type objects (i.e. classes) that can handle class attributes that are implemented as properties on a metaclass. Normally `getattr` on a class with a `property` (say, "foo"), would return the `propert...
This implements an improved attrgetter for type objects (i.e. classes) that can handle class attributes that are implemented as properties on a metaclass. Normally `getattr` on a class with a `property` (say, "foo"), would return the `property` object itself. However, if the class has a metaclass whic...
Below is the the instruction that describes the task: ### Input: This implements an improved attrgetter for type objects (i.e. classes) that can handle class attributes that are implemented as properties on a metaclass. Normally `getattr` on a class with a `property` (say, "foo"), would return the ...
def setCurrentRegItem(self, regItem): """ Sets the current registry item. """ rowIndex = self.model().indexFromItem(regItem) if not rowIndex.isValid(): logger.warn("Can't select {!r} in table".format(regItem)) self.setCurrentIndex(rowIndex)
Sets the current registry item.
Below is the the instruction that describes the task: ### Input: Sets the current registry item. ### Response: def setCurrentRegItem(self, regItem): """ Sets the current registry item. """ rowIndex = self.model().indexFromItem(regItem) if not rowIndex.isValid(): logger.w...
def recipe_status(self, kitchen, recipe, local_dir=None): """ gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :param local_dir: string -- :rtype: dict """ rc = DKReturnCode() if kitchen is No...
gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :param local_dir: string -- :rtype: dict
Below is the the instruction that describes the task: ### Input: gets the status of a recipe :param self: DKCloudAPI :param kitchen: string :param recipe: string :param local_dir: string -- :rtype: dict ### Response: def recipe_status(self, kitchen, recipe, local_dir=None): ...
async def add(self, setname, ip, timeout): """ Adds the given IP address to the specified set. If timeout is specified, the IP will stay in the set for the given duration. Else it will stay in the set during the set default timeout. timeout must be given in seconds. Th...
Adds the given IP address to the specified set. If timeout is specified, the IP will stay in the set for the given duration. Else it will stay in the set during the set default timeout. timeout must be given in seconds. The resulting command looks like this: ``nft add element...
Below is the the instruction that describes the task: ### Input: Adds the given IP address to the specified set. If timeout is specified, the IP will stay in the set for the given duration. Else it will stay in the set during the set default timeout. timeout must be given in seconds. ...
def small_abc_image_recognition(): """! @brief Trains network using letters 'A', 'B', 'C', and recognize each of them with and without noise. """ images = []; images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_A; images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_B; images += IMAG...
! @brief Trains network using letters 'A', 'B', 'C', and recognize each of them with and without noise.
Below is the the instruction that describes the task: ### Input: ! @brief Trains network using letters 'A', 'B', 'C', and recognize each of them with and without noise. ### Response: def small_abc_image_recognition(): """! @brief Trains network using letters 'A', 'B', 'C', and recognize each of them...
def post_refresh_system_metadata(request): """MNStorage.systemMetadataChanged(session, did, serialVersion, dateSysMetaLastModified) → boolean.""" d1_gmn.app.views.assert_db.post_has_mime_parts( request, ( ('field', 'pid'), ('field', 'serialVersion'), ('fie...
MNStorage.systemMetadataChanged(session, did, serialVersion, dateSysMetaLastModified) → boolean.
Below is the the instruction that describes the task: ### Input: MNStorage.systemMetadataChanged(session, did, serialVersion, dateSysMetaLastModified) → boolean. ### Response: def post_refresh_system_metadata(request): """MNStorage.systemMetadataChanged(session, did, serialVersion, dateSysMetaLastModif...
def mul(left, right): """ Distribution multiplication. Args: left (Dist, numpy.ndarray) : left hand side. right (Dist, numpy.ndarray) : right hand side. """ from .mv_mul import MvMul length = max(left, right) if length == 1: return Mul(left, right) return MvMul(l...
Distribution multiplication. Args: left (Dist, numpy.ndarray) : left hand side. right (Dist, numpy.ndarray) : right hand side.
Below is the the instruction that describes the task: ### Input: Distribution multiplication. Args: left (Dist, numpy.ndarray) : left hand side. right (Dist, numpy.ndarray) : right hand side. ### Response: def mul(left, right): """ Distribution multiplication. Args: left (...
def borrow_readwrite_instance(cls, working_dir, block_number, expected_snapshots={}): """ Get a read/write database handle to the blockstack db. At most one such handle can exist within the program. When the caller is done with the handle, it should call release_readwrite_instance() ...
Get a read/write database handle to the blockstack db. At most one such handle can exist within the program. When the caller is done with the handle, it should call release_readwrite_instance() Returns the handle on success Returns None if we can't set up the db. Aborts if ther...
Below is the the instruction that describes the task: ### Input: Get a read/write database handle to the blockstack db. At most one such handle can exist within the program. When the caller is done with the handle, it should call release_readwrite_instance() Returns the handle on success ...
def parse(self, input): """ Parses a time delta from the input. See :py:class:`TimeDeltaParameter` for details on supported formats. """ result = self._parseIso8601(input) if not result: result = self._parseSimple(input) if result is not None: ...
Parses a time delta from the input. See :py:class:`TimeDeltaParameter` for details on supported formats.
Below is the the instruction that describes the task: ### Input: Parses a time delta from the input. See :py:class:`TimeDeltaParameter` for details on supported formats. ### Response: def parse(self, input): """ Parses a time delta from the input. See :py:class:`TimeDeltaParameter...
def _eval_xpath(self, xpath): """ Evaluates xpath expressions. Either string or XPath object. """ if isinstance(xpath, etree.XPath): result = xpath(self._dataObject) else: result = self._dataObject.xpath(xpath,namespaces=self._namespaces) ...
Evaluates xpath expressions. Either string or XPath object.
Below is the the instruction that describes the task: ### Input: Evaluates xpath expressions. Either string or XPath object. ### Response: def _eval_xpath(self, xpath): """ Evaluates xpath expressions. Either string or XPath object. """ if isinstance(xpath, etree.X...
def setup_client_rpc(self): """Setup RPC client for dfa agent.""" # Setup RPC client. self.clnt = rpc.DfaRpcClient(self._url, constants.DFA_SERVER_QUEUE, exchange=constants.DFA_EXCHANGE)
Setup RPC client for dfa agent.
Below is the the instruction that describes the task: ### Input: Setup RPC client for dfa agent. ### Response: def setup_client_rpc(self): """Setup RPC client for dfa agent.""" # Setup RPC client. self.clnt = rpc.DfaRpcClient(self._url, constants.DFA_SERVER_QUEUE, ...
def query_form_data(self): """ Get the formdata stored in the database for existing slice. params: slice_id: integer """ form_data = {} slice_id = request.args.get('slice_id') if slice_id: slc = db.session.query(models.Slice).filter_by(id=slice_id).one...
Get the formdata stored in the database for existing slice. params: slice_id: integer
Below is the the instruction that describes the task: ### Input: Get the formdata stored in the database for existing slice. params: slice_id: integer ### Response: def query_form_data(self): """ Get the formdata stored in the database for existing slice. params: slice_id: integer ...
def _parse_conf(conf_file=None, in_mem=False, family='ipv4'): ''' If a file is not passed in, and the correct one for this OS is not detected, return False ''' if _conf() and not conf_file and not in_mem: conf_file = _conf(family) rules = '' if conf_file: with salt.utils.fil...
If a file is not passed in, and the correct one for this OS is not detected, return False
Below is the the instruction that describes the task: ### Input: If a file is not passed in, and the correct one for this OS is not detected, return False ### Response: def _parse_conf(conf_file=None, in_mem=False, family='ipv4'): ''' If a file is not passed in, and the correct one for this OS is not ...
def is_isomorphic_to(self, other): """ Returns true if all fields of other struct are isomorphic to this struct's fields """ return (isinstance(other, self.__class__) and len(self.fields) == len(other.fields) and all...
Returns true if all fields of other struct are isomorphic to this struct's fields
Below is the the instruction that describes the task: ### Input: Returns true if all fields of other struct are isomorphic to this struct's fields ### Response: def is_isomorphic_to(self, other): """ Returns true if all fields of other struct are isomorphic to this struct's fields ...
def can_add_new_content(self, block, file_info): """ new content from file_info can be added into block iff - file count limit hasn't been reached for the block - there is enough space to completely fit the info into the block - OR the info can be split and some info can fit into...
new content from file_info can be added into block iff - file count limit hasn't been reached for the block - there is enough space to completely fit the info into the block - OR the info can be split and some info can fit into the block
Below is the the instruction that describes the task: ### Input: new content from file_info can be added into block iff - file count limit hasn't been reached for the block - there is enough space to completely fit the info into the block - OR the info can be split and some info can fit into...
def validate_arg(f, arg_name, *validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ A decorator to apply function input validation for the given argument name, with the provided base validation function(s)...
A decorator to apply function input validation for the given argument name, with the provided base validation function(s). You may use several such decorators on a given function as long as they are stacked on top of each other (no external decorator in the middle) :param arg_name: :param validation_fu...
Below is the the instruction that describes the task: ### Input: A decorator to apply function input validation for the given argument name, with the provided base validation function(s). You may use several such decorators on a given function as long as they are stacked on top of each other (no external de...
def read_geo(fid, key): """Read geolocation and related datasets.""" dsid = GEO_NAMES[key.name] add_epoch = False if "time" in key.name: days = fid["/L1C/" + dsid["day"]].value msecs = fid["/L1C/" + dsid["msec"]].value data = _form_datetimes(days, msecs) add_epoch = True ...
Read geolocation and related datasets.
Below is the the instruction that describes the task: ### Input: Read geolocation and related datasets. ### Response: def read_geo(fid, key): """Read geolocation and related datasets.""" dsid = GEO_NAMES[key.name] add_epoch = False if "time" in key.name: days = fid["/L1C/" + dsid["day"]].va...
def last_index_of(self, item): """ Returns the last index of specified items's occurrences in this list. If specified item is not present in this list, returns -1. :param item: (object), the specified item to be searched for. :return: (int), the last index of specified items's o...
Returns the last index of specified items's occurrences in this list. If specified item is not present in this list, returns -1. :param item: (object), the specified item to be searched for. :return: (int), the last index of specified items's occurrences, -1 if item is not present in this list.
Below is the the instruction that describes the task: ### Input: Returns the last index of specified items's occurrences in this list. If specified item is not present in this list, returns -1. :param item: (object), the specified item to be searched for. :return: (int), the last index of s...
def fix_surrogates(text): """ Replace 16-bit surrogate codepoints with the characters they represent (when properly paired), or with \ufffd otherwise. >>> high_surrogate = chr(0xd83d) >>> low_surrogate = chr(0xdca9) >>> print(fix_surrogates(high_surrogate + low_surrogate)) �...
Replace 16-bit surrogate codepoints with the characters they represent (when properly paired), or with \ufffd otherwise. >>> high_surrogate = chr(0xd83d) >>> low_surrogate = chr(0xdca9) >>> print(fix_surrogates(high_surrogate + low_surrogate)) 💩 >>> print(fix_surrogates(low...
Below is the the instruction that describes the task: ### Input: Replace 16-bit surrogate codepoints with the characters they represent (when properly paired), or with \ufffd otherwise. >>> high_surrogate = chr(0xd83d) >>> low_surrogate = chr(0xdca9) >>> print(fix_surrogates(high_surrog...
def parse_time(time_input): """ Parse input time/date string into ISO 8601 string :param time_input: time/date to parse :type time_input: str or datetime.date or datetime.datetime :return: parsed string in ISO 8601 format :rtype: str """ if isinstance(time_input, datetime.date): ret...
Parse input time/date string into ISO 8601 string :param time_input: time/date to parse :type time_input: str or datetime.date or datetime.datetime :return: parsed string in ISO 8601 format :rtype: str
Below is the the instruction that describes the task: ### Input: Parse input time/date string into ISO 8601 string :param time_input: time/date to parse :type time_input: str or datetime.date or datetime.datetime :return: parsed string in ISO 8601 format :rtype: str ### Response: def parse_time(ti...
def _render_val_with_prev(self, w, n, current_val, symbol_len): """Return a string encoding the given value in a waveform. :param w: The WireVector we are rendering to a waveform :param n: An integer from 0 to segment_len-1 :param current_val: the value to be rendered :param sym...
Return a string encoding the given value in a waveform. :param w: The WireVector we are rendering to a waveform :param n: An integer from 0 to segment_len-1 :param current_val: the value to be rendered :param symbol_len: and integer for how big to draw the current value Returns...
Below is the the instruction that describes the task: ### Input: Return a string encoding the given value in a waveform. :param w: The WireVector we are rendering to a waveform :param n: An integer from 0 to segment_len-1 :param current_val: the value to be rendered :param symbol_le...
def no_counterpart_found(string, options, rc_so_far): """Takes action determined by options.else_action. Unless told to raise an exception, this function returns the errno that is supposed to be returned in this case. :param string: The lookup string. :param options: ArgumentParser or equivalent t...
Takes action determined by options.else_action. Unless told to raise an exception, this function returns the errno that is supposed to be returned in this case. :param string: The lookup string. :param options: ArgumentParser or equivalent to provide options.else_action, options.else_errno, op...
Below is the the instruction that describes the task: ### Input: Takes action determined by options.else_action. Unless told to raise an exception, this function returns the errno that is supposed to be returned in this case. :param string: The lookup string. :param options: ArgumentParser or equi...
def ensure_workspace(self, target): """Ensures that an up-to-date Go workspace exists for the given target. Creates any necessary symlinks to source files based on the target and its transitive dependencies, and removes any symlinks which do not correspond to any needed dep. """ gopath = self.get_g...
Ensures that an up-to-date Go workspace exists for the given target. Creates any necessary symlinks to source files based on the target and its transitive dependencies, and removes any symlinks which do not correspond to any needed dep.
Below is the the instruction that describes the task: ### Input: Ensures that an up-to-date Go workspace exists for the given target. Creates any necessary symlinks to source files based on the target and its transitive dependencies, and removes any symlinks which do not correspond to any needed dep. ### R...
def timezone(self, value): """Set the timezone.""" self._timezone = (value if isinstance(value, datetime.tzinfo) else tz.gettz(value))
Set the timezone.
Below is the the instruction that describes the task: ### Input: Set the timezone. ### Response: def timezone(self, value): """Set the timezone.""" self._timezone = (value if isinstance(value, datetime.tzinfo) else tz.gettz(value))
def constraint_from_parent_conflicts(self): """ Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints ...
Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constraints :raises: :exc:`~pipenv.exceptions.DependencyConflict` if...
Below is the the instruction that describes the task: ### Input: Given a resolved entry with multiple parent dependencies with different constraints, searches for the resolution that satisfies all of the parent constraints. :return: A new **InstallRequirement** satisfying all parent constra...
def get_interface_detail_input_request_type_get_next_request_last_rcvd_interface_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail input = ET.Sub...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_interface_detail_input_request_type_get_next_request_last_rcvd_interface_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_...
def get_shots(self): """Returns the shot chart data as a pandas DataFrame.""" shots = self.response.json()['resultSets'][0]['rowSet'] headers = self.response.json()['resultSets'][0]['headers'] return pd.DataFrame(shots, columns=headers)
Returns the shot chart data as a pandas DataFrame.
Below is the the instruction that describes the task: ### Input: Returns the shot chart data as a pandas DataFrame. ### Response: def get_shots(self): """Returns the shot chart data as a pandas DataFrame.""" shots = self.response.json()['resultSets'][0]['rowSet'] headers = self.response.jso...
def save_state(state, output_dir, keep=False): """Save State and optionally gin config.""" params_file = os.path.join(output_dir, "model.pkl") with gfile.GFile(params_file, "wb") as f: pickle.dump((state.params, state.step, state.history), f) if keep: params_file = os.path.join(output_dir, "model_{}.pkl...
Save State and optionally gin config.
Below is the the instruction that describes the task: ### Input: Save State and optionally gin config. ### Response: def save_state(state, output_dir, keep=False): """Save State and optionally gin config.""" params_file = os.path.join(output_dir, "model.pkl") with gfile.GFile(params_file, "wb") as f: pic...
def get_dataframe(self, tickers, startDate=None, endDate=None, metric_name=None, frequency='daily'): """ Return a pandas.DataFrame of historical prices for one or more ticker symbols. By default, return latest EOD Composite Price for a list of stock tickers. On av...
Return a pandas.DataFrame of historical prices for one or more ticker symbols. By default, return latest EOD Composite Price for a list of stock tickers. On average, each feed contains 3 data sources. Supported tickers + Available Day Ranges are here: https://apimedia.t...
Below is the the instruction that describes the task: ### Input: Return a pandas.DataFrame of historical prices for one or more ticker symbols. By default, return latest EOD Composite Price for a list of stock tickers. On average, each feed contains 3 data sources. Supported ti...
def _longestCommonPrefix(seq1, seq2, start1=0, start2=0): """ Returns the length of the longest common prefix of seq1 starting at offset start1 and seq2 starting at offset start2. >>> _longestCommonPrefix("abcdef", "abcghj") 3 >>> _longestCommonPrefix("abcghj", "abcdef") 3 >>> _longes...
Returns the length of the longest common prefix of seq1 starting at offset start1 and seq2 starting at offset start2. >>> _longestCommonPrefix("abcdef", "abcghj") 3 >>> _longestCommonPrefix("abcghj", "abcdef") 3 >>> _longestCommonPrefix("miss", "") 0 >>> _longestCommonPrefix("", "mr"...
Below is the the instruction that describes the task: ### Input: Returns the length of the longest common prefix of seq1 starting at offset start1 and seq2 starting at offset start2. >>> _longestCommonPrefix("abcdef", "abcghj") 3 >>> _longestCommonPrefix("abcghj", "abcdef") 3 >>> _longest...
def compressBWTPoolProcess(tup): ''' During compression, each available process will calculate a subportion of the BWT independently using this function. This process takes the chunk and rewrites it into a given filename using the technique described in the compressBWT(...) function header ''' ...
During compression, each available process will calculate a subportion of the BWT independently using this function. This process takes the chunk and rewrites it into a given filename using the technique described in the compressBWT(...) function header
Below is the the instruction that describes the task: ### Input: During compression, each available process will calculate a subportion of the BWT independently using this function. This process takes the chunk and rewrites it into a given filename using the technique described in the compressBWT(...) fun...
def flush_one(self, process_name, ignore_priority=False): """ method iterates over the reprocessing queue for the given process and re-submits UOW whose waiting time has expired """ q = self.reprocess_uows[process_name] self._flush_queue(q, ignore_priority)
method iterates over the reprocessing queue for the given process and re-submits UOW whose waiting time has expired
Below is the the instruction that describes the task: ### Input: method iterates over the reprocessing queue for the given process and re-submits UOW whose waiting time has expired ### Response: def flush_one(self, process_name, ignore_priority=False): """ method iterates over the reprocessing ...
def record(self): # type: () -> bytes ''' A method to generate the string representing this UDF Primary Volume Descriptor. Parameters: None. Returns: A string representing this UDF Primary Volume Descriptor. ''' if not self._initialized:...
A method to generate the string representing this UDF Primary Volume Descriptor. Parameters: None. Returns: A string representing this UDF Primary Volume Descriptor.
Below is the the instruction that describes the task: ### Input: A method to generate the string representing this UDF Primary Volume Descriptor. Parameters: None. Returns: A string representing this UDF Primary Volume Descriptor. ### Response: def record(self): #...
def do_worker(self, arg): """ Usage: worker approve (--all | --hit <hit_id> ... | <assignment_id> ...) [--all-studies] [--force] worker reject (--hit <hit_id> | <assignment_id> ...) worker unreject (--hit <hit_id> | <assignment_id> ...) worker bonus (--amount <am...
Usage: worker approve (--all | --hit <hit_id> ... | <assignment_id> ...) [--all-studies] [--force] worker reject (--hit <hit_id> | <assignment_id> ...) worker unreject (--hit <hit_id> | <assignment_id> ...) worker bonus (--amount <amount> | --auto) (--hit <hit_id> | <assignment_...
Below is the the instruction that describes the task: ### Input: Usage: worker approve (--all | --hit <hit_id> ... | <assignment_id> ...) [--all-studies] [--force] worker reject (--hit <hit_id> | <assignment_id> ...) worker unreject (--hit <hit_id> | <assignment_id> ...) work...
def serializeG1(x, compress=True): """ Converts G1 element @x into an array of bytes. If @compress is True, the point will be compressed resulting in a much shorter string of bytes. """ assertType(x, G1Element) return _serialize(x, compress, librelic.g1_size_bin_abi, librelic.g1_write_b...
Converts G1 element @x into an array of bytes. If @compress is True, the point will be compressed resulting in a much shorter string of bytes.
Below is the the instruction that describes the task: ### Input: Converts G1 element @x into an array of bytes. If @compress is True, the point will be compressed resulting in a much shorter string of bytes. ### Response: def serializeG1(x, compress=True): """ Converts G1 element @x into an array of b...
def parse_quantitationesultsline(self, line): """ Parses quantitation result lines Please see samples/GC-MS output.txt [MS Quantitative Results] section """ if line == ',,,,,,,,,,,,,,,,,,': return 0 if line.startswith('SampleID'): self._e...
Parses quantitation result lines Please see samples/GC-MS output.txt [MS Quantitative Results] section
Below is the the instruction that describes the task: ### Input: Parses quantitation result lines Please see samples/GC-MS output.txt [MS Quantitative Results] section ### Response: def parse_quantitationesultsline(self, line): """ Parses quantitation result lines Please...
def respond_list_directory(self, dir_path, query=None): """ Respond to the client with an HTML page listing the contents of the specified directory. :param str dir_path: The path of the directory to list the contents of. """ del query try: dir_contents = os.listdir(dir_path) except os.error: self...
Respond to the client with an HTML page listing the contents of the specified directory. :param str dir_path: The path of the directory to list the contents of.
Below is the the instruction that describes the task: ### Input: Respond to the client with an HTML page listing the contents of the specified directory. :param str dir_path: The path of the directory to list the contents of. ### Response: def respond_list_directory(self, dir_path, query=None): """ Respon...
def read_list_from_csv(filepath, dict_form=False, headers=None, **kwargs): # type: (str, bool, Union[int, List[int], List[str], None], Any) -> List[Union[Dict, List]] """Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of mu...
Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line headers) to be considered as headers (rows start counting at 1), or the actual headers defined a list of strings. If not set, all rows will be treated as c...
Below is the the instruction that describes the task: ### Input: Read a list of rows in dict or list form from a csv. (The headers argument is either a row number or list of row numbers (in case of multi-line headers) to be considered as headers (rows start counting at 1), or the actual headers define...
def compute(datetimes, to_np=None): # @NoSelf """ Computes the provided date/time components into CDF epoch value(s). For CDF_EPOCH: For computing into CDF_EPOCH value, each date/time elements should have exactly seven (7) components, as year, month, day, hour, ...
Computes the provided date/time components into CDF epoch value(s). For CDF_EPOCH: For computing into CDF_EPOCH value, each date/time elements should have exactly seven (7) components, as year, month, day, hour, minute, second and millisecond, in a list. For exam...
Below is the the instruction that describes the task: ### Input: Computes the provided date/time components into CDF epoch value(s). For CDF_EPOCH: For computing into CDF_EPOCH value, each date/time elements should have exactly seven (7) components, as year, month, day, hour...
def register_model(self, key, *models, **kwargs): """ Register a cache_group with this manager. Use this method to register more simple groups where all models share the same parameters. Any arguments are treated as models that you would like to register. Any k...
Register a cache_group with this manager. Use this method to register more simple groups where all models share the same parameters. Any arguments are treated as models that you would like to register. Any keyword arguments received are passed to the register method wh...
Below is the the instruction that describes the task: ### Input: Register a cache_group with this manager. Use this method to register more simple groups where all models share the same parameters. Any arguments are treated as models that you would like to register. Any ke...
def save(self, obj): """Required functionality.""" if not obj.id: obj.id = uuid() stored_data = { 'id': obj.id, 'value': obj.to_data() } index_vals = obj.indexes() or {} for key in obj.__class__.index_names() or []: val = ...
Required functionality.
Below is the the instruction that describes the task: ### Input: Required functionality. ### Response: def save(self, obj): """Required functionality.""" if not obj.id: obj.id = uuid() stored_data = { 'id': obj.id, 'value': obj.to_data() } ...
def close(self) -> None: """ Close the server and terminate connections with close code 1001. This method is idempotent. """ if self.close_task is None: self.close_task = self.loop.create_task(self._close())
Close the server and terminate connections with close code 1001. This method is idempotent.
Below is the the instruction that describes the task: ### Input: Close the server and terminate connections with close code 1001. This method is idempotent. ### Response: def close(self) -> None: """ Close the server and terminate connections with close code 1001. This method is i...
def _run_atexit(): '''Hook frameworks must invoke this after the main hook body has successfully completed. Do not invoke it if the hook fails.''' global _atexit for callback, args, kwargs in reversed(_atexit): callback(*args, **kwargs) del _atexit[:]
Hook frameworks must invoke this after the main hook body has successfully completed. Do not invoke it if the hook fails.
Below is the the instruction that describes the task: ### Input: Hook frameworks must invoke this after the main hook body has successfully completed. Do not invoke it if the hook fails. ### Response: def _run_atexit(): '''Hook frameworks must invoke this after the main hook body has successfully compl...
def dispatch(self, *args, **kwargs): """ Only staff members can access this view """ return super(GetAppListJsonView, self).dispatch(*args, **kwargs)
Only staff members can access this view
Below is the the instruction that describes the task: ### Input: Only staff members can access this view ### Response: def dispatch(self, *args, **kwargs): """ Only staff members can access this view """ return super(GetAppListJsonView, self).dispatch(*args, **kwargs)
def _calculate_optimal_column_widths(self): """Calculates widths of columns :return: Length of longest data in each column (labels and data) """ columns = len(self.data[0]) # number of columns str_labels = [parse_colorama(str(l)) for l in self.labels] # l...
Calculates widths of columns :return: Length of longest data in each column (labels and data)
Below is the the instruction that describes the task: ### Input: Calculates widths of columns :return: Length of longest data in each column (labels and data) ### Response: def _calculate_optimal_column_widths(self): """Calculates widths of columns :return: Length of longest data in each ...