code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _string2Duration(text): """ CONVERT SIMPLE <float><type> TO A DURATION OBJECT """ if text == "" or text == "zero": return ZERO amount, interval = re.match(r"([\d\.]*)(.*)", text).groups() amount = int(amount) if amount else 1 if MILLI_VALUES[interval] == None: from mo_l...
CONVERT SIMPLE <float><type> TO A DURATION OBJECT
Below is the the instruction that describes the task: ### Input: CONVERT SIMPLE <float><type> TO A DURATION OBJECT ### Response: def _string2Duration(text): """ CONVERT SIMPLE <float><type> TO A DURATION OBJECT """ if text == "" or text == "zero": return ZERO amount, interval = re.matc...
def pairs(self, strand, cutoff=0.001, temp=37.0, pseudo=False, material=None, dangles='some', sodium=1.0, magnesium=0.0): '''Compute the pair probabilities for an ordered complex of strands. Runs the \'pairs\' command. :param strand: Strand on which to run pairs. Strands must be e...
Compute the pair probabilities for an ordered complex of strands. Runs the \'pairs\' command. :param strand: Strand on which to run pairs. Strands must be either coral.DNA or coral.RNA). :type strand: list :param cutoff: Only probabilities above this cutoff appear...
Below is the the instruction that describes the task: ### Input: Compute the pair probabilities for an ordered complex of strands. Runs the \'pairs\' command. :param strand: Strand on which to run pairs. Strands must be either coral.DNA or coral.RNA). :type strand: li...
def translate_request(request): """This function takes the arguments passed to the request handler and uses them to generate a WSGI compatible environ dictionary. """ class AwaitablePayload(object): def __init__(self, payload): self.payload = payload or b'' async def read(se...
This function takes the arguments passed to the request handler and uses them to generate a WSGI compatible environ dictionary.
Below is the the instruction that describes the task: ### Input: This function takes the arguments passed to the request handler and uses them to generate a WSGI compatible environ dictionary. ### Response: def translate_request(request): """This function takes the arguments passed to the request handler a...
def dump_handler_config_data(self): ''' Return capture handler configuration data. Return a dictionary of capture handler configuration data of the form: .. code-block:: none [{ 'handler': <handler configuration dictionary>, 'log_file_path': <Path ...
Return capture handler configuration data. Return a dictionary of capture handler configuration data of the form: .. code-block:: none [{ 'handler': <handler configuration dictionary>, 'log_file_path': <Path to the current log file that the logger ...
Below is the the instruction that describes the task: ### Input: Return capture handler configuration data. Return a dictionary of capture handler configuration data of the form: .. code-block:: none [{ 'handler': <handler configuration dictionary>, 'l...
def validate(self, path): """Run path against filter sets and return True if all pass""" # Exclude hidden files and folders with '.' prefix if os.path.basename(path).startswith('.'): return False # Check that current path level is more than min path and less than max path ...
Run path against filter sets and return True if all pass
Below is the the instruction that describes the task: ### Input: Run path against filter sets and return True if all pass ### Response: def validate(self, path): """Run path against filter sets and return True if all pass""" # Exclude hidden files and folders with '.' prefix if os.path.base...
def gt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores greater than v. """ if limit is not None and offset is None: offset = 0 return self.zrangebyscore("(%f" % v, self._max_score, start=offset, num=lim...
Returns the list of the members of the set that have scores greater than v.
Below is the the instruction that describes the task: ### Input: Returns the list of the members of the set that have scores greater than v. ### Response: def gt(self, v, limit=None, offset=None): """Returns the list of the members of the set that have scores greater than v. """ ...
def pitch_class_to_semitone(pitch_class): r'''Convert a pitch class to semitone. Parameters ---------- pitch_class : str Spelling of a given pitch class, e.g. 'C#', 'Gbb' Returns ------- semitone : int Semitone value of the pitch class. ''' semitone = 0 for idx...
r'''Convert a pitch class to semitone. Parameters ---------- pitch_class : str Spelling of a given pitch class, e.g. 'C#', 'Gbb' Returns ------- semitone : int Semitone value of the pitch class.
Below is the the instruction that describes the task: ### Input: r'''Convert a pitch class to semitone. Parameters ---------- pitch_class : str Spelling of a given pitch class, e.g. 'C#', 'Gbb' Returns ------- semitone : int Semitone value of the pitch class. ### Response: ...
def CreateLink(target_path, link_path, override=True): ''' Create a symbolic link at `link_path` pointing to `target_path`. :param unicode target_path: Link target :param unicode link_path: Fullpath to link name :param bool override: If True and `link_path` already exists ...
Create a symbolic link at `link_path` pointing to `target_path`. :param unicode target_path: Link target :param unicode link_path: Fullpath to link name :param bool override: If True and `link_path` already exists as a link, that link is overridden.
Below is the the instruction that describes the task: ### Input: Create a symbolic link at `link_path` pointing to `target_path`. :param unicode target_path: Link target :param unicode link_path: Fullpath to link name :param bool override: If True and `link_path` already exist...
def get_color_stops(self): """Return this gradient’s color stops so far. :returns: A list of ``(offset, red, green, blue, alpha)`` tuples of floats. """ count = ffi.new('int *') _check_status(cairo.cairo_pattern_get_color_stop_count( self._pointer, count...
Return this gradient’s color stops so far. :returns: A list of ``(offset, red, green, blue, alpha)`` tuples of floats.
Below is the the instruction that describes the task: ### Input: Return this gradient’s color stops so far. :returns: A list of ``(offset, red, green, blue, alpha)`` tuples of floats. ### Response: def get_color_stops(self): """Return this gradient’s color stops so far. :retur...
def copy_fs( src_fs, # type: Union[FS, Text] dst_fs, # type: Union[FS, Text] walker=None, # type: Optional[Walker] on_copy=None, # type: Optional[_OnCopy] workers=0, # type: int ): # type: (...) -> None """Copy the contents of one filesystem to another. Arguments: src_fs (F...
Copy the contents of one filesystem to another. Arguments: src_fs (FS or str): Source filesystem (URL or instance). dst_fs (FS or str): Destination filesystem (URL or instance). walker (~fs.walk.Walker, optional): A walker object that will be used to scan for files in ``src_fs``...
Below is the the instruction that describes the task: ### Input: Copy the contents of one filesystem to another. Arguments: src_fs (FS or str): Source filesystem (URL or instance). dst_fs (FS or str): Destination filesystem (URL or instance). walker (~fs.walk.Walker, optional): A walker...
def transpose(self): ''' transpose all calibration arrays in case different array shape orders were used (x,y) vs. (y,x) ''' def _t(item): if type(item) == list: for n, it in enumerate(item): if type(it) == tuple: ...
transpose all calibration arrays in case different array shape orders were used (x,y) vs. (y,x)
Below is the the instruction that describes the task: ### Input: transpose all calibration arrays in case different array shape orders were used (x,y) vs. (y,x) ### Response: def transpose(self): ''' transpose all calibration arrays in case different array shape orders were used...
def load_dataset(self, dataset_key, force_update=False, auto_update=False): """Load a dataset from the local filesystem, downloading it from data.world first, if necessary. This function returns an object of type `LocalDataset`. The object allows access to metedata via it's `describe()`...
Load a dataset from the local filesystem, downloading it from data.world first, if necessary. This function returns an object of type `LocalDataset`. The object allows access to metedata via it's `describe()` method and to all the data via three properties `raw_data`, `tables` and `data...
Below is the the instruction that describes the task: ### Input: Load a dataset from the local filesystem, downloading it from data.world first, if necessary. This function returns an object of type `LocalDataset`. The object allows access to metedata via it's `describe()` method and to all...
def validate_words(word_list): ''' Checks for each edited word in word_list if that word is a valid english word.abs Returns all validated words as a set instance. ''' if word_list is None: return {} elif isinstance(word_list, list): if not word_list: return {} ...
Checks for each edited word in word_list if that word is a valid english word.abs Returns all validated words as a set instance.
Below is the the instruction that describes the task: ### Input: Checks for each edited word in word_list if that word is a valid english word.abs Returns all validated words as a set instance. ### Response: def validate_words(word_list): ''' Checks for each edited word in word_list if that word is a v...
def _line_tracer(self, frame, exc_info=False): """This function is called when debugger has decided that it must stop or break at this frame.""" # next logging statement commented for performance _logger.f_debug("user_line() with " "threadName=%s, frame=%s, frame...
This function is called when debugger has decided that it must stop or break at this frame.
Below is the the instruction that describes the task: ### Input: This function is called when debugger has decided that it must stop or break at this frame. ### Response: def _line_tracer(self, frame, exc_info=False): """This function is called when debugger has decided that it must stop or...
def write_parent (self, url_data): """Write url_data.parent_url.""" self.write(self.part('parenturl') + self.spaces("parenturl")) txt = url_data.parent_url if url_data.line > 0: txt += _(", line %d") % url_data.line if url_data.column > 0: txt += _(", col ...
Write url_data.parent_url.
Below is the the instruction that describes the task: ### Input: Write url_data.parent_url. ### Response: def write_parent (self, url_data): """Write url_data.parent_url.""" self.write(self.part('parenturl') + self.spaces("parenturl")) txt = url_data.parent_url if url_data.line > 0:...
def highlighted_abstract(self): """Highlight the found terms in the abstract text.""" abstract_terms = self.fields.get('abstract', []) if abstract_terms: sql = _read_sql_file('highlighted-abstract') else: sql = _read_sql_file('get-abstract') arguments = {'...
Highlight the found terms in the abstract text.
Below is the the instruction that describes the task: ### Input: Highlight the found terms in the abstract text. ### Response: def highlighted_abstract(self): """Highlight the found terms in the abstract text.""" abstract_terms = self.fields.get('abstract', []) if abstract_terms: ...
def _get_parent_classes_transparent(cls, slot, page, instance=None): """ Return all parent classes including those marked as "transparent". """ parent_classes = super(CascadePluginBase, cls).get_parent_classes(slot, page, instance) if parent_classes is None: if cls.ge...
Return all parent classes including those marked as "transparent".
Below is the the instruction that describes the task: ### Input: Return all parent classes including those marked as "transparent". ### Response: def _get_parent_classes_transparent(cls, slot, page, instance=None): """ Return all parent classes including those marked as "transparent". """ ...
def deploy_master_contract(self, deployer_account=None, deployer_private_key=None) -> str: """ Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key :param deployer_account: Unlocked ethereum account :param deployer_private_key: Private key ...
Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key :param deployer_account: Unlocked ethereum account :param deployer_private_key: Private key of an ethereum account :return: deployed contract address
Below is the the instruction that describes the task: ### Input: Deploy master contract. Takes deployer_account (if unlocked in the node) or the deployer private key :param deployer_account: Unlocked ethereum account :param deployer_private_key: Private key of an ethereum account :return: de...
def sI(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: """Return the Pauli sigma_I (identity) operator. The qubit is irrelevant, but kept as an argument for consistency""" return Pauli.sigma(qubit, 'I', coefficient)
Return the Pauli sigma_I (identity) operator. The qubit is irrelevant, but kept as an argument for consistency
Below is the the instruction that describes the task: ### Input: Return the Pauli sigma_I (identity) operator. The qubit is irrelevant, but kept as an argument for consistency ### Response: def sI(qubit: Qubit, coefficient: complex = 1.0) -> Pauli: """Return the Pauli sigma_I (identity) operator. The qubi...
def find_unique_identity(session, uuid): """Find a unique identity. Find a unique identity by its UUID using the given `session`. When the unique identity does not exist the function will return `None`. :param session: database session :param uuid: id of the unique identity to find :retur...
Find a unique identity. Find a unique identity by its UUID using the given `session`. When the unique identity does not exist the function will return `None`. :param session: database session :param uuid: id of the unique identity to find :returns: a unique identity object; `None` when the un...
Below is the the instruction that describes the task: ### Input: Find a unique identity. Find a unique identity by its UUID using the given `session`. When the unique identity does not exist the function will return `None`. :param session: database session :param uuid: id of the unique identit...
def verify_path(path, is_collection): """Verifies that a ``path`` has the correct form. Checks that all of the elements in ``path`` are strings. Args: path (Tuple[str, ...]): The components in a collection or document path. is_collection (bool): Indicates if the ``path`` repres...
Verifies that a ``path`` has the correct form. Checks that all of the elements in ``path`` are strings. Args: path (Tuple[str, ...]): The components in a collection or document path. is_collection (bool): Indicates if the ``path`` represents a document or a collection. ...
Below is the the instruction that describes the task: ### Input: Verifies that a ``path`` has the correct form. Checks that all of the elements in ``path`` are strings. Args: path (Tuple[str, ...]): The components in a collection or document path. is_collection (bool): Indicate...
def input_from_blif(blif, block=None, merge_io_vectors=True): """ Read an open blif file or string as input, updating the block appropriately Assumes the blif has been flattened and their is only a single module. Assumes that there is only one single shared clock and reset Assumes that output is genera...
Read an open blif file or string as input, updating the block appropriately Assumes the blif has been flattened and their is only a single module. Assumes that there is only one single shared clock and reset Assumes that output is generated by Yosys with formals in a particular order Ignores reset sign...
Below is the the instruction that describes the task: ### Input: Read an open blif file or string as input, updating the block appropriately Assumes the blif has been flattened and their is only a single module. Assumes that there is only one single shared clock and reset Assumes that output is generat...
def pipecmd (cmd1, cmd2): """Return output of "cmd1 | cmd2".""" p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE) p2 = subprocess.Popen(cmd2, stdin=p1.stdout, stdout=subprocess.PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. return p2.communicate()[0]
Return output of "cmd1 | cmd2".
Below is the the instruction that describes the task: ### Input: Return output of "cmd1 | cmd2". ### Response: def pipecmd (cmd1, cmd2): """Return output of "cmd1 | cmd2".""" p1 = subprocess.Popen(cmd1, stdout=subprocess.PIPE) p2 = subprocess.Popen(cmd2, stdin=p1.stdout, stdout=subprocess.PIPE) p1....
def update(self, quote_id, product_data, store_view=None): """ Allows you to update one or several products in the shopping cart (quote). :param quote_id: Shopping cart ID (quote ID) :param product_data, list of dicts of product details, see def add() :param store_view: ...
Allows you to update one or several products in the shopping cart (quote). :param quote_id: Shopping cart ID (quote ID) :param product_data, list of dicts of product details, see def add() :param store_view: Store view ID or code :return: boolean, True if the product is updated ...
Below is the the instruction that describes the task: ### Input: Allows you to update one or several products in the shopping cart (quote). :param quote_id: Shopping cart ID (quote ID) :param product_data, list of dicts of product details, see def add() :param store_view: Store view...
def wcomplex(wave): r""" Convert a waveform's dependent variable vector to complex. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for ...
r""" Convert a waveform's dependent variable vector to complex. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. Auto-generated exceptions documentation for .. peng.wave_function...
Below is the the instruction that describes the task: ### Input: r""" Convert a waveform's dependent variable vector to complex. :param wave: Waveform :type wave: :py:class:`peng.eng.Waveform` :rtype: :py:class:`peng.eng.Waveform` .. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]] .. ...
def _autodetect_fs(self, cmd="dir", pattern=r"Directory of (.*)/"): """Autodetect the file system on the remote device. Used by SCP operations.""" if not self.check_enable_mode(): raise ValueError("Must be in enable mode to auto-detect the file-system.") output = self.send_command_ex...
Autodetect the file system on the remote device. Used by SCP operations.
Below is the the instruction that describes the task: ### Input: Autodetect the file system on the remote device. Used by SCP operations. ### Response: def _autodetect_fs(self, cmd="dir", pattern=r"Directory of (.*)/"): """Autodetect the file system on the remote device. Used by SCP operations.""" ...
def transition(self): """ Implements a QAM-like transition. This function assumes ``program`` and ``program_counter`` instance variables are set appropriately, and that the wavefunction simulator and classical memory ``ram`` instance variables are in the desired QAM input state....
Implements a QAM-like transition. This function assumes ``program`` and ``program_counter`` instance variables are set appropriately, and that the wavefunction simulator and classical memory ``ram`` instance variables are in the desired QAM input state. :return: whether the QAM should ...
Below is the the instruction that describes the task: ### Input: Implements a QAM-like transition. This function assumes ``program`` and ``program_counter`` instance variables are set appropriately, and that the wavefunction simulator and classical memory ``ram`` instance variables are in t...
def shapesides(inputtocheck, inputtype='shape'): """ Get the sides of a shape. inputtocheck: The amount of sides or the shape to be checked, depending on the value of inputtype. inputtype: The type of input provided. Can be: 'shape', 'sides'. """ # Define the array of sides to...
Get the sides of a shape. inputtocheck: The amount of sides or the shape to be checked, depending on the value of inputtype. inputtype: The type of input provided. Can be: 'shape', 'sides'.
Below is the the instruction that describes the task: ### Input: Get the sides of a shape. inputtocheck: The amount of sides or the shape to be checked, depending on the value of inputtype. inputtype: The type of input provided. Can be: 'shape', 'sides'. ### Response: def shapesides(input...
def text(self): """Formatted Command declaration. This is the C declaration for the command. """ params = ', '.join(x.text for x in self.params) return '{0} ({1})'.format(self.proto_text, params)
Formatted Command declaration. This is the C declaration for the command.
Below is the the instruction that describes the task: ### Input: Formatted Command declaration. This is the C declaration for the command. ### Response: def text(self): """Formatted Command declaration. This is the C declaration for the command. """ params = ', '.join(x.te...
def set_value(self, value): """Determine the proper value based on the data_type""" if self.data_type == self.BOOLEAN_TYPE: self.value_boolean = bool(value) elif self.data_type == self.NUMBER_TYPE: self.value_number = float(value) else: self.value = v...
Determine the proper value based on the data_type
Below is the the instruction that describes the task: ### Input: Determine the proper value based on the data_type ### Response: def set_value(self, value): """Determine the proper value based on the data_type""" if self.data_type == self.BOOLEAN_TYPE: self.value_boolean = bool(value) ...
def _expand_join(join_definition): """Expand join definition to `join' call. :param join_definition: join definition :return: expanded join definition """ join_table_name = join_definition.pop('table') join_func = getattr(mosql_query, join_definition.pop('join_type', 'join')) return join_fu...
Expand join definition to `join' call. :param join_definition: join definition :return: expanded join definition
Below is the the instruction that describes the task: ### Input: Expand join definition to `join' call. :param join_definition: join definition :return: expanded join definition ### Response: def _expand_join(join_definition): """Expand join definition to `join' call. :param join_definition: join...
def get_instance(self, payload): """ Build an instance of TaskQueueRealTimeStatisticsInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance :rtype: ...
Build an instance of TaskQueueRealTimeStatisticsInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.task_q...
Below is the the instruction that describes the task: ### Input: Build an instance of TaskQueueRealTimeStatisticsInstance :param dict payload: Payload response from the API :returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics.TaskQueueRealTimeStatisticsInstance ...
def ConsultarCaracteres(self, sep="||"): "Retorna listado de caracteres emisor/receptor (código, descripción)" ret = self.client.consultarCaracteresParticipante( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cu...
Retorna listado de caracteres emisor/receptor (código, descripción)
Below is the the instruction that describes the task: ### Input: Retorna listado de caracteres emisor/receptor (código, descripción) ### Response: def ConsultarCaracteres(self, sep="||"): "Retorna listado de caracteres emisor/receptor (código, descripción)" ret = self.client.consultarCaracteresPart...
def p_expression_unor(self, p): 'expression : NOR expression %prec UNOR' p[0] = Unor(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
expression : NOR expression %prec UNOR
Below is the the instruction that describes the task: ### Input: expression : NOR expression %prec UNOR ### Response: def p_expression_unor(self, p): 'expression : NOR expression %prec UNOR' p[0] = Unor(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
def listunspent( self, address: str="", minconf: int=1, maxconf: int=999999, ) -> list: '''list UTXOs modified version to allow filtering by address. ''' if address: return self.req("listunspent", [minconf, maxconf, [address]]) ret...
list UTXOs modified version to allow filtering by address.
Below is the the instruction that describes the task: ### Input: list UTXOs modified version to allow filtering by address. ### Response: def listunspent( self, address: str="", minconf: int=1, maxconf: int=999999, ) -> list: '''list UTXOs modified versio...
def create_project(self, name, **kwargs): """ Creates a project with a name. All other parameters are optional. They are: `note`, `customer_id`, `budget`, `budget_type`, `active_hourly_rate`, `hourly_rate`, `hourly_rates_per_service`, and `archived`. """ data = s...
Creates a project with a name. All other parameters are optional. They are: `note`, `customer_id`, `budget`, `budget_type`, `active_hourly_rate`, `hourly_rate`, `hourly_rates_per_service`, and `archived`.
Below is the the instruction that describes the task: ### Input: Creates a project with a name. All other parameters are optional. They are: `note`, `customer_id`, `budget`, `budget_type`, `active_hourly_rate`, `hourly_rate`, `hourly_rates_per_service`, and `archived`. ### Response: def cr...
def get_or_add_bgPr(self): """Return `p:bg/p:bgPr` grandchild. If no such grandchild is present, any existing `p:bg` child is first removed and a new default `p:bg` with noFill settings is added. """ bg = self.bg if bg is None or bg.bgPr is None: self._change...
Return `p:bg/p:bgPr` grandchild. If no such grandchild is present, any existing `p:bg` child is first removed and a new default `p:bg` with noFill settings is added.
Below is the the instruction that describes the task: ### Input: Return `p:bg/p:bgPr` grandchild. If no such grandchild is present, any existing `p:bg` child is first removed and a new default `p:bg` with noFill settings is added. ### Response: def get_or_add_bgPr(self): """Return `p:bg/p:...
def run(icon=None): """ .. versionchanged:: 2.0.0 Remove parameter *debug*. """ app = wx.App() frame = myappframe.MyAppFrame(None, u'Lattice Viewer \u2014 Accelerator Online Modeling Tool') frame.SetSize((1024, 768)) frame.Show() if icon is not No...
.. versionchanged:: 2.0.0 Remove parameter *debug*.
Below is the the instruction that describes the task: ### Input: .. versionchanged:: 2.0.0 Remove parameter *debug*. ### Response: def run(icon=None): """ .. versionchanged:: 2.0.0 Remove parameter *debug*. """ app = wx.App() frame = myappframe.MyAppFrame(None, ...
def instruction_ROL_register(self, opcode, register): """ Rotate accumulator left """ a = register.value r = self.ROL(a) # log.debug("$%x ROL %s value $%x << 1 | Carry = $%x" % ( # self.program_counter, # register.name, a, r # )) register.set(r)
Rotate accumulator left
Below is the the instruction that describes the task: ### Input: Rotate accumulator left ### Response: def instruction_ROL_register(self, opcode, register): """ Rotate accumulator left """ a = register.value r = self.ROL(a) # log.debug("$%x ROL %s value $%x << 1 | Carry = $%x" % ( # ...
def area_fraction_dict(self): """ Returns: (dict): {hkl: area_hkl/total area on wulff} """ return {hkl: self.miller_area_dict[hkl] / self.surface_area for hkl in self.miller_area_dict.keys()}
Returns: (dict): {hkl: area_hkl/total area on wulff}
Below is the the instruction that describes the task: ### Input: Returns: (dict): {hkl: area_hkl/total area on wulff} ### Response: def area_fraction_dict(self): """ Returns: (dict): {hkl: area_hkl/total area on wulff} """ return {hkl: self.miller_area_dict[h...
def _get_sorted_methods(self, methods): """Get a copy of 'methods' sorted the way they would be on the live server. Args: methods: JSON configuration of an API's methods. Returns: The same configuration with the methods sorted based on what order they'll be checked by the server. """...
Get a copy of 'methods' sorted the way they would be on the live server. Args: methods: JSON configuration of an API's methods. Returns: The same configuration with the methods sorted based on what order they'll be checked by the server.
Below is the the instruction that describes the task: ### Input: Get a copy of 'methods' sorted the way they would be on the live server. Args: methods: JSON configuration of an API's methods. Returns: The same configuration with the methods sorted based on what order they'll be checked ...
def _buffer_decode_step(self, input, errors, final): """ There are three possibilities for each decoding step: - Decode as much real UTF-8 as possible. - Decode a six-byte CESU-8 sequence at the current position. - Decode a Java-style null at the current position. This ...
There are three possibilities for each decoding step: - Decode as much real UTF-8 as possible. - Decode a six-byte CESU-8 sequence at the current position. - Decode a Java-style null at the current position. This method figures out which step is appropriate, and does it.
Below is the the instruction that describes the task: ### Input: There are three possibilities for each decoding step: - Decode as much real UTF-8 as possible. - Decode a six-byte CESU-8 sequence at the current position. - Decode a Java-style null at the current position. This meth...
def create( cls, model, parent = None, uifile = '', commit = True ): """ Prompts the user to create a new record for the inputed table. :param model | <subclass of orb.Table> parent | <QWidget> :return <orb.Table> || None/ | instan...
Prompts the user to create a new record for the inputed table. :param model | <subclass of orb.Table> parent | <QWidget> :return <orb.Table> || None/ | instance of the inputed table class
Below is the the instruction that describes the task: ### Input: Prompts the user to create a new record for the inputed table. :param model | <subclass of orb.Table> parent | <QWidget> :return <orb.Table> || None/ | instance of the inputed tabl...
def stop(self): """ Stop services and requestors and then connection. :return: self """ LOGGER.debug("rabbitmq.Driver.stop") for requester in self.requester_registry: requester.stop() self.requester_registry.clear() for service in self.service...
Stop services and requestors and then connection. :return: self
Below is the the instruction that describes the task: ### Input: Stop services and requestors and then connection. :return: self ### Response: def stop(self): """ Stop services and requestors and then connection. :return: self """ LOGGER.debug("rabbitmq.Driver.stop")...
def node_path_transforms(self, node): """Return the list of transforms along the path to another node. The transforms are listed in reverse order, such that the last transform should be applied first when mapping from this node to the other. Parameters -------...
Return the list of transforms along the path to another node. The transforms are listed in reverse order, such that the last transform should be applied first when mapping from this node to the other. Parameters ---------- node : instance of Node T...
Below is the the instruction that describes the task: ### Input: Return the list of transforms along the path to another node. The transforms are listed in reverse order, such that the last transform should be applied first when mapping from this node to the other. Parame...
def loop_template_list(loop_positions, instance, instance_type, default_template, registry): """ Build a list of templates from a position within a loop and a registry of templates. """ templates = [] local_loop_position = loop_positions[1] global_loop_position = loop_...
Build a list of templates from a position within a loop and a registry of templates.
Below is the the instruction that describes the task: ### Input: Build a list of templates from a position within a loop and a registry of templates. ### Response: def loop_template_list(loop_positions, instance, instance_type, default_template, registry): """ Build a list of tem...
def list(self, **params): """ Retrieve visit outcomes Returns Visit Outcomes, according to the parameters provided :calls: ``get /visit_outcomes`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access, which rep...
Retrieve visit outcomes Returns Visit Outcomes, according to the parameters provided :calls: ``get /visit_outcomes`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-style access, which represent collection of VisitOutcomes. :r...
Below is the the instruction that describes the task: ### Input: Retrieve visit outcomes Returns Visit Outcomes, according to the parameters provided :calls: ``get /visit_outcomes`` :param dict params: (optional) Search options. :return: List of dictionaries that support attriubte-...
def get_neurommsig_scores(graph: BELGraph, genes: List[Gene], annotation: str = 'Subgraph', ora_weight: Optional[float] = None, hub_weight: Optional[float] = None, top_percent: Optional[floa...
Preprocess the graph, stratify by the given annotation, then run the NeuroMMSig algorithm on each. :param graph: A BEL graph :param genes: A list of gene nodes :param annotation: The annotation to use to stratify the graph to subgraphs :param ora_weight: The relative weight of the over-enrichment analy...
Below is the the instruction that describes the task: ### Input: Preprocess the graph, stratify by the given annotation, then run the NeuroMMSig algorithm on each. :param graph: A BEL graph :param genes: A list of gene nodes :param annotation: The annotation to use to stratify the graph to subgraphs ...
def email_confirm(request, confirmation_key, template_name='accounts/email_confirm_fail.html', success_url=None, extra_context=None): """ Confirms an email address with a confirmation key. Confirms a new email address by running :func:`User.objects.confirm_email` met...
Confirms an email address with a confirmation key. Confirms a new email address by running :func:`User.objects.confirm_email` method. If the method returns an :class:`User` the user will have his new e-mail address set and redirected to ``success_url``. If no ``User`` is returned the user will be repre...
Below is the the instruction that describes the task: ### Input: Confirms an email address with a confirmation key. Confirms a new email address by running :func:`User.objects.confirm_email` method. If the method returns an :class:`User` the user will have his new e-mail address set and redirected to `...
def func_attr(f, attr): """ Helper function to get the attribute of a function like, name, code, defaults across Python 2.x and 3.x """ if hasattr(f, 'func_%s' % attr): return getattr(f, 'func_%s' % attr) elif hasattr(f, '__%s__' % attr): return getattr(f, '__%s__' % attr) el...
Helper function to get the attribute of a function like, name, code, defaults across Python 2.x and 3.x
Below is the the instruction that describes the task: ### Input: Helper function to get the attribute of a function like, name, code, defaults across Python 2.x and 3.x ### Response: def func_attr(f, attr): """ Helper function to get the attribute of a function like, name, code, defaults across Pyt...
async def login( host: str, password: str, websession: ClientSession, *, port: int = 8080, ssl: bool = True, request_timeout: int = DEFAULT_TIMEOUT) -> Controller: """Authenticate against a RainMachine device.""" print('regenmaschine.client.login() is depr...
Authenticate against a RainMachine device.
Below is the the instruction that describes the task: ### Input: Authenticate against a RainMachine device. ### Response: async def login( host: str, password: str, websession: ClientSession, *, port: int = 8080, ssl: bool = True, request_timeout: int = DEFAU...
def handle_connection(stream): ''' Handle a connection. The server operates a request/response cycle, so it performs a synchronous loop: 1) Read data from network into wsproto 2) Get next wsproto event 3) Handle event 4) Send data from wsproto to network :param stream: a socket st...
Handle a connection. The server operates a request/response cycle, so it performs a synchronous loop: 1) Read data from network into wsproto 2) Get next wsproto event 3) Handle event 4) Send data from wsproto to network :param stream: a socket stream
Below is the the instruction that describes the task: ### Input: Handle a connection. The server operates a request/response cycle, so it performs a synchronous loop: 1) Read data from network into wsproto 2) Get next wsproto event 3) Handle event 4) Send data from wsproto to network ...
def unpack_rows(self, parameters_metadata, connection): """Unpack output or input/output parameters from the stored procedure call result :parameters_metadata: a stored procedure parameters metadata :returns: parameter values """ values = [] for param in parameters_metada...
Unpack output or input/output parameters from the stored procedure call result :parameters_metadata: a stored procedure parameters metadata :returns: parameter values
Below is the the instruction that describes the task: ### Input: Unpack output or input/output parameters from the stored procedure call result :parameters_metadata: a stored procedure parameters metadata :returns: parameter values ### Response: def unpack_rows(self, parameters_metadata, connection...
def hexagon_coordinates(i, j, k): """ Computes coordinates of the constituent hexagons of a hexagonal heatmap. Parameters ---------- i, j, k: enumeration of the desired hexagon Returns ------- A numpy array of coordinates of the hexagon (unprojected) """ signature = "" for...
Computes coordinates of the constituent hexagons of a hexagonal heatmap. Parameters ---------- i, j, k: enumeration of the desired hexagon Returns ------- A numpy array of coordinates of the hexagon (unprojected)
Below is the the instruction that describes the task: ### Input: Computes coordinates of the constituent hexagons of a hexagonal heatmap. Parameters ---------- i, j, k: enumeration of the desired hexagon Returns ------- A numpy array of coordinates of the hexagon (unprojected) ### Response...
def read_archive(self,header,prepend=None): """ Extract a copy of WCS keywords from an open file header, if they have already been created and remember the prefix used for those keywords. Otherwise, setup the current WCS keywords as the archive values. """ # S...
Extract a copy of WCS keywords from an open file header, if they have already been created and remember the prefix used for those keywords. Otherwise, setup the current WCS keywords as the archive values.
Below is the the instruction that describes the task: ### Input: Extract a copy of WCS keywords from an open file header, if they have already been created and remember the prefix used for those keywords. Otherwise, setup the current WCS keywords as the archive values. ### Respon...
def proposals(ctx, account): """ List proposals """ proposals = Proposals(account) t = PrettyTable( [ "id", "expiration", "proposer", "required approvals", "available approvals", "review period time", "proposal",...
List proposals
Below is the the instruction that describes the task: ### Input: List proposals ### Response: def proposals(ctx, account): """ List proposals """ proposals = Proposals(account) t = PrettyTable( [ "id", "expiration", "proposer", "required appro...
def inputs_valid(self, outputs=None): """Validates the Inputs in the Transaction against given Outputs. Note: Given a `CREATE` Transaction is passed, dummy values for Outputs are submitted for validation that evaluate parts of the validation-c...
Validates the Inputs in the Transaction against given Outputs. Note: Given a `CREATE` Transaction is passed, dummy values for Outputs are submitted for validation that evaluate parts of the validation-checks to `True`. Args: ...
Below is the the instruction that describes the task: ### Input: Validates the Inputs in the Transaction against given Outputs. Note: Given a `CREATE` Transaction is passed, dummy values for Outputs are submitted for validation that evaluate parts...
def delete_reserved_ip_address(self, name): ''' Deletes a reserved IP address from the specified subscription. name: Required. Name of the reserved IP address. ''' _validate_not_none('name', name) return self._perform_delete(self._get_reserved_ip_path(name), ...
Deletes a reserved IP address from the specified subscription. name: Required. Name of the reserved IP address.
Below is the the instruction that describes the task: ### Input: Deletes a reserved IP address from the specified subscription. name: Required. Name of the reserved IP address. ### Response: def delete_reserved_ip_address(self, name): ''' Deletes a reserved IP address from the ...
def get_users(self, condensed=False): '''Grabs all users in the slack team This should should only be used for getting list of all users. Do not use it for searching users. Use get_user_info instead. Args: condensed (bool): if true triggers list condensing functionality ...
Grabs all users in the slack team This should should only be used for getting list of all users. Do not use it for searching users. Use get_user_info instead. Args: condensed (bool): if true triggers list condensing functionality Returns: dict: Dict of users in...
Below is the the instruction that describes the task: ### Input: Grabs all users in the slack team This should should only be used for getting list of all users. Do not use it for searching users. Use get_user_info instead. Args: condensed (bool): if true triggers list condensi...
def xmlprint(element): """ pretty prints an ElementTree (or an Element of it), or the XML representation of a SaltDocument (or an element thereof, e.g. a node, edge, layer etc.) """ if isinstance(element, (etree._Element, etree._ElementTree)): print etree.tostring(element, pretty_print=T...
pretty prints an ElementTree (or an Element of it), or the XML representation of a SaltDocument (or an element thereof, e.g. a node, edge, layer etc.)
Below is the the instruction that describes the task: ### Input: pretty prints an ElementTree (or an Element of it), or the XML representation of a SaltDocument (or an element thereof, e.g. a node, edge, layer etc.) ### Response: def xmlprint(element): """ pretty prints an ElementTree (or an Elemen...
def get_attribute_values(self, att_name): """ Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - in...
Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueError - invalid attribute name
Below is the the instruction that describes the task: ### Input: Returns the values of attribute "att_name" of CPE Name. By default a only element in each part. :param string att_name: Attribute name to get :returns: List of attribute values :rtype: list :exception: ValueErr...
def from_string(cls, token_string): """ `token_string` should be the string representation from the server. """ # unhexlify works fine with unicode input in everythin but pypy3, where it Raises "TypeError: 'str' does not support the buffer interface" if isinstance(token_string, six.text_type): ...
`token_string` should be the string representation from the server.
Below is the the instruction that describes the task: ### Input: `token_string` should be the string representation from the server. ### Response: def from_string(cls, token_string): """ `token_string` should be the string representation from the server. """ # unhexlify works fine with unicode inpu...
def try_encode(field_encoders, entity_dict): """ Inner encoding and try return string from entity dictionary :param field_encoders: :param entity_dict: :return: """ result = '' for field_encoder in field_encoders: try: result +=...
Inner encoding and try return string from entity dictionary :param field_encoders: :param entity_dict: :return:
Below is the the instruction that describes the task: ### Input: Inner encoding and try return string from entity dictionary :param field_encoders: :param entity_dict: :return: ### Response: def try_encode(field_encoders, entity_dict): """ Inner encoding and try return strin...
def enqueue_sync(self, func, *func_args): ''' Enqueue an arbitrary synchronous function. Deprecated: Use async version instead ''' worker = self.pick_sticky(0) # just pick first always args = (func,) + func_args coro = worker.enqueue(enums.Task.FUNC, args) ...
Enqueue an arbitrary synchronous function. Deprecated: Use async version instead
Below is the the instruction that describes the task: ### Input: Enqueue an arbitrary synchronous function. Deprecated: Use async version instead ### Response: def enqueue_sync(self, func, *func_args): ''' Enqueue an arbitrary synchronous function. Deprecated: Use async version in...
def prune(self, minimum_word_frequency_percentage=1): """ Filter out words that occur less than minimum_word_frequency times. :param minimum_word_frequency_percentage: minimum frequency of words to keep """ pruned_resulting_documents = [] for document in self.result...
Filter out words that occur less than minimum_word_frequency times. :param minimum_word_frequency_percentage: minimum frequency of words to keep
Below is the the instruction that describes the task: ### Input: Filter out words that occur less than minimum_word_frequency times. :param minimum_word_frequency_percentage: minimum frequency of words to keep ### Response: def prune(self, minimum_word_frequency_percentage=1): """ Filt...
def parse_timemap_from_blocks(profile_block_list): """ Build a map from times to line_profile blocks """ prefix_list = [] timemap = ut.ddict(list) for ix in range(len(profile_block_list)): block = profile_block_list[ix] total_time = get_block_totaltime(block) # Blocks wit...
Build a map from times to line_profile blocks
Below is the the instruction that describes the task: ### Input: Build a map from times to line_profile blocks ### Response: def parse_timemap_from_blocks(profile_block_list): """ Build a map from times to line_profile blocks """ prefix_list = [] timemap = ut.ddict(list) for ix in range(len...
def add_command_line_options(add_argument, use_short_options=True): """ :param add_argument: The add_argument method of an ArgParser. :param use_short_options: Whether or not to add short options. """ logger_args = ("--enable-logger",) credentials_args = ("--credentials",) if use_short_optio...
:param add_argument: The add_argument method of an ArgParser. :param use_short_options: Whether or not to add short options.
Below is the the instruction that describes the task: ### Input: :param add_argument: The add_argument method of an ArgParser. :param use_short_options: Whether or not to add short options. ### Response: def add_command_line_options(add_argument, use_short_options=True): """ :param add_argument: The ad...
def endpoint_from_job(self, job_name, initial_instance_count, instance_type, deployment_image=None, name=None, role=None, wait=True, model_environment_vars=None, vpc_config_override=vpc_utils.VPC_CONFIG_DEFAULT, accelerator_type=None): ...
Create an ``Endpoint`` using the results of a successful training job. Specify the job name, Docker image containing the inference code, and hardware configuration to deploy the model. Internally the API, creates an Amazon SageMaker model (that describes the model artifacts and the Docker image...
Below is the the instruction that describes the task: ### Input: Create an ``Endpoint`` using the results of a successful training job. Specify the job name, Docker image containing the inference code, and hardware configuration to deploy the model. Internally the API, creates an Amazon SageMaker m...
def run(args): """Run a CWL preparation pipeline. """ dirs, config, run_info_yaml = run_info.prep_system(args.sample_config, args.systemconfig) integrations = args.integrations if hasattr(args, "integrations") else {} world = run_info.organize(dirs, config, run_info_yaml, is_cwl=True, integrations=i...
Run a CWL preparation pipeline.
Below is the the instruction that describes the task: ### Input: Run a CWL preparation pipeline. ### Response: def run(args): """Run a CWL preparation pipeline. """ dirs, config, run_info_yaml = run_info.prep_system(args.sample_config, args.systemconfig) integrations = args.integrations if hasattr(...
def mavlink_to_json(msg): '''Translate mavlink python messages in json string''' ret = '\"%s\": {' % msg._type for fieldname in msg._fieldnames: data = getattr(msg, fieldname) ret += '\"%s\" : \"%s\", ' % (fieldname, data) ret = ret[0:-2] + '}' return ret
Translate mavlink python messages in json string
Below is the the instruction that describes the task: ### Input: Translate mavlink python messages in json string ### Response: def mavlink_to_json(msg): '''Translate mavlink python messages in json string''' ret = '\"%s\": {' % msg._type for fieldname in msg._fieldnames: data = getattr(msg, fi...
def find_command(self, argv): """Given an argument list, find a command and return the processor and any remaining arguments. """ search_args = argv[:] name = '' while search_args: if search_args[0].startswith('-'): name = '%s %s' % (name, sear...
Given an argument list, find a command and return the processor and any remaining arguments.
Below is the the instruction that describes the task: ### Input: Given an argument list, find a command and return the processor and any remaining arguments. ### Response: def find_command(self, argv): """Given an argument list, find a command and return the processor and any remaining argu...
def report(function, *args, **kwds): """Run a function, catch, report and discard exceptions""" try: function(*args, **kwds) except Exception: traceback.print_exc()
Run a function, catch, report and discard exceptions
Below is the the instruction that describes the task: ### Input: Run a function, catch, report and discard exceptions ### Response: def report(function, *args, **kwds): """Run a function, catch, report and discard exceptions""" try: function(*args, **kwds) except Exception: traceback.pr...
def validate_ids(ctx, param, value): """Validate a list of IDs and convert them to a list.""" if not value: return None ids = [x.strip() for x in value.split(',')] for id_item in ids: if not id_item.isdigit(): raise click.BadParameter('Non-numeric value "{0}" provided for an...
Validate a list of IDs and convert them to a list.
Below is the the instruction that describes the task: ### Input: Validate a list of IDs and convert them to a list. ### Response: def validate_ids(ctx, param, value): """Validate a list of IDs and convert them to a list.""" if not value: return None ids = [x.strip() for x in value.split(',')] ...
def append_partition_by_name(self, db_name, tbl_name, part_name): """ Parameters: - db_name - tbl_name - part_name """ self.send_append_partition_by_name(db_name, tbl_name, part_name) return self.recv_append_partition_by_name()
Parameters: - db_name - tbl_name - part_name
Below is the the instruction that describes the task: ### Input: Parameters: - db_name - tbl_name - part_name ### Response: def append_partition_by_name(self, db_name, tbl_name, part_name): """ Parameters: - db_name - tbl_name - part_name """ self.send_append_partition...
def _resolved_type(self): """Return the type for the columns, and a flag to indicate that the column has codes.""" import datetime self.type_ratios = {test: (float(self.type_counts[test]) / float(self.count)) if self.count else None for test, testf in tests +...
Return the type for the columns, and a flag to indicate that the column has codes.
Below is the the instruction that describes the task: ### Input: Return the type for the columns, and a flag to indicate that the column has codes. ### Response: def _resolved_type(self): """Return the type for the columns, and a flag to indicate that the column has codes.""" import...
def rpc_get_DID_record(self, did, **con_info): """ Given a DID, return the name or subdomain it corresponds to """ if not isinstance(did, (str,unicode)): return {'error': 'Invalid DID: not a string', 'http_status': 400} try: did_info = parse_DID(did) ...
Given a DID, return the name or subdomain it corresponds to
Below is the the instruction that describes the task: ### Input: Given a DID, return the name or subdomain it corresponds to ### Response: def rpc_get_DID_record(self, did, **con_info): """ Given a DID, return the name or subdomain it corresponds to """ if not isinstance(did, (str,u...
def leave_room(self, sid, namespace, room): """Remove a client from a room.""" try: del self.rooms[namespace][room][sid] if len(self.rooms[namespace][room]) == 0: del self.rooms[namespace][room] if len(self.rooms[namespace]) == 0: ...
Remove a client from a room.
Below is the the instruction that describes the task: ### Input: Remove a client from a room. ### Response: def leave_room(self, sid, namespace, room): """Remove a client from a room.""" try: del self.rooms[namespace][room][sid] if len(self.rooms[namespace][room]) == 0: ...
def force_string(val=None): """Force a string representation of an object Args: val: object to parse into a string Returns: str: String representation """ if val is None: return '' if isinstance(val, list): newval = [str(x) for x in val] return ';'.join...
Force a string representation of an object Args: val: object to parse into a string Returns: str: String representation
Below is the the instruction that describes the task: ### Input: Force a string representation of an object Args: val: object to parse into a string Returns: str: String representation ### Response: def force_string(val=None): """Force a string representation of an object Args: ...
def invoke(self, args, kwargs): """ Send the required soap message to invoke the specified method @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @return: The resul...
Send the required soap message to invoke the specified method @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @return: The result of the method invocation. @rtype: I{builti...
Below is the the instruction that describes the task: ### Input: Send the required soap message to invoke the specified method @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @...
def _got_features(self, features): """Process incoming <stream:features/> element. [initiating entity only] The received features node is available in `features`.""" self.features = features logger.debug("got features, passing to event handlers...") handled = self.event...
Process incoming <stream:features/> element. [initiating entity only] The received features node is available in `features`.
Below is the the instruction that describes the task: ### Input: Process incoming <stream:features/> element. [initiating entity only] The received features node is available in `features`. ### Response: def _got_features(self, features): """Process incoming <stream:features/> element. ...
def __new_job_sync(self, message, future_results): """ Synchronous part of _new_job. Creates needed directories, copy files, and starts the container. """ course_id = message.course_id task_id = message.task_id debug = message.debug environment_name = message.environment ...
Synchronous part of _new_job. Creates needed directories, copy files, and starts the container.
Below is the the instruction that describes the task: ### Input: Synchronous part of _new_job. Creates needed directories, copy files, and starts the container. ### Response: def __new_job_sync(self, message, future_results): """ Synchronous part of _new_job. Creates needed directories, copy files, and sta...
def DOM_node_to_XML(tree, xml_declaration=True): """ Prints a DOM tree to its Unicode representation. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.Element`` object :param xml_declaration: if ``True`` (default) prints a leading XML declaration line :type xml_dec...
Prints a DOM tree to its Unicode representation. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.Element`` object :param xml_declaration: if ``True`` (default) prints a leading XML declaration line :type xml_declaration: bool :returns: Unicode object
Below is the the instruction that describes the task: ### Input: Prints a DOM tree to its Unicode representation. :param tree: the input DOM tree :type tree: an ``xml.etree.ElementTree.Element`` object :param xml_declaration: if ``True`` (default) prints a leading XML declaration line :type...
def _hat_integral(self, x): """Integral of the `hat` function, used for sampling. We choose a `hat` function, h(x) = x^(-power), which is a continuous (unnormalized) density touching each positive integer at the (unnormalized) pmf. This function implements `hat` integral: H(x) = int_x^inf h(t) dt; ...
Integral of the `hat` function, used for sampling. We choose a `hat` function, h(x) = x^(-power), which is a continuous (unnormalized) density touching each positive integer at the (unnormalized) pmf. This function implements `hat` integral: H(x) = int_x^inf h(t) dt; which is needed for sampling purpos...
Below is the the instruction that describes the task: ### Input: Integral of the `hat` function, used for sampling. We choose a `hat` function, h(x) = x^(-power), which is a continuous (unnormalized) density touching each positive integer at the (unnormalized) pmf. This function implements `hat` integr...
def get_asset_temporal_assignment_session_for_repository(self, repository_id, proxy): """Gets the session for assigning temporal coverage of an asset for the given repository. arg: repository_id (osid.id.Id): the Id of the repository arg proxy (osid.proxy.Proxy): a proxy ...
Gets the session for assigning temporal coverage of an asset for the given repository. arg: repository_id (osid.id.Id): the Id of the repository arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetTemporalAssignmentSession) - an AssetTemporalAssign...
Below is the the instruction that describes the task: ### Input: Gets the session for assigning temporal coverage of an asset for the given repository. arg: repository_id (osid.id.Id): the Id of the repository arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.Ass...
def modify_macho_file_headers(macho_file_path, modificator_func): """ Modifies headers of a Mach-O file at the given path by calling the modificator function on each header. Returns True on success, otherwise rises an exeption (e.g. from macholib) """ if not os.path.isfile(macho_file_path): raise Exception("Yo...
Modifies headers of a Mach-O file at the given path by calling the modificator function on each header. Returns True on success, otherwise rises an exeption (e.g. from macholib)
Below is the the instruction that describes the task: ### Input: Modifies headers of a Mach-O file at the given path by calling the modificator function on each header. Returns True on success, otherwise rises an exeption (e.g. from macholib) ### Response: def modify_macho_file_headers(macho_file_path, modific...
def commit_hash(self): """Return the current commit hash if available. This is not a required task so best effort is fine. In other words this is not guaranteed to work 100% of the time. """ commit_hash = None branch = None branch_file = '.git/HEAD' # ref: refs/...
Return the current commit hash if available. This is not a required task so best effort is fine. In other words this is not guaranteed to work 100% of the time.
Below is the the instruction that describes the task: ### Input: Return the current commit hash if available. This is not a required task so best effort is fine. In other words this is not guaranteed to work 100% of the time. ### Response: def commit_hash(self): """Return the current commi...
def _eval(self): "Evaluates a individual using recursion and self._pos as pointer" pos = self._pos self._pos += 1 node = self._ind[pos] if isinstance(node, Function): args = [self._eval() for x in range(node.nargs)] node.eval(args) for x in arg...
Evaluates a individual using recursion and self._pos as pointer
Below is the the instruction that describes the task: ### Input: Evaluates a individual using recursion and self._pos as pointer ### Response: def _eval(self): "Evaluates a individual using recursion and self._pos as pointer" pos = self._pos self._pos += 1 node = self._ind[pos] ...
def fit(self, X=None, y=None, **kwargs): """Fit the blocks of this pipeline. Sequentially call the `fit` and the `produce` methods of each block, capturing the outputs each `produce` method before calling the `fit` method of the next one. During the whole process a context dict...
Fit the blocks of this pipeline. Sequentially call the `fit` and the `produce` methods of each block, capturing the outputs each `produce` method before calling the `fit` method of the next one. During the whole process a context dictionary is built, where both the passed argum...
Below is the the instruction that describes the task: ### Input: Fit the blocks of this pipeline. Sequentially call the `fit` and the `produce` methods of each block, capturing the outputs each `produce` method before calling the `fit` method of the next one. During the whole proce...
def independent_interdomain_conditional(Kmn, Kmm, Knn, f, *, full_cov=False, full_output_cov=False, q_sqrt=None, white=False): """ The inducing outputs live in the g-space (R^L). Interdomain conditional calculation. :param Kmn: M x L x N x P :param Kmm: L x M...
The inducing outputs live in the g-space (R^L). Interdomain conditional calculation. :param Kmn: M x L x N x P :param Kmm: L x M x M :param Knn: N x P or N x N or P x N x N or N x P x N x P :param f: data matrix, M x L :param q_sqrt: L x M x M or M x L :param full_cov: calculate cov...
Below is the the instruction that describes the task: ### Input: The inducing outputs live in the g-space (R^L). Interdomain conditional calculation. :param Kmn: M x L x N x P :param Kmm: L x M x M :param Knn: N x P or N x N or P x N x N or N x P x N x P :param f: data matrix, M x L :...
def bool_2_indices(a): """ Convert boolean array into a 2D array of (start, stop) pairs. """ if any(a): lims = [] lims.append(np.where(a[:-1] != a[1:])[0]) if a[0]: lims.append([0]) if a[-1]: lims.append([len(a) - 1]) lims = np.concatenate...
Convert boolean array into a 2D array of (start, stop) pairs.
Below is the the instruction that describes the task: ### Input: Convert boolean array into a 2D array of (start, stop) pairs. ### Response: def bool_2_indices(a): """ Convert boolean array into a 2D array of (start, stop) pairs. """ if any(a): lims = [] lims.append(np.where(a[:-1] ...
def get_process_tag(program, ccd, version='p'): """ make a process tag have a suffix indicating which ccd its for. @param program: Name of the process that a tag is built for. @param ccd: the CCD number that this process ran on. @param version: The version of the exposure (s, p, o) that the process ...
make a process tag have a suffix indicating which ccd its for. @param program: Name of the process that a tag is built for. @param ccd: the CCD number that this process ran on. @param version: The version of the exposure (s, p, o) that the process ran on. @return: The string that represents the processi...
Below is the the instruction that describes the task: ### Input: make a process tag have a suffix indicating which ccd its for. @param program: Name of the process that a tag is built for. @param ccd: the CCD number that this process ran on. @param version: The version of the exposure (s, p, o) that the...
def __find_child_classes(self, file): """ Return a list of all <__base_class> based classes found in <file> """ child_classes = [] folder, name = os.path.split(file) name = os.path.splitext(name)[0] import imp module = imp.load_source(name, file) ...
Return a list of all <__base_class> based classes found in <file>
Below is the the instruction that describes the task: ### Input: Return a list of all <__base_class> based classes found in <file> ### Response: def __find_child_classes(self, file): """ Return a list of all <__base_class> based classes found in <file> """ child_classes = [] ...
def print(self, *args, end='\n', file=None): """Convenience function so you don't need to remember to put the \n at the end of the line. """ if file is None: file = self.stdout s = ' '.join(str(arg) for arg in args) + end file.write(s)
Convenience function so you don't need to remember to put the \n at the end of the line.
Below is the the instruction that describes the task: ### Input: Convenience function so you don't need to remember to put the \n at the end of the line. ### Response: def print(self, *args, end='\n', file=None): """Convenience function so you don't need to remember to put the \n at t...
def dim_reduce_data(data, d): """ Does a MDS on the data directly, not on the means. Args: data (array): genes x cells d (int): desired dimensionality Returns: X, a cells x d matrix """ genes, cells = data.shape distances = np.zeros((cells, cells)) for i in rang...
Does a MDS on the data directly, not on the means. Args: data (array): genes x cells d (int): desired dimensionality Returns: X, a cells x d matrix
Below is the the instruction that describes the task: ### Input: Does a MDS on the data directly, not on the means. Args: data (array): genes x cells d (int): desired dimensionality Returns: X, a cells x d matrix ### Response: def dim_reduce_data(data, d): """ Does a MDS o...
def compose(f, g): """Chain functions""" fun = lambda *args, **kwargs: f(g(*args, **kwargs)) fun.__name__ = "%s o %s" % (f.__name__, g.__name__) return fun
Chain functions
Below is the the instruction that describes the task: ### Input: Chain functions ### Response: def compose(f, g): """Chain functions""" fun = lambda *args, **kwargs: f(g(*args, **kwargs)) fun.__name__ = "%s o %s" % (f.__name__, g.__name__) return fun
def authenticate(self, request): """ Authenticate the request and return a two-tuple of (user, token). """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'token': return None if len(auth) == 1: msg = _('Invali...
Authenticate the request and return a two-tuple of (user, token).
Below is the the instruction that describes the task: ### Input: Authenticate the request and return a two-tuple of (user, token). ### Response: def authenticate(self, request): """ Authenticate the request and return a two-tuple of (user, token). """ auth = get_authorization_header...
def update(self, num): """Update metrics with the new number.""" num = float(num) self.count += 1 self.low = min(self.low, num) self.high = max(self.high, num) # Welford's online mean and variance algorithm. delta = num - self.mean self.mean = self.mean +...
Update metrics with the new number.
Below is the the instruction that describes the task: ### Input: Update metrics with the new number. ### Response: def update(self, num): """Update metrics with the new number.""" num = float(num) self.count += 1 self.low = min(self.low, num) self.high = max(self.high, num) ...
def compute_dominators(nodes): ''' Naive implementation of Cooper, Harvey, Kennedy algo See 'A Simple,Fast Dominance Algorithm' Compute strict domniators ''' changed = True for n in nodes: n.dominators = set(nodes) while changed: changed = False fo...
Naive implementation of Cooper, Harvey, Kennedy algo See 'A Simple,Fast Dominance Algorithm' Compute strict domniators
Below is the the instruction that describes the task: ### Input: Naive implementation of Cooper, Harvey, Kennedy algo See 'A Simple,Fast Dominance Algorithm' Compute strict domniators ### Response: def compute_dominators(nodes): ''' Naive implementation of Cooper, Harvey, Kennedy algo ...
def export_hcurves_csv(ekey, dstore): """ Exports the hazard curves into several .csv files :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] info = get_info(dstore) rlzs_assoc = dstore['csm_info'].get_rlzs_assoc() R...
Exports the hazard curves into several .csv files :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
Below is the the instruction that describes the task: ### Input: Exports the hazard curves into several .csv files :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object ### Response: def export_hcurves_csv(ekey, dstore): """ Exports the hazard curves into severa...
def unmap_namespace(self, plain_target_ns): """Given a plain target namespace, return the corresponding source namespace. """ # Return the same namespace if there are no included namespaces. if not self._regex_map and not self._plain: return plain_target_ns s...
Given a plain target namespace, return the corresponding source namespace.
Below is the the instruction that describes the task: ### Input: Given a plain target namespace, return the corresponding source namespace. ### Response: def unmap_namespace(self, plain_target_ns): """Given a plain target namespace, return the corresponding source namespace. """ ...