Unnamed: 0.1 int64 0 499 | Unnamed: 0 int64 136 24.3k | code stringlengths 85 19.1k | docstring stringlengths 8 20.3k | prompt stringlengths 264 39.5k |
|---|---|---|---|---|
0 | 22,453 | def collect(self):
with SCCallSiteSync(self.context) as css:
sock_info = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
return list(_load_from_socket(sock_info, self._jrdd_deserializer)) | Return a list that contains all of the elements in this RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return a list that contains all of the elements in this RDD.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is load... |
1 | 1,603 | def load_configuration(yaml: yaml.ruamel.yaml.YAML, filename: str) -> DictLike:
with open(filename, "r") as f:
config = yaml.load(f)
return config | Load an analysis configuration from a file.
Args:
yaml: YAML object to use in loading the configuration.
filename: Filename of the YAML configuration file.
Returns:
dict-like object containing the loaded configuration | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Load an analysis configuration from a file.
Args:
yaml: YAML object to use in loading the configuration.
filename: Filename of the YAML configuration file.
Returns:
... |
2 | 11,441 | def _get_view_name(self, request):
method = request.method.lower()
try:
attributes = getattr(self, method)
view_name = type(attributes.__self__).__module__ + + type(attributes.__self__).__name__
return view_name
except AttributeError:
ret... | Get view name. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Get view name.
### Output:
def _get_view_name(self, request):
method = request.method.lower()
try:
attributes = getattr(self, method)
view_name =... |
3 | 16,982 | def random_sample(obj, n_samples, seed=None):
import ROOT
if n_samples <= 0:
raise ValueError("n_samples must be greater than 0")
if seed is not None:
if seed < 0:
raise ValueError("seed must be positive or 0")
ROOT.gRandom.SetSeed(seed)
if isinstance(obj, R... | Create a random array by sampling a ROOT function or histogram.
Parameters
----------
obj : TH[1|2|3] or TF[1|2|3]
The ROOT function or histogram to sample.
n_samples : positive int
The number of random samples to generate.
seed : None, positive int or 0, optional (default=None)
... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Create a random array by sampling a ROOT function or histogram.
Parameters
----------
obj : TH[1|2|3] or TF[1|2|3]
The ROOT function or histogram to sample.
n_samples : p... |
4 | 21,082 | def getitem(source, index):
if isinstance(index, builtins.slice):
return slice.raw(source, index.start, index.stop, index.step)
if isinstance(index, int):
return item.raw(source, index)
raise TypeError("Not a valid index (int or slice)") | Forward one or several items from an asynchronous sequence.
The argument can either be a slice or an integer.
See the slice and item operators for more information. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Forward one or several items from an asynchronous sequence.
The argument can either be a slice or an integer.
See the slice and item operators for more information.
### Output:
def geti... |
5 | 6,045 | def _get_user_data(self):
key = ipa_utils.generate_public_ssh_key(
self.ssh_private_key_file
).decode()
script = BASH_SSH_SCRIPT.format(user=self.ssh_user, key=key)
return script | Return formatted bash script string.
The public ssh key is added by cloud init to the instance based on
the ssh user and private key file. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return formatted bash script string.
The public ssh key is added by cloud init to the instance based on
the ssh user and private key file.
### Output:
def _get_user_data(self):
... |
6 | 7,316 | def cli_command_restart(self, msg):
info =
if self.state == State.RUNNING and self.sprocess and self.sprocess.proc:
self.state = State.RESTARTING
self.sprocess.set_exit_callback(self.proc_exit_cb_restart)
self.sprocess.proc.kill()
info =
... | \
restart the subprocess
i. we set our state to RESTARTING - on restarting we still send heartbeat
ii. we kill the subprocess
iii. we start again
iv. if its started we set our state to RUNNING, else we set it to WAITING
:param msg:
:return: | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
\
restart the subprocess
i. we set our state to RESTARTING - on restarting we still send heartbeat
ii. we kill the subprocess
iii. we start again
iv. if it... |
7 | 21,301 | def server_systems(self):
response = self._post(self.apiurl + "/v2/server/systems", data={: self.apikey})
return self._raise_or_extract(response) | Retrieve a list of available systems. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Retrieve a list of available systems.
### Output:
def server_systems(self):
response = self._post(self.apiurl + "/v2/server/systems", data={: self.apikey})
return self.... |
8 | 9,750 | def precesion(date):
zeta, theta, z = np.deg2rad(_precesion(date))
return rot3(zeta) @ rot2(-theta) @ rot3(z) | Precession as a rotation matrix | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Precession as a rotation matrix
### Output:
def precesion(date):
zeta, theta, z = np.deg2rad(_precesion(date))
return rot3(zeta) @ rot2(-theta) @ rot3(z) |
9 | 17,359 | def prompt_for_trilateral_choice(self, prompt, option1, option2, option3):
if prompt is None:
prompt =
prompt = prompt.rstrip() + + option1 + + option2 + + option3 +
while True:
user_input = self.__screen.input(prompt)
if str(user_input).lower() ... | Prompt the user for a response that must be one of the three supplied choices.
NOTE: The user input verification is case-insensitive, but will return the original case provided
by the given options. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Prompt the user for a response that must be one of the three supplied choices.
NOTE: The user input verification is case-insensitive, but will return the original case provided
by... |
10 | 23,570 | def fit(self, y):
event, time = check_y_survival(y, allow_all_censored=True)
unique_time, prob = kaplan_meier_estimator(event, time)
self.unique_time_ = numpy.concatenate(([-numpy.infty], unique_time))
self.prob_ = numpy.concatenate(([1.], prob))
return self | Estimate survival distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary event indicator
as first field, and time of event or time of censoring as
second field.
Retur... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Estimate survival distribution from training data.
Parameters
----------
y : structured array, shape = (n_samples,)
A structured array containing the binary e... |
11 | 7,013 | def deflate(self, value):
if not isinstance(value, NeomodelPoint):
raise TypeError(.format(type(value)))
if not value.crs == self._crs:
raise ValueError(
.format(self._crs, value.crs))
if value.crs == :... | Handles the marshalling from NeomodelPoint to Neo4J POINT
:param value: The point that was assigned as value to a property in the model
:type value: NeomodelPoint
:return: Neo4J POINT | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Handles the marshalling from NeomodelPoint to Neo4J POINT
:param value: The point that was assigned as value to a property in the model
:type value: NeomodelPoint
:return... |
12 | 19,592 | def saveProfile(self, settings=None):
self._updateNonDefaultsForInspector(self.inspectorRegItem, self.inspector)
if settings is None:
settings = QtCore.QSettings()
logger.debug("Writing settings to: {}".format(settings.group()))
settings.beginGroup()
try:
... | Writes the view settings to the persistent store | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Writes the view settings to the persistent store
### Output:
def saveProfile(self, settings=None):
self._updateNonDefaultsForInspector(self.inspectorRegItem, self.inspector)
... |
13 | 8,312 | def do_put(self, from_path, to_path):
from_file = open(os.path.expanduser(from_path), "rb")
self.n.put(self.current_path + "/" + from_path, to_path) | Copy local file to Ndrive
Examples:
Ndrive> put ~/test.txt ndrive-copy-test.txt | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Copy local file to Ndrive
Examples:
Ndrive> put ~/test.txt ndrive-copy-test.txt
### Output:
def do_put(self, from_path, to_path):
from_file = open(os.path.exp... |
14 | 10,164 | def snapshot_id_to_name(name, snap_id, strict=False, runas=None):
*
name = salt.utils.data.decode(name)
if not re.match(GUID_REGEX, snap_id):
raise SaltInvocationError(
.format(salt.utils.data.decode(snap_id))
)
info = prlctl(, [name, , snap_id], runas=runas)
... | Attempt to convert a snapshot ID to a snapshot name. If the snapshot has
no name or if the ID is not found or invalid, an empty string will be returned
:param str name:
Name/ID of VM whose snapshots are inspected
:param str snap_id:
ID of the snapshot
:param bool strict:
Rais... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Attempt to convert a snapshot ID to a snapshot name. If the snapshot has
no name or if the ID is not found or invalid, an empty string will be returned
:param str name:
Name/ID ... |
15 | 16,912 | def session_expired(self):
if not self._login_time or (datetime.datetime.now()-self._login_time).total_seconds() > 12000:
return True | Returns True if login_time not set or seconds since
login time is greater than 200 mins. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Returns True if login_time not set or seconds since
login time is greater than 200 mins.
### Output:
def session_expired(self):
if not self._login_time or (datetime.date... |
16 | 10,250 | def grab_checksums_file(entry):
http_url = convert_ftp_url(entry[])
full_url = .format(http_url)
req = requests.get(full_url)
return req.text | Grab the checksum file for a given entry. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Grab the checksum file for a given entry.
### Output:
def grab_checksums_file(entry):
http_url = convert_ftp_url(entry[])
full_url = .format(http_url)
req = requests.get(full_ur... |
17 | 20,535 | def delete_file(self, id):
path = {}
data = {}
params = {}
path["id"] = id
self.logger.debug("DELETE /api/v1/files/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_... | Delete file.
Remove the specified file
curl -XDELETE 'https://<canvas>/api/v1/files/<file_id>' \
-H 'Authorization: Bearer <token>' | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Delete file.
Remove the specified file
curl -XDELETE 'https://<canvas>/api/v1/files/<file_id>' \
-H 'Authorization: Bearer <token>'
### Output:
de... |
18 | 2,676 | def tofile(self, f):
f.write(pack(self.FILE_FMT, self.error_rate, self.num_slices,
self.bits_per_slice, self.capacity, self.count))
(f.write(self.bitarray.tobytes()) if is_string_io(f)
else self.bitarray.tofile(f)) | Write the bloom filter to file object `f'. Underlying bits
are written as machine values. This is much more space
efficient than pickling the object. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Write the bloom filter to file object `f'. Underlying bits
are written as machine values. This is much more space
efficient than pickling the object.
### Output:
def tofile(self,... |
19 | 22,209 | def validate_target(func, *args, **kwargs):
def inner(self, *args, **kwargs):
target_id = None
if in kwargs and kwargs[] != None:
target_id = kwargs[]
else:
target_id = 0
if not self.target_is_valid(target_id):
raise NoSuch... | A decorator that ensures that the specified target_id exists and
is valid.
Expects the target ID to be either the 'target_id' param in kwargs,
or the first positional parameter.
Raises a NoSuchTargetException if the target does not exist. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
A decorator that ensures that the specified target_id exists and
is valid.
Expects the target ID to be either the 'target_id' param in kwargs,
or the first positional parameter.
... |
20 | 20,048 | def wrap_json_body(func=None, *, preserve_raw_body=False):
if func is None:
return functools.partial(
wrap_json_body,
preserve_raw_body=preserve_raw_body
)
@functools.wraps(func)
def wrapper(request, *args, **kwargs):
ctype, pdict = parse_header(request... | A middleware that parses the body of json requests and
add it to the request under the `body` attribute (replacing
the previous value). Can preserve the original value in
a new attribute `raw_body` if you give preserve_raw_body=True. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
A middleware that parses the body of json requests and
add it to the request under the `body` attribute (replacing
the previous value). Can preserve the original value in
a new attrib... |
21 | 23,057 | def on_go(self, target):
if not target:
Log.error("expecting target")
with self.lock:
if not self._go:
DEBUG and self._name and Log.note("Adding target to signal {{name|quote}}", name=self.name)
if not self.job_queue:
... | RUN target WHEN SIGNALED | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
RUN target WHEN SIGNALED
### Output:
def on_go(self, target):
if not target:
Log.error("expecting target")
with self.lock:
if not self._go:
... |
22 | 22,158 | def pip_version(self):
if not self._pip_exists:
return None
if not hasattr(self, ):
return self._pip_version | Version of installed pip. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Version of installed pip.
### Output:
def pip_version(self):
if not self._pip_exists:
return None
if not hasattr(self, ):
return self._p... |
23 | 1,764 | def get_domain_info(self, domain):
url = self.API_TEMPLATE + self.DOMAIN_INFO.format(domain=domain)
return self._get_json_from_response(url) | Get the GoDaddy supplied information about a specific domain.
:param domain: The domain to obtain info about.
:type domain: str
:return A JSON string representing the domain information | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Get the GoDaddy supplied information about a specific domain.
:param domain: The domain to obtain info about.
:type domain: str
:return A JSON string representing the do... |
24 | 18,456 | def log(logger=None, start_message=, end_message=):
def actual_log(f, real_logger=logger):
logger = real_logger or _logger
@wraps(f)
def timed(*args, **kwargs):
logger.info(f)
start = time.time()
res = f(*args, **kwargs)
end = time.time()... | Basic log decorator
Can be used as :
- @log (with default logger)
- @log(mylogger)
- @log(start_message='Hello !", logger=mylogger, end_message='Bye !') | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Basic log decorator
Can be used as :
- @log (with default logger)
- @log(mylogger)
- @log(start_message='Hello !", logger=mylogger, end_message='Bye !')
### Output:
def log(logge... |
25 | 1,040 | async def props_del(self):
endpoint = "{bucket}/props".format(bucket=self.path)
try:
async with self._client.delete(endpoint,
headers=self.headers) as r:
if r.status != 204:
raise Error("Bucket {} not fo... | Fix me after support 204 code in aiohttp | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Fix me after support 204 code in aiohttp
### Output:
async def props_del(self):
endpoint = "{bucket}/props".format(bucket=self.path)
try:
async with self._c... |
26 | 8,236 | def measure_topology(script):
filter_xml =
util.write_filter(script, filter_xml)
if isinstance(script, mlx.FilterScript):
script.parse_topology = True
return None | Compute a set of topological measures over a mesh
Args:
script: the mlx.FilterScript object or script filename to write
the filter to.
Layer stack:
No impacts
MeshLab versions:
2016.12
1.3.4BETA | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Compute a set of topological measures over a mesh
Args:
script: the mlx.FilterScript object or script filename to write
the filter to.
Layer stack:
No impact... |
27 | 4,708 | def get_network_by_full_name(self, si, default_network_full_name):
path, name = get_path_and_name(default_network_full_name)
return self.find_network_by_name(si, path, name) if name else None | Find network by a Full Name
:param default_network_full_name: <str> Full Network Name - likes 'Root/Folder/Network'
:return: | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Find network by a Full Name
:param default_network_full_name: <str> Full Network Name - likes 'Root/Folder/Network'
:return:
### Output:
def get_network_by_full_name(self, si, de... |
28 | 10,837 | def Run(self, args):
if args.length > constants.CLIENT_MAX_BUFFER_SIZE:
raise RuntimeError("Can not read buffers this large.")
data = vfs.ReadVFS(args.pathspec, args.offset, args.length)
digest = hashlib.sha256(data).digest()
self.SendReply(
rdf_client.BufferReferenc... | Reads a buffer on the client and sends it to the server. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Reads a buffer on the client and sends it to the server.
### Output:
def Run(self, args):
if args.length > constants.CLIENT_MAX_BUFFER_SIZE:
raise RuntimeError("Can not read ... |
29 | 20,372 | def statistics(self):
try:
return self._local.statistics
except AttributeError:
self._local.statistics = {}
return self._local.statistics | Return a dictionary of runtime statistics.
This dictionary will be empty when the controller has never been
ran. When it is running or has ran previously it should have (but
may not) have useful and/or informational keys and values when
running is underway and/or completed.
.. ... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return a dictionary of runtime statistics.
This dictionary will be empty when the controller has never been
ran. When it is running or has ran previously it should have (but
... |
30 | 21,592 | def build_static(self):
if not os.path.isdir(self.build_static_dir):
os.makedirs(self.build_static_dir)
copy_tree(self.static_dir, self.build_static_dir)
if self.webassets_cmd:
self.webassets_cmd.build() | Build static files | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Build static files
### Output:
def build_static(self):
if not os.path.isdir(self.build_static_dir):
os.makedirs(self.build_static_dir)
copy_tree(self.static_... |
31 | 17,808 | def update_linode(linode_id, update_args=None):
s properties.
linode_id
The ID of the Linode to shutdown. Required.
update_args
The args to update the Linode with. Must be in dictionary form.
LinodeIDlinodeupdate', args=update_args)
return _clean_data(result) | Updates a Linode's properties.
linode_id
The ID of the Linode to shutdown. Required.
update_args
The args to update the Linode with. Must be in dictionary form. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Updates a Linode's properties.
linode_id
The ID of the Linode to shutdown. Required.
update_args
The args to update the Linode with. Must be in dictionary form.
### Outp... |
32 | 23,736 | def covered_interval(bin):
if bin < 0 or bin > MAX_BIN:
raise OutOfRangeError(
% (bin, MAX_BIN))
shift = SHIFT_FIRST
for offset in BIN_OFFSETS:
if offset <= bin:
return bin - offset << shift, bin + 1 - offset << shift
shift += SHIFT_NEXT | Given a bin number `bin`, return the interval covered by this bin.
:arg int bin: Bin number.
:return: Tuple of `start, stop` being the zero-based, open-ended interval
covered by `bin`.
:rtype: tuple(int)
:raise OutOfRangeError: If bin number `bin` exceeds the maximum bin
number. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Given a bin number `bin`, return the interval covered by this bin.
:arg int bin: Bin number.
:return: Tuple of `start, stop` being the zero-based, open-ended interval
covered by `... |
33 | 5,257 | def initialise_api(f):
@click.option(
"--api-host", envvar="CLOUDSMITH_API_HOST", help="The API host to connect to."
)
@click.option(
"--api-proxy",
envvar="CLOUDSMITH_API_PROXY",
help="The API proxy to connect through.",
)
@click.option(
"--api-user-age... | Initialise the Cloudsmith API for use. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Initialise the Cloudsmith API for use.
### Output:
def initialise_api(f):
@click.option(
"--api-host", envvar="CLOUDSMITH_API_HOST", help="The API host to connect to."
)
... |
34 | 12,619 | def run_func(func, *args, **kwargs):
ray.init()
func = ray.remote(func)
result = ray.get(func.remote(*args))
caller = inspect.stack()[1][3]
print("%s: %s" % (caller, str(result)))
return result | Helper function for running examples | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Helper function for running examples
### Output:
def run_func(func, *args, **kwargs):
ray.init()
func = ray.remote(func)
result = ray.get(func.remote(*args))
ca... |
35 | 12,075 | def should_record_thread(self, participants):
if not self.thread_filter:
return True
if len(participants) != len(self.thread_filter):
return False
participants = [[p.lower()] + p.lower().split(" ")
for p in participants]
matches = ... | Determines if the thread should be parsed based on the
participants and the filter given.
For example, if the filter states ['jack', 'billy joe'],
then only threads with exactly two participants
(excluding the owner of the chat history) containing
someone with the first or last ... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Determines if the thread should be parsed based on the
participants and the filter given.
For example, if the filter states ['jack', 'billy joe'],
then only threads with ... |
36 | 10,336 | def clean_stacks(self, stacks: List[List[BaseLayer]]) \
-> List[List[BaseLayer]]:
ns: List[List[BaseLayer]] = []
for stack in stacks:
if isinstance(stack[-1], lyr.Sleep):
ns.extend([x] for x in stack)
else:
ns.append([x for x... | Two cases: if a stack finishes by a sleep then let's keep it (it means
that there was nothing after the text). However if the stack finishes
with something else (like a quick reply) then we don't risk an
is preserved. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Two cases: if a stack finishes by a sleep then let's keep it (it means
that there was nothing after the text). However if the stack finishes
with something else (like a quick repl... |
37 | 1,159 | def predict_from_variants(
self,
variants,
transcript_expression_dict=None,
gene_expression_dict=None):
variants = apply_variant_expression_filters(
variants,
transcript_expression_dict=... | Predict epitopes from a Variant collection, filtering options, and
optional gene and transcript expression data.
Parameters
----------
variants : varcode.VariantCollection
transcript_expression_dict : dict
Maps from Ensembl transcript IDs to FPKM expression values.
... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Predict epitopes from a Variant collection, filtering options, and
optional gene and transcript expression data.
Parameters
----------
variants : varcode.VariantC... |
38 | 1,567 | def _tty_stdio(cls, env):
tty_fileno = tty.fileno()
with stdio_as(stdin_fd=tty_fileno, stdout_fd=tty_fileno, stderr_fd=tty_fileno):
def finalizer():
termios.tcdrain(tty_fileno)
yield finalizer | Handles stdio redirection in the case of all stdio descriptors being the same tty. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Handles stdio redirection in the case of all stdio descriptors being the same tty.
### Output:
def _tty_stdio(cls, env):
tty_fileno = tty.fileno()
with stdio_as(stdin_fd=tt... |
39 | 12,527 | def rank(self, method=, ascending=True, na_option=,
pct=False, axis=0):
if na_option not in {, , }:
msg = "na_option must be one of , , or "
raise ValueError(msg)
return self._cython_transform(, numeric_only=False,
ties_... | Provide the rank of values within each group.
Parameters
----------
method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'
* average: average rank of group
* min: lowest rank in group
* max: highest rank in group
* first: ranks as... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Provide the rank of values within each group.
Parameters
----------
method : {'average', 'min', 'max', 'first', 'dense'}, default 'average'
* average: average... |
40 | 19,720 | def resample_image(image, resample_params, use_voxels=False, interp_type=1):
if image.components == 1:
inimage = image.clone()
outimage = image.clone()
rsampar = .join([str(rp) for rp in resample_params])
args = [image.dimension, inimage, outimage, rsampar, int(use_voxels), int... | Resample image by spacing or number of voxels with
various interpolators. Works with multi-channel images.
ANTsR function: `resampleImage`
Arguments
---------
image : ANTsImage
input image
resample_params : tuple/list
vector of size dimension with numeric values
... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Resample image by spacing or number of voxels with
various interpolators. Works with multi-channel images.
ANTsR function: `resampleImage`
Arguments
---------
image : ANTsI... |
41 | 6,824 | def format_stack(f=None, limit=None):
if f is None:
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
return format_list(extract_stack(f, limit)) | Shorthand for 'format_list(extract_stack(f, limit))'. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Shorthand for 'format_list(extract_stack(f, limit))'.
### Output:
def format_stack(f=None, limit=None):
if f is None:
try:
raise ZeroDivisionError
except Zer... |
42 | 19,306 | def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.generic is not None:
_dict[] = [x._to_dict() for x in self.generic]
if hasattr(self, ) and self.intents is not None:
_dict[] = [x._to_dict() for x in self.intents]
if hasattr(self, ) and self.enti... | Return a json dictionary representing this model. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return a json dictionary representing this model.
### Output:
def _to_dict(self):
_dict = {}
if hasattr(self, ) and self.generic is not None:
_dict[] = [x._t... |
43 | 12,407 | def toggle_wrap_mode(self, checked):
self.plain_text.editor.toggle_wrap_mode(checked)
self.set_option(, checked) | Toggle wrap mode | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Toggle wrap mode
### Output:
def toggle_wrap_mode(self, checked):
self.plain_text.editor.toggle_wrap_mode(checked)
self.set_option(, checked) |
44 | 20,548 | def eglQueryString(display, name):
out = _lib.eglQueryString(display, name)
if not out:
raise RuntimeError( % name)
return out | Query string from display | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Query string from display
### Output:
def eglQueryString(display, name):
out = _lib.eglQueryString(display, name)
if not out:
raise RuntimeError( % name)
return out |
45 | 21,927 | def extract_github_repo_and_revision_from_source_url(url):
_check_github_url_is_supported(url)
parts = get_parts_of_url_path(url)
repo_name = parts[1]
try:
revision = parts[3]
except IndexError:
raise ValueError(.format(url))
end_index = url.index(repo_name) + len(repo_nam... | Given an URL, return the repo name and who owns it.
Args:
url (str): The URL to the GitHub repository
Raises:
ValueError: on url that aren't from github or when the revision cannot be extracted
Returns:
str, str: the owner of the repository, the repository name | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Given an URL, return the repo name and who owns it.
Args:
url (str): The URL to the GitHub repository
Raises:
ValueError: on url that aren't from github or when the revi... |
46 | 2,413 | def create_matching_kernel(source_psf, target_psf, window=None):
source_psf = np.copy(np.asanyarray(source_psf))
target_psf = np.copy(np.asanyarray(target_psf))
if source_psf.shape != target_psf.shape:
raise ValueError(
)
source_psf /= source_psf.sum()
... | Create a kernel to match 2D point spread functions (PSF) using the
ratio of Fourier transforms.
Parameters
----------
source_psf : 2D `~numpy.ndarray`
The source PSF. The source PSF should have higher resolution
(i.e. narrower) than the target PSF. ``source_psf`` and
``target_... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Create a kernel to match 2D point spread functions (PSF) using the
ratio of Fourier transforms.
Parameters
----------
source_psf : 2D `~numpy.ndarray`
The source PSF. Th... |
47 | 13,384 | def get_gaf_format(self):
sep =
return sep.join(
[self.gene, self.db_ref, self.term.id, self.evidence,
.join(self.db_ref), .join(self.with_)]) | Return a GAF 2.0-compatible string representation of the annotation.
Parameters
----------
Returns
-------
str
The formatted string. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return a GAF 2.0-compatible string representation of the annotation.
Parameters
----------
Returns
-------
str
The formatted string.
### Outp... |
48 | 4,529 | def locate_tool(name, verbose=True):
m = get_tool(name)
tool_bin = which(m.cmd)
if tool_bin:
if verbose:
print("Found {} in {}".format(m.name, tool_bin))
return tool_bin
else:
print("Couldn't find {}".format(m.name)) | Returns the binary of a tool.
Parameters
----------
name : str
Name of the tool (case-insensitive).
Returns
-------
tool_bin : str
Binary of tool. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Returns the binary of a tool.
Parameters
----------
name : str
Name of the tool (case-insensitive).
Returns
-------
tool_bin : str
Binary of tool.
### Ou... |
49 | 21,163 | def make_constants(builtin_only=False, stoplist=[], verbose=False):
if type(builtin_only) == type(make_constants):
raise ValueError("The make_constants decorator must have arguments.")
return lambda f: _make_constants(f, builtin_only, stoplist, verbose) | Return a decorator for optimizing global references.
Verify that the first argument is a function. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return a decorator for optimizing global references.
Verify that the first argument is a function.
### Output:
def make_constants(builtin_only=False, stoplist=[], verbose=False):
... |
50 | 17,523 | def _get_random_fp_raw():
fp_list = []
fp_list.append(get_random_ua())
fp_list.append()
fp_list.append()
fp_list.append(__get_random_screen_resolution())
fp_list.append()
fp_list.append()
fp_list.append()
fp_list.append()
fp_list.append()
fp_list.append()... | 生成随机的原始指纹列表 | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
生成随机的原始指纹列表
### Output:
def _get_random_fp_raw():
fp_list = []
fp_list.append(get_random_ua())
fp_list.append()
fp_list.append()
fp_list.append(__get_random_screen... |
51 | 23,823 | def main():
description = .join([
,
,
])
parser = argparse.ArgumentParser(
prog=, formatter_class=argparse.RawTextHelpFormatter,
description=description)
parser.add_argument(, help=,
action=)
parser.add_argument(
, metav... | Main function for pyssim. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Main function for pyssim.
### Output:
def main():
description = .join([
,
,
])
parser = argparse.ArgumentParser(
prog=, formatter_class=argpar... |
52 | 12,852 | def attempt_datastructure_upgrade(didl_item):
try:
resource = didl_item.resources[0]
except IndexError:
_LOG.debug()
return didl_item
if resource.uri.startswith():
uri = resource.uri
path = urlparse(uri).path
path = path.rsplit... | Attempt to upgrade a didl_item to a music services data structure
if it originates from a music services | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Attempt to upgrade a didl_item to a music services data structure
if it originates from a music services
### Output:
def attempt_datastructure_upgrade(didl_item):
try:
resou... |
53 | 19,557 | def wrap_case_result(raw, expr):
raw_1d = np.atleast_1d(raw)
if np.any(pd.isnull(raw_1d)):
result = pd.Series(raw_1d)
else:
result = pd.Series(
raw_1d, dtype=constants.IBIS_TYPE_TO_PANDAS_TYPE[expr.type()]
)
if result.size == 1 and isinstance(expr, ir.ScalarExpr)... | Wrap a CASE statement result in a Series and handle returning scalars.
Parameters
----------
raw : ndarray[T]
The raw results of executing the ``CASE`` expression
expr : ValueExpr
The expression from the which `raw` was computed
Returns
-------
Union[scalar, Series] | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Wrap a CASE statement result in a Series and handle returning scalars.
Parameters
----------
raw : ndarray[T]
The raw results of executing the ``CASE`` expression
expr : ... |
54 | 1,037 | def _apply_sort(cursor, sort_by, sort_direction):
if sort_direction is not None and sort_direction.lower() == "desc":
sort = pymongo.DESCENDING
else:
sort = pymongo.ASCENDING
return cursor.sort(sort_by, sort) | Apply sort to a cursor.
:param cursor: The cursor to apply sort on.
:param sort_by: The field name to sort by.
:param sort_direction: The direction to sort, "asc" or "desc".
:return: | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Apply sort to a cursor.
:param cursor: The cursor to apply sort on.
:param sort_by: The field name to sort by.
:param sort_direction: The direction to sort, "asc" or "des... |
55 | 10,694 | def do_execute(self):
result = None
data = self.input.payload
pltdataset.line_plot(
data,
atts=self.resolve_option("attributes"),
percent=float(self.resolve_option("percent")),
seed=int(self.resolve_option("seed")),
title=self.... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
### Output:
def do_execute(self):
result = None
data... |
56 | 14,574 | def run_model(self, model_run, run_url):
request = RequestFactory().get_request(model_run, run_url)
self.collection.insert_one({
: self.connector,
: request.to_dict()
}) | Create entry in run request buffer.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model run information | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Create entry in run request buffer.
Parameters
----------
model_run : ModelRunHandle
Handle to model run
run_url : string
URL for model ru... |
57 | 19,662 | def validate(self, value):
url = self.get_item_url(value)
try:
data = self.http_call(url=url)
except requests.HTTPError:
raise ItemNotFound()
data = self.get_http_result(data)
try:
self.item(data)
except SkipItem:
... | From a value available on the remote server, the method returns the
complete item matching the value.
If case the value is not available on the server side or filtered
through :meth:`item`, the class:`agnocomplete.exceptions.ItemNotFound`
is raised. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
From a value available on the remote server, the method returns the
complete item matching the value.
If case the value is not available on the server side or filtered
thr... |
58 | 12,382 | def _set_src_ip_any(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="src-ip-any", rest_name="src-ip-any", parent=self, choice=(u, u), path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, ex... | Setter method for src_ip_any, mapped from YANG variable /overlay/access_list/type/vxlan/extended/ext_seq/src_ip_any (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_src_ip_any is considered as a private
method. Backends looking to populate this variable should
do ... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Setter method for src_ip_any, mapped from YANG variable /overlay/access_list/type/vxlan/extended/ext_seq/src_ip_any (empty)
If this variable is read-only (config: false) in the
source YAN... |
59 | 20,234 | def diff(self, obj=None):
if self.no_resource:
return NOOP
if not self.present:
if self.existing:
return DEL
return NOOP
if not obj:
obj = self.obj()
is_diff = NOOP
if self.present and self.existing:
... | Determine if something has changed or not | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Determine if something has changed or not
### Output:
def diff(self, obj=None):
if self.no_resource:
return NOOP
if not self.present:
if self.ex... |
60 | 244 | def as_unit(unit, precision=2, location=):
if not isinstance(precision, Integral):
raise TypeError("Precision must be an integer.")
if location == :
formatter = partial(_format_numer, prefix=unit)
elif location == :
formatter = partial(_format_numer, suffix=unit)
else:
... | Convert value to unit.
Parameters:
-----------
:param v: numerical value
:param unit: string of unit
:param precision: int
decimal places to round to
:param location:
'prefix' or 'suffix' representing where the currency symbol falls
relative to the value | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Convert value to unit.
Parameters:
-----------
:param v: numerical value
:param unit: string of unit
:param precision: int
decimal places to round to
:param locat... |
61 | 12,095 | def optimize_logger_level(logger, log_level):
function_name = _log_functions[log_level]
if getattr(logger, function_name) is _dummy_log:
return False
is_level_logged = logger.isEnabledFor(log_level)
if not is_level_logged:
setattr(logger, function_name, _dummy_log)
return is_l... | At runtime, when logging is not active,
replace the .debug() call with a no-op. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
At runtime, when logging is not active,
replace the .debug() call with a no-op.
### Output:
def optimize_logger_level(logger, log_level):
function_name = _log_functions[log_level]
... |
62 | 18,745 | def int80(self, cpu):
syscalls = {0x00000001: self.sys_terminate,
0x00000002: self.sys_transmit,
0x00000003: self.sys_receive,
0x00000004: self.sys_fdwait,
0x00000005: self.sys_allocate,
0x00000006: self... | 32 bit dispatcher.
:param cpu: current CPU.
_terminate, transmit, receive, fdwait, allocate, deallocate and random | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
32 bit dispatcher.
:param cpu: current CPU.
_terminate, transmit, receive, fdwait, allocate, deallocate and random
### Output:
def int80(self, cpu):
syscalls = {... |
63 | 24,326 | def _generate_ngram_table(self, output_dir, labels, results):
html = []
grouped = results.groupby(constants.NGRAM_FIELDNAME)
row_template = self._generate_ngram_row_template(labels)
for name, group in grouped:
html.append(self._render_ngram_row(name, group, row_templ... | Returns an HTML table containing data on each n-gram in
`results`. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Returns an HTML table containing data on each n-gram in
`results`.
### Output:
def _generate_ngram_table(self, output_dir, labels, results):
html = []
grouped = ... |
64 | 3,242 | def backward_step(self):
logger.debug("Executing backward step ...")
self.run_to_states = []
self.set_execution_mode(StateMachineExecutionStatus.BACKWARD) | Take a backward step for all active states in the state machine | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Take a backward step for all active states in the state machine
### Output:
def backward_step(self):
logger.debug("Executing backward step ...")
self.run_to_states = []
... |
65 | 23,327 | def ipv6_acl_ipv6_access_list_standard_seq_seq_id(self, **kwargs):
config = ET.Element("config")
ipv6_acl = ET.SubElement(config, "ipv6-acl", xmlns="urn:brocade.com:mgmt:brocade-ipv6-access-list")
ipv6 = ET.SubElement(ipv6_acl, "ipv6")
access_list = ET.SubElement(ipv6, "access-l... | Auto Generated Code | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Auto Generated Code
### Output:
def ipv6_acl_ipv6_access_list_standard_seq_seq_id(self, **kwargs):
config = ET.Element("config")
ipv6_acl = ET.SubElement(config, "ipv6-a... |
66 | 10,211 | def random(self, n: Optional[int] = None) -> Union[List[float], float]:
randoms = []
n_or_default = 1 if n is None else n
for _ in range(n_or_default):
number_of_digits = _RandintsToFloatOptions.RANDINTS_NUMBER_OF_DIGITS.value
max_int = int( * number_of_digits)
... | Generate random float(s) by using integers as fractional part.
random.org's API doesn't offer floats, but a sequence of integers can emulate this:
[06357, 114, 0210] => 0.06357_00114_00210 | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Generate random float(s) by using integers as fractional part.
random.org's API doesn't offer floats, but a sequence of integers can emulate this:
[06357, 114, 0210] => 0.06357_... |
67 | 10,076 | def plot_amino_diagrams(self):
for res in self.topology_data.dict_of_plotted_res:
try:
color = [self.colors_amino_acids[self.amino_acids[res[0]]],]
except KeyError:
color = ["pink",]
plt.figure(figsize=(2.5,2.5))
ring1,_=p... | Plotting of amino diagrams - circles with residue name and id, colored according to the
residue type. If the protein has more than one chain, chain identity is also included in
the plot. The plot is saved as svg file with residue id and chain id as filename for more
certain identification. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Plotting of amino diagrams - circles with residue name and id, colored according to the
residue type. If the protein has more than one chain, chain identity is also included in
th... |
68 | 2,596 | def get_restricted_index(index, length, length_index_allowed=True):
if index and index >= length:
index = length if length_index_allowed else length-1
return get_non_negative_index(index, length) | Converts negative indices to positive ones and indices above length to length or
length-1 depending on lengthAllowed. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Converts negative indices to positive ones and indices above length to length or
length-1 depending on lengthAllowed.
### Output:
def get_restricted_index(index, length, length_index_allowed... |
69 | 8,671 | def write_float_matrices(scp_path, ark_path, matrices):
scp_entries = []
with open(ark_path, ) as f:
for utterance_id in sorted(list(matrices.keys())):
matrix = matrices[utterance_id]
assert (matrix.dtype == np.float32)
f.write((.f... | Write the given dict matrices (utt-id/float ndarray) to the given scp and ark files. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Write the given dict matrices (utt-id/float ndarray) to the given scp and ark files.
### Output:
def write_float_matrices(scp_path, ark_path, matrices):
scp_entries = []
... |
70 | 14,779 | def xiphias_get_users(self, peer_jids: Union[str, List[str]]):
return self._send_xmpp_element(xiphias.UsersRequest(peer_jids)) | Calls the new format xiphias message to request user data such as profile creation date
and background picture URL.
:param peer_jids: one jid, or a list of jids | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Calls the new format xiphias message to request user data such as profile creation date
and background picture URL.
:param peer_jids: one jid, or a list of jids
### Output:
def ... |
71 | 1,413 | def channel(self):
guild = self.guild
return guild and guild.get_channel(self.channel_id) | Optional[:class:`TextChannel`]: The text channel this webhook belongs to.
If this is a partial webhook, then this will always return ``None``. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Optional[:class:`TextChannel`]: The text channel this webhook belongs to.
If this is a partial webhook, then this will always return ``None``.
### Output:
def channel(self):
... |
72 | 16,354 | def get_surface_sites(self, tag=False):
from pymatgen.analysis.local_env import VoronoiNN
a = SpacegroupAnalyzer(self.oriented_unit_cell)
ucell = a.get_symmetrized_structure()
cn_dict = {}
v = VoronoiNN()
unique_indices = [equ[0] for equ in uc... | Returns the surface sites and their indices in a dictionary. The
oriented unit cell of the slab will determine the coordination number
of a typical site. We use VoronoiNN to determine the
coordination number of bulk sites and slab sites. Due to the
pathological error resulting from some ... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Returns the surface sites and their indices in a dictionary. The
oriented unit cell of the slab will determine the coordination number
of a typical site. We use VoronoiNN to deter... |
73 | 11,066 | def _abort_http(method, http_resp):
exc_template =
headers = _pp.pformat(dict(http_resp.headers))
message = exc_template.format(
http_resp,
method=method,
headers=headers,
)
raise _exc.FastbillResponseError(message, http_resp) | >>> class FakeResp(object):
... content = 'Wohoo!'
... headers = {'foo': 'bar'}
... status_code = 200
... reason = 'OK'
>>> _abort_http("foo.get", FakeResp())
Traceback (most recent call last):
...
FastbillResponseError: POST foo.get 200 OK
Headers:
{'foo': '... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
>>> class FakeResp(object):
... content = 'Wohoo!'
... headers = {'foo': 'bar'}
... status_code = 200
... reason = 'OK'
>>> _abort_http("foo.get", FakeRes... |
74 | 11,849 | def find_one_and_replace(self, filter, replacement, **kwargs):
self._arctic_lib.check_quota()
return self._collection.find_one_and_replace(filter, replacement, **kwargs) | See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_replace | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_replace
### Output:
def find_one_and_replace(self, filter, replacement, **kwargs)... |
75 | 24,046 | def get_plural_name(cls):
if not hasattr(cls.Meta, ):
setattr(
cls.Meta,
,
inflection.pluralize(cls.get_name())
)
return cls.Meta.plural_name | Get the serializer's plural name.
The plural name may be defined on the Meta class.
If the plural name is not defined,
the pluralized form of the name will be returned. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Get the serializer's plural name.
The plural name may be defined on the Meta class.
If the plural name is not defined,
the pluralized form of the name will be returned.
#... |
76 | 16,828 | def add_callback_to_shortcut_manager(self, action, callback):
if action not in self.registered_shortcut_callbacks:
self.registered_shortcut_callbacks[action] = []
self.registered_shortcut_callbacks[action].append(callback)
self.shortcut_manager.add_callback_for_action(action... | Helper function to add an callback for an action to the shortcut manager.
:param action: the action to add a shortcut for
:param callback: the callback if the action is executed
:return: | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Helper function to add an callback for an action to the shortcut manager.
:param action: the action to add a shortcut for
:param callback: the callback if the action is executed
... |
77 | 3,445 | def _indiff_mixed_action(payoff_matrix, own_supp, opp_supp, A, out):
m = payoff_matrix.shape[0]
k = len(own_supp)
for i in range(k):
for j in range(k):
A[j, i] = payoff_matrix[own_supp[i], opp_supp[j]]
A[:-1, -1] = 1
A[-1, :-1] = -1
A[-1, -1] = 0
out[:-1] = 0
... | Given a player's payoff matrix `payoff_matrix`, an array `own_supp`
of this player's actions, and an array `opp_supp` of the opponent's
actions, each of length k, compute the opponent's mixed action whose
support equals `opp_supp` and for which the player is indifferent
among the actions in `own_supp`, ... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Given a player's payoff matrix `payoff_matrix`, an array `own_supp`
of this player's actions, and an array `opp_supp` of the opponent's
actions, each of length k, compute the opponent's m... |
78 | 832 | def today(self, chamber):
"Return today's votes in a given chamber"
now = datetime.date.today()
return self.by_range(chamber, now, now) | Return today's votes in a given chamber | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return today's votes in a given chamber
### Output:
def today(self, chamber):
"Return today's votes in a given chamber"
now = datetime.date.today()
return self.by_range(c... |
79 | 8,505 | def fill_zero(
x=None,
y=None,
label=None,
color=None,
width=None,
dash=None,
opacity=None,
mode=,
**kargs
):
return line(
x=x,
y=y,
label=label,
color=color,
width=width,
dash=dash,
opacity=opacity,
mode=mode,
... | Fill to zero.
Parameters
----------
x : array-like, optional
y : TODO, optional
label : TODO, optional
Returns
-------
Chart | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Fill to zero.
Parameters
----------
x : array-like, optional
y : TODO, optional
label : TODO, optional
Returns
-------
Chart
### Output:
def fill_zero(
x=No... |
80 | 10,900 | def preprocess_model(model, rewrap=True, **kwargs):
args = {**kwargs, **config.get(, {})}
model = _process_template(model, **args)
if rewrap:
model = rewrap_model(model)
return model | Preprocess a MiniZinc model.
This function takes care of preprocessing the model by resolving the
template using the arguments passed as keyword arguments to this function.
Optionally, this function can also "rewrap" the model, deleting spaces at
the beginning of the lines while preserving indentation.... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Preprocess a MiniZinc model.
This function takes care of preprocessing the model by resolving the
template using the arguments passed as keyword arguments to this function.
Optionall... |
81 | 19,382 | def top_corr(self, df):
tag_freq = df.sum()
tag_freq.sort(ascending=False)
corr = df.corr().fillna(1)
corr_dict = corr.to_dict()
for tag, count in tag_freq.iteritems():
print % (color.Green, tag, color.LightBlue, count, color.Normal),
tag_corrs ... | Give aggregation counts and correlations | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Give aggregation counts and correlations
### Output:
def top_corr(self, df):
tag_freq = df.sum()
tag_freq.sort(ascending=False)
corr = df.corr().fillna(1)
... |
82 | 963 | def parse(self, text, as_html=True):
if not text:
return text
entity_text = self.get_text(text)
if self.type == MessageEntityType.BOLD:
if as_html:
return markdown.hbold(entity_text)
return markdown.bold(entity_text)
elif self... | Get entity value with markup
:param text: original text
:param as_html: as html?
:return: entity text with markup | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Get entity value with markup
:param text: original text
:param as_html: as html?
:return: entity text with markup
### Output:
def parse(self, text, as_html=True):
... |
83 | 23,814 | def resource_created_response(resource):
if _get_acceptable_response_type() == JSON:
response = _single_resource_json_response(resource)
else:
response = _single_resource_html_response(resource)
response.status_code = 201
response.headers[] = .format(
resource.resource_uri()... | Return HTTP response with status code *201*, signaling a created
*resource*
:param resource: resource created as a result of current request
:type resource: :class:`sandman.model.Model`
:rtype: :class:`flask.Response` | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Return HTTP response with status code *201*, signaling a created
*resource*
:param resource: resource created as a result of current request
:type resource: :class:`sandman.model.Mod... |
84 | 6,625 | def getTmpFilename(self, tmp_dir="/tmp",prefix=,suffix=,\
include_class_id=False,result_constructor=FilePath):
return super(Pplacer,self).getTmpFilename(tmp_dir=tmp_dir,
prefix=prefix,
suffix=suffix,
... | Define Tmp filename to contain .fasta suffix, since pplacer requires
the suffix to be .fasta | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Define Tmp filename to contain .fasta suffix, since pplacer requires
the suffix to be .fasta
### Output:
def getTmpFilename(self, tmp_dir="/tmp",prefix=,suffix=,\
include_... |
85 | 21,609 | def _cursor(self):
if self._conn is None:
self._conn = sqlite3.connect(self.filename,
check_same_thread=False)
return self._conn.cursor() | Asserts that the connection is open and returns a cursor | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Asserts that the connection is open and returns a cursor
### Output:
def _cursor(self):
if self._conn is None:
self._conn = sqlite3.connect(self.filename,
... |
86 | 3,703 | def form_to_params(fn=None, return_json=True):
def forms_to_params_decorator(fn):
@handle_type_error
@wraps(fn)
def forms_to_params_wrapper(*args, **kwargs):
kwargs.update(
dict(request.forms)
)
if not return_json:
ret... | Convert bottle forms request to parameters for the wrapped function.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned value to JSON? | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Convert bottle forms request to parameters for the wrapped function.
Args:
return_json (bool, default True): Should the decorator automatically
convert returned v... |
87 | 22,249 | def start(self, request=None):
self.connection.processed += 1
self.producer.requests_processed += 1
self.event().bind(self.finished_reading)
self.request = request or self.create_request()
try:
self.fire_event()
except AbortEvent:
if self.... | Starts processing the request for this protocol consumer.
There is no need to override this method,
implement :meth:`start_request` instead.
If either :attr:`connection` or :attr:`transport` are missing, a
:class:`RuntimeError` occurs.
For server side consumer, this method simp... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Starts processing the request for this protocol consumer.
There is no need to override this method,
implement :meth:`start_request` instead.
If either :attr:`connection` ... |
88 | 7,323 | def loaddate(self):
ld = csv.reader(open( % _CSVFILEPATH, ))
re = {}
re[] = []
re[] = []
for i in ld:
if i[1] == :
re[] += [datetime.strptime(i[0],).date()]
elif i[1] == :
re[] += [datetime.strptime(i[0],).date()]
else:
pass
return re | 載入檔案
檔案依據 http://www.twse.com.tw/ch/trading/trading_days.php | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
載入檔案
檔案依據 http://www.twse.com.tw/ch/trading/trading_days.php
### Output:
def loaddate(self):
ld = csv.reader(open( % _CSVFILEPATH, ))
re = {}
re[] = []
re[] = []
... |
89 | 10,898 | def htmlsafe(unsafe):
unsafe = unsafe.replace(, )
unsafe = unsafe.replace(, )
unsafe = unsafe.replace(, )
return unsafe | Escapes all x(ht)ml control characters. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Escapes all x(ht)ml control characters.
### Output:
def htmlsafe(unsafe):
unsafe = unsafe.replace(, )
unsafe = unsafe.replace(, )
unsafe = unsafe.replace(, )
return unsafe |
90 | 6,417 | def get_item(dictionary, tuple_key, default_value):
u, v = tuple_key
tuple1 = dictionary.get((u, v), None)
tuple2 = dictionary.get((v, u), None)
return tuple1 or tuple2 or default_value | Grab values from a dictionary using an unordered tuple as a key.
Dictionary should not contain None, 0, or False as dictionary values.
Args:
dictionary: Dictionary that uses two-element tuple as keys
tuple_key: Unordered tuple of two elements
default_value: Value that is returned when ... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Grab values from a dictionary using an unordered tuple as a key.
Dictionary should not contain None, 0, or False as dictionary values.
Args:
dictionary: Dictionary that uses two... |
91 | 4,932 | def rtt_control(self, command, config):
config_byref = ctypes.byref(config) if config is not None else None
res = self._dll.JLINK_RTTERMINAL_Control(command, config_byref)
if res < 0:
raise errors.JLinkRTTException(res)
return res | Issues an RTT Control command.
All RTT control is done through a single API call which expects
specifically laid-out configuration structures.
Args:
self (JLink): the ``JLink`` instance
command (int): the command to issue (see enums.JLinkRTTCommand)
config (ctypes... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Issues an RTT Control command.
All RTT control is done through a single API call which expects
specifically laid-out configuration structures.
Args:
self (JLin... |
92 | 15,692 | def and_filter(self, filter_or_string, *args, **kwargs):
self.root_filter.and_filter(filter_or_string, *args, **kwargs)
return self | Convenience method to delegate to the root_filter to generate an
:class:`~es_fluent.filters.core.And` clause.
:return: :class:`~es_fluent.builder.QueryBuilder` | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Convenience method to delegate to the root_filter to generate an
:class:`~es_fluent.filters.core.And` clause.
:return: :class:`~es_fluent.builder.QueryBuilder`
### Output:
def a... |
93 | 557 | def _get_show_ids(self):
logger.info()
r = self.session.get(self.server_url + , timeout=10)
r.raise_for_status()
soup = ParserBeautifulSoup(r.content, [, ])
show_ids = {}
for show in soup.select():
show_ids[sanitize(show.text)] = in... | Get the ``dict`` of show ids per series by querying the `shows.php` page.
:return: show id per series, lower case and without quotes.
:rtype: dict | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Get the ``dict`` of show ids per series by querying the `shows.php` page.
:return: show id per series, lower case and without quotes.
:rtype: dict
### Output:
def _get_show_ids(... |
94 | 4,894 | def encoded(string, encoding=):
assert isinstance(string, string_types) or isinstance(string, binary_type)
if isinstance(string, text_type):
return string.encode(encoding)
try:
string.decode(encoding)
return string
except UnicodeDecodeError:
... | Cast string to binary_type.
:param string: six.binary_type or six.text_type
:param encoding: encoding which the object is forced to
:return: six.binary_type | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Cast string to binary_type.
:param string: six.binary_type or six.text_type
:param encoding: encoding which the object is forced to
:return: six.binary_type
### Output:
def encoded(... |
95 | 2,870 | def delete_organization_course(organization, course_key):
try:
relationship = internal.OrganizationCourse.objects.get(
organization=organization[],
course_id=text_type(course_key),
active=True,
)
_inactivate_organization_course_relationship(relationsh... | Removes an existing organization-course relationship from app/local state
No response currently defined for this operation | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Removes an existing organization-course relationship from app/local state
No response currently defined for this operation
### Output:
def delete_organization_course(organization, course_key... |
96 | 817 | def get_element(self, tag_name, attribute, **attribute_filter):
for i in self.xml:
if self.xml[i] is None:
continue
tag = self.xml[i].findall( + tag_name)
if len(tag) == 0:
return None
for item in tag:
skip_... | :Deprecated: use `get_attribute_value()` instead
Return element in xml files which match with the tag name and the specific attribute
:param tag_name: specify the tag name
:type tag_name: string
:param attribute: specify the attribute
:type attribute: string
:rtype: strin... | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
:Deprecated: use `get_attribute_value()` instead
Return element in xml files which match with the tag name and the specific attribute
:param tag_name: specify the tag name
... |
97 | 22,579 | def transformer_imagenet64_memory_v0():
hparams = transformer_cifar10_memory_v0()
hparams.max_length = 64 * 64 * 3
hparams.split_targets_chunk_length = 64 * 3
hparams.split_targets_max_chunks = int(
hparams.max_length / hparams.split_targets_chunk_length)
hparams.num_memory_items = 128 * 3
tar... | HParams for training image_imagenet64_gen_flat_rev with memory. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
HParams for training image_imagenet64_gen_flat_rev with memory.
### Output:
def transformer_imagenet64_memory_v0():
hparams = transformer_cifar10_memory_v0()
hparams.max_length = 64 * 64... |
98 | 3,675 | def evalrepr(self):
args = [repr(arg) for arg in get_interfaces(self.argvalues)]
param = ", ".join(args)
return "%s(%s)" % (self.parent.evalrepr, param) | Evaluable repr | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Evaluable repr
### Output:
def evalrepr(self):
args = [repr(arg) for arg in get_interfaces(self.argvalues)]
param = ", ".join(args)
return "%s(%s)" % (self.paren... |
99 | 19,651 | def enforce_vertical_symmetry(pixmap):
mirror = []
for item in pixmap:
y = item[0]
x = item[1]
if x <= IMAGE_APEX:
diff_x = diff(x, IMAGE_APEX)
mirror.append((y, x + (2 * diff_x) - 1))
if x > IMAGE_APEX:
diff_x = diff(x, IMAGE_APEX)
... | Enforces vertical symmetry of the pixelmap.
Returns a pixelmap with all pixels mirrored in the middle.
The initial ones still remain. | Below is an instruction that describes a task. Write a response that appropriately completes the request.
### Instruction:
Enforces vertical symmetry of the pixelmap.
Returns a pixelmap with all pixels mirrored in the middle.
The initial ones still remain.
### Output:
def enforce_vertical_symmetry(pixmap):
... |
End of preview. Expand in Data Studio
- Downloads last month
- 10