code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _load_rsp(rsp):
"""
Converts raw Flickr string response to Python dict
"""
first = rsp.find('(') + 1
last = rsp.rfind(')')
return json.loads(rsp[first:last]) | Converts raw Flickr string response to Python dict | Below is the the instruction that describes the task:
### Input:
Converts raw Flickr string response to Python dict
### Response:
def _load_rsp(rsp):
"""
Converts raw Flickr string response to Python dict
"""
first = rsp.find('(') + 1
last = rsp.rfind(')')
return jso... |
def read_xml(filename):
"""
Use et to read in a xml file, or string, into a Element object.
:param filename: File to parse.
:return: lxml._elementTree object or None
"""
parser = et.XMLParser(remove_blank_text=True)
isfile=False
try:
isfile = os.path.exists(filename)
except ... | Use et to read in a xml file, or string, into a Element object.
:param filename: File to parse.
:return: lxml._elementTree object or None | Below is the the instruction that describes the task:
### Input:
Use et to read in a xml file, or string, into a Element object.
:param filename: File to parse.
:return: lxml._elementTree object or None
### Response:
def read_xml(filename):
"""
Use et to read in a xml file, or string, into a Eleme... |
def process(self, processor:PreProcessors=None):
"Apply `processor` or `self.processor` to `self`."
if processor is not None: self.processor = processor
self.processor = listify(self.processor)
for p in self.processor: p.process(self)
return self | Apply `processor` or `self.processor` to `self`. | Below is the the instruction that describes the task:
### Input:
Apply `processor` or `self.processor` to `self`.
### Response:
def process(self, processor:PreProcessors=None):
"Apply `processor` or `self.processor` to `self`."
if processor is not None: self.processor = processor
self.proce... |
def selected_fields(self):
"""Obtain the fields selected by user.
:returns: Keyword of the selected field.
:rtype: list, str
"""
items = self.lstFields.selectedItems()
if items and self.mode == MULTI_MODE:
return [item.text() for item in items]
elif i... | Obtain the fields selected by user.
:returns: Keyword of the selected field.
:rtype: list, str | Below is the the instruction that describes the task:
### Input:
Obtain the fields selected by user.
:returns: Keyword of the selected field.
:rtype: list, str
### Response:
def selected_fields(self):
"""Obtain the fields selected by user.
:returns: Keyword of the selected field.
... |
def serialize(self, buf, offset):
"""
Outputs the expression of the wire protocol of the flow stats into
the buf.
Returns the output length.
"""
fields = [ofproto.oxs_from_user(k, uv) for (k, uv)
in self.fields]
hdr_pack_str = '!HH'
fiel... | Outputs the expression of the wire protocol of the flow stats into
the buf.
Returns the output length. | Below is the the instruction that describes the task:
### Input:
Outputs the expression of the wire protocol of the flow stats into
the buf.
Returns the output length.
### Response:
def serialize(self, buf, offset):
"""
Outputs the expression of the wire protocol of the flow stats i... |
def extract_commands(imported_vars):
"""
从传入的变量列表中提取命令( ``click.core.Command`` )对象
:param dict_items imported_vars: 字典的键值条目列表
:return: 判定为终端命令的对象字典
:rtype: dict(str, object)
"""
commands = dict()
for tup in imported_vars:
name, obj = tup
if is_command_object(obj):
... | 从传入的变量列表中提取命令( ``click.core.Command`` )对象
:param dict_items imported_vars: 字典的键值条目列表
:return: 判定为终端命令的对象字典
:rtype: dict(str, object) | Below is the the instruction that describes the task:
### Input:
从传入的变量列表中提取命令( ``click.core.Command`` )对象
:param dict_items imported_vars: 字典的键值条目列表
:return: 判定为终端命令的对象字典
:rtype: dict(str, object)
### Response:
def extract_commands(imported_vars):
"""
从传入的变量列表中提取命令( ``click.core.Command`` )对象... |
def common_items_metrics(all_items, common_items):
"""
Calculates the percentage of common items for each project
in each segment and calculates the mean and std of this percentage
for each segment.
"""
segments = common_items.index.unique()
metrics = {}
for seg in segments:
seg_... | Calculates the percentage of common items for each project
in each segment and calculates the mean and std of this percentage
for each segment. | Below is the the instruction that describes the task:
### Input:
Calculates the percentage of common items for each project
in each segment and calculates the mean and std of this percentage
for each segment.
### Response:
def common_items_metrics(all_items, common_items):
"""
Calculates the percen... |
def fromtsv(source=None, encoding=None, errors='strict', header=None,
**csvargs):
"""
Convenience function, as :func:`petl.io.csv.fromcsv` but with different
default dialect (tab delimited).
"""
csvargs.setdefault('dialect', 'excel-tab')
return fromcsv(source, encoding=encoding, e... | Convenience function, as :func:`petl.io.csv.fromcsv` but with different
default dialect (tab delimited). | Below is the the instruction that describes the task:
### Input:
Convenience function, as :func:`petl.io.csv.fromcsv` but with different
default dialect (tab delimited).
### Response:
def fromtsv(source=None, encoding=None, errors='strict', header=None,
**csvargs):
"""
Convenience function... |
def _build_indices(self):
"""Build indices for the different field types"""
result = {key: OrderedDict() for key in LINES_WITH_ID}
for line in self.lines:
if line.key in LINES_WITH_ID:
result.setdefault(line.key, OrderedDict())
if line.mapping["ID"] in... | Build indices for the different field types | Below is the the instruction that describes the task:
### Input:
Build indices for the different field types
### Response:
def _build_indices(self):
"""Build indices for the different field types"""
result = {key: OrderedDict() for key in LINES_WITH_ID}
for line in self.lines:
i... |
def nb_persons(self, role = None):
"""
Returns the number of persons contained in the entity.
If ``role`` is provided, only the entity member with the given role are taken into account.
"""
if role:
if role.subroles:
role_condition = np.logica... | Returns the number of persons contained in the entity.
If ``role`` is provided, only the entity member with the given role are taken into account. | Below is the the instruction that describes the task:
### Input:
Returns the number of persons contained in the entity.
If ``role`` is provided, only the entity member with the given role are taken into account.
### Response:
def nb_persons(self, role = None):
"""
Returns the numbe... |
def get_all(self, seq_set: SequenceSet) \
-> Sequence[Tuple[int, CachedMessage]]:
"""Return the cached messages, and their sequence numbers, for the
given sequence set.
Args:
seq_set: The message sequence set.
"""
if seq_set.uid:
all_uids = s... | Return the cached messages, and their sequence numbers, for the
given sequence set.
Args:
seq_set: The message sequence set. | Below is the the instruction that describes the task:
### Input:
Return the cached messages, and their sequence numbers, for the
given sequence set.
Args:
seq_set: The message sequence set.
### Response:
def get_all(self, seq_set: SequenceSet) \
-> Sequence[Tuple[int, Cache... |
def detect_language(self, text: str, hint: str = None):
"""
Detects the language of a text
:param text:
Text to analyze
:param hint:
A list which are hints for the API
in which language the text is written in
example:
"de, ... | Detects the language of a text
:param text:
Text to analyze
:param hint:
A list which are hints for the API
in which language the text is written in
example:
"de, en"
:return:
detected language code. example: "en" | Below is the the instruction that describes the task:
### Input:
Detects the language of a text
:param text:
Text to analyze
:param hint:
A list which are hints for the API
in which language the text is written in
example:
"de, en"
... |
def add_to_cache(cls, remote_info, container): # pylint: disable=g-bad-name
"""Adds a ResourceContainer to a cache tying it to a protorpc method.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
container: An instance of ResourceContainer.
... | Adds a ResourceContainer to a cache tying it to a protorpc method.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
container: An instance of ResourceContainer.
Raises:
TypeError: if the container is not an instance of cls.
KeyError:... | Below is the the instruction that describes the task:
### Input:
Adds a ResourceContainer to a cache tying it to a protorpc method.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
container: An instance of ResourceContainer.
Raises:
T... |
def __read(self):
"""
Reads packets from the socket
"""
# Set the socket as non-blocking
self._socket.setblocking(0)
while not self._stop_event.is_set():
# Watch for content
ready = select.select([self._socket], [], [], 1)
if ready[0]:... | Reads packets from the socket | Below is the the instruction that describes the task:
### Input:
Reads packets from the socket
### Response:
def __read(self):
"""
Reads packets from the socket
"""
# Set the socket as non-blocking
self._socket.setblocking(0)
while not self._stop_event.is_set():
... |
def __check_mecab_dict_path(self):
"""check path to dict of Mecab in system environment
"""
mecab_dic_cmd = "echo `{} --dicdir`".format(os.path.join(self._path_mecab_config, 'mecab-config'))
try:
if six.PY2:
path_mecab_dict = subprocess.check_output( mecab_di... | check path to dict of Mecab in system environment | Below is the the instruction that describes the task:
### Input:
check path to dict of Mecab in system environment
### Response:
def __check_mecab_dict_path(self):
"""check path to dict of Mecab in system environment
"""
mecab_dic_cmd = "echo `{} --dicdir`".format(os.path.join(self._path_me... |
def get_request_headers(self):
"""
Determine the headers to send along with the request. These are
pretty much the same for every request, with Route53.
"""
date_header = time.asctime(time.gmtime())
# We sign the time string above with the user's AWS secret access key
... | Determine the headers to send along with the request. These are
pretty much the same for every request, with Route53. | Below is the the instruction that describes the task:
### Input:
Determine the headers to send along with the request. These are
pretty much the same for every request, with Route53.
### Response:
def get_request_headers(self):
"""
Determine the headers to send along with the request. These... |
def make_2D_samples_gauss(n, m, sigma, random_state=None):
"""return n samples drawn from 2D gaussian N(m,sigma)
Parameters
----------
n : int
number of samples to make
m : np.array (2,)
mean value of the gaussian distribution
sigma : np.array (2,2)
covariance matrix of... | return n samples drawn from 2D gaussian N(m,sigma)
Parameters
----------
n : int
number of samples to make
m : np.array (2,)
mean value of the gaussian distribution
sigma : np.array (2,2)
covariance matrix of the gaussian distribution
random_state : int, RandomState ins... | Below is the the instruction that describes the task:
### Input:
return n samples drawn from 2D gaussian N(m,sigma)
Parameters
----------
n : int
number of samples to make
m : np.array (2,)
mean value of the gaussian distribution
sigma : np.array (2,2)
covariance matrix... |
def define_function(self, function, name=None):
"""Define the Python function within the CLIPS environment.
If a name is given, it will be the function name within CLIPS.
Otherwise, the name of the Python function will be used.
The Python function will be accessible within CLIPS via it... | Define the Python function within the CLIPS environment.
If a name is given, it will be the function name within CLIPS.
Otherwise, the name of the Python function will be used.
The Python function will be accessible within CLIPS via its name
as if it was defined via the `deffunction` c... | Below is the the instruction that describes the task:
### Input:
Define the Python function within the CLIPS environment.
If a name is given, it will be the function name within CLIPS.
Otherwise, the name of the Python function will be used.
The Python function will be accessible within CL... |
def maximum_active_partitions(self):
"""
Integer: The maximum number of active logical partitions or partitions
of this CPC.
The following table shows the maximum number of active logical
partitions or partitions by machine generations supported at the HMC
API:
... | Integer: The maximum number of active logical partitions or partitions
of this CPC.
The following table shows the maximum number of active logical
partitions or partitions by machine generations supported at the HMC
API:
========================= ==================
Mac... | Below is the the instruction that describes the task:
### Input:
Integer: The maximum number of active logical partitions or partitions
of this CPC.
The following table shows the maximum number of active logical
partitions or partitions by machine generations supported at the HMC
AP... |
def get_scm_status(config, read_modules=False, repo_url=None, mvn_repo_local=None, additional_params=None):
"""
Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by
default, although it can be requested to read the whole available module struct... | Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by
default, although it can be requested to read the whole available module structure.
:param config: artifact config (ArtifactConfig instance)
:param read_modules: if True all modules are read... | Below is the the instruction that describes the task:
### Input:
Gets the artifact status (MavenArtifact instance) from SCM defined by config. Only the top-level artifact is read by
default, although it can be requested to read the whole available module structure.
:param config: artifact config (ArtifactC... |
def get_keeper_token(host, username, password):
"""Get a temporary auth token from LTD Keeper.
Parameters
----------
host : `str`
Hostname of the LTD Keeper API (e.g., ``'https://keeper.lsst.codes'``).
username : `str`
Username.
password : `str`
Password.
Returns
... | Get a temporary auth token from LTD Keeper.
Parameters
----------
host : `str`
Hostname of the LTD Keeper API (e.g., ``'https://keeper.lsst.codes'``).
username : `str`
Username.
password : `str`
Password.
Returns
-------
token : `str`
LTD Keeper API toke... | Below is the the instruction that describes the task:
### Input:
Get a temporary auth token from LTD Keeper.
Parameters
----------
host : `str`
Hostname of the LTD Keeper API (e.g., ``'https://keeper.lsst.codes'``).
username : `str`
Username.
password : `str`
Password.
... |
def format_message(self, msg):
"""format message."""
return {'timestamp': int(msg.created * 1000),
'message': self.format(msg),
'stream': self.log_stream or msg.name,
'group': self.log_group} | format message. | Below is the the instruction that describes the task:
### Input:
format message.
### Response:
def format_message(self, msg):
"""format message."""
return {'timestamp': int(msg.created * 1000),
'message': self.format(msg),
'stream': self.log_stream or msg.name,
... |
def natural_neighbor(xp, yp, variable, grid_x, grid_y):
"""Wrap natural_neighbor_to_grid for deprecated natural_neighbor function."""
return natural_neighbor_to_grid(xp, yp, variable, grid_x, grid_y) | Wrap natural_neighbor_to_grid for deprecated natural_neighbor function. | Below is the the instruction that describes the task:
### Input:
Wrap natural_neighbor_to_grid for deprecated natural_neighbor function.
### Response:
def natural_neighbor(xp, yp, variable, grid_x, grid_y):
"""Wrap natural_neighbor_to_grid for deprecated natural_neighbor function."""
return natural_neighbo... |
def find_folder_recipes(base_folder,
pattern="Singularity",
manifest=None,
base=None):
'''find folder recipes will find recipes based on a particular pattern.
Parameters
==========
base_folder: the base folder to r... | find folder recipes will find recipes based on a particular pattern.
Parameters
==========
base_folder: the base folder to recursively walk
pattern: a default pattern to search for
manifest: an already started manifest
base: if defined, consider folders under this level... | Below is the the instruction that describes the task:
### Input:
find folder recipes will find recipes based on a particular pattern.
Parameters
==========
base_folder: the base folder to recursively walk
pattern: a default pattern to search for
manifest: an already starte... |
def provider_list(self, lookup='all'):
'''
Return a mapping of all image data for available providers
'''
data = {}
lookups = self.lookup_providers(lookup)
if not lookups:
return data
for alias, driver in lookups:
if alias not in data:
... | Return a mapping of all image data for available providers | Below is the the instruction that describes the task:
### Input:
Return a mapping of all image data for available providers
### Response:
def provider_list(self, lookup='all'):
'''
Return a mapping of all image data for available providers
'''
data = {}
lookups = self.lookup... |
def list_files(self, project):
"""
List files in the project on computes
"""
path = "/projects/{}/files".format(project.id)
res = yield from self.http_query("GET", path, timeout=120)
return res.json | List files in the project on computes | Below is the the instruction that describes the task:
### Input:
List files in the project on computes
### Response:
def list_files(self, project):
"""
List files in the project on computes
"""
path = "/projects/{}/files".format(project.id)
res = yield from self.http_query("... |
def insert_before(self, text):
"""
Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync.
"""
selection_state = self.selection
if selection_state:
selection_state = SelectionState(
... | Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync. | Below is the the instruction that describes the task:
### Input:
Create a new document, with this text inserted before the buffer.
It keeps selection ranges and cursor position in sync.
### Response:
def insert_before(self, text):
"""
Create a new document, with this text inserted before th... |
def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):
"""
If we're not on the first line (of a multiline input) go a line up,
otherwise go back in history. (If nothing is selected.)
"""
if self.complete_state:
self.complete_previous(count=count)
... | If we're not on the first line (of a multiline input) go a line up,
otherwise go back in history. (If nothing is selected.) | Below is the the instruction that describes the task:
### Input:
If we're not on the first line (of a multiline input) go a line up,
otherwise go back in history. (If nothing is selected.)
### Response:
def auto_up(self, count=1, go_to_start_of_line_if_history_changes=False):
"""
If we're n... |
def run(
self,
num_episodes=-1,
max_episode_timesteps=-1,
episode_finished=None,
summary_report=None,
summary_interval=0,
num_timesteps=None,
deterministic=False,
episodes=None,
max_timesteps=None,
testing=False,
sleep=None
... | Executes this runner by starting all Agents in parallel (each one in one thread).
Args:
episodes (int): Deprecated; see num_episodes.
max_timesteps (int): Deprecated; see max_episode_timesteps. | Below is the the instruction that describes the task:
### Input:
Executes this runner by starting all Agents in parallel (each one in one thread).
Args:
episodes (int): Deprecated; see num_episodes.
max_timesteps (int): Deprecated; see max_episode_timesteps.
### Response:
def run(
... |
def flush_tx_buffer(self):
"""
Flushes the transmit buffer.
:raises can.CanError:
If flushing of the transmit buffer failed.
"""
log.info('Flushing transmit buffer')
self._ucan.reset_can(self.channel, ResetFlags.RESET_ONLY_TX_BUFF) | Flushes the transmit buffer.
:raises can.CanError:
If flushing of the transmit buffer failed. | Below is the the instruction that describes the task:
### Input:
Flushes the transmit buffer.
:raises can.CanError:
If flushing of the transmit buffer failed.
### Response:
def flush_tx_buffer(self):
"""
Flushes the transmit buffer.
:raises can.CanError:
If... |
def from_agent_proto(agent_info_list, brain_params):
"""
Converts list of agent infos to BrainInfo.
"""
vis_obs = []
for i in range(brain_params.number_visual_observations):
obs = [BrainInfo.process_pixels(x.visual_observations[i],
... | Converts list of agent infos to BrainInfo. | Below is the the instruction that describes the task:
### Input:
Converts list of agent infos to BrainInfo.
### Response:
def from_agent_proto(agent_info_list, brain_params):
"""
Converts list of agent infos to BrainInfo.
"""
vis_obs = []
for i in range(brain_params.number_v... |
def check_geophysical_vars_fill_value(self, ds):
'''
Check that geophysical variables contain fill values.
:param netCDF4.Dataset ds: An open netCDF dataset
'''
results = []
for geo_var in get_geophysical_variables(ds):
results.append(
self._h... | Check that geophysical variables contain fill values.
:param netCDF4.Dataset ds: An open netCDF dataset | Below is the the instruction that describes the task:
### Input:
Check that geophysical variables contain fill values.
:param netCDF4.Dataset ds: An open netCDF dataset
### Response:
def check_geophysical_vars_fill_value(self, ds):
'''
Check that geophysical variables contain fill values.
... |
def draw_summary(self, history, title=""):
"""Inserts a text summary at the top that lists the number of steps and total
training time."""
# Generate summary string
time_str = str(history.get_total_time()).split(".")[0] # remove microseconds
summary = "Step: {} Time: {}".fo... | Inserts a text summary at the top that lists the number of steps and total
training time. | Below is the the instruction that describes the task:
### Input:
Inserts a text summary at the top that lists the number of steps and total
training time.
### Response:
def draw_summary(self, history, title=""):
"""Inserts a text summary at the top that lists the number of steps and total
t... |
def create_set_cmap(values, cmap_name, alpha=255):
"""
return a dict of colors corresponding to the unique values
:param values: values to be mapped
:param cmap_name: colormap name
:param alpha: color alpha
:return: dict of colors corresponding to the unique values
"""
unique_values... | return a dict of colors corresponding to the unique values
:param values: values to be mapped
:param cmap_name: colormap name
:param alpha: color alpha
:return: dict of colors corresponding to the unique values | Below is the the instruction that describes the task:
### Input:
return a dict of colors corresponding to the unique values
:param values: values to be mapped
:param cmap_name: colormap name
:param alpha: color alpha
:return: dict of colors corresponding to the unique values
### Response:
def ... |
def handle_error(err, halt=True):
"""Print errors message and optionally exit.
Args:
err (str): The error message to print.
halt (bool, optional): Defaults to True. If True the script will exit.
"""
print('{}{}{}'.format(c.Style.BRIGHT, c.Fore.RED, err))
... | Print errors message and optionally exit.
Args:
err (str): The error message to print.
halt (bool, optional): Defaults to True. If True the script will exit. | Below is the the instruction that describes the task:
### Input:
Print errors message and optionally exit.
Args:
err (str): The error message to print.
halt (bool, optional): Defaults to True. If True the script will exit.
### Response:
def handle_error(err, halt=True):
"""... |
def get_hwclock():
'''
Get current hardware clock setting (UTC or localtime)
CLI Example:
.. code-block:: bash
salt '*' timezone.get_hwclock
'''
if salt.utils.path.which('timedatectl'):
ret = _timedatectl()
for line in (x.strip() for x in ret['stdout'].splitlines()):
... | Get current hardware clock setting (UTC or localtime)
CLI Example:
.. code-block:: bash
salt '*' timezone.get_hwclock | Below is the the instruction that describes the task:
### Input:
Get current hardware clock setting (UTC or localtime)
CLI Example:
.. code-block:: bash
salt '*' timezone.get_hwclock
### Response:
def get_hwclock():
'''
Get current hardware clock setting (UTC or localtime)
CLI Examp... |
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_flogi(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, "output")... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_flogi(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_inte... |
def _build_cached_instances(self):
"""
Build lookup table of VM instances known to the cloud provider.
The returned dictionary links VM id with the actual VM object.
"""
connection = self._connect()
reservations = connection.get_all_reservations()
cached_instance... | Build lookup table of VM instances known to the cloud provider.
The returned dictionary links VM id with the actual VM object. | Below is the the instruction that describes the task:
### Input:
Build lookup table of VM instances known to the cloud provider.
The returned dictionary links VM id with the actual VM object.
### Response:
def _build_cached_instances(self):
"""
Build lookup table of VM instances known to t... |
def add_file(self, *args):
"""
Add single file or list of files to bundle
:type: file_path: str|unicode
"""
for file_path in args:
self.files.append(FilePath(file_path, self)) | Add single file or list of files to bundle
:type: file_path: str|unicode | Below is the the instruction that describes the task:
### Input:
Add single file or list of files to bundle
:type: file_path: str|unicode
### Response:
def add_file(self, *args):
"""
Add single file or list of files to bundle
:type: file_path: str|unicode
"""
for f... |
def reset_passwd(self, data):
""" Reset the user password """
error = False
msg = ""
# Check input format
if len(data["passwd"]) < 6:
error = True
msg = _("Password too short.")
elif data["passwd"] != data["passwd2"]:
error = True
... | Reset the user password | Below is the the instruction that describes the task:
### Input:
Reset the user password
### Response:
def reset_passwd(self, data):
""" Reset the user password """
error = False
msg = ""
# Check input format
if len(data["passwd"]) < 6:
error = True
... |
def setup_dirs(data):
""" sets up directories for step3 data """
## make output folder for clusters
pdir = os.path.realpath(data.paramsdict["project_dir"])
data.dirs.clusts = os.path.join(pdir, "{}_clust_{}"\
.format(data.name, data.paramsdict["clust_threshold"]))
if not os.pa... | sets up directories for step3 data | Below is the the instruction that describes the task:
### Input:
sets up directories for step3 data
### Response:
def setup_dirs(data):
""" sets up directories for step3 data """
## make output folder for clusters
pdir = os.path.realpath(data.paramsdict["project_dir"])
data.dirs.clusts = os.path.jo... |
def get(self, name, default, allow_default=True):
""" Return a setting value.
:param str name: Setting key name.
:param default: Default value of setting if it's not explicitly
set.
:param bool allow_default: If true, use the parameter default as
... | Return a setting value.
:param str name: Setting key name.
:param default: Default value of setting if it's not explicitly
set.
:param bool allow_default: If true, use the parameter default as
default if the key is not set, els... | Below is the the instruction that describes the task:
### Input:
Return a setting value.
:param str name: Setting key name.
:param default: Default value of setting if it's not explicitly
set.
:param bool allow_default: If true, use the parameter defa... |
def weighted_median(data, weights=None):
"""Calculate the weighted median of a list."""
if weights is None:
return median(data)
midpoint = 0.5 * sum(weights)
if any([j > midpoint for j in weights]):
return data[weights.index(max(weights))]
if any([j > 0 for j in weights]):
so... | Calculate the weighted median of a list. | Below is the the instruction that describes the task:
### Input:
Calculate the weighted median of a list.
### Response:
def weighted_median(data, weights=None):
"""Calculate the weighted median of a list."""
if weights is None:
return median(data)
midpoint = 0.5 * sum(weights)
if any([j > m... |
def import_emails(self, archives_path, all, exclude_lists=None):
"""Get emails from the filesystem from the `archives_path`
and store them into the database. If `all` is set to True all
the filesystem storage will be imported otherwise the
importation will resume from the last message pr... | Get emails from the filesystem from the `archives_path`
and store them into the database. If `all` is set to True all
the filesystem storage will be imported otherwise the
importation will resume from the last message previously
imported. The lists set in `exclude_lists` won't be importe... | Below is the the instruction that describes the task:
### Input:
Get emails from the filesystem from the `archives_path`
and store them into the database. If `all` is set to True all
the filesystem storage will be imported otherwise the
importation will resume from the last message previousl... |
def _iter_from_process_or_stream(cls, repo, proc_or_stream):
"""Parse out commit information into a list of Commit objects
We expect one-line per commit, and parse the actual commit information directly
from our lighting fast object database
:param proc: git-rev-list process instance - ... | Parse out commit information into a list of Commit objects
We expect one-line per commit, and parse the actual commit information directly
from our lighting fast object database
:param proc: git-rev-list process instance - one sha per line
:return: iterator returning Commit objects | Below is the the instruction that describes the task:
### Input:
Parse out commit information into a list of Commit objects
We expect one-line per commit, and parse the actual commit information directly
from our lighting fast object database
:param proc: git-rev-list process instance - one... |
def _update(self, **kwargs):
"""wrapped with update, override that in a subclass to customize"""
requests_params, update_uri, session, read_only = \
self._prepare_put_or_patch(kwargs)
read_only_mutations = []
for attr in read_only:
if attr in kwargs:
... | wrapped with update, override that in a subclass to customize | Below is the the instruction that describes the task:
### Input:
wrapped with update, override that in a subclass to customize
### Response:
def _update(self, **kwargs):
"""wrapped with update, override that in a subclass to customize"""
requests_params, update_uri, session, read_only = \
... |
def get_or_create_time_series(self, label_values):
"""Get a mutable measurement for the given set of label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:rtype: :class:`GaugePointLong`, :class:`GaugePointDouble`
:... | Get a mutable measurement for the given set of label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:rtype: :class:`GaugePointLong`, :class:`GaugePointDouble`
:class:`opencensus.metrics.export.cumulative.CumulativePointLon... | Below is the the instruction that describes the task:
### Input:
Get a mutable measurement for the given set of label values.
:type label_values: list(:class:`LabelValue`)
:param label_values: The measurement's label values.
:rtype: :class:`GaugePointLong`, :class:`GaugePointDouble`
... |
def get_resources(self, ids, cache=True):
"""Support server side filtering on arns or names
"""
if ids[0].startswith('arn:'):
params = {'LoadBalancerArns': ids}
else:
params = {'Names': ids}
return self.query.filter(self.manager, **params) | Support server side filtering on arns or names | Below is the the instruction that describes the task:
### Input:
Support server side filtering on arns or names
### Response:
def get_resources(self, ids, cache=True):
"""Support server side filtering on arns or names
"""
if ids[0].startswith('arn:'):
params = {'LoadBalancerArns... |
def addresses_for_key(gpg, key):
"""
Takes a key and extracts the email addresses for it.
"""
return [address.split("<")[-1].strip(">")
for address in gpg.list_keys().key_map[key['fingerprint']]["uids"]
if address] | Takes a key and extracts the email addresses for it. | Below is the the instruction that describes the task:
### Input:
Takes a key and extracts the email addresses for it.
### Response:
def addresses_for_key(gpg, key):
"""
Takes a key and extracts the email addresses for it.
"""
return [address.split("<")[-1].strip(">")
for address in... |
def get_descriptor_defaults(self, api_info, hostname=None):
"""Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dicti... | Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dictionary with the default configuration. | Below is the the instruction that describes the task:
### Input:
Gets a default configuration for a service.
Args:
api_info: _ApiInfo object for this service.
hostname: string, Hostname of the API, to override the value set on the
current service. Defaults to None.
Returns:
A dic... |
def convert_convolution(builder, layer, input_names, output_names, keras_layer):
"""
Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
_check... | Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | Below is the the instruction that describes the task:
### Input:
Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
### Response:
def convert_convolution(buil... |
def _superclasses_for_subject(self, graph, typeof):
"""helper, returns a list of all superclasses of a given class"""
# TODO - this might be replacing a fairly simple graph API query where
# it doesn't need to
classes = []
superclass = typeof
while True:
found... | helper, returns a list of all superclasses of a given class | Below is the the instruction that describes the task:
### Input:
helper, returns a list of all superclasses of a given class
### Response:
def _superclasses_for_subject(self, graph, typeof):
"""helper, returns a list of all superclasses of a given class"""
# TODO - this might be replacing a fairly ... |
def all_examples(self, pred_name=None):
'''
Emits all examples in prolog form for RSD.
:param pred_name: override for the emitted predicate name
'''
target = self.db.target_table
pred_name = pred_name if pred_name else target
examples = self.db.rows(target, [... | Emits all examples in prolog form for RSD.
:param pred_name: override for the emitted predicate name | Below is the the instruction that describes the task:
### Input:
Emits all examples in prolog form for RSD.
:param pred_name: override for the emitted predicate name
### Response:
def all_examples(self, pred_name=None):
'''
Emits all examples in prolog form for RSD.
:param... |
def render(self, template: str, **vars) -> str:
"""
Render the named template.
The current context will be available to the template as the ``ctx`` variable.
:param template: name of the template file
:param vars: extra template variables
:return: the rendered results
... | Render the named template.
The current context will be available to the template as the ``ctx`` variable.
:param template: name of the template file
:param vars: extra template variables
:return: the rendered results | Below is the the instruction that describes the task:
### Input:
Render the named template.
The current context will be available to the template as the ``ctx`` variable.
:param template: name of the template file
:param vars: extra template variables
:return: the rendered results
... |
def diff_dumps(ih1, ih2, tofile=None, name1="a", name2="b", n_context=3):
"""Diff 2 IntelHex objects and produce unified diff output for their
hex dumps.
@param ih1 first IntelHex object to compare
@param ih2 second IntelHex object to compare
@param tofile file-like object to writ... | Diff 2 IntelHex objects and produce unified diff output for their
hex dumps.
@param ih1 first IntelHex object to compare
@param ih2 second IntelHex object to compare
@param tofile file-like object to write output
@param name1 name of the first hex file to show in the diff hea... | Below is the the instruction that describes the task:
### Input:
Diff 2 IntelHex objects and produce unified diff output for their
hex dumps.
@param ih1 first IntelHex object to compare
@param ih2 second IntelHex object to compare
@param tofile file-like object to write output
... |
def setup_graph(self):
""" Will setup the assign operator for that variable. """
all_vars = tfv1.global_variables() + tfv1.local_variables()
for v in all_vars:
if v.name == self.var_name:
self.var = v
break
else:
raise ValueError("{... | Will setup the assign operator for that variable. | Below is the the instruction that describes the task:
### Input:
Will setup the assign operator for that variable.
### Response:
def setup_graph(self):
""" Will setup the assign operator for that variable. """
all_vars = tfv1.global_variables() + tfv1.local_variables()
for v in all_vars:
... |
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, sort_keys=False, **kw):
"""Serialize ``obj`` as a DSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
I... | Serialize ``obj`` as a DSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If `... | Below is the the instruction that describes the task:
### Input:
Serialize ``obj`` as a DSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None... |
def list_scores(self, update_keys, session=None, lightweight=None):
"""
Returns a list of current scores for the given events.
:param list update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'las... | Returns a list of current scores for the given events.
:param list update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastUpdateSequenceProcessed': 2}]
:param requests.session session: Requests session... | Below is the the instruction that describes the task:
### Input:
Returns a list of current scores for the given events.
:param list update_keys: The filter to select desired markets. All markets that match
the criteria in the filter are selected e.g. [{'eventId': '28205674', 'lastUpdateSequenceProc... |
def visit_lambda(self, node):
"""check whether or not the lambda is suspicious
"""
# if the body of the lambda is a call expression with the same
# argument list as the lambda itself, then the lambda is
# possibly unnecessary and at least suspicious.
if node.args.defaults... | check whether or not the lambda is suspicious | Below is the the instruction that describes the task:
### Input:
check whether or not the lambda is suspicious
### Response:
def visit_lambda(self, node):
"""check whether or not the lambda is suspicious
"""
# if the body of the lambda is a call expression with the same
# argument l... |
def remove(self, option):
"""
Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup.
"""
for existing_option in self._options:
if exist... | Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup. | Below is the the instruction that describes the task:
### Input:
Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup.
### Response:
def remove(self, option):
"""
... |
def getsecret(self, section, option, **kwargs):
"""Get a secret from Custodia
"""
# keyword-only arguments, vars and fallback are directly passed through
raw = kwargs.get('raw', False)
value = self.get(section, option, **kwargs)
if raw:
return value
re... | Get a secret from Custodia | Below is the the instruction that describes the task:
### Input:
Get a secret from Custodia
### Response:
def getsecret(self, section, option, **kwargs):
"""Get a secret from Custodia
"""
# keyword-only arguments, vars and fallback are directly passed through
raw = kwargs.get('raw',... |
def safe_get(self, section, key):
"""
Attempt to get a configuration value from a certain section
in a ``cfg`` object but returning None if not found. Avoids the need
to be doing try/except {ConfigParser Exceptions} every time.
"""
try:
#Use full parent functi... | Attempt to get a configuration value from a certain section
in a ``cfg`` object but returning None if not found. Avoids the need
to be doing try/except {ConfigParser Exceptions} every time. | Below is the the instruction that describes the task:
### Input:
Attempt to get a configuration value from a certain section
in a ``cfg`` object but returning None if not found. Avoids the need
to be doing try/except {ConfigParser Exceptions} every time.
### Response:
def safe_get(self, section, ke... |
def create_meta_main(create_path, config, role, categories):
"""
Create a meta template.
"""
meta_file = c.DEFAULT_META_FILE.replace(
"%author_name", config["author_name"])
meta_file = meta_file.replace(
"%author_company", config["author_company"])
meta_file = meta_file.replace("... | Create a meta template. | Below is the the instruction that describes the task:
### Input:
Create a meta template.
### Response:
def create_meta_main(create_path, config, role, categories):
"""
Create a meta template.
"""
meta_file = c.DEFAULT_META_FILE.replace(
"%author_name", config["author_name"])
meta_file =... |
def _pusher_connect_handler(self, data):
"""Event handler for the connection_established event. Binds the
shortlink_scanned event
"""
self.channel = self.pusher.subscribe(self.pos_callback_chan)
for listener in self.pusher_connected_listeners:
listener(data) | Event handler for the connection_established event. Binds the
shortlink_scanned event | Below is the the instruction that describes the task:
### Input:
Event handler for the connection_established event. Binds the
shortlink_scanned event
### Response:
def _pusher_connect_handler(self, data):
"""Event handler for the connection_established event. Binds the
shortlink_scanned ev... |
def t_NAME(self,t):
'[A-Za-z]\w*|\"char\"'
# warning: this allows stuff like SeLeCt with mixed case. who cares.
t.type = KEYWORDS[t.value.lower()] if t.value.lower() in KEYWORDS else 'BOOL' if t.value.lower() in ('is','not') else 'NAME'
return t | [A-Za-z]\w*|\"char\" | Below is the the instruction that describes the task:
### Input:
[A-Za-z]\w*|\"char\"
### Response:
def t_NAME(self,t):
'[A-Za-z]\w*|\"char\"'
# warning: this allows stuff like SeLeCt with mixed case. who cares.
t.type = KEYWORDS[t.value.lower()] if t.value.lower() in KEYWORDS else 'BOOL' if t.value.lo... |
def write(self, data, **keys):
"""
Write data into this HDU
parameters
----------
data: ndarray or list of ndarray
A numerical python array. Should be an ordinary array for image
HDUs, should have fields for tables. To write an ordinary array to
... | Write data into this HDU
parameters
----------
data: ndarray or list of ndarray
A numerical python array. Should be an ordinary array for image
HDUs, should have fields for tables. To write an ordinary array to
a column in a table HDU, use write_column. If... | Below is the the instruction that describes the task:
### Input:
Write data into this HDU
parameters
----------
data: ndarray or list of ndarray
A numerical python array. Should be an ordinary array for image
HDUs, should have fields for tables. To write an ordinar... |
def publish_wp(site_name, output_file, resources, args):
"""Publish a notebook to a wordpress post, using Gutenberg blocks.
Here is what the metadata looks like, in a section of the notebook tagged 'frontmatter'
show_input: hide
github: https://github.com/sandiegodata/notebooks/blob/master/tutorial/A... | Publish a notebook to a wordpress post, using Gutenberg blocks.
Here is what the metadata looks like, in a section of the notebook tagged 'frontmatter'
show_input: hide
github: https://github.com/sandiegodata/notebooks/blob/master/tutorial/American%20Community%20Survey.ipynb
identifier: 5c987397-a954-... | Below is the the instruction that describes the task:
### Input:
Publish a notebook to a wordpress post, using Gutenberg blocks.
Here is what the metadata looks like, in a section of the notebook tagged 'frontmatter'
show_input: hide
github: https://github.com/sandiegodata/notebooks/blob/master/tutori... |
def blake2b(data, digest_size=BLAKE2B_BYTES, key=b'',
salt=b'', person=b'',
encoder=nacl.encoding.HexEncoder):
"""
Hashes ``data`` with blake2b.
:param data: the digest input byte sequence
:type data: bytes
:param digest_size: the requested digest size; must be at most
... | Hashes ``data`` with blake2b.
:param data: the digest input byte sequence
:type data: bytes
:param digest_size: the requested digest size; must be at most
:const:`BLAKE2B_BYTES_MAX`;
the default digest size is
:const:`BLAKE2B_BYTES`
... | Below is the the instruction that describes the task:
### Input:
Hashes ``data`` with blake2b.
:param data: the digest input byte sequence
:type data: bytes
:param digest_size: the requested digest size; must be at most
:const:`BLAKE2B_BYTES_MAX`;
the def... |
def load_df_from_file(file_path, sep=",", header=0):
"""Wrapper around pandas' read_csv."""
with tf.gfile.Open(file_path) as infile:
df = pd.read_csv(infile, sep=sep, header=header)
return df | Wrapper around pandas' read_csv. | Below is the the instruction that describes the task:
### Input:
Wrapper around pandas' read_csv.
### Response:
def load_df_from_file(file_path, sep=",", header=0):
"""Wrapper around pandas' read_csv."""
with tf.gfile.Open(file_path) as infile:
df = pd.read_csv(infile, sep=sep, header=header)
return df |
def set_representative_sequence(self, force_rerun=False):
"""Automatically consolidate loaded sequences (manual, UniProt, or KEGG) and set a single representative
sequence.
Manually set representative sequences override all existing mappings. UniProt mappings override KEGG mappings
exce... | Automatically consolidate loaded sequences (manual, UniProt, or KEGG) and set a single representative
sequence.
Manually set representative sequences override all existing mappings. UniProt mappings override KEGG mappings
except when KEGG mappings have PDBs associated with them and UniProt does... | Below is the the instruction that describes the task:
### Input:
Automatically consolidate loaded sequences (manual, UniProt, or KEGG) and set a single representative
sequence.
Manually set representative sequences override all existing mappings. UniProt mappings override KEGG mappings
exce... |
def udot(op1, op2):
"""Matrix or vector dot product that preserves units
This is a wrapper around np.dot that preserves units.
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(udot(a, b))
[[2. 2.]
[2. 2.]] km*s
"""... | Matrix or vector dot product that preserves units
This is a wrapper around np.dot that preserves units.
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(udot(a, b))
[[2. 2.]
[2. 2.]] km*s | Below is the the instruction that describes the task:
### Input:
Matrix or vector dot product that preserves units
This is a wrapper around np.dot that preserves units.
Examples
--------
>>> from unyt import km, s
>>> a = np.eye(2)*km
>>> b = (np.ones((2, 2)) * 2)*s
>>> print(udot(a, b... |
def replace(self, v):
"""Replace an individual selected by negative tournament selection with
individual v"""
if self.popsize < self._popsize:
return self.add(v)
k = self.tournament(negative=True)
self.clean(self.population[k])
self.population[k] = v
v... | Replace an individual selected by negative tournament selection with
individual v | Below is the the instruction that describes the task:
### Input:
Replace an individual selected by negative tournament selection with
individual v
### Response:
def replace(self, v):
"""Replace an individual selected by negative tournament selection with
individual v"""
if self.pops... |
def get_notebook_name() -> str:
"""Return the full path of the jupyter notebook.
References
----------
https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246
"""
kernel_id = re.search( # type: ignore
'kernel-(.*).json',
ipykernel.connect.get_connection_file()
... | Return the full path of the jupyter notebook.
References
----------
https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246 | Below is the the instruction that describes the task:
### Input:
Return the full path of the jupyter notebook.
References
----------
https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246
### Response:
def get_notebook_name() -> str:
"""Return the full path of the jupyter notebook.... |
def string(self, *pattern, **kwargs):
"""
Add string pattern
:param pattern:
:type pattern:
:return: self
:rtype: Rebulk
"""
self.pattern(self.build_string(*pattern, **kwargs))
return self | Add string pattern
:param pattern:
:type pattern:
:return: self
:rtype: Rebulk | Below is the the instruction that describes the task:
### Input:
Add string pattern
:param pattern:
:type pattern:
:return: self
:rtype: Rebulk
### Response:
def string(self, *pattern, **kwargs):
"""
Add string pattern
:param pattern:
:type pattern:... |
def draw_dot(self, pos, color):
"""
Draw one single dot with the given color on the screen.
:param pos: Position of the dot
:param color: COlor for the dot
:type pos: tuple
:type color: tuple
"""
if 0 <= pos[0] < self.width and 0 <= pos[1] < self.height:
... | Draw one single dot with the given color on the screen.
:param pos: Position of the dot
:param color: COlor for the dot
:type pos: tuple
:type color: tuple | Below is the the instruction that describes the task:
### Input:
Draw one single dot with the given color on the screen.
:param pos: Position of the dot
:param color: COlor for the dot
:type pos: tuple
:type color: tuple
### Response:
def draw_dot(self, pos, color):
"""
... |
def PrimaryDatacenter(self):
"""Returns the primary datacenter object associated with the account.
>>> clc.v2.Account(alias='BTDI').PrimaryDatacenter()
<clc.APIv2.datacenter.Datacenter instance at 0x10a45ce18>
>>> print _
WA1
"""
return(clc.v2.Datacenter(alias=... | Returns the primary datacenter object associated with the account.
>>> clc.v2.Account(alias='BTDI').PrimaryDatacenter()
<clc.APIv2.datacenter.Datacenter instance at 0x10a45ce18>
>>> print _
WA1 | Below is the the instruction that describes the task:
### Input:
Returns the primary datacenter object associated with the account.
>>> clc.v2.Account(alias='BTDI').PrimaryDatacenter()
<clc.APIv2.datacenter.Datacenter instance at 0x10a45ce18>
>>> print _
WA1
### Response:
def Prima... |
def begin(self, sql=None):
"""Begin a transaction."""
self._transaction = True
try:
begin = self._con.begin
except AttributeError:
return self._con.query(sql or 'begin')
else:
# use existing method if available
if sql:
... | Begin a transaction. | Below is the the instruction that describes the task:
### Input:
Begin a transaction.
### Response:
def begin(self, sql=None):
"""Begin a transaction."""
self._transaction = True
try:
begin = self._con.begin
except AttributeError:
return self._con.query(sql o... |
def OnMeasureItem(self, item):
"""Returns the height of the items in the popup"""
item_name = self.GetItems()[item]
return icons[item_name].GetHeight() | Returns the height of the items in the popup | Below is the the instruction that describes the task:
### Input:
Returns the height of the items in the popup
### Response:
def OnMeasureItem(self, item):
"""Returns the height of the items in the popup"""
item_name = self.GetItems()[item]
return icons[item_name].GetHeight() |
def _clean_data(cls, *args, **kwargs):
"""
Convert raw data into a dictionary with plot-type specific methods.
The result of the cleaning operation should be a dictionary.
If the dictionary contains a 'data' field it will be passed directly
(ensuring appropriate formatting). Oth... | Convert raw data into a dictionary with plot-type specific methods.
The result of the cleaning operation should be a dictionary.
If the dictionary contains a 'data' field it will be passed directly
(ensuring appropriate formatting). Otherwise, it should be a
dictionary of data-type spec... | Below is the the instruction that describes the task:
### Input:
Convert raw data into a dictionary with plot-type specific methods.
The result of the cleaning operation should be a dictionary.
If the dictionary contains a 'data' field it will be passed directly
(ensuring appropriate format... |
def summary(self):
"""
Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the
training set. An exception is thrown if no summary exists.
"""
if self.hasSummary:
return BisectingKMeansSummary(super(BisectingKMeansModel, self).summary)
... | Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the
training set. An exception is thrown if no summary exists. | Below is the the instruction that describes the task:
### Input:
Gets summary (e.g. cluster assignments, cluster sizes) of the model trained on the
training set. An exception is thrown if no summary exists.
### Response:
def summary(self):
"""
Gets summary (e.g. cluster assignments, cluster... |
def iter_intersecting(self, iterable, key=None, descending=False):
"""Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect.
"""
return _ContainsVersionIterator(self, iterable, key, descending,
... | Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect. | Below is the the instruction that describes the task:
### Input:
Like `iter_intersect_test`, but returns intersections only.
Returns:
An iterator that returns items from `iterable` that intersect.
### Response:
def iter_intersecting(self, iterable, key=None, descending=False):
"""Like ... |
def cume_dist(expr, sort=None, ascending=True):
"""
Calculate cumulative ratio of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column
"""
return _rank_op(expr,... | Calculate cumulative ratio of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column | Below is the the instruction that describes the task:
### Input:
Calculate cumulative ratio of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:return: calculated column
### Response:
def cume_... |
def contains_points(intersector,
points,
check_direction=None):
"""
Check if a mesh contains a set of points, using ray tests.
If the point is on the surface of the mesh, behavior is
undefined.
Parameters
---------
mesh: Trimesh object
points: (n... | Check if a mesh contains a set of points, using ray tests.
If the point is on the surface of the mesh, behavior is
undefined.
Parameters
---------
mesh: Trimesh object
points: (n,3) points in space
Returns
---------
contains : (n) bool
Whether point is inside mes... | Below is the the instruction that describes the task:
### Input:
Check if a mesh contains a set of points, using ray tests.
If the point is on the surface of the mesh, behavior is
undefined.
Parameters
---------
mesh: Trimesh object
points: (n,3) points in space
Returns
---------
... |
def _bool_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
op_name = _get_op_name(op, special)
def na_op(x, y):
try:
result = op(x, y)
except TypeError:
assert not isinstance(y, (list, ... | Wrapper function for Series arithmetic operations, to avoid
code duplication. | Below is the the instruction that describes the task:
### Input:
Wrapper function for Series arithmetic operations, to avoid
code duplication.
### Response:
def _bool_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
op_na... |
def get_parameter_p_value_too_high_warning(
model_type, model_params, parameter, p_value, maximum_p_value
):
""" Return an empty list or a single warning wrapped in a list indicating
whether model parameter p-value is too high.
Parameters
----------
model_type : :any:`str`
Model type (e... | Return an empty list or a single warning wrapped in a list indicating
whether model parameter p-value is too high.
Parameters
----------
model_type : :any:`str`
Model type (e.g., ``'cdd_hdd'``).
model_params : :any:`dict`
Parameters as stored in :any:`eemeter.CalTRACKUsagePerDayCand... | Below is the the instruction that describes the task:
### Input:
Return an empty list or a single warning wrapped in a list indicating
whether model parameter p-value is too high.
Parameters
----------
model_type : :any:`str`
Model type (e.g., ``'cdd_hdd'``).
model_params : :any:`dict`
... |
def sweep(port, rate, ID, retry=3):
"""
Sends a ping packet to ID's from 0 to maximum and prints out any returned
messages.
Actually send a broadcast and will retry (resend) the ping 3 times ...
"""
if port == 'dummy':
s = ServoSerial(port, rate, fake=True)
else:
s = ServoSerial(port, rate)
if ID < 0:
I... | Sends a ping packet to ID's from 0 to maximum and prints out any returned
messages.
Actually send a broadcast and will retry (resend) the ping 3 times ... | Below is the the instruction that describes the task:
### Input:
Sends a ping packet to ID's from 0 to maximum and prints out any returned
messages.
Actually send a broadcast and will retry (resend) the ping 3 times ...
### Response:
def sweep(port, rate, ID, retry=3):
"""
Sends a ping packet to ID's from 0 t... |
def cache_key(*args, **kwargs):
"""
Base method for computing the cache key with respect to the given
arguments.
"""
key = ""
for arg in args:
if callable(arg):
key += ":%s" % repr(arg)
else:
key += ":%s" % str(arg)
return key | Base method for computing the cache key with respect to the given
arguments. | Below is the the instruction that describes the task:
### Input:
Base method for computing the cache key with respect to the given
arguments.
### Response:
def cache_key(*args, **kwargs):
"""
Base method for computing the cache key with respect to the given
arguments.
"""
key = ""
for a... |
def add_column_xsd(self, tb, column, attrs):
""" Add the XSD for a column to tb (a TreeBuilder) """
if column.nullable:
attrs['minOccurs'] = str(0)
attrs['nillable'] = 'true'
for cls, xsd_type in six.iteritems(self.SIMPLE_XSD_TYPES):
if isinstance(column.type,... | Add the XSD for a column to tb (a TreeBuilder) | Below is the the instruction that describes the task:
### Input:
Add the XSD for a column to tb (a TreeBuilder)
### Response:
def add_column_xsd(self, tb, column, attrs):
""" Add the XSD for a column to tb (a TreeBuilder) """
if column.nullable:
attrs['minOccurs'] = str(0)
a... |
def view_package_path(self, package: str) -> _PATH:
'''Print the path to the APK of the given.'''
if package not in self.view_packgets_list():
raise NoSuchPackageException(
f'There is no such package {package!r}.')
output, _ = self._execute(
'-s', self.dev... | Print the path to the APK of the given. | Below is the the instruction that describes the task:
### Input:
Print the path to the APK of the given.
### Response:
def view_package_path(self, package: str) -> _PATH:
'''Print the path to the APK of the given.'''
if package not in self.view_packgets_list():
raise NoSuchPackageExcept... |
def transform(self, image_feature, bigdl_type="float"):
"""
transform ImageFeature
"""
callBigDlFunc(bigdl_type, "transformImageFeature", self.value, image_feature)
return image_feature | transform ImageFeature | Below is the the instruction that describes the task:
### Input:
transform ImageFeature
### Response:
def transform(self, image_feature, bigdl_type="float"):
"""
transform ImageFeature
"""
callBigDlFunc(bigdl_type, "transformImageFeature", self.value, image_feature)
return i... |
def birch(args):
"""
%prog birch seqids layout
Plot birch macro-synteny, with an embedded phylogenetic tree to the right.
"""
p = OptionParser(birch.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="8x6")
if len(args) != 2:
sys.exit(not p.print_help())
seqids, la... | %prog birch seqids layout
Plot birch macro-synteny, with an embedded phylogenetic tree to the right. | Below is the the instruction that describes the task:
### Input:
%prog birch seqids layout
Plot birch macro-synteny, with an embedded phylogenetic tree to the right.
### Response:
def birch(args):
"""
%prog birch seqids layout
Plot birch macro-synteny, with an embedded phylogenetic tree to the ri... |
def port_bindings(self, value):
"""
{
u'8080/tcp': [
{
u'host_port': u'8080',
u'host_ip': u''
}
]
}
"""
if isinstance(value, (list, dict)):
... | {
u'8080/tcp': [
{
u'host_port': u'8080',
u'host_ip': u''
}
]
} | Below is the the instruction that describes the task:
### Input:
{
u'8080/tcp': [
{
u'host_port': u'8080',
u'host_ip': u''
}
]
}
### Response:
def port_bindings(self, value):
... |
def remove(cls, repo, name):
"""Remove the remote with the given name
:return: the passed remote name to remove
"""
repo.git.remote("rm", name)
if isinstance(name, cls):
name._clear_cache()
return name | Remove the remote with the given name
:return: the passed remote name to remove | Below is the the instruction that describes the task:
### Input:
Remove the remote with the given name
:return: the passed remote name to remove
### Response:
def remove(cls, repo, name):
"""Remove the remote with the given name
:return: the passed remote name to remove
"""
... |
def richtext_filters(content):
"""
Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting.
"""
for filter_name in settings.RICHTEXT_FILTERS:
filter_func = import_dotted_path(filter_name)
content = filter_func... | Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting. | Below is the the instruction that describes the task:
### Input:
Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting.
### Response:
def richtext_filters(content):
"""
Takes a value edited via the WYSIWYG editor, and passes i... |
def hidelist(self, window_name, object_name):
"""
Hide combo box list / menu
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full na... | Hide combo box list / menu
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type... | Below is the the instruction that describes the task:
### Input:
Hide combo box list / menu
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to type in, either full... |
def encode_pdf_date(d: datetime) -> str:
"""Encode Python datetime object as PDF date string
From Adobe pdfmark manual:
(D:YYYYMMDDHHmmSSOHH'mm')
D: is an optional prefix. YYYY is the year. All fields after the year are
optional. MM is the month (01-12), DD is the day (01-31), HH is the
hour (0... | Encode Python datetime object as PDF date string
From Adobe pdfmark manual:
(D:YYYYMMDDHHmmSSOHH'mm')
D: is an optional prefix. YYYY is the year. All fields after the year are
optional. MM is the month (01-12), DD is the day (01-31), HH is the
hour (00-23), mm are the minutes (00-59), and SS are th... | Below is the the instruction that describes the task:
### Input:
Encode Python datetime object as PDF date string
From Adobe pdfmark manual:
(D:YYYYMMDDHHmmSSOHH'mm')
D: is an optional prefix. YYYY is the year. All fields after the year are
optional. MM is the month (01-12), DD is the day (01-31), ... |
def fgrad_y(self, y, return_precalc=False):
"""
gradient of f w.r.t to y ([N x 1])
:returns: Nx1 vector of derivatives, unless return_precalc is true,
then it also returns the precomputed stuff
"""
d = self.d
mpsi = self.psi
# vectorized version
... | gradient of f w.r.t to y ([N x 1])
:returns: Nx1 vector of derivatives, unless return_precalc is true,
then it also returns the precomputed stuff | Below is the the instruction that describes the task:
### Input:
gradient of f w.r.t to y ([N x 1])
:returns: Nx1 vector of derivatives, unless return_precalc is true,
then it also returns the precomputed stuff
### Response:
def fgrad_y(self, y, return_precalc=False):
"""
gradient... |
def instance_of(klass, arg):
"""Require that a value has a particular Python type."""
if not isinstance(arg, klass):
raise com.IbisTypeError(
'Given argument with type {} is not an instance of {}'.format(
type(arg), klass
)
)
return arg | Require that a value has a particular Python type. | Below is the the instruction that describes the task:
### Input:
Require that a value has a particular Python type.
### Response:
def instance_of(klass, arg):
"""Require that a value has a particular Python type."""
if not isinstance(arg, klass):
raise com.IbisTypeError(
'Given argument... |
def get_tab_tip(self, filename, is_modified=None, is_readonly=None):
"""Return tab menu title"""
text = u"%s — %s"
text = self.__modified_readonly_title(text,
is_modified, is_readonly)
if self.tempfile_path is not None\
and f... | Return tab menu title | Below is the the instruction that describes the task:
### Input:
Return tab menu title
### Response:
def get_tab_tip(self, filename, is_modified=None, is_readonly=None):
"""Return tab menu title"""
text = u"%s — %s"
text = self.__modified_readonly_title(text,
... |
def from_array(array):
"""
Deserialize a new ResponseParameters from a given dictionary.
:return: new ResponseParameters instance.
:rtype: ResponseParameters
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, d... | Deserialize a new ResponseParameters from a given dictionary.
:return: new ResponseParameters instance.
:rtype: ResponseParameters | Below is the the instruction that describes the task:
### Input:
Deserialize a new ResponseParameters from a given dictionary.
:return: new ResponseParameters instance.
:rtype: ResponseParameters
### Response:
def from_array(array):
"""
Deserialize a new ResponseParameters from a g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.