code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def control_message_target(self, slack_user_name, text, loaded_groups, trigger_string):
'''Returns a tuple of (target, cmdline,) for the response
Raises IndexError if a user can't be looked up from all_slack_users
Returns (False, False) if the user doesn't have permission
These are re... | Returns a tuple of (target, cmdline,) for the response
Raises IndexError if a user can't be looked up from all_slack_users
Returns (False, False) if the user doesn't have permission
These are returned together because the commandline and the targeting
interact with the group config (s... | Below is the the instruction that describes the task:
### Input:
Returns a tuple of (target, cmdline,) for the response
Raises IndexError if a user can't be looked up from all_slack_users
Returns (False, False) if the user doesn't have permission
These are returned together because the co... |
def read_gbq(
query,
project_id=None,
index_col=None,
col_order=None,
reauth=False,
auth_local_webserver=False,
dialect=None,
location=None,
configuration=None,
credentials=None,
use_bqstorage_api=False,
verbose=None,
private_key=None,
):
r"""Load data from Google... | r"""Load data from Google BigQuery using google-cloud-python
The main method a user calls to execute a Query in Google BigQuery
and read results into a pandas DataFrame.
This method uses the Google Cloud client library to make requests to
Google BigQuery, documented `here
<https://google-cloud-pyt... | Below is the the instruction that describes the task:
### Input:
r"""Load data from Google BigQuery using google-cloud-python
The main method a user calls to execute a Query in Google BigQuery
and read results into a pandas DataFrame.
This method uses the Google Cloud client library to make requests t... |
def uuid5(namespace, name):
"""Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
import sha
hash = sha.sha(namespace.bytes + name).digest()
return UUID(bytes=hash[:16], version=5) | Generate a UUID from the SHA-1 hash of a namespace UUID and a name. | Below is the the instruction that describes the task:
### Input:
Generate a UUID from the SHA-1 hash of a namespace UUID and a name.
### Response:
def uuid5(namespace, name):
"""Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
import sha
hash = sha.sha(namespace.bytes + name).dige... |
def set_dotted(self, key, value):
"""
qs.set_dotted('foo.bar', 'baz')
is equivelent to:
qs.foo.bar = baz
"""
parts = key.split('.')
cobj = self
if len(parts) > 1:
key = parts.pop()
for name in parts:
... | qs.set_dotted('foo.bar', 'baz')
is equivelent to:
qs.foo.bar = baz | Below is the the instruction that describes the task:
### Input:
qs.set_dotted('foo.bar', 'baz')
is equivelent to:
qs.foo.bar = baz
### Response:
def set_dotted(self, key, value):
"""
qs.set_dotted('foo.bar', 'baz')
is equivelent to:
... |
def create_app():
"""create_app."""
app = Flask(__name__)
app.logger.disabled = True
for h in app.logger.handlers[:]:
app.logger.removeHandler(h)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
def dated_url_for(endpoint, **values):
"""dated_url_for."""
if endpoint ==... | create_app. | Below is the the instruction that describes the task:
### Input:
create_app.
### Response:
def create_app():
"""create_app."""
app = Flask(__name__)
app.logger.disabled = True
for h in app.logger.handlers[:]:
app.logger.removeHandler(h)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False... |
def rerecord(ctx, rest):
"""Rerecord tests."""
run('tox -e py27 -- --cassette-mode all --record --credentials {0} -s'
.format(rest), pty=True)
run('tox -e py27 -- --resave --scrub --credentials test_credentials {0} -s'
.format(rest), pty=True) | Rerecord tests. | Below is the the instruction that describes the task:
### Input:
Rerecord tests.
### Response:
def rerecord(ctx, rest):
"""Rerecord tests."""
run('tox -e py27 -- --cassette-mode all --record --credentials {0} -s'
.format(rest), pty=True)
run('tox -e py27 -- --resave --scrub --credentials test_c... |
def CALLDATALOAD(self, offset):
"""Get input data of current environment"""
if issymbolic(offset):
if solver.can_be_true(self._constraints, offset == self._used_calldata_size):
self.constraints.add(offset == self._used_calldata_size)
raise ConcretizeArgument(1, p... | Get input data of current environment | Below is the the instruction that describes the task:
### Input:
Get input data of current environment
### Response:
def CALLDATALOAD(self, offset):
"""Get input data of current environment"""
if issymbolic(offset):
if solver.can_be_true(self._constraints, offset == self._used_calldata... |
def GET_save_timegrid(self) -> None:
"""Save the current simulation period."""
state.timegrids[self._id] = copy.deepcopy(hydpy.pub.timegrids.sim) | Save the current simulation period. | Below is the the instruction that describes the task:
### Input:
Save the current simulation period.
### Response:
def GET_save_timegrid(self) -> None:
"""Save the current simulation period."""
state.timegrids[self._id] = copy.deepcopy(hydpy.pub.timegrids.sim) |
def busy(self):
"""Return if the connection is currently executing a query or is locked
by a session that still exists.
:rtype: bool
"""
if self.handle.isexecuting():
return True
elif self.used_by is None:
return False
return not self.use... | Return if the connection is currently executing a query or is locked
by a session that still exists.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Return if the connection is currently executing a query or is locked
by a session that still exists.
:rtype: bool
### Response:
def busy(self):
"""Return if the connection is currently executing a query or is locked
b... |
def _create_safe_task(self, coroutine):
""" Calls self._loop.create_task with a safe (== with logged exception) coroutine. When run() ends, these tasks
are automatically cancelled"""
task = self._loop.create_task(coroutine)
self.__asyncio_tasks_running.add(task)
task.add_done... | Calls self._loop.create_task with a safe (== with logged exception) coroutine. When run() ends, these tasks
are automatically cancelled | Below is the the instruction that describes the task:
### Input:
Calls self._loop.create_task with a safe (== with logged exception) coroutine. When run() ends, these tasks
are automatically cancelled
### Response:
def _create_safe_task(self, coroutine):
""" Calls self._loop.create_task with a ... |
def dedent(content):
"""
Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
Note that python's `textwrap.dedent` doesn't quite cut it,
as it fails to dedent multiline docstrings that include
unindented text on the initial line.
"""
content = f... | Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
Note that python's `textwrap.dedent` doesn't quite cut it,
as it fails to dedent multiline docstrings that include
unindented text on the initial line. | Below is the the instruction that describes the task:
### Input:
Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
Note that python's `textwrap.dedent` doesn't quite cut it,
as it fails to dedent multiline docstrings that include
unindented text on the i... |
def get_collection_by_id(cls, collection_id, **kwargs):
"""Find Collection
Return single instance of Collection by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_collection_by_id(... | Find Collection
Return single instance of Collection by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_collection_by_id(collection_id, async=True)
>>> result = thread.get()
... | Below is the the instruction that describes the task:
### Input:
Find Collection
Return single instance of Collection by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_collection_by_i... |
def split_pow_tgh(self, text):
"""Split a power/toughness string on the correct slash.
Correctly accounts for curly braces to denote fractions.
E.g., '2/2' --> ['2', '2']
'3{1/2}/3{1/2}' --> ['3{1/2}', '3{1/2}']
"""
return [n for n in re.split(r"/(?=([^{}]*{[^{}]*})*[^{... | Split a power/toughness string on the correct slash.
Correctly accounts for curly braces to denote fractions.
E.g., '2/2' --> ['2', '2']
'3{1/2}/3{1/2}' --> ['3{1/2}', '3{1/2}'] | Below is the the instruction that describes the task:
### Input:
Split a power/toughness string on the correct slash.
Correctly accounts for curly braces to denote fractions.
E.g., '2/2' --> ['2', '2']
'3{1/2}/3{1/2}' --> ['3{1/2}', '3{1/2}']
### Response:
def split_pow_tgh(self, text):
... |
def make_input_from_factored_string(sentence_id: SentenceId,
factored_string: str,
translator: 'Translator',
delimiter: str = C.DEFAULT_FACTOR_DELIMITER) -> TranslatorInput:
"""
Returns a TranslatorInput ... | Returns a TranslatorInput object from a string with factor annotations on a token level, separated by delimiter.
If translator does not require any source factors, the string is parsed as a plain token string.
:param sentence_id: Sentence id.
:param factored_string: An input string with additional factors ... | Below is the the instruction that describes the task:
### Input:
Returns a TranslatorInput object from a string with factor annotations on a token level, separated by delimiter.
If translator does not require any source factors, the string is parsed as a plain token string.
:param sentence_id: Sentence id.... |
def get_image_set(self):
"""
Obtain existing ImageSet if `pk` is specified, otherwise
create a new ImageSet for the user.
"""
image_set_pk = self.kwargs.get("pk", None)
if image_set_pk is None:
return self.request.user.image_sets.create()
return get_ob... | Obtain existing ImageSet if `pk` is specified, otherwise
create a new ImageSet for the user. | Below is the the instruction that describes the task:
### Input:
Obtain existing ImageSet if `pk` is specified, otherwise
create a new ImageSet for the user.
### Response:
def get_image_set(self):
"""
Obtain existing ImageSet if `pk` is specified, otherwise
create a new ImageSet for... |
def set_feedback_from_tpl(tpl_name, parameters, problem_id=None, append=False):
""" Parse a template, using the given parameters, and set it as the feedback message.
tpl_name must indicate a file. Given that XX_XX is the lang code of the current user ('en_US' or 'fr_FR', for example),
this function... | Parse a template, using the given parameters, and set it as the feedback message.
tpl_name must indicate a file. Given that XX_XX is the lang code of the current user ('en_US' or 'fr_FR', for example),
this function will search template file in different locations, in the following order:
- [cu... | Below is the the instruction that describes the task:
### Input:
Parse a template, using the given parameters, and set it as the feedback message.
tpl_name must indicate a file. Given that XX_XX is the lang code of the current user ('en_US' or 'fr_FR', for example),
this function will search templa... |
def run_create_sm(self, tenant_id, fw_dict, is_fw_virt):
"""Runs the create State Machine.
Goes through every state function until the end or when one state
returns failure.
"""
ret = True
serv_obj = self.get_service_obj(tenant_id)
state = serv_obj.get_state()
... | Runs the create State Machine.
Goes through every state function until the end or when one state
returns failure. | Below is the the instruction that describes the task:
### Input:
Runs the create State Machine.
Goes through every state function until the end or when one state
returns failure.
### Response:
def run_create_sm(self, tenant_id, fw_dict, is_fw_virt):
"""Runs the create State Machine.
... |
def pin_to_ipfs(
manifest: Manifest, *, backend: BaseIPFSBackend, prettify: Optional[bool] = False
) -> List[Dict[str, str]]:
"""
Returns the IPFS pin data after pinning the manifest to the provided IPFS Backend.
`pin_to_ipfs()` Should *always* be the last argument in a builder, as it will return the p... | Returns the IPFS pin data after pinning the manifest to the provided IPFS Backend.
`pin_to_ipfs()` Should *always* be the last argument in a builder, as it will return the pin
data and not the manifest. | Below is the the instruction that describes the task:
### Input:
Returns the IPFS pin data after pinning the manifest to the provided IPFS Backend.
`pin_to_ipfs()` Should *always* be the last argument in a builder, as it will return the pin
data and not the manifest.
### Response:
def pin_to_ipfs(
man... |
def connect_delete_namespaced_service_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_delete_namespaced_service_proxy # noqa: E501
connect DELETE requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous... | connect_delete_namespaced_service_proxy # noqa: E501
connect DELETE requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.connect_delete_namespaced_service_pr... | Below is the the instruction that describes the task:
### Input:
connect_delete_namespaced_service_proxy # noqa: E501
connect DELETE requests to proxy of Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_r... |
def recurse(desc, pre='pre_recursion', post=None, python_path=None):
"""
Depth first recursion through a dictionary containing type constructors
The arguments pre, post and children are independently either:
* None, which means to do nothing
* a string, which means to use the static class method o... | Depth first recursion through a dictionary containing type constructors
The arguments pre, post and children are independently either:
* None, which means to do nothing
* a string, which means to use the static class method of that name on the
class being constructed, or
* a callable, to be call... | Below is the the instruction that describes the task:
### Input:
Depth first recursion through a dictionary containing type constructors
The arguments pre, post and children are independently either:
* None, which means to do nothing
* a string, which means to use the static class method of that name ... |
def expose_event(self, widget, event):
"""When an area of the window is exposed, we just copy out of the
server-side, off-screen surface to that area.
"""
x, y, width, height = event.area
self.logger.debug("surface is %s" % self.surface)
if self.surface is not None:
... | When an area of the window is exposed, we just copy out of the
server-side, off-screen surface to that area. | Below is the the instruction that describes the task:
### Input:
When an area of the window is exposed, we just copy out of the
server-side, off-screen surface to that area.
### Response:
def expose_event(self, widget, event):
"""When an area of the window is exposed, we just copy out of the
... |
async def create_revocation_state(blob_storage_reader_handle: int,
rev_reg_def_json: str,
rev_reg_delta_json: str,
timestamp: int,
cred_rev_id: str) -> str:
"""
Create revocati... | Create revocation state for a credential in the particular time moment.
:param blob_storage_reader_handle: configuration of blob storage reader handle that will allow to read revocation tails
:param rev_reg_def_json: revocation registry definition json
:param rev_reg_delta_json: revocation registry definit... | Below is the the instruction that describes the task:
### Input:
Create revocation state for a credential in the particular time moment.
:param blob_storage_reader_handle: configuration of blob storage reader handle that will allow to read revocation tails
:param rev_reg_def_json: revocation registry defin... |
def to_numpy(self, dtype=None, copy=False):
"""
Convert the PandasArray to a :class:`numpy.ndarray`.
By default, this requires no coercion or copying of data.
Parameters
----------
dtype : numpy.dtype
The NumPy dtype to pass to :func:`numpy.asarray`.
... | Convert the PandasArray to a :class:`numpy.ndarray`.
By default, this requires no coercion or copying of data.
Parameters
----------
dtype : numpy.dtype
The NumPy dtype to pass to :func:`numpy.asarray`.
copy : bool, default False
Whether to copy the unde... | Below is the the instruction that describes the task:
### Input:
Convert the PandasArray to a :class:`numpy.ndarray`.
By default, this requires no coercion or copying of data.
Parameters
----------
dtype : numpy.dtype
The NumPy dtype to pass to :func:`numpy.asarray`.
... |
def random_by_edges(graph: BELGraph, percentage: Optional[float] = None) -> BELGraph:
"""Get a random graph by keeping a certain percentage of original edges.
:param graph: A BEL graph
:param percentage: What percentage of eges to take
"""
percentage = percentage or 0.9
assert 0 < percentage <=... | Get a random graph by keeping a certain percentage of original edges.
:param graph: A BEL graph
:param percentage: What percentage of eges to take | Below is the the instruction that describes the task:
### Input:
Get a random graph by keeping a certain percentage of original edges.
:param graph: A BEL graph
:param percentage: What percentage of eges to take
### Response:
def random_by_edges(graph: BELGraph, percentage: Optional[float] = None) -> BELG... |
def export(self, nidm_version, export_dir):
"""
Create prov entities and activities.
"""
atts = (
(PROV['type'], NIDM_ERROR_MODEL),
(NIDM_HAS_ERROR_DISTRIBUTION, self.error_distribution),
(NIDM_ERROR_VARIANCE_HOMOGENEOUS, self.variance_homo),
... | Create prov entities and activities. | Below is the the instruction that describes the task:
### Input:
Create prov entities and activities.
### Response:
def export(self, nidm_version, export_dir):
"""
Create prov entities and activities.
"""
atts = (
(PROV['type'], NIDM_ERROR_MODEL),
(NIDM_HAS_E... |
def does_match_definition(given, main, secondary):
"""implementation details"""
assert isinstance(secondary, tuple)
assert len(secondary) == 2 # general solution could be provided
types = decompose_type(given)
if isinstance(types[0], main):
return True
if len(types) >= 2:
cond... | implementation details | Below is the the instruction that describes the task:
### Input:
implementation details
### Response:
def does_match_definition(given, main, secondary):
"""implementation details"""
assert isinstance(secondary, tuple)
assert len(secondary) == 2 # general solution could be provided
types = decompos... |
def get_media_list_by_selector(
self, media_selector, media_attribute="src"
):
"""Return a list of media."""
page_url = urlparse.urlparse(self.uri)
return [
mediafile.get_instance(
urlparse.urljoin(
"%s://%s" % (
... | Return a list of media. | Below is the the instruction that describes the task:
### Input:
Return a list of media.
### Response:
def get_media_list_by_selector(
self, media_selector, media_attribute="src"
):
"""Return a list of media."""
page_url = urlparse.urlparse(self.uri)
return [
mediafi... |
def next_power_of_2(x):
"""Finds the next power of 2 value
Args:
x: Input value
Returns:
power_of_2: Next power of 2 value
"""
power_of_2 = 1 if x == 0 else 2 ** np.ceil(np.log2(x))
return power_of_2 | Finds the next power of 2 value
Args:
x: Input value
Returns:
power_of_2: Next power of 2 value | Below is the the instruction that describes the task:
### Input:
Finds the next power of 2 value
Args:
x: Input value
Returns:
power_of_2: Next power of 2 value
### Response:
def next_power_of_2(x):
"""Finds the next power of 2 value
Args:
x: Input value
... |
def _check_errors(self):
"""Call this function after parsing the args to see if there are any
errors in the way things are input. Specifically for glotk-sweep, make
sure that all of the parameters for sweep have arguemnts if at least one
does."""
# use this to make sure that swee... | Call this function after parsing the args to see if there are any
errors in the way things are input. Specifically for glotk-sweep, make
sure that all of the parameters for sweep have arguemnts if at least one
does. | Below is the the instruction that describes the task:
### Input:
Call this function after parsing the args to see if there are any
errors in the way things are input. Specifically for glotk-sweep, make
sure that all of the parameters for sweep have arguemnts if at least one
does.
### Respons... |
def ISIs(self,time_dimension=0,units=None,min_t=None,max_t=None):
"""
returns the Inter Spike Intervals
`time_dimension`: which dimension contains the spike times (by default the first)
`units`,`min_t`,`max_t`: define the units of the output and the range of spikes ... | returns the Inter Spike Intervals
`time_dimension`: which dimension contains the spike times (by default the first)
`units`,`min_t`,`max_t`: define the units of the output and the range of spikes that should be considered | Below is the the instruction that describes the task:
### Input:
returns the Inter Spike Intervals
`time_dimension`: which dimension contains the spike times (by default the first)
`units`,`min_t`,`max_t`: define the units of the output and the range of spikes that should be consid... |
def course(self, dept, course_number):
"""Return an object of semester-independent course info. All arguments
should be strings.
>>> cis120 = r.course('cis', '120')
"""
response = self._request(path.join(ENDPOINTS['CATALOG'], dept, course_number))
return response['result... | Return an object of semester-independent course info. All arguments
should be strings.
>>> cis120 = r.course('cis', '120') | Below is the the instruction that describes the task:
### Input:
Return an object of semester-independent course info. All arguments
should be strings.
>>> cis120 = r.course('cis', '120')
### Response:
def course(self, dept, course_number):
"""Return an object of semester-independent cours... |
def validate(self, value, param_name, exc=None, logger=None):
"""
:param value: value to validate
:param param_name: name of the value (for logging purpose)
:param exc: exception to raise (default is "ValidatorError")
:param logger: logger to use (default will be "Validator.logge... | :param value: value to validate
:param param_name: name of the value (for logging purpose)
:param exc: exception to raise (default is "ValidatorError")
:param logger: logger to use (default will be "Validator.logger") | Below is the the instruction that describes the task:
### Input:
:param value: value to validate
:param param_name: name of the value (for logging purpose)
:param exc: exception to raise (default is "ValidatorError")
:param logger: logger to use (default will be "Validator.logger")
### Respo... |
def p_gate_op_1(self, program):
"""
gate_op : CX id ',' id ';'
"""
program[0] = node.Cnot([program[2], program[4]])
self.verify_declared_bit(program[2])
self.verify_declared_bit(program[4])
self.verify_distinct([program[2], program[4]]) | gate_op : CX id ',' id ';' | Below is the the instruction that describes the task:
### Input:
gate_op : CX id ',' id ';'
### Response:
def p_gate_op_1(self, program):
"""
gate_op : CX id ',' id ';'
"""
program[0] = node.Cnot([program[2], program[4]])
self.verify_declared_bit(program[2])
self.ver... |
def query(self, string, repeat_n_times=None):
"""
This method performs the operations onto self.g
:param string: The list of operations to perform. The sequences of commands should be separated by a semicolon
An example might be
CREATE {'tag': 'PE... | This method performs the operations onto self.g
:param string: The list of operations to perform. The sequences of commands should be separated by a semicolon
An example might be
CREATE {'tag': 'PERSON', 'text': 'joseph'}(v1), {'relation': 'LIVES_AT'}(v1,v2),
... | Below is the the instruction that describes the task:
### Input:
This method performs the operations onto self.g
:param string: The list of operations to perform. The sequences of commands should be separated by a semicolon
An example might be
CREATE {'tag': ... |
def _add_eutils_api_key(url):
"""Adds eutils api key to the query
:param url: eutils url with a query string
:return: url with api_key parameter set to the value of environment
variable 'NCBI_API_KEY' if available
"""
apikey = os.environ.get("NCBI_API_KEY")
if apikey:
url += "&api_k... | Adds eutils api key to the query
:param url: eutils url with a query string
:return: url with api_key parameter set to the value of environment
variable 'NCBI_API_KEY' if available | Below is the the instruction that describes the task:
### Input:
Adds eutils api key to the query
:param url: eutils url with a query string
:return: url with api_key parameter set to the value of environment
variable 'NCBI_API_KEY' if available
### Response:
def _add_eutils_api_key(url):
"""Adds ... |
def focusOutEvent(self, event):
""" The default 'focusOutEvent' implementation.
"""
widget = self.widget
type(widget).focusOutEvent(widget, event)
self.declaration.focus_lost() | The default 'focusOutEvent' implementation. | Below is the the instruction that describes the task:
### Input:
The default 'focusOutEvent' implementation.
### Response:
def focusOutEvent(self, event):
""" The default 'focusOutEvent' implementation.
"""
widget = self.widget
type(widget).focusOutEvent(widget, event)
self... |
def get_rmsd(self, mol1, mol2):
"""
Get RMSD between two molecule with arbitrary atom order.
Returns:
RMSD if topology of the two molecules are the same
Infinite if the topology is different
"""
label1, label2 = self._mapper.uniform_labels(mol1, mol2)
... | Get RMSD between two molecule with arbitrary atom order.
Returns:
RMSD if topology of the two molecules are the same
Infinite if the topology is different | Below is the the instruction that describes the task:
### Input:
Get RMSD between two molecule with arbitrary atom order.
Returns:
RMSD if topology of the two molecules are the same
Infinite if the topology is different
### Response:
def get_rmsd(self, mol1, mol2):
"""
... |
def _get_gos_upper(self, ntpltgo1, max_upper, go2parentids):
"""Plot a GO DAG for the upper portion of a single Group of user GOs."""
# Get GO IDs which are in the hdrgo path
goids_possible = ntpltgo1.gosubdag.go2obj.keys()
# Get upper GO IDs which have the most descendants
retur... | Plot a GO DAG for the upper portion of a single Group of user GOs. | Below is the the instruction that describes the task:
### Input:
Plot a GO DAG for the upper portion of a single Group of user GOs.
### Response:
def _get_gos_upper(self, ntpltgo1, max_upper, go2parentids):
"""Plot a GO DAG for the upper portion of a single Group of user GOs."""
# Get GO IDs which ... |
def run_line_magic(self, magic_name, line):
"""Execute the given line magic.
Parameters
----------
magic_name : str
Name of the desired magic function, without '%' prefix.
line : str
The rest of the input line as a single string.
"""
fn = sel... | Execute the given line magic.
Parameters
----------
magic_name : str
Name of the desired magic function, without '%' prefix.
line : str
The rest of the input line as a single string. | Below is the the instruction that describes the task:
### Input:
Execute the given line magic.
Parameters
----------
magic_name : str
Name of the desired magic function, without '%' prefix.
line : str
The rest of the input line as a single string.
### Response: ... |
def _discover_uri_type(uri):
"""Given a ``uri``, determine if it is internal or external."""
parsed_uri = urlparse(uri)
if not parsed_uri.netloc:
if parsed_uri.scheme == 'data':
type_ = INLINE_REFERENCE_TYPE
else:
type_ = INTERNAL_REFERENCE_TYPE
else:
type... | Given a ``uri``, determine if it is internal or external. | Below is the the instruction that describes the task:
### Input:
Given a ``uri``, determine if it is internal or external.
### Response:
def _discover_uri_type(uri):
"""Given a ``uri``, determine if it is internal or external."""
parsed_uri = urlparse(uri)
if not parsed_uri.netloc:
if parsed_ur... |
def get_session_id(self):
"""
get a unique id (shortish string) to allow simple aggregation
of log records from multiple sources. This id is used for the
life of the running program to allow extraction from all logs.
WARING - this can give duplicate sessions when 2 apps hit it
... | get a unique id (shortish string) to allow simple aggregation
of log records from multiple sources. This id is used for the
life of the running program to allow extraction from all logs.
WARING - this can give duplicate sessions when 2 apps hit it
at the same time. | Below is the the instruction that describes the task:
### Input:
get a unique id (shortish string) to allow simple aggregation
of log records from multiple sources. This id is used for the
life of the running program to allow extraction from all logs.
WARING - this can give duplicate sessio... |
def lv_to_pypsa(network):
"""
Convert LV grid topology to PyPSA representation
Includes grid topology of all LV grids of :attr:`~.grid.grid.Grid.lv_grids`
Parameters
----------
network : Network
eDisGo grid container
Returns
-------
dict of :pandas:`pandas.DataFrame<datafr... | Convert LV grid topology to PyPSA representation
Includes grid topology of all LV grids of :attr:`~.grid.grid.Grid.lv_grids`
Parameters
----------
network : Network
eDisGo grid container
Returns
-------
dict of :pandas:`pandas.DataFrame<dataframe>`
A DataFrame for each typ... | Below is the the instruction that describes the task:
### Input:
Convert LV grid topology to PyPSA representation
Includes grid topology of all LV grids of :attr:`~.grid.grid.Grid.lv_grids`
Parameters
----------
network : Network
eDisGo grid container
Returns
-------
dict of :... |
def get_column_header_for_number(self, column_var_names, header=False):
"""This function subtracts 1 from inputted column number to comply
with programmers counting (i.e. from 0, not from 1). For TSV data."""
if not header:
header = self.oldheader
for col in column_var_names:... | This function subtracts 1 from inputted column number to comply
with programmers counting (i.e. from 0, not from 1). For TSV data. | Below is the the instruction that describes the task:
### Input:
This function subtracts 1 from inputted column number to comply
with programmers counting (i.e. from 0, not from 1). For TSV data.
### Response:
def get_column_header_for_number(self, column_var_names, header=False):
"""This function ... |
def run_mutation(config, filename, mutation_id):
"""
:type config: Config
:type filename: str
:type mutation_id: MutationID
:return: (computed or cached) status of the tested mutant
:rtype: str
"""
context = Context(
mutation_id=mutation_id,
filename=filename,
exc... | :type config: Config
:type filename: str
:type mutation_id: MutationID
:return: (computed or cached) status of the tested mutant
:rtype: str | Below is the the instruction that describes the task:
### Input:
:type config: Config
:type filename: str
:type mutation_id: MutationID
:return: (computed or cached) status of the tested mutant
:rtype: str
### Response:
def run_mutation(config, filename, mutation_id):
"""
:type config: Conf... |
def _buildTraitCovar(self, trait_covar_type='freeform', rank=1, fixed_trait_covar=None, jitter=1e-4):
"""
Internal functions that builds the trait covariance matrix using the LIMIX framework
Args:
trait_covar_type: type of covaraince to use. Default 'freeform'. possible values are
... | Internal functions that builds the trait covariance matrix using the LIMIX framework
Args:
trait_covar_type: type of covaraince to use. Default 'freeform'. possible values are
rank: rank of a possible lowrank component (default 1)
fixed_trait_covar: PxP matr... | Below is the the instruction that describes the task:
### Input:
Internal functions that builds the trait covariance matrix using the LIMIX framework
Args:
trait_covar_type: type of covaraince to use. Default 'freeform'. possible values are
rank: rank of a possible lo... |
def fix_sign_with_K(dataframe):
"""Swap electrode denotations so that geometrical (K) factors become
positive. Also, swap signs of all parameters affected by this process.
Affected parameters, at the moment, are:
* K
* r
* Vmn
* Zt
* rho_a
* rpha
Parame... | Swap electrode denotations so that geometrical (K) factors become
positive. Also, swap signs of all parameters affected by this process.
Affected parameters, at the moment, are:
* K
* r
* Vmn
* Zt
* rho_a
* rpha
Parameters
----------
dataframe : pan... | Below is the the instruction that describes the task:
### Input:
Swap electrode denotations so that geometrical (K) factors become
positive. Also, swap signs of all parameters affected by this process.
Affected parameters, at the moment, are:
* K
* r
* Vmn
* Zt
* rh... |
async def claim_work(context):
"""Find and claim the next pending task in the queue, if any.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict: a dict containing a list of the task definitions of the tasks claimed.
"""
log.debug("Calling claimWo... | Find and claim the next pending task in the queue, if any.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict: a dict containing a list of the task definitions of the tasks claimed. | Below is the the instruction that describes the task:
### Input:
Find and claim the next pending task in the queue, if any.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict: a dict containing a list of the task definitions of the tasks claimed.
### Resp... |
def set_state(self, state):
"""
:param state: a boolean of true (on) or false ('off')
:return: nothing
"""
values = {"desired_state": {"powered": state}}
response = self.api_interface.set_device_state(self, values)
self._update_state_from_response(respons... | :param state: a boolean of true (on) or false ('off')
:return: nothing | Below is the the instruction that describes the task:
### Input:
:param state: a boolean of true (on) or false ('off')
:return: nothing
### Response:
def set_state(self, state):
"""
:param state: a boolean of true (on) or false ('off')
:return: nothing
"""
... |
def db_chainstate_get_block(cls, cur, block_height):
"""
Get the list of virtualchain transactions accepted at a given block.
Returns the list of rows, where each row is a dict.
"""
query = 'SELECT * FROM chainstate WHERE block_id = ? ORDER BY vtxindex;'
args = (block_hei... | Get the list of virtualchain transactions accepted at a given block.
Returns the list of rows, where each row is a dict. | Below is the the instruction that describes the task:
### Input:
Get the list of virtualchain transactions accepted at a given block.
Returns the list of rows, where each row is a dict.
### Response:
def db_chainstate_get_block(cls, cur, block_height):
"""
Get the list of virtualchain trans... |
def create(self, **kwargs):
"""
Creates entity instance and related Attr instances.
Note that while entity instances may filter schemata by fields, that
filtering does not take place here. Attribute of any schema will be saved
successfully as long as such schema exists.
... | Creates entity instance and related Attr instances.
Note that while entity instances may filter schemata by fields, that
filtering does not take place here. Attribute of any schema will be saved
successfully as long as such schema exists.
Note that we cannot create attribute with no pr... | Below is the the instruction that describes the task:
### Input:
Creates entity instance and related Attr instances.
Note that while entity instances may filter schemata by fields, that
filtering does not take place here. Attribute of any schema will be saved
successfully as long as such sc... |
def get_last_commit(git_path=None):
"""
Get the HEAD commit SHA1 of repository in current dir.
"""
if git_path is None: git_path = GIT_PATH
line = get_last_commit_line(git_path)
revision_id = line.split()[1]
return revision_id | Get the HEAD commit SHA1 of repository in current dir. | Below is the the instruction that describes the task:
### Input:
Get the HEAD commit SHA1 of repository in current dir.
### Response:
def get_last_commit(git_path=None):
"""
Get the HEAD commit SHA1 of repository in current dir.
"""
if git_path is None: git_path = GIT_PATH
line = get_last_commi... |
def load(obj, env=None, silent=True, key=None):
"""Loads envvars with prefixes:
`DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_`
"""
global_env = obj.get("ENVVAR_PREFIX_FOR_DYNACONF")
if global_env is False or global_env.upper() != "DYNACONF":
load_from_env(IDENTIFIER + "_gl... | Loads envvars with prefixes:
`DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_` | Below is the the instruction that describes the task:
### Input:
Loads envvars with prefixes:
`DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_`
### Response:
def load(obj, env=None, silent=True, key=None):
"""Loads envvars with prefixes:
`DYNACONF_` (default global) or `$(ENVVAR_PREFIX... |
def get_private_xml(self, query_xso):
"""
Get the private XML data for the element `query_xso` from the
server.
:param query_xso: the object to retrieve.
:returns: the stored private XML data.
`query_xso` *must* serialize to an empty XML node of the
wanted names... | Get the private XML data for the element `query_xso` from the
server.
:param query_xso: the object to retrieve.
:returns: the stored private XML data.
`query_xso` *must* serialize to an empty XML node of the
wanted namespace and type and *must* be registered as private
... | Below is the the instruction that describes the task:
### Input:
Get the private XML data for the element `query_xso` from the
server.
:param query_xso: the object to retrieve.
:returns: the stored private XML data.
`query_xso` *must* serialize to an empty XML node of the
w... |
def values_above_sweep(abf,dataI,dataY,ylabel="",useFigure=None):
"""
To make plots like AP frequency over original trace.
dataI=[i] #the i of the sweep
dataY=[1.234] #something like inst freq
"""
xOffset = abf.currentSweep*abf.sweepInterval
if not useFigure: #just passing the figure makes i... | To make plots like AP frequency over original trace.
dataI=[i] #the i of the sweep
dataY=[1.234] #something like inst freq | Below is the the instruction that describes the task:
### Input:
To make plots like AP frequency over original trace.
dataI=[i] #the i of the sweep
dataY=[1.234] #something like inst freq
### Response:
def values_above_sweep(abf,dataI,dataY,ylabel="",useFigure=None):
"""
To make plots like AP frequ... |
def wait(self, timeout=None, raise_error=True):
""" alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
"""
return self.get(t... | alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError | Below is the the instruction that describes the task:
### Input:
alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
### Response:
def wait(self... |
def remove_many(self, it):
"""Removes a collection of objects from the table."""
# find indicies of objects in iterable
to_be_deleted = list(it)
del_indices = []
for i, ob in enumerate(self.obs):
try:
tbd_index = to_be_deleted.index(ob)
exc... | Removes a collection of objects from the table. | Below is the the instruction that describes the task:
### Input:
Removes a collection of objects from the table.
### Response:
def remove_many(self, it):
"""Removes a collection of objects from the table."""
# find indicies of objects in iterable
to_be_deleted = list(it)
del_indices... |
def getKeyType(self, account, pub):
""" Get key type
"""
for authority in ["owner", "active"]:
for key in account[authority]["key_auths"]:
if str(pub) == key[0]:
return authority
if str(pub) == account["options"]["memo_key"]:
re... | Get key type | Below is the the instruction that describes the task:
### Input:
Get key type
### Response:
def getKeyType(self, account, pub):
""" Get key type
"""
for authority in ["owner", "active"]:
for key in account[authority]["key_auths"]:
if str(pub) == key[0]:
... |
def peek(iterable):
"""
Get the next value from an iterable, but also return an iterable
that will subsequently return that value and the rest of the
original iterable.
>>> l = iter([1,2,3])
>>> val, l = peek(l)
>>> val
1
>>> list(l)
[1, 2, 3]
"""
peeker, original = itertools.tee(iterable)
return next(pee... | Get the next value from an iterable, but also return an iterable
that will subsequently return that value and the rest of the
original iterable.
>>> l = iter([1,2,3])
>>> val, l = peek(l)
>>> val
1
>>> list(l)
[1, 2, 3] | Below is the the instruction that describes the task:
### Input:
Get the next value from an iterable, but also return an iterable
that will subsequently return that value and the rest of the
original iterable.
>>> l = iter([1,2,3])
>>> val, l = peek(l)
>>> val
1
>>> list(l)
[1, 2, 3]
### Response:
def pee... |
def absent(name,
user=None,
maintenance_db=None,
db_password=None,
db_host=None,
db_port=None,
db_user=None):
'''
Ensure that the named group is absent
name
The groupname of the group to remove
user
System user all opera... | Ensure that the named group is absent
name
The groupname of the group to remove
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
db_user
database username if different from config or defaul
db_password
user password if... | Below is the the instruction that describes the task:
### Input:
Ensure that the named group is absent
name
The groupname of the group to remove
user
System user all operations should be performed on behalf of
.. versionadded:: 0.17.0
db_user
database username if diff... |
def attachable(name, path=None):
'''
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'm... | Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt 'minion' lxc.attachable ubuntu | Below is the the instruction that describes the task:
### Input:
Return True if the named container can be attached to via the lxc-attach
command
path
path to the container parent
default: /var/lib/lxc (system default)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block... |
def calc2dcoords(mol):
""" Calculate optimal 2D coordinates of chemical structure
"""
topology.recognize(mol)
g = set(i for i, _ in mol.atoms_iter())
# 1: get nodes in scaffolds
scaffolds = []
belongs = {}
for i, rkeys in enumerate(sorted(mol.scaffolds, key=len)):
scf = []
... | Calculate optimal 2D coordinates of chemical structure | Below is the the instruction that describes the task:
### Input:
Calculate optimal 2D coordinates of chemical structure
### Response:
def calc2dcoords(mol):
""" Calculate optimal 2D coordinates of chemical structure
"""
topology.recognize(mol)
g = set(i for i, _ in mol.atoms_iter())
# 1: get no... |
def generate_to(self, worksheet, row):
'''Generate row report.
Generates a row report of the item represented by this instance and
inserts it into a given worksheet at a specified row number.
:param worksheet: Reference to a worksheet in which to insert row
report.
:pa... | Generate row report.
Generates a row report of the item represented by this instance and
inserts it into a given worksheet at a specified row number.
:param worksheet: Reference to a worksheet in which to insert row
report.
:param row: Row number. | Below is the the instruction that describes the task:
### Input:
Generate row report.
Generates a row report of the item represented by this instance and
inserts it into a given worksheet at a specified row number.
:param worksheet: Reference to a worksheet in which to insert row
r... |
def isolated():
"""Returns a chroot for third_party isolated from the ``sys.path``.
PEX will typically be installed in site-packages flat alongside many other distributions; as such,
adding the location of the pex distribution to the ``sys.path`` will typically expose many other
distributions. An isolated chro... | Returns a chroot for third_party isolated from the ``sys.path``.
PEX will typically be installed in site-packages flat alongside many other distributions; as such,
adding the location of the pex distribution to the ``sys.path`` will typically expose many other
distributions. An isolated chroot can be used as a `... | Below is the the instruction that describes the task:
### Input:
Returns a chroot for third_party isolated from the ``sys.path``.
PEX will typically be installed in site-packages flat alongside many other distributions; as such,
adding the location of the pex distribution to the ``sys.path`` will typically exp... |
def gps_status_encode(self, satellites_visible, satellite_prn, satellite_used, satellite_elevation, satellite_azimuth, satellite_snr):
'''
The positioning status, as reported by GPS. This message is intended
to display status information about each satellite
... | The positioning status, as reported by GPS. This message is intended
to display status information about each satellite
visible to the receiver. See message GLOBAL_POSITION
for the global position estimate. This message can
contain information for up to 20... | Below is the the instruction that describes the task:
### Input:
The positioning status, as reported by GPS. This message is intended
to display status information about each satellite
visible to the receiver. See message GLOBAL_POSITION
for the global position estima... |
def determine_timestamp_format(datetime_str, warn=True):
r"""
Args:
datetime_str (str):
Returns:
str:
References:
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
CommandLine:
python -m utool.util_time --exec-determine_timestamp_format... | r"""
Args:
datetime_str (str):
Returns:
str:
References:
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
CommandLine:
python -m utool.util_time --exec-determine_timestamp_format
Example:
>>> # ENABLE_DOCTEST
>>> from ... | Below is the the instruction that describes the task:
### Input:
r"""
Args:
datetime_str (str):
Returns:
str:
References:
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
CommandLine:
python -m utool.util_time --exec-determine_timestam... |
def yellow(cls, string, auto=False):
"""Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color
"""
return cls.colorize('yellow', stri... | Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color | Below is the the instruction that describes the task:
### Input:
Color-code entire string.
:param str string: String to colorize.
:param bool auto: Enable auto-color (dark/light terminal).
:return: Class instance for colorized string.
:rtype: Color
### Response:
def yellow(cls, st... |
def snapped_speed_limits(client, path):
"""Returns the posted speed limit (in km/h) for given road segments.
The provided points will first be snapped to the most likely roads the
vehicle was traveling along.
:param path: The path of points to be snapped.
:type path: a single location, or a list o... | Returns the posted speed limit (in km/h) for given road segments.
The provided points will first be snapped to the most likely roads the
vehicle was traveling along.
:param path: The path of points to be snapped.
:type path: a single location, or a list of locations, where a
location is a stri... | Below is the the instruction that describes the task:
### Input:
Returns the posted speed limit (in km/h) for given road segments.
The provided points will first be snapped to the most likely roads the
vehicle was traveling along.
:param path: The path of points to be snapped.
:type path: a single... |
def cost_loss(y_true, y_pred, cost_mat):
#TODO: update description
"""Cost classification loss.
This function calculates the cost of using y_pred on y_true with
cost-matrix cost-mat. It differ from traditional classification evaluation
measures since measures such as accuracy asing the same cost to... | Cost classification loss.
This function calculates the cost of using y_pred on y_true with
cost-matrix cost-mat. It differ from traditional classification evaluation
measures since measures such as accuracy asing the same cost to different
errors, but that is not the real case in several real-world cla... | Below is the the instruction that describes the task:
### Input:
Cost classification loss.
This function calculates the cost of using y_pred on y_true with
cost-matrix cost-mat. It differ from traditional classification evaluation
measures since measures such as accuracy asing the same cost to differen... |
def get_analysis_question(hazard, exposure):
"""Construct analysis question based on hazard and exposure.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:returns: Analysis question based on reporting standards.
:rtype: ... | Construct analysis question based on hazard and exposure.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:returns: Analysis question based on reporting standards.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Construct analysis question based on hazard and exposure.
:param hazard: A hazard definition.
:type hazard: dict
:param exposure: An exposure definition.
:type exposure: dict
:returns: Analysis question based on reporting standa... |
def base(ctx, verbose, config):
"""Puzzle: manage DNA variant resources."""
# configure root logger to print to STDERR
loglevel = LEVELS.get(min(verbose, 3))
configure_stream(level=loglevel)
ctx.obj = {}
if config and os.path.exists(config):
ctx.obj = yaml.load(open(config, 'r')) or {}
... | Puzzle: manage DNA variant resources. | Below is the the instruction that describes the task:
### Input:
Puzzle: manage DNA variant resources.
### Response:
def base(ctx, verbose, config):
"""Puzzle: manage DNA variant resources."""
# configure root logger to print to STDERR
loglevel = LEVELS.get(min(verbose, 3))
configure_stream(level=l... |
def list(self, resource=None, sort=None):
"""Get a list of tags.
:param resource: (optional) Restrict to given resource type as string.
:param sort: (optional) Sort fields to apply as string list.
:return: :class:`tags.Tag <tags.Tag>` list
"""
schema = TagSchema()
... | Get a list of tags.
:param resource: (optional) Restrict to given resource type as string.
:param sort: (optional) Sort fields to apply as string list.
:return: :class:`tags.Tag <tags.Tag>` list | Below is the the instruction that describes the task:
### Input:
Get a list of tags.
:param resource: (optional) Restrict to given resource type as string.
:param sort: (optional) Sort fields to apply as string list.
:return: :class:`tags.Tag <tags.Tag>` list
### Response:
def list(self, r... |
def writes(self, nb, metadata=None, **kwargs):
"""Return the text representation of the notebook"""
if self.fmt.get('format_name') == 'pandoc':
metadata = insert_jupytext_info_and_filter_metadata(metadata, self.ext, self.implementation)
cells = []
for cell in nb.cell... | Return the text representation of the notebook | Below is the the instruction that describes the task:
### Input:
Return the text representation of the notebook
### Response:
def writes(self, nb, metadata=None, **kwargs):
"""Return the text representation of the notebook"""
if self.fmt.get('format_name') == 'pandoc':
metadata = insert... |
def taper(self):
"""Taper the spectrum by adding zero flux to each end.
This is similar to :meth:`SpectralElement.taper`.
There is no check to see if the spectrum is already tapered.
Hence, calling this on a tapered spectrum will result in
multiple zero-flux entries at both ends... | Taper the spectrum by adding zero flux to each end.
This is similar to :meth:`SpectralElement.taper`.
There is no check to see if the spectrum is already tapered.
Hence, calling this on a tapered spectrum will result in
multiple zero-flux entries at both ends.
The wavelengths t... | Below is the the instruction that describes the task:
### Input:
Taper the spectrum by adding zero flux to each end.
This is similar to :meth:`SpectralElement.taper`.
There is no check to see if the spectrum is already tapered.
Hence, calling this on a tapered spectrum will result in
... |
def update(self):
"""Gets the latest version of your metadata from the infrastructure and updates your local copy
Returns `True` if successful, `False` otherwise - OR -
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrast... | Gets the latest version of your metadata from the infrastructure and updates your local copy
Returns `True` if successful, `False` otherwise - OR -
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
containing the error if the infrastructure detects a problem
... | Below is the the instruction that describes the task:
### Input:
Gets the latest version of your metadata from the infrastructure and updates your local copy
Returns `True` if successful, `False` otherwise - OR -
Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException)
... |
def memoize(fn):
"""
Simple memoization decorator for functions and methods,
assumes that all arguments to the function can be hashed and
compared.
"""
memoized_values = {}
@wraps(fn)
def wrapped_fn(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
try:
... | Simple memoization decorator for functions and methods,
assumes that all arguments to the function can be hashed and
compared. | Below is the the instruction that describes the task:
### Input:
Simple memoization decorator for functions and methods,
assumes that all arguments to the function can be hashed and
compared.
### Response:
def memoize(fn):
"""
Simple memoization decorator for functions and methods,
assumes that... |
def discover(url, options={}):
"""
Retrieve the API definition from the given URL and construct
a Patchboard to interface with it.
"""
try:
resp = requests.get(url, headers=Patchboard.default_headers)
except Exception as e:
raise PatchboardError("Problem discovering API: {0}".for... | Retrieve the API definition from the given URL and construct
a Patchboard to interface with it. | Below is the the instruction that describes the task:
### Input:
Retrieve the API definition from the given URL and construct
a Patchboard to interface with it.
### Response:
def discover(url, options={}):
"""
Retrieve the API definition from the given URL and construct
a Patchboard to interface wi... |
def fix_tour(self, tour):
"""
Test each scaffold if dropping does not decrease LMS.
"""
scaffolds, oos = zip(*tour)
keep = set()
for mlg in self.linkage_groups:
lg = mlg.lg
for s, o in tour:
i = scaffolds.index(s)
L ... | Test each scaffold if dropping does not decrease LMS. | Below is the the instruction that describes the task:
### Input:
Test each scaffold if dropping does not decrease LMS.
### Response:
def fix_tour(self, tour):
"""
Test each scaffold if dropping does not decrease LMS.
"""
scaffolds, oos = zip(*tour)
keep = set()
for m... |
def validate(self):
"""Validate that the FoldCountContextField is correctly representable."""
if not isinstance(self.fold_scope_location, FoldScopeLocation):
raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format(
type(self.fold_scope_location), ... | Validate that the FoldCountContextField is correctly representable. | Below is the the instruction that describes the task:
### Input:
Validate that the FoldCountContextField is correctly representable.
### Response:
def validate(self):
"""Validate that the FoldCountContextField is correctly representable."""
if not isinstance(self.fold_scope_location, FoldScopeLocat... |
def handle_execution_mode(self, container_state, next_child_state_to_execute=None):
"""Checks the current execution status and returns it.
Depending on the execution state, the calling thread (currently only hierarchy states) waits for the
execution to continue.
If the execution mode i... | Checks the current execution status and returns it.
Depending on the execution state, the calling thread (currently only hierarchy states) waits for the
execution to continue.
If the execution mode is any of the step modes, a condition variable stops the current execution,
until it get... | Below is the the instruction that describes the task:
### Input:
Checks the current execution status and returns it.
Depending on the execution state, the calling thread (currently only hierarchy states) waits for the
execution to continue.
If the execution mode is any of the step modes, a... |
def define_density_matrix(Ne, explicitly_hermitian=False, normalized=False,
variables=None):
r"""Return a symbolic density matrix.
The arguments are
Ne (integer):
The number of atomic states.
explicitly_hermitian (boolean):
Whether to make $\rho_{ij}=\bar{\rho... | r"""Return a symbolic density matrix.
The arguments are
Ne (integer):
The number of atomic states.
explicitly_hermitian (boolean):
Whether to make $\rho_{ij}=\bar{\rho}_{ij}$ for $i<j$
normalized (boolean):
Whether to make $\rho_{11}=1-\sum_{i>1} \rho_{ii}$
A very simple e... | Below is the the instruction that describes the task:
### Input:
r"""Return a symbolic density matrix.
The arguments are
Ne (integer):
The number of atomic states.
explicitly_hermitian (boolean):
Whether to make $\rho_{ij}=\bar{\rho}_{ij}$ for $i<j$
normalized (boolean):
Wh... |
def remove_annotations(self, remove_sequence):
"""
Removes several annotations from this AST.
:param remove_sequence: a sequence/set of the annotations to remove
:returns: a new AST, with the annotations removed
"""
return self._apply_to_annotations(lambda alist: tuple(o... | Removes several annotations from this AST.
:param remove_sequence: a sequence/set of the annotations to remove
:returns: a new AST, with the annotations removed | Below is the the instruction that describes the task:
### Input:
Removes several annotations from this AST.
:param remove_sequence: a sequence/set of the annotations to remove
:returns: a new AST, with the annotations removed
### Response:
def remove_annotations(self, remove_sequence):
"""... |
def UpdateResourcesFromDict(dstpath, res, types=None, names=None,
languages=None):
"""
Update or add resources from resource dict in dll/exe file dstpath.
types = a list of resource types to update (None = all)
names = a list of resource names to update (None = all)
... | Update or add resources from resource dict in dll/exe file dstpath.
types = a list of resource types to update (None = all)
names = a list of resource names to update (None = all)
languages = a list of resource languages to update (None = all) | Below is the the instruction that describes the task:
### Input:
Update or add resources from resource dict in dll/exe file dstpath.
types = a list of resource types to update (None = all)
names = a list of resource names to update (None = all)
languages = a list of resource languages to update (No... |
def pixbuf_to_cairo_png(pixbuf):
"""Convert from PixBuf to ImageSurface, by going through the PNG format.
This method is 10~30x slower than GDK but always works.
"""
buffer_pointer = ffi.new('gchar **')
buffer_size = ffi.new('gsize *')
error = ffi.new('GError **')
handle_g_error(error, pix... | Convert from PixBuf to ImageSurface, by going through the PNG format.
This method is 10~30x slower than GDK but always works. | Below is the the instruction that describes the task:
### Input:
Convert from PixBuf to ImageSurface, by going through the PNG format.
This method is 10~30x slower than GDK but always works.
### Response:
def pixbuf_to_cairo_png(pixbuf):
"""Convert from PixBuf to ImageSurface, by going through the PNG for... |
def select(self,sql):
"""
Execute an SQL select statement and stuff the results into a
dictionary.
sql = the (case sensitve) SQL statment to execute
"""
if not self.curs:
raise LIGOLwDBError, "Database connection not initalized"
if len(self.table) != 0:
raise LIGOLwDBError, 'att... | Execute an SQL select statement and stuff the results into a
dictionary.
sql = the (case sensitve) SQL statment to execute | Below is the the instruction that describes the task:
### Input:
Execute an SQL select statement and stuff the results into a
dictionary.
sql = the (case sensitve) SQL statment to execute
### Response:
def select(self,sql):
"""
Execute an SQL select statement and stuff the results into a
dicti... |
def _process_redirect(self):
'''Update the Redirect Tracker.'''
_logger.debug('Handling redirect.')
if self._redirect_tracker.exceeded():
raise ProtocolError('Too many redirects.')
try:
url = self._redirect_tracker.next_location()
if not url:
... | Update the Redirect Tracker. | Below is the the instruction that describes the task:
### Input:
Update the Redirect Tracker.
### Response:
def _process_redirect(self):
'''Update the Redirect Tracker.'''
_logger.debug('Handling redirect.')
if self._redirect_tracker.exceeded():
raise ProtocolError('Too many re... |
def hmset(self, name, mapping):
"""
Sets or updates the fields with their corresponding values.
:param name: str the name of the redis key
:param mapping: a dict with keys and values
:return: Future()
"""
with self.pipe as pipe:
m_encode = self.me... | Sets or updates the fields with their corresponding values.
:param name: str the name of the redis key
:param mapping: a dict with keys and values
:return: Future() | Below is the the instruction that describes the task:
### Input:
Sets or updates the fields with their corresponding values.
:param name: str the name of the redis key
:param mapping: a dict with keys and values
:return: Future()
### Response:
def hmset(self, name, mapping):
""... |
def _delta_sigma(**cosmo):
""" Perturb best-fit constant of proportionality Ascaling for
rho_crit - rho_2 relation for unknown cosmology (Correa et al 2015c)
Parameters
----------
cosmo : dict
Dictionary of cosmological parameters, similar in format to:
{'N_nu': 0,'Y_He': 0.24, ... | Perturb best-fit constant of proportionality Ascaling for
rho_crit - rho_2 relation for unknown cosmology (Correa et al 2015c)
Parameters
----------
cosmo : dict
Dictionary of cosmological parameters, similar in format to:
{'N_nu': 0,'Y_He': 0.24, 'h': 0.702, 'n': 0.963,'omega_M_0':... | Below is the the instruction that describes the task:
### Input:
Perturb best-fit constant of proportionality Ascaling for
rho_crit - rho_2 relation for unknown cosmology (Correa et al 2015c)
Parameters
----------
cosmo : dict
Dictionary of cosmological parameters, similar in format to:... |
def _rewrite_tag_attrs(self, tag, tag_attrs, set_parsing_context=True):
"""Rewrite a tags attributes.
If set_parsing_context is false then the parsing context will not set.
If the head insert has not been added to the HTML being rewritten, there
is no parsing context and the tag is not ... | Rewrite a tags attributes.
If set_parsing_context is false then the parsing context will not set.
If the head insert has not been added to the HTML being rewritten, there
is no parsing context and the tag is not in BEFORE_HEAD_TAGS then the
head_insert will be "inserted" and set to None... | Below is the the instruction that describes the task:
### Input:
Rewrite a tags attributes.
If set_parsing_context is false then the parsing context will not set.
If the head insert has not been added to the HTML being rewritten, there
is no parsing context and the tag is not in BEFORE_HEAD... |
def phonon_flow(workdir, scf_input, ph_inputs, with_nscf=False, with_ddk=False, with_dde=False,
manager=None, flow_class=PhononFlow, allocate=True):
"""
Build a :class:`PhononFlow` for phonon calculations.
Args:
workdir: Working directory.
scf_input: Input for the GS SCF run... | Build a :class:`PhononFlow` for phonon calculations.
Args:
workdir: Working directory.
scf_input: Input for the GS SCF run.
ph_inputs: List of Inputs for the phonon runs.
with_nscf: add an nscf task in front of al phonon tasks to make sure the q point is covered
with_ddk: ad... | Below is the the instruction that describes the task:
### Input:
Build a :class:`PhononFlow` for phonon calculations.
Args:
workdir: Working directory.
scf_input: Input for the GS SCF run.
ph_inputs: List of Inputs for the phonon runs.
with_nscf: add an nscf task in front of al ... |
def resetToDefault(self, resetChildren=True):
""" Resets the data to the default data. By default the children will be reset as well
"""
self.data = self.defaultData
if resetChildren:
for child in self.childItems:
child.resetToDefault(resetChildren=True) | Resets the data to the default data. By default the children will be reset as well | Below is the the instruction that describes the task:
### Input:
Resets the data to the default data. By default the children will be reset as well
### Response:
def resetToDefault(self, resetChildren=True):
""" Resets the data to the default data. By default the children will be reset as well
"""
... |
def _getDirection(coord1, coord2):
"""
Return the direction the line formed by the (x, y)
points in `coord1` and `coord2`.
"""
x1, y1 = coord1
x2, y2 = coord2
if x1 == x2 and y1 == y2:
return None # two coordinates are the same.
elif x1 == x2 and y1 > y2:
return UP
e... | Return the direction the line formed by the (x, y)
points in `coord1` and `coord2`. | Below is the the instruction that describes the task:
### Input:
Return the direction the line formed by the (x, y)
points in `coord1` and `coord2`.
### Response:
def _getDirection(coord1, coord2):
"""
Return the direction the line formed by the (x, y)
points in `coord1` and `coord2`.
"""
x... |
def indicator_constraints(self,x):
"""
Returns array of ones and zeros indicating if x is within the constraints
"""
x = np.atleast_2d(x)
I_x = np.ones((x.shape[0],1))
if self.constraints is not None:
for d in self.constraints:
try:
... | Returns array of ones and zeros indicating if x is within the constraints | Below is the the instruction that describes the task:
### Input:
Returns array of ones and zeros indicating if x is within the constraints
### Response:
def indicator_constraints(self,x):
"""
Returns array of ones and zeros indicating if x is within the constraints
"""
x = np.atleas... |
def touchstone_options(obj):
r"""
Validate if an object is an :ref:`TouchstoneOptions` pseudo-type object.
:param obj: Object
:type obj: any
:raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The
token \*[argument_name]\* is replaced by the name of the argument the
con... | r"""
Validate if an object is an :ref:`TouchstoneOptions` pseudo-type object.
:param obj: Object
:type obj: any
:raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The
token \*[argument_name]\* is replaced by the name of the argument the
contract is attached to
:rtype:... | Below is the the instruction that describes the task:
### Input:
r"""
Validate if an object is an :ref:`TouchstoneOptions` pseudo-type object.
:param obj: Object
:type obj: any
:raises: RuntimeError (Argument \`*[argument_name]*\` is not valid). The
token \*[argument_name]\* is replaced by t... |
def get_mathitemsinsertion(cls, indent) -> str:
"""Return a string defining a model specific XML type extending
`ItemType`.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_mathitemsinsertion(1)) # doctest: +ELLIPSIS
<complexType name="arma_v1_mathite... | Return a string defining a model specific XML type extending
`ItemType`.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_mathitemsinsertion(1)) # doctest: +ELLIPSIS
<complexType name="arma_v1_mathitemType">
<complexContent>
... | Below is the the instruction that describes the task:
### Input:
Return a string defining a model specific XML type extending
`ItemType`.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_mathitemsinsertion(1)) # doctest: +ELLIPSIS
<complexType name="arma_... |
def WriteBlobs(self, blob_id_data_map):
"""Creates or overwrites blobs."""
urns = {self._BlobUrn(blob_id): blob_id for blob_id in blob_id_data_map}
mutation_pool = data_store.DB.GetMutationPool()
existing = aff4.FACTORY.MultiOpen(
urns, aff4_type=aff4.AFF4MemoryStreamBase, mode="r")
for ... | Creates or overwrites blobs. | Below is the the instruction that describes the task:
### Input:
Creates or overwrites blobs.
### Response:
def WriteBlobs(self, blob_id_data_map):
"""Creates or overwrites blobs."""
urns = {self._BlobUrn(blob_id): blob_id for blob_id in blob_id_data_map}
mutation_pool = data_store.DB.GetMutationPool... |
def source_set(method_name):
"""
Creates a setter that will call the source method with the context's
key as first parameter and the value as second parameter.
@param method_name: the name of a method belonging to the source.
@type method_name: str
"""
def source_set(value, context, **_para... | Creates a setter that will call the source method with the context's
key as first parameter and the value as second parameter.
@param method_name: the name of a method belonging to the source.
@type method_name: str | Below is the the instruction that describes the task:
### Input:
Creates a setter that will call the source method with the context's
key as first parameter and the value as second parameter.
@param method_name: the name of a method belonging to the source.
@type method_name: str
### Response:
def sour... |
def GetMemOverheadMB(self):
'''Retrieves the amount of "overhead" memory associated with this virtual
machine that is currently consumed on the host system. Overhead
memory is additional memory that is reserved for data structures required
by the virtualization layer.'''
... | Retrieves the amount of "overhead" memory associated with this virtual
machine that is currently consumed on the host system. Overhead
memory is additional memory that is reserved for data structures required
by the virtualization layer. | Below is the the instruction that describes the task:
### Input:
Retrieves the amount of "overhead" memory associated with this virtual
machine that is currently consumed on the host system. Overhead
memory is additional memory that is reserved for data structures required
by the vi... |
def coord_to_tile(self, lat, lon, zoom):
'''convert lat/lon/zoom to a TileInfo'''
world_tiles = 1<<zoom
x = world_tiles / 360.0 * (lon + 180.0)
tiles_pre_radian = world_tiles / (2 * math.pi)
e = math.sin(lat * (1/180.*math.pi))
y = world_tiles/2 + 0.5*math.log((1+e)/(1-e)) * (-tiles_pre_radian)
offsetx = ... | convert lat/lon/zoom to a TileInfo | Below is the the instruction that describes the task:
### Input:
convert lat/lon/zoom to a TileInfo
### Response:
def coord_to_tile(self, lat, lon, zoom):
'''convert lat/lon/zoom to a TileInfo'''
world_tiles = 1<<zoom
x = world_tiles / 360.0 * (lon + 180.0)
tiles_pre_radian = world_tiles / (2 * math.pi)
... |
def forward(self, x, boxes):
"""
Arguments:
x (tuple[tensor, tensor]): x contains the class logits
and the box_regression from the model.
boxes (list[BoxList]): bounding boxes that are used as
reference, one for ech image
Returns:
... | Arguments:
x (tuple[tensor, tensor]): x contains the class logits
and the box_regression from the model.
boxes (list[BoxList]): bounding boxes that are used as
reference, one for ech image
Returns:
results (list[BoxList]): one BoxList for each... | Below is the the instruction that describes the task:
### Input:
Arguments:
x (tuple[tensor, tensor]): x contains the class logits
and the box_regression from the model.
boxes (list[BoxList]): bounding boxes that are used as
reference, one for ech image
... |
def add_downloads(self, filemap):
"""Add the dict of downloads. (Note the Winscp command line accepts wildcards)
Parameters
----------
filemap: dict, (remote_filename -> local_filename)
"""
[self.add_download(k, v) for k, v in filemap.iteritems()] | Add the dict of downloads. (Note the Winscp command line accepts wildcards)
Parameters
----------
filemap: dict, (remote_filename -> local_filename) | Below is the the instruction that describes the task:
### Input:
Add the dict of downloads. (Note the Winscp command line accepts wildcards)
Parameters
----------
filemap: dict, (remote_filename -> local_filename)
### Response:
def add_downloads(self, filemap):
"""Add the dict of d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.