code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def imu_changed(self, val):
"""Handle clicks on the IMU index spinner."""
self.current_imuid = '{}_IMU{}'.format(self.sk8.get_device_name(), val)
self.update_data_display(self.get_current_data()) | Handle clicks on the IMU index spinner. | Below is the the instruction that describes the task:
### Input:
Handle clicks on the IMU index spinner.
### Response:
def imu_changed(self, val):
"""Handle clicks on the IMU index spinner."""
self.current_imuid = '{}_IMU{}'.format(self.sk8.get_device_name(), val)
self.update_data_display(s... |
def run_azure(target, jobs, n=1, nproc=None, path='.', delete=True, config=None, **kwargs):
"""
Evaluate the given function with each set of arguments, and return a list of results.
This function does in parallel with Microsoft Azure Batch.
This function is the work in progress.
The argument `nproc... | Evaluate the given function with each set of arguments, and return a list of results.
This function does in parallel with Microsoft Azure Batch.
This function is the work in progress.
The argument `nproc` doesn't work yet.
See `ecell4.extra.azure_batch.run_azure` for details.
See Also
--------... | Below is the the instruction that describes the task:
### Input:
Evaluate the given function with each set of arguments, and return a list of results.
This function does in parallel with Microsoft Azure Batch.
This function is the work in progress.
The argument `nproc` doesn't work yet.
See `ecell4... |
def _complete_multipart_upload(self, bucket_name, object_name,
upload_id, uploaded_parts):
"""
Complete an active multipart upload request.
:param bucket_name: Bucket name of the multipart request.
:param object_name: Object name of the multipart reque... | Complete an active multipart upload request.
:param bucket_name: Bucket name of the multipart request.
:param object_name: Object name of the multipart request.
:param upload_id: Upload id of the active multipart request.
:param uploaded_parts: Key, Value dictionary of uploaded parts. | Below is the the instruction that describes the task:
### Input:
Complete an active multipart upload request.
:param bucket_name: Bucket name of the multipart request.
:param object_name: Object name of the multipart request.
:param upload_id: Upload id of the active multipart request.
... |
def short_title(self):
"""
Generates an abbreviated title by subtracting the parent's title from this instance's title.
"""
if self.title and self.parent is not None and hasattr(self.parent, 'title') and self.parent.title:
if self.title.startswith(self.parent.title):
... | Generates an abbreviated title by subtracting the parent's title from this instance's title. | Below is the the instruction that describes the task:
### Input:
Generates an abbreviated title by subtracting the parent's title from this instance's title.
### Response:
def short_title(self):
"""
Generates an abbreviated title by subtracting the parent's title from this instance's title.
... |
def dump_report_content(self, request, result):
"""
Dumps the content to a string, suitable to being written on a file.
:param result: The result being processed.
:return: string
"""
output = StringIO()
writer = csv.writer(output, **self.csv_kwargs)
write... | Dumps the content to a string, suitable to being written on a file.
:param result: The result being processed.
:return: string | Below is the the instruction that describes the task:
### Input:
Dumps the content to a string, suitable to being written on a file.
:param result: The result being processed.
:return: string
### Response:
def dump_report_content(self, request, result):
"""
Dumps the content to a st... |
def get_authorization_user(self, **kwargs):
"""Gets the user the authorization object is for."""
if self.authorization_user is not None:
return self.authorization_user
self.authorization_user = self.request.user
return self.request.user | Gets the user the authorization object is for. | Below is the the instruction that describes the task:
### Input:
Gets the user the authorization object is for.
### Response:
def get_authorization_user(self, **kwargs):
"""Gets the user the authorization object is for."""
if self.authorization_user is not None:
return self.authorizatio... |
def lint(to_lint):
"""
Run all linters against a list of files.
:param to_lint: a list of files to lint.
"""
exit_code = 0
for linter, options in (('pyflakes', []), ('pep8', [])):
try:
output = local[linter](*(options + to_lint))
except commands.ProcessExecutionErro... | Run all linters against a list of files.
:param to_lint: a list of files to lint. | Below is the the instruction that describes the task:
### Input:
Run all linters against a list of files.
:param to_lint: a list of files to lint.
### Response:
def lint(to_lint):
"""
Run all linters against a list of files.
:param to_lint: a list of files to lint.
"""
exit_code = 0
... |
def _get_exception_class_from_status_code(status_code):
"""
Utility function that accepts a status code, and spits out a reference
to the correct exception class to raise.
:param str status_code: The status code to return an exception class for.
:rtype: PetfinderAPIError or None
:returns: The a... | Utility function that accepts a status code, and spits out a reference
to the correct exception class to raise.
:param str status_code: The status code to return an exception class for.
:rtype: PetfinderAPIError or None
:returns: The appropriate PetfinderAPIError subclass. If the status code
is... | Below is the the instruction that describes the task:
### Input:
Utility function that accepts a status code, and spits out a reference
to the correct exception class to raise.
:param str status_code: The status code to return an exception class for.
:rtype: PetfinderAPIError or None
:returns: The ... |
def exchange(self, data):
"""
Perform SPI transaction.
The first received byte is either ACK or NACK.
:TODO: enforce rule that up to 63 bytes of data can be sent.
:TODO: enforce rule that there is no gaps in data bytes (what define a gap?)
:param data: List of bytes
... | Perform SPI transaction.
The first received byte is either ACK or NACK.
:TODO: enforce rule that up to 63 bytes of data can be sent.
:TODO: enforce rule that there is no gaps in data bytes (what define a gap?)
:param data: List of bytes
:returns: List of bytes
:rtype: ... | Below is the the instruction that describes the task:
### Input:
Perform SPI transaction.
The first received byte is either ACK or NACK.
:TODO: enforce rule that up to 63 bytes of data can be sent.
:TODO: enforce rule that there is no gaps in data bytes (what define a gap?)
:param... |
def eth_getCode(self, address):
"""Get account code.
:param address:
:return:
"""
account = self.reader._get_account(address)
return _encode_hex(account.code) | Get account code.
:param address:
:return: | Below is the the instruction that describes the task:
### Input:
Get account code.
:param address:
:return:
### Response:
def eth_getCode(self, address):
"""Get account code.
:param address:
:return:
"""
account = self.reader._get_account(address)
r... |
def disassemble(self, offset, size):
"""
Disassembles a given offset in the DEX file
:param offset: offset to disassemble in the file (from the beginning of the file)
:type offset: int
:param size:
:type size:
"""
for i in DCode(
self.CM, ... | Disassembles a given offset in the DEX file
:param offset: offset to disassemble in the file (from the beginning of the file)
:type offset: int
:param size:
:type size: | Below is the the instruction that describes the task:
### Input:
Disassembles a given offset in the DEX file
:param offset: offset to disassemble in the file (from the beginning of the file)
:type offset: int
:param size:
:type size:
### Response:
def disassemble(self, offset, size... |
def get_default_key_store(*args, config, **kwargs):
""" This method returns the default **key** store
that uses an SQLite database internally.
:params str appname: The appname that is used internally to distinguish
different SQLite files
"""
kwargs["appname"] = kwargs.get("appna... | This method returns the default **key** store
that uses an SQLite database internally.
:params str appname: The appname that is used internally to distinguish
different SQLite files | Below is the the instruction that describes the task:
### Input:
This method returns the default **key** store
that uses an SQLite database internally.
:params str appname: The appname that is used internally to distinguish
different SQLite files
### Response:
def get_default_key_store... |
def download_and_extract_dataset(self, destination_directory: str):
"""
Downloads and extracts the MUSCIMA++ dataset along with the images from the CVC-MUSCIMA dataset
that were manually annotated (140 out of 1000 images).
"""
if not os.path.exists(self.get_dataset_filename()):
... | Downloads and extracts the MUSCIMA++ dataset along with the images from the CVC-MUSCIMA dataset
that were manually annotated (140 out of 1000 images). | Below is the the instruction that describes the task:
### Input:
Downloads and extracts the MUSCIMA++ dataset along with the images from the CVC-MUSCIMA dataset
that were manually annotated (140 out of 1000 images).
### Response:
def download_and_extract_dataset(self, destination_directory: str):
"... |
def register_form_factory(Form, app):
"""Return extended registration form."""
if app.config.get('RECAPTCHA_PUBLIC_KEY') and \
app.config.get('RECAPTCHA_PRIVATE_KEY'):
class RegisterForm(Form):
recaptcha = FormField(RegistrationFormRecaptcha, separator='.')
return Regist... | Return extended registration form. | Below is the the instruction that describes the task:
### Input:
Return extended registration form.
### Response:
def register_form_factory(Form, app):
"""Return extended registration form."""
if app.config.get('RECAPTCHA_PUBLIC_KEY') and \
app.config.get('RECAPTCHA_PRIVATE_KEY'):
class... |
def save(self):
'''saves our config objet to file'''
if self.app.cfg_mode == 'json':
with open(self.app.cfg_file, 'w') as opened_file:
json.dump(self.app.cfg, opened_file)
else:
with open(self.app.cfg_file, 'w')as opened_file:
yaml.dump(sel... | saves our config objet to file | Below is the the instruction that describes the task:
### Input:
saves our config objet to file
### Response:
def save(self):
'''saves our config objet to file'''
if self.app.cfg_mode == 'json':
with open(self.app.cfg_file, 'w') as opened_file:
json.dump(self.app.cfg, op... |
def get_next_entry(self, method, info, request):
"""Cycle through available responses, but only once.
Any subsequent requests will receive the last response"""
if method not in self.current_entries:
self.current_entries[method] = 0
# restrict selection to entries that match... | Cycle through available responses, but only once.
Any subsequent requests will receive the last response | Below is the the instruction that describes the task:
### Input:
Cycle through available responses, but only once.
Any subsequent requests will receive the last response
### Response:
def get_next_entry(self, method, info, request):
"""Cycle through available responses, but only once.
Any s... |
def name_for_callable(func):
"""Returns a module name for a callable or `None` if no name can be found."""
if isinstance(func, functools.partial):
return name_for_callable(func.func)
try:
name = func.__name__
except AttributeError:
return None
if name == "<lambda>":
return None
else:
r... | Returns a module name for a callable or `None` if no name can be found. | Below is the the instruction that describes the task:
### Input:
Returns a module name for a callable or `None` if no name can be found.
### Response:
def name_for_callable(func):
"""Returns a module name for a callable or `None` if no name can be found."""
if isinstance(func, functools.partial):
return na... |
def stop(self):
"""
Stop the interface
:rtype: None
"""
should_sleep = self._is_running
super(Sensor, self).stop()
if should_sleep:
# Make sure everything has enough time to exit
time.sleep(max(self._select_timeout, self._retransmit_timeou... | Stop the interface
:rtype: None | Below is the the instruction that describes the task:
### Input:
Stop the interface
:rtype: None
### Response:
def stop(self):
"""
Stop the interface
:rtype: None
"""
should_sleep = self._is_running
super(Sensor, self).stop()
if should_sleep:
... |
def __all_parameters_processed(self):
"""
Finish the argument processing.
Should be called after all the web service operation's parameters have
been successfully processed and, afterwards, no further parameter
processing is allowed.
Returns a 2-tuple containing the num... | Finish the argument processing.
Should be called after all the web service operation's parameters have
been successfully processed and, afterwards, no further parameter
processing is allowed.
Returns a 2-tuple containing the number of required & allowed
arguments.
See ... | Below is the the instruction that describes the task:
### Input:
Finish the argument processing.
Should be called after all the web service operation's parameters have
been successfully processed and, afterwards, no further parameter
processing is allowed.
Returns a 2-tuple contain... |
def unregister_path(self, path):
"""
Unregisters given path.
:param path: Path name.
:type path: unicode
:return: Method success.
:rtype: bool
"""
if not path in self:
raise umbra.exceptions.PathExistsError("{0} | '{1}' path isn't registered!... | Unregisters given path.
:param path: Path name.
:type path: unicode
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Unregisters given path.
:param path: Path name.
:type path: unicode
:return: Method success.
:rtype: bool
### Response:
def unregister_path(self, path):
"""
Unregisters given path.
:param path... |
def _max_gain_split(self, examples):
"""
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
"""
gains = self._new_set_of_gain_counters()
for example in examples:
for gain in gains:
gain.add(example)
win... | Returns an OnlineInformationGain of the attribute with
max gain based on `examples`. | Below is the the instruction that describes the task:
### Input:
Returns an OnlineInformationGain of the attribute with
max gain based on `examples`.
### Response:
def _max_gain_split(self, examples):
"""
Returns an OnlineInformationGain of the attribute with
max gain based on `exam... |
def find_node(self, point, cur_node = None):
"""!
@brief Find node with coordinates that are defined by specified point.
@details If node with specified parameters does not exist then None will be returned,
otherwise required node will be returned.
@para... | !
@brief Find node with coordinates that are defined by specified point.
@details If node with specified parameters does not exist then None will be returned,
otherwise required node will be returned.
@param[in] point (list): Coordinates of the point whose node s... | Below is the the instruction that describes the task:
### Input:
!
@brief Find node with coordinates that are defined by specified point.
@details If node with specified parameters does not exist then None will be returned,
otherwise required node will be returned.
... |
def zip(self, destination: typing.Union[str, Path] = None, encode: bool = True) -> str:
"""
Write mission, dictionary etc. to a MIZ file
Args:
destination: target MIZ file (if none, defaults to source MIZ + "_EMIZ"
Returns: destination file
"""
if encode:
... | Write mission, dictionary etc. to a MIZ file
Args:
destination: target MIZ file (if none, defaults to source MIZ + "_EMIZ"
Returns: destination file | Below is the the instruction that describes the task:
### Input:
Write mission, dictionary etc. to a MIZ file
Args:
destination: target MIZ file (if none, defaults to source MIZ + "_EMIZ"
Returns: destination file
### Response:
def zip(self, destination: typing.Union[str, Path] = None... |
def temperature(self):
"""Get the temperature from the sensor.
:returns: The temperature in degree celcius as a float
:example:
>>> sensor = BMP180(gw)
>>> sensor.load_calibration()
>>> sensor.temperature()
21.4
"""
ut = self.get_raw_temp()
... | Get the temperature from the sensor.
:returns: The temperature in degree celcius as a float
:example:
>>> sensor = BMP180(gw)
>>> sensor.load_calibration()
>>> sensor.temperature()
21.4 | Below is the the instruction that describes the task:
### Input:
Get the temperature from the sensor.
:returns: The temperature in degree celcius as a float
:example:
>>> sensor = BMP180(gw)
>>> sensor.load_calibration()
>>> sensor.temperature()
21.4
### Response: ... |
def create_shipping_address(self, shipping_address):
"""Creates a shipping address on an existing account. If you are
creating an account, you can embed the shipping addresses with the
request"""
url = urljoin(self._url, '/shipping_addresses')
return shipping_address.post(url) | Creates a shipping address on an existing account. If you are
creating an account, you can embed the shipping addresses with the
request | Below is the the instruction that describes the task:
### Input:
Creates a shipping address on an existing account. If you are
creating an account, you can embed the shipping addresses with the
request
### Response:
def create_shipping_address(self, shipping_address):
"""Creates a shipping ... |
def t0_supconj_to_perpass(t0_supconj, period, ecc, per0):
"""
TODO: add documentation
"""
return ConstraintParameter(t0_supconj._bundle, "t0_supconj_to_perpass({}, {}, {}, {})".format(_get_expr(t0_supconj), _get_expr(period), _get_expr(ecc), _get_expr(per0))) | TODO: add documentation | Below is the the instruction that describes the task:
### Input:
TODO: add documentation
### Response:
def t0_supconj_to_perpass(t0_supconj, period, ecc, per0):
"""
TODO: add documentation
"""
return ConstraintParameter(t0_supconj._bundle, "t0_supconj_to_perpass({}, {}, {}, {})".format(_get_expr(t0... |
def update(self, *args, **kwargs):
"""Modifies the parameters and adds metadata for update results.
Currently it does not support `PUT` method, which works as replacing
the resource. This is somehow questionable in relation DB.
"""
if request.method == 'PUT':
logging... | Modifies the parameters and adds metadata for update results.
Currently it does not support `PUT` method, which works as replacing
the resource. This is somehow questionable in relation DB. | Below is the the instruction that describes the task:
### Input:
Modifies the parameters and adds metadata for update results.
Currently it does not support `PUT` method, which works as replacing
the resource. This is somehow questionable in relation DB.
### Response:
def update(self, *args, **kwa... |
async def deploy(self, charm, series, application, options, constraints,
storage, endpoint_bindings, *args):
"""
:param charm string:
Charm holds the URL of the charm to be used to deploy this
application.
:param series string:
Series hol... | :param charm string:
Charm holds the URL of the charm to be used to deploy this
application.
:param series string:
Series holds the series of the application to be deployed
if the charm default is not sufficient.
:param application string:
Ap... | Below is the the instruction that describes the task:
### Input:
:param charm string:
Charm holds the URL of the charm to be used to deploy this
application.
:param series string:
Series holds the series of the application to be deployed
if the charm default ... |
def nn_poll(fds, timeout=-1):
"""
nn_pollfds
:param fds: dict (file descriptor => pollmode)
:param timeout: timeout in milliseconds
:return:
"""
polls = []
for i, entry in enumerate(fds.items()):
s = PollFds()
fd, event = entry
s.fd = fd
s.events = event
... | nn_pollfds
:param fds: dict (file descriptor => pollmode)
:param timeout: timeout in milliseconds
:return: | Below is the the instruction that describes the task:
### Input:
nn_pollfds
:param fds: dict (file descriptor => pollmode)
:param timeout: timeout in milliseconds
:return:
### Response:
def nn_poll(fds, timeout=-1):
"""
nn_pollfds
:param fds: dict (file descriptor => pollmode)
:param ti... |
def execute(self, jvm_options=None, args=None, executor=None,
workunit_factory=None, workunit_name=None, workunit_labels=None):
"""Executes the ivy commandline client with the given args.
Raises Ivy.Error if the command fails for any reason.
:param executor: Java executor to run ivy with.
... | Executes the ivy commandline client with the given args.
Raises Ivy.Error if the command fails for any reason.
:param executor: Java executor to run ivy with. | Below is the the instruction that describes the task:
### Input:
Executes the ivy commandline client with the given args.
Raises Ivy.Error if the command fails for any reason.
:param executor: Java executor to run ivy with.
### Response:
def execute(self, jvm_options=None, args=None, executor=None,
... |
def gcs_write(self, log, remote_log_location, append=True):
"""
Writes the log to the remote_log_location. Fails silently if no hook
was created.
:param log: the log to write to the remote_log_location
:type log: str
:param remote_log_location: the log's location in remot... | Writes the log to the remote_log_location. Fails silently if no hook
was created.
:param log: the log to write to the remote_log_location
:type log: str
:param remote_log_location: the log's location in remote storage
:type remote_log_location: str (path)
:param append: i... | Below is the the instruction that describes the task:
### Input:
Writes the log to the remote_log_location. Fails silently if no hook
was created.
:param log: the log to write to the remote_log_location
:type log: str
:param remote_log_location: the log's location in remote storage
... |
def _stop(self):
""" Stops recording. Returns all recorded data and their timestamps. Destroys recorder process."""
self._pause()
self._cmds_q.put(("stop",))
try:
self._recorder.terminate()
except Exception:
pass
self._recording = False | Stops recording. Returns all recorded data and their timestamps. Destroys recorder process. | Below is the the instruction that describes the task:
### Input:
Stops recording. Returns all recorded data and their timestamps. Destroys recorder process.
### Response:
def _stop(self):
""" Stops recording. Returns all recorded data and their timestamps. Destroys recorder process."""
self._pause(... |
def start_service(addr, n):
""" Start a service """
s = Service(addr)
s.register('add', lambda x, y: x + y)
started = time.time()
for _ in range(n):
s.process()
duration = time.time() - started
time.sleep(0.1)
print('Service stats:')
util.print_stats(n, duration)
return | Start a service | Below is the the instruction that describes the task:
### Input:
Start a service
### Response:
def start_service(addr, n):
""" Start a service """
s = Service(addr)
s.register('add', lambda x, y: x + y)
started = time.time()
for _ in range(n):
s.process()
duration = time.time() - s... |
def pull(self, repository, tag=None, stream=True, **kwargs):
"""
Identical to :meth:`dockermap.client.base.DockerClientWrapper.pull` with two enhancements:
* additional logging;
* the ``insecure_registry`` flag can be passed through ``kwargs``, or set as default using
``env.do... | Identical to :meth:`dockermap.client.base.DockerClientWrapper.pull` with two enhancements:
* additional logging;
* the ``insecure_registry`` flag can be passed through ``kwargs``, or set as default using
``env.docker_registry_insecure``. | Below is the the instruction that describes the task:
### Input:
Identical to :meth:`dockermap.client.base.DockerClientWrapper.pull` with two enhancements:
* additional logging;
* the ``insecure_registry`` flag can be passed through ``kwargs``, or set as default using
``env.docker_registr... |
def nonzero_pixels(self):
""" Return an array of the nonzero pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the nonzero pixels
"""
nonzero_px = np.where(np.sum(self.raw_data, axis=2) > 0)
nonzero_px = np.c_[nonzero_px[0], nonzero_px[1]]
... | Return an array of the nonzero pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the nonzero pixels | Below is the the instruction that describes the task:
### Input:
Return an array of the nonzero pixels.
Returns
-------
:obj:`numpy.ndarray`
Nx2 array of the nonzero pixels
### Response:
def nonzero_pixels(self):
""" Return an array of the nonzero pixels.
Retu... |
def send_one_ping(self, current_socket):
"""
Send one ICMP ECHO_REQUEST.
"""
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
checksum = 0
# Make a dummy header with a 0 checksum.
header = struct.pack(
"!BBHHH", ICMP_ECHO, 0, chec... | Send one ICMP ECHO_REQUEST. | Below is the the instruction that describes the task:
### Input:
Send one ICMP ECHO_REQUEST.
### Response:
def send_one_ping(self, current_socket):
"""
Send one ICMP ECHO_REQUEST.
"""
# Header is type (8), code (8), checksum (16), id (16), sequence (16)
checksum = 0
... |
def get_or_create_media(self, api_media):
"""
Find or create a Media object given API data.
:param api_media: the API data for the Media
:return: a tuple of an Media instance and a boolean indicating whether the Media was created or not
"""
return Media.objects.get_or_cr... | Find or create a Media object given API data.
:param api_media: the API data for the Media
:return: a tuple of an Media instance and a boolean indicating whether the Media was created or not | Below is the the instruction that describes the task:
### Input:
Find or create a Media object given API data.
:param api_media: the API data for the Media
:return: a tuple of an Media instance and a boolean indicating whether the Media was created or not
### Response:
def get_or_create_media(self... |
def _set_show_mpls_rsvp(self, v, load=False):
"""
Setter method for show_mpls_rsvp, mapped from YANG variable /brocade_mpls_rpc/show_mpls_rsvp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_rsvp is considered as a private
method. Backends looking to ... | Setter method for show_mpls_rsvp, mapped from YANG variable /brocade_mpls_rpc/show_mpls_rsvp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_rsvp is considered as a private
method. Backends looking to populate this variable should
do so via calling thisOb... | Below is the the instruction that describes the task:
### Input:
Setter method for show_mpls_rsvp, mapped from YANG variable /brocade_mpls_rpc/show_mpls_rsvp (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_show_mpls_rsvp is considered as a private
method. Backends ... |
def as_command(self):
"""Creates the click command wrapping the function
"""
try:
params = self.unbound_func.__click_params__
params.reverse()
del self.unbound_func.__click_params__
except AttributeError:
params = []
help = inspect.... | Creates the click command wrapping the function | Below is the the instruction that describes the task:
### Input:
Creates the click command wrapping the function
### Response:
def as_command(self):
"""Creates the click command wrapping the function
"""
try:
params = self.unbound_func.__click_params__
params.reverse... |
def p_expression_ulnot(self, p):
'expression : LNOT expression %prec ULNOT'
p[0] = Ulnot(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | expression : LNOT expression %prec ULNOT | Below is the the instruction that describes the task:
### Input:
expression : LNOT expression %prec ULNOT
### Response:
def p_expression_ulnot(self, p):
'expression : LNOT expression %prec ULNOT'
p[0] = Ulnot(p[2], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) |
def scale_in(self, blocks=0, machines=0, strategy=None):
''' Scale in resources
'''
count = 0
instances = self.client.servers.list()
for instance in instances[0:machines]:
print("Deleting : ", instance)
instance.delete()
count += 1
ret... | Scale in resources | Below is the the instruction that describes the task:
### Input:
Scale in resources
### Response:
def scale_in(self, blocks=0, machines=0, strategy=None):
''' Scale in resources
'''
count = 0
instances = self.client.servers.list()
for instance in instances[0:machines]:
... |
def serialize(self, value, **kwargs):
"""Serialize instance to JSON
If the value is a HasProperties instance, it is serialized with
the include_class argument passed along. Otherwise, to_json is
called.
"""
kwargs.update({'include_class': kwargs.get('include_class', True... | Serialize instance to JSON
If the value is a HasProperties instance, it is serialized with
the include_class argument passed along. Otherwise, to_json is
called. | Below is the the instruction that describes the task:
### Input:
Serialize instance to JSON
If the value is a HasProperties instance, it is serialized with
the include_class argument passed along. Otherwise, to_json is
called.
### Response:
def serialize(self, value, **kwargs):
"""... |
def endure_multi(self, keys, persist_to=-1, replicate_to=-1,
timeout=5.0, interval=0.010, check_removed=False):
"""Check durability requirements for multiple keys
:param keys: The keys to check
The type of keys may be one of the following:
* Sequence of keys
... | Check durability requirements for multiple keys
:param keys: The keys to check
The type of keys may be one of the following:
* Sequence of keys
* A :class:`~couchbase.result.MultiResult` object
* A ``dict`` with CAS values as the dictionary value
* A seq... | Below is the the instruction that describes the task:
### Input:
Check durability requirements for multiple keys
:param keys: The keys to check
The type of keys may be one of the following:
* Sequence of keys
* A :class:`~couchbase.result.MultiResult` object
* A... |
def get_source_by_alias(self, alias):
"""Given an alias, find the corresponding source in this entry.
If the given alias doesn't exist (e.g. there are no sources), then a
`ValueError` is raised.
Arguments
---------
alias : str
The str-integer (e.g. '8') of t... | Given an alias, find the corresponding source in this entry.
If the given alias doesn't exist (e.g. there are no sources), then a
`ValueError` is raised.
Arguments
---------
alias : str
The str-integer (e.g. '8') of the target source.
Returns
------... | Below is the the instruction that describes the task:
### Input:
Given an alias, find the corresponding source in this entry.
If the given alias doesn't exist (e.g. there are no sources), then a
`ValueError` is raised.
Arguments
---------
alias : str
The str-int... |
def get_box_field(self, box_key, field_key = None):
'''Gets one/all field in a box
Args:
box_key key for pipeline
field_key key for field (default: None i.e. ALL)
returns status code, field dict or list thereof
'''
#does not work
self._raise_unimplemented_error()
uri = '/'.join([self.api... | Gets one/all field in a box
Args:
box_key key for pipeline
field_key key for field (default: None i.e. ALL)
returns status code, field dict or list thereof | Below is the the instruction that describes the task:
### Input:
Gets one/all field in a box
Args:
box_key key for pipeline
field_key key for field (default: None i.e. ALL)
returns status code, field dict or list thereof
### Response:
def get_box_field(self, box_key, field_key = None):
'''Gets... |
def _extract(self, raw: str, station: str) -> str: # type: ignore
"""
Extracts the reports message using string finding
"""
report = raw[raw.find(station.upper() + ' '):]
report = report[:report.find(' =')]
return report | Extracts the reports message using string finding | Below is the the instruction that describes the task:
### Input:
Extracts the reports message using string finding
### Response:
def _extract(self, raw: str, station: str) -> str: # type: ignore
"""
Extracts the reports message using string finding
"""
report = raw[raw.find(station... |
def _validate_region(self):
"""Validate region was passed in and is a valid GCE zone."""
if not self.region:
raise GCECloudException(
'Zone is required for GCE cloud framework: '
'Example: us-west1-a'
)
try:
zone = self.compute... | Validate region was passed in and is a valid GCE zone. | Below is the the instruction that describes the task:
### Input:
Validate region was passed in and is a valid GCE zone.
### Response:
def _validate_region(self):
"""Validate region was passed in and is a valid GCE zone."""
if not self.region:
raise GCECloudException(
'Zo... |
def save_xml(self, doc, element):
'''Save this configuration data into an xml.dom.Element object.'''
element.setAttributeNS(RTS_NS, RTS_NS_S + 'name', self.name)
if self.data:
element.setAttributeNS(RTS_NS, RTS_NS_S + 'data', self.data) | Save this configuration data into an xml.dom.Element object. | Below is the the instruction that describes the task:
### Input:
Save this configuration data into an xml.dom.Element object.
### Response:
def save_xml(self, doc, element):
'''Save this configuration data into an xml.dom.Element object.'''
element.setAttributeNS(RTS_NS, RTS_NS_S + 'name', self.nam... |
def add_transition_to_state(from_port, to_port):
"""Interface method between Gaphas and RAFCON core for adding transitions
The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary
parameters for the add_transition method of the RAFCON core. Also the ... | Interface method between Gaphas and RAFCON core for adding transitions
The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary
parameters for the add_transition method of the RAFCON core. Also the parent state is derived from the ports.
:param from... | Below is the the instruction that describes the task:
### Input:
Interface method between Gaphas and RAFCON core for adding transitions
The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary
parameters for the add_transition method of the RAFCON co... |
def remove_terms_by_indices(self, idx_to_delete_list):
'''
Parameters
----------
idx_to_delete_list, list
Returns
-------
TermDocMatrix
'''
new_X, new_term_idx_store = self._get_X_after_delete_terms(idx_to_delete_list)
return self._make_ne... | Parameters
----------
idx_to_delete_list, list
Returns
-------
TermDocMatrix | Below is the the instruction that describes the task:
### Input:
Parameters
----------
idx_to_delete_list, list
Returns
-------
TermDocMatrix
### Response:
def remove_terms_by_indices(self, idx_to_delete_list):
'''
Parameters
----------
idx_t... |
def get_changes_between_builds(self, project, from_build_id=None, to_build_id=None, top=None):
"""GetChangesBetweenBuilds.
[Preview API] Gets the changes made to the repository between two given builds.
:param str project: Project ID or project name
:param int from_build_id: The ID of th... | GetChangesBetweenBuilds.
[Preview API] Gets the changes made to the repository between two given builds.
:param str project: Project ID or project name
:param int from_build_id: The ID of the first build.
:param int to_build_id: The ID of the last build.
:param int top: The maxim... | Below is the the instruction that describes the task:
### Input:
GetChangesBetweenBuilds.
[Preview API] Gets the changes made to the repository between two given builds.
:param str project: Project ID or project name
:param int from_build_id: The ID of the first build.
:param int to_... |
def command(self, profile=False):
"""This is a Flask-Script like decorator, provide functionality like
@manager.command
def foo():
pass
@manager.command
def foo(first_arg, second_arg, first_option=True, second_option=3):
pass
"""
def wrape... | This is a Flask-Script like decorator, provide functionality like
@manager.command
def foo():
pass
@manager.command
def foo(first_arg, second_arg, first_option=True, second_option=3):
pass | Below is the the instruction that describes the task:
### Input:
This is a Flask-Script like decorator, provide functionality like
@manager.command
def foo():
pass
@manager.command
def foo(first_arg, second_arg, first_option=True, second_option=3):
pass
### R... |
def attach(self, canvas):
"""Attach this interact to a canvas."""
super(PanZoom, self).attach(canvas)
canvas.panzoom = self
canvas.transforms.add_on_gpu([self._translate, self._scale])
# Add the variable declarations.
vs = ('uniform vec2 {};\n'.format(self.pan_var_name) ... | Attach this interact to a canvas. | Below is the the instruction that describes the task:
### Input:
Attach this interact to a canvas.
### Response:
def attach(self, canvas):
"""Attach this interact to a canvas."""
super(PanZoom, self).attach(canvas)
canvas.panzoom = self
canvas.transforms.add_on_gpu([self._translate... |
def get_body_hash(params):
"""
Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec.
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2
"""
norm_params = get_normalized_params(params)
return binascii.b2a_base64(hashlib.sha1(norm_params).digest())[:-1] | Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec.
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2 | Below is the the instruction that describes the task:
### Input:
Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC spec.
http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-00#section-3.2
### Response:
def get_body_hash(params):
"""
Returns BASE64 ( HASH (text) ) as described in OAuth2 MAC... |
def parse_asf(source, world, jointgroup=None, density=1000, color=None):
'''Load and parse a source file.
Parameters
----------
source : file
A file-like object that contains text information describing bodies and
joints to add to the world.
world : :class:`pagoda.physics.World`
... | Load and parse a source file.
Parameters
----------
source : file
A file-like object that contains text information describing bodies and
joints to add to the world.
world : :class:`pagoda.physics.World`
The world to add objects and joints to.
jointgroup : ode.JointGroup, op... | Below is the the instruction that describes the task:
### Input:
Load and parse a source file.
Parameters
----------
source : file
A file-like object that contains text information describing bodies and
joints to add to the world.
world : :class:`pagoda.physics.World`
The wo... |
def bitwise_or(self, t):
"""
Binary operation: logical or
:param b: The other operand
:return: self | b
"""
"""
This implementation combines the approaches used by 'WYSINWYX: what you see is not what you execute'
paper and 'Signedness-Agnostic Program Ana... | Binary operation: logical or
:param b: The other operand
:return: self | b | Below is the the instruction that describes the task:
### Input:
Binary operation: logical or
:param b: The other operand
:return: self | b
### Response:
def bitwise_or(self, t):
"""
Binary operation: logical or
:param b: The other operand
:return: self | b
... |
def get_class(class_string):
"""
Get a class from a dotted string
"""
split_string = class_string.encode('ascii').split('.')
import_path = '.'.join(split_string[:-1])
class_name = split_string[-1]
if class_name:
try:
if import_path:
mod = __import__(impor... | Get a class from a dotted string | Below is the the instruction that describes the task:
### Input:
Get a class from a dotted string
### Response:
def get_class(class_string):
"""
Get a class from a dotted string
"""
split_string = class_string.encode('ascii').split('.')
import_path = '.'.join(split_string[:-1])
class_name =... |
def classifiers(self):
"""
Returns the list of base classifiers.
:return: the classifier list
:rtype: list
"""
objects = javabridge.get_env().get_object_array_elements(
javabridge.call(self.jobject, "getClassifiers", "()[Lweka/classifiers/Classifier;"))
... | Returns the list of base classifiers.
:return: the classifier list
:rtype: list | Below is the the instruction that describes the task:
### Input:
Returns the list of base classifiers.
:return: the classifier list
:rtype: list
### Response:
def classifiers(self):
"""
Returns the list of base classifiers.
:return: the classifier list
:rtype: list... |
def save(self, *args, **kwargs):
"""
Custom save method
"""
# change status to scheduled if necessary
if self.is_scheduled and self.status is not OUTWARD_STATUS.get('scheduled'):
self.status = OUTWARD_STATUS.get('scheduled')
# call super.save()
super(... | Custom save method | Below is the the instruction that describes the task:
### Input:
Custom save method
### Response:
def save(self, *args, **kwargs):
"""
Custom save method
"""
# change status to scheduled if necessary
if self.is_scheduled and self.status is not OUTWARD_STATUS.get('scheduled')... |
def update_collisions(self):
"""
Test player for collisions with items
"""
if not self.mode['items'] or len(self.mode['items']) == 0: return
# update collman
# FIXME: Why update each frame?
self.collman.clear()
for z, node in self.children:
if... | Test player for collisions with items | Below is the the instruction that describes the task:
### Input:
Test player for collisions with items
### Response:
def update_collisions(self):
"""
Test player for collisions with items
"""
if not self.mode['items'] or len(self.mode['items']) == 0: return
# update collman... |
def get_mx_records(domain):
"""
Gets an array of MXRecords associated to the domain specified.
:param domain:
:return: [MXRecord]
"""
import dns.resolver
response = dns.resolver.query(domain, 'MX')
mx_records = []
for answer in response.answers:... | Gets an array of MXRecords associated to the domain specified.
:param domain:
:return: [MXRecord] | Below is the the instruction that describes the task:
### Input:
Gets an array of MXRecords associated to the domain specified.
:param domain:
:return: [MXRecord]
### Response:
def get_mx_records(domain):
"""
Gets an array of MXRecords associated to the domain specified.
:... |
def draw(self):
"""
Draws the plot to screen.
Note to self: Do NOT call super(MatrixPlot, self).draw(); the
underlying logic for drawing here is completely different from other
plots, and as such necessitates a different implementation.
"""
matrix = nx.to_numpy_m... | Draws the plot to screen.
Note to self: Do NOT call super(MatrixPlot, self).draw(); the
underlying logic for drawing here is completely different from other
plots, and as such necessitates a different implementation. | Below is the the instruction that describes the task:
### Input:
Draws the plot to screen.
Note to self: Do NOT call super(MatrixPlot, self).draw(); the
underlying logic for drawing here is completely different from other
plots, and as such necessitates a different implementation.
### Respo... |
def decode(self, bytes, raw=False):
"""decode(bytearray, raw=False) -> value
Decodes the given bytearray and returns the number of
(fractional) seconds.
If the optional parameter ``raw`` is ``True``, the byte (U8)
itself will be returned.
"""
result = super(Tim... | decode(bytearray, raw=False) -> value
Decodes the given bytearray and returns the number of
(fractional) seconds.
If the optional parameter ``raw`` is ``True``, the byte (U8)
itself will be returned. | Below is the the instruction that describes the task:
### Input:
decode(bytearray, raw=False) -> value
Decodes the given bytearray and returns the number of
(fractional) seconds.
If the optional parameter ``raw`` is ``True``, the byte (U8)
itself will be returned.
### Response:
de... |
def register(cls, name, description, options_registrar_cls=None):
"""Register a goal description.
Otherwise the description must be set when registering some task on the goal,
which is clunky, and dependent on things like registration order of tasks in the goal.
A goal that isn't explicitly registered... | Register a goal description.
Otherwise the description must be set when registering some task on the goal,
which is clunky, and dependent on things like registration order of tasks in the goal.
A goal that isn't explicitly registered with a description will fall back to the description
of the task in ... | Below is the the instruction that describes the task:
### Input:
Register a goal description.
Otherwise the description must be set when registering some task on the goal,
which is clunky, and dependent on things like registration order of tasks in the goal.
A goal that isn't explicitly registered wit... |
def loadRecord(self, domain, rtype, callback=None, errback=None):
"""
Load a high level Record object from a domain within this Zone.
:param str domain: The name of the record to load
:param str rtype: The DNS record type
:rtype: ns1.records.Record
:return: new Record
... | Load a high level Record object from a domain within this Zone.
:param str domain: The name of the record to load
:param str rtype: The DNS record type
:rtype: ns1.records.Record
:return: new Record | Below is the the instruction that describes the task:
### Input:
Load a high level Record object from a domain within this Zone.
:param str domain: The name of the record to load
:param str rtype: The DNS record type
:rtype: ns1.records.Record
:return: new Record
### Response:
def ... |
def p_always_comb(self, p):
'always_comb : ALWAYS_COMB senslist always_statement'
p[0] = AlwaysComb(p[2], p[3], lineno=p.lineno(1)) | always_comb : ALWAYS_COMB senslist always_statement | Below is the the instruction that describes the task:
### Input:
always_comb : ALWAYS_COMB senslist always_statement
### Response:
def p_always_comb(self, p):
'always_comb : ALWAYS_COMB senslist always_statement'
p[0] = AlwaysComb(p[2], p[3], lineno=p.lineno(1)) |
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
continue
try:
validated[key] = value_schema(value)
except NotValid:
continue
... | Validate a key's value by type. | Below is the the instruction that describes the task:
### Input:
Validate a key's value by type.
### Response:
def _validate_type_key(key, value, types, validated):
"""Validate a key's value by type."""
for key_schema, value_schema in types.items():
if not isinstance(key, key_schema):
c... |
def load_contents(self):
"""
Loads contents of the tables into database.
"""
with open(METADATA_FILE) as f:
lines = f.readlines()
lines = map(lambda x: x.strip(), lines)
exclude_strings = ['<begin_table>', '<end_table>']
list_of_databases_and_co... | Loads contents of the tables into database. | Below is the the instruction that describes the task:
### Input:
Loads contents of the tables into database.
### Response:
def load_contents(self):
"""
Loads contents of the tables into database.
"""
with open(METADATA_FILE) as f:
lines = f.readlines()
lines... |
def run_queries(self, backfill_num_days=7):
"""
Run the data queries for the specified projects.
:param backfill_num_days: number of days of historical data to backfill,
if missing
:type backfill_num_days: int
"""
available_tables = self._get_download_table_ids... | Run the data queries for the specified projects.
:param backfill_num_days: number of days of historical data to backfill,
if missing
:type backfill_num_days: int | Below is the the instruction that describes the task:
### Input:
Run the data queries for the specified projects.
:param backfill_num_days: number of days of historical data to backfill,
if missing
:type backfill_num_days: int
### Response:
def run_queries(self, backfill_num_days=7):
... |
def validate_url(self, url):
"""Validate the :class:`~urllib.parse.ParseResult` object.
This method will make sure the :meth:`~brownant.app.BrownAnt.parse_url`
could work as expected even meet a unexpected URL string.
:param url: the parsed url.
:type url: :class:`~urllib.parse... | Validate the :class:`~urllib.parse.ParseResult` object.
This method will make sure the :meth:`~brownant.app.BrownAnt.parse_url`
could work as expected even meet a unexpected URL string.
:param url: the parsed url.
:type url: :class:`~urllib.parse.ParseResult` | Below is the the instruction that describes the task:
### Input:
Validate the :class:`~urllib.parse.ParseResult` object.
This method will make sure the :meth:`~brownant.app.BrownAnt.parse_url`
could work as expected even meet a unexpected URL string.
:param url: the parsed url.
:ty... |
def dehydrate(self, iterator):
"""
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet.
"""
for line in iterator:
try:
yield json.loads(line)['id_str']
except Exception as e:
log.error("uhoh... | Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet. | Below is the the instruction that describes the task:
### Input:
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tweet.
### Response:
def dehydrate(self, iterator):
"""
Pass in an iterator of tweets' JSON and get back an iterator of the
IDs of each tw... |
def pwa(self, val, wa='WARN'):
""" Print val: WARN in yellow on STDOUT """
self.pstd(self.color.yellow('{}: {}'.format(val, wa))) | Print val: WARN in yellow on STDOUT | Below is the the instruction that describes the task:
### Input:
Print val: WARN in yellow on STDOUT
### Response:
def pwa(self, val, wa='WARN'):
""" Print val: WARN in yellow on STDOUT """
self.pstd(self.color.yellow('{}: {}'.format(val, wa))) |
def fastp_read_gc_plot(self):
""" Make the read GC plot for Fastp """
data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_gc_content_data, 'Base Content Percent')
pconfig = {
'id': 'fastp-seq-content-gc-plot',
'title': 'Fastp: Read GC Content',
... | Make the read GC plot for Fastp | Below is the the instruction that describes the task:
### Input:
Make the read GC plot for Fastp
### Response:
def fastp_read_gc_plot(self):
""" Make the read GC plot for Fastp """
data_labels, pdata = self.filter_pconfig_pdata_subplots(self.fastp_gc_content_data, 'Base Content Percent')
pc... |
def remove_tier(self, id_tier, clean=True):
"""Remove a tier.
:param str id_tier: Name of the tier.
:param bool clean: Flag to also clean the timeslots.
:raises KeyError: If tier is non existent.
"""
del(self.tiers[id_tier])
if clean:
self.clean_time_... | Remove a tier.
:param str id_tier: Name of the tier.
:param bool clean: Flag to also clean the timeslots.
:raises KeyError: If tier is non existent. | Below is the the instruction that describes the task:
### Input:
Remove a tier.
:param str id_tier: Name of the tier.
:param bool clean: Flag to also clean the timeslots.
:raises KeyError: If tier is non existent.
### Response:
def remove_tier(self, id_tier, clean=True):
"""Remove ... |
def setStartAction(self, action, *args, **kwargs):
"""
Set a function to call when run() is called, before the main action is called.
Parameters
----------
action: function pointer
The function to call.
*args
Positional arguments to pass to action.
**kwargs:
Keyword arguments to pass to action.
... | Set a function to call when run() is called, before the main action is called.
Parameters
----------
action: function pointer
The function to call.
*args
Positional arguments to pass to action.
**kwargs:
Keyword arguments to pass to action. | Below is the the instruction that describes the task:
### Input:
Set a function to call when run() is called, before the main action is called.
Parameters
----------
action: function pointer
The function to call.
*args
Positional arguments to pass to action.
**kwargs:
Keyword arguments to pass t... |
def _build_toctree(self):
"""Create a hidden toctree node with the contents of a directory
prefixed by the directory name specified by the `toctree` directive
option.
"""
dirname = posixpath.dirname(self._env.docname)
tree_prefix = self.options['toctree'].strip()
... | Create a hidden toctree node with the contents of a directory
prefixed by the directory name specified by the `toctree` directive
option. | Below is the the instruction that describes the task:
### Input:
Create a hidden toctree node with the contents of a directory
prefixed by the directory name specified by the `toctree` directive
option.
### Response:
def _build_toctree(self):
"""Create a hidden toctree node with the content... |
def stdformD(D, Cd, M, dimN=2):
"""Reshape dictionary array (`D` in :mod:`.admm.cbpdn` module, `X` in
:mod:`.admm.ccmod` module) to internal standard form.
Parameters
----------
D : array_like
Dictionary array
Cd : int
Size of dictionary channel index
M : int
Number of fil... | Reshape dictionary array (`D` in :mod:`.admm.cbpdn` module, `X` in
:mod:`.admm.ccmod` module) to internal standard form.
Parameters
----------
D : array_like
Dictionary array
Cd : int
Size of dictionary channel index
M : int
Number of filters in dictionary
dimN : int, opti... | Below is the the instruction that describes the task:
### Input:
Reshape dictionary array (`D` in :mod:`.admm.cbpdn` module, `X` in
:mod:`.admm.ccmod` module) to internal standard form.
Parameters
----------
D : array_like
Dictionary array
Cd : int
Size of dictionary channel index
... |
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
"""
name = name.upper()
if name in ISO_LANGUAGE_CODES:
name = ISO_LANGUAGE_CODES[name]
if name in ISO_MAJOR_LANGUAGE_TYPES:
namespace = '639-2'
... | Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type | Below is the the instruction that describes the task:
### Input:
Return dictionary representation of type.
Can be used to initialize primordium.type.primitives.Type
### Response:
def get_type_data(name):
"""Return dictionary representation of type.
Can be used to initialize primordium.type.primitives... |
def _extract_transform_colander_schema(self, args):
"""
Extract schema from view args and transform it using
the pipeline of schema transformers
:param args:
Arguments from the view decorator.
:rtype: colander.MappingSchema()
:returns: View schema cloned and... | Extract schema from view args and transform it using
the pipeline of schema transformers
:param args:
Arguments from the view decorator.
:rtype: colander.MappingSchema()
:returns: View schema cloned and transformed | Below is the the instruction that describes the task:
### Input:
Extract schema from view args and transform it using
the pipeline of schema transformers
:param args:
Arguments from the view decorator.
:rtype: colander.MappingSchema()
:returns: View schema cloned and tr... |
def _make_minimal(dictionary):
"""
This function removes all the keys whose value is either None or an empty
dictionary.
"""
new_dict = {}
for key, value in dictionary.items():
if value is not None:
if isinstance(value, dict):
new_value = _make_minimal(value)
... | This function removes all the keys whose value is either None or an empty
dictionary. | Below is the the instruction that describes the task:
### Input:
This function removes all the keys whose value is either None or an empty
dictionary.
### Response:
def _make_minimal(dictionary):
"""
This function removes all the keys whose value is either None or an empty
dictionary.
"""
n... |
def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]:
"""
Return a dict containing the IPFS hash, file name, and size of a file.
"""
if file_or_dir_path.is_dir():
asset_data = [dummy_ipfs_pin(path) for path in file_or_dir_path.glob("*")]
elif file_or_d... | Return a dict containing the IPFS hash, file name, and size of a file. | Below is the the instruction that describes the task:
### Input:
Return a dict containing the IPFS hash, file name, and size of a file.
### Response:
def pin_assets(self, file_or_dir_path: Path) -> List[Dict[str, str]]:
"""
Return a dict containing the IPFS hash, file name, and size of a file.
... |
def send_sysex(self, sysex_cmd, data):
"""
Sends a SysEx msg.
:arg sysex_cmd: A sysex command byte
: arg data: a bytearray of 7-bit bytes of arbitrary data
"""
msg = bytearray([START_SYSEX, sysex_cmd])
msg.extend(data)
msg.append(END_SYSEX)
self.s... | Sends a SysEx msg.
:arg sysex_cmd: A sysex command byte
: arg data: a bytearray of 7-bit bytes of arbitrary data | Below is the the instruction that describes the task:
### Input:
Sends a SysEx msg.
:arg sysex_cmd: A sysex command byte
: arg data: a bytearray of 7-bit bytes of arbitrary data
### Response:
def send_sysex(self, sysex_cmd, data):
"""
Sends a SysEx msg.
:arg sysex_cmd: A s... |
def _generate_section(self, name, config, cfg_section='default', remove_sasbase=False):
"""Generate the relevant Sphinx nodes.
Generates a section for the Tree datamodel. Formats a tree section
as a list-table directive.
Parameters:
name (str):
The name of ... | Generate the relevant Sphinx nodes.
Generates a section for the Tree datamodel. Formats a tree section
as a list-table directive.
Parameters:
name (str):
The name of the config to be documented, e.g. 'sdsswork'
config (dict):
The tree di... | Below is the the instruction that describes the task:
### Input:
Generate the relevant Sphinx nodes.
Generates a section for the Tree datamodel. Formats a tree section
as a list-table directive.
Parameters:
name (str):
The name of the config to be documented, e... |
def bare_except(logical_line, noqa):
r"""When catching exceptions, mention specific exceptions whenever possible.
Okay: except Exception:
Okay: except BaseException:
E722: except:
"""
if noqa:
return
regex = re.compile(r"except\s*:")
match = regex.match(logical_line)
if mat... | r"""When catching exceptions, mention specific exceptions whenever possible.
Okay: except Exception:
Okay: except BaseException:
E722: except: | Below is the the instruction that describes the task:
### Input:
r"""When catching exceptions, mention specific exceptions whenever possible.
Okay: except Exception:
Okay: except BaseException:
E722: except:
### Response:
def bare_except(logical_line, noqa):
r"""When catching exceptions, mention s... |
def remove_child_catalog(self, catalog_id, child_id):
"""Removes a child from a catalog.
arg: catalog_id (osid.id.Id): the ``Id`` of a catalog
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: NotFound - ``catalog_id`` is not a parent of
``child_id``
... | Removes a child from a catalog.
arg: catalog_id (osid.id.Id): the ``Id`` of a catalog
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: NotFound - ``catalog_id`` is not a parent of
``child_id``
raise: NullArgument - ``catalog_id`` or ``child_id`` is
... | Below is the the instruction that describes the task:
### Input:
Removes a child from a catalog.
arg: catalog_id (osid.id.Id): the ``Id`` of a catalog
arg: child_id (osid.id.Id): the ``Id`` of the new child
raise: NotFound - ``catalog_id`` is not a parent of
``child_i... |
def put_policy(Bucket, Policy,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
... | Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_policy my_bucket {...} | Below is the the instruction that describes the task:
### Input:
Given a valid config, update the policy for a bucket.
Returns {updated: true} if policy was updated and returns
{updated: False} if policy was not updated.
CLI Example:
.. code-block:: bash
salt myminion boto_s3_bucket.put_... |
def find_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
'''
Finds a view function, class-based view, or template view.
Raises ViewDoesNotExist if not found.
'''
dmp = apps.get_app_config('django_mako_plus')
# I'm first calling find_s... | Finds a view function, class-based view, or template view.
Raises ViewDoesNotExist if not found. | Below is the the instruction that describes the task:
### Input:
Finds a view function, class-based view, or template view.
Raises ViewDoesNotExist if not found.
### Response:
def find_view_function(module_name, function_name, fallback_app=None, fallback_template=None, verify_decorator=True):
'''
Finds... |
def get_memory_maps(self):
"""Return process's mapped memory regions as a list of nameduples.
Fields are explained in 'man proc'; here is an updated (Apr 2012)
version: http://goo.gl/fmebo
"""
f = None
try:
f = open("/proc/%s/smaps" % self.pid)
fir... | Return process's mapped memory regions as a list of nameduples.
Fields are explained in 'man proc'; here is an updated (Apr 2012)
version: http://goo.gl/fmebo | Below is the the instruction that describes the task:
### Input:
Return process's mapped memory regions as a list of nameduples.
Fields are explained in 'man proc'; here is an updated (Apr 2012)
version: http://goo.gl/fmebo
### Response:
def get_memory_maps(self):
"""Return process's mapped... |
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if public_key_filename is not None:
public_key_filename = os.path.expanduser(public_key_... | Load the public key file if exists. | Below is the the instruction that describes the task:
### Input:
Load the public key file if exists.
### Response:
def load_public_key(vm_):
'''
Load the public key file if exists.
'''
public_key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False,... |
def infer_reference_name(reference_name_or_path):
"""
Given a string containing a reference name (such as a path to
that reference's FASTA file), return its canonical name
as used by Ensembl.
"""
# identify all cases where reference name or path matches candidate aliases
reference_file_name ... | Given a string containing a reference name (such as a path to
that reference's FASTA file), return its canonical name
as used by Ensembl. | Below is the the instruction that describes the task:
### Input:
Given a string containing a reference name (such as a path to
that reference's FASTA file), return its canonical name
as used by Ensembl.
### Response:
def infer_reference_name(reference_name_or_path):
"""
Given a string containing a ... |
def create_country(cls, country, **kwargs):
"""Create Country
Create a new Country
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_country(country, async=True)
>>> result = thre... | Create Country
Create a new Country
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_country(country, async=True)
>>> result = thread.get()
:param async bool
:param Coun... | Below is the the instruction that describes the task:
### Input:
Create Country
Create a new Country
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_country(country, async=True)
>>>... |
def add_function(self, function):
"""
Registers the function to the server's default fixed function manager.
"""
#noinspection PyTypeChecker
if not len(self.settings.FUNCTION_MANAGERS):
raise ConfigurationError(
'Where have the default function manager... | Registers the function to the server's default fixed function manager. | Below is the the instruction that describes the task:
### Input:
Registers the function to the server's default fixed function manager.
### Response:
def add_function(self, function):
"""
Registers the function to the server's default fixed function manager.
"""
#noinspection PyType... |
def K2findCampaigns_byname_main(args=None):
"""Exposes K2findCampaigns to the command line."""
parser = argparse.ArgumentParser(
description="Check if a target is "
"(or was) observable by any past or future "
"observing campaig... | Exposes K2findCampaigns to the command line. | Below is the the instruction that describes the task:
### Input:
Exposes K2findCampaigns to the command line.
### Response:
def K2findCampaigns_byname_main(args=None):
"""Exposes K2findCampaigns to the command line."""
parser = argparse.ArgumentParser(
description="Check if a target is ... |
def _ParseFValue(self, registry_key):
"""Parses an F value.
Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
Returns:
f_value: F value stored in the Windows Registry key.
Raises:
ParseError: if the Windows Registry key does not contain an F value or
F va... | Parses an F value.
Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
Returns:
f_value: F value stored in the Windows Registry key.
Raises:
ParseError: if the Windows Registry key does not contain an F value or
F value cannot be parsed. | Below is the the instruction that describes the task:
### Input:
Parses an F value.
Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
Returns:
f_value: F value stored in the Windows Registry key.
Raises:
ParseError: if the Windows Registry key does not contain an F... |
def base64_user_pass(self):
"""
Composes a basic http auth string, suitable for use with the
_replicator database, and other places that need it.
:returns: Basic http authentication string
"""
if self._username is None or self._password is None:
return None
... | Composes a basic http auth string, suitable for use with the
_replicator database, and other places that need it.
:returns: Basic http authentication string | Below is the the instruction that describes the task:
### Input:
Composes a basic http auth string, suitable for use with the
_replicator database, and other places that need it.
:returns: Basic http authentication string
### Response:
def base64_user_pass(self):
"""
Composes a bas... |
def enumeration_ask(X, e, bn):
"""Return the conditional probability distribution of variable X
given evidence e, from BayesNet bn. [Fig. 14.9]
>>> enumeration_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary
... ).show_approx()
'False: 0.716, True: 0.284'"""
assert X not in e, "Query v... | Return the conditional probability distribution of variable X
given evidence e, from BayesNet bn. [Fig. 14.9]
>>> enumeration_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary
... ).show_approx()
'False: 0.716, True: 0.284 | Below is the the instruction that describes the task:
### Input:
Return the conditional probability distribution of variable X
given evidence e, from BayesNet bn. [Fig. 14.9]
>>> enumeration_ask('Burglary', dict(JohnCalls=T, MaryCalls=T), burglary
... ).show_approx()
'False: 0.716, True: 0.284
### ... |
def Morsi_Alexander(Re):
r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_ as described in [2]_.
.. math::
C_D = \left\{ \begin{array}{ll}
\frac{24}{Re} & \mbox{if $Re < 0.1$}\\
\frac{22.73}{Re}+\frac{0.0903}{Re^2} + 3.69 & \mbox{if $0.1 < Re < 1$}\\
... | r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_ as described in [2]_.
.. math::
C_D = \left\{ \begin{array}{ll}
\frac{24}{Re} & \mbox{if $Re < 0.1$}\\
\frac{22.73}{Re}+\frac{0.0903}{Re^2} + 3.69 & \mbox{if $0.1 < Re < 1$}\\
\frac{29.1667}{Re}-\frac{3.... | Below is the the instruction that describes the task:
### Input:
r'''Calculates drag coefficient of a smooth sphere using the method in
[1]_ as described in [2]_.
.. math::
C_D = \left\{ \begin{array}{ll}
\frac{24}{Re} & \mbox{if $Re < 0.1$}\\
\frac{22.73}{Re}+\frac{0.0903}{Re^2} + ... |
def diffs_prof(step):
"""Scaled diffusion.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the diffusion and the radial position
at ... | Scaled diffusion.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the diffusion and the radial position
at which it is evaluated. | Below is the the instruction that describes the task:
### Input:
Scaled diffusion.
This computation takes sphericity into account if necessary.
Args:
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
Returns:
tuple of :class:`numpy.array`: the diffu... |
def delete(self, synchronous=True):
"""Delete the current entity.
Call :meth:`delete_raw` and check for an HTTP 4XX or 5XX response.
Return either the JSON-decoded response or information about a
completed foreman task.
:param synchronous: A boolean. What should happen if the s... | Delete the current entity.
Call :meth:`delete_raw` and check for an HTTP 4XX or 5XX response.
Return either the JSON-decoded response or information about a
completed foreman task.
:param synchronous: A boolean. What should happen if the server returns
an HTTP 202 (accepted... | Below is the the instruction that describes the task:
### Input:
Delete the current entity.
Call :meth:`delete_raw` and check for an HTTP 4XX or 5XX response.
Return either the JSON-decoded response or information about a
completed foreman task.
:param synchronous: A boolean. What ... |
def get_month_start_date(self):
"""Returns the first day of the current month"""
now = timezone.now()
return timezone.datetime(day=1, month=now.month, year=now.year, tzinfo=now.tzinfo) | Returns the first day of the current month | Below is the the instruction that describes the task:
### Input:
Returns the first day of the current month
### Response:
def get_month_start_date(self):
"""Returns the first day of the current month"""
now = timezone.now()
return timezone.datetime(day=1, month=now.month, year=now.year, tzi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.