Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> if unit:
unit = '<tr><td><b>%s</b>: </td><td>%s</td></tr>' % (
tr('Unit'), unit)
description = """
<table border="0" width="100%%">
<tr><td><b>%s</b>: </td><td>%s</td></tr>
<tr><td><b>%s</b>: </td><td>... | geom_type = layer_geometry_point['key'] |
Given the code snippet: <|code_start|> tr('Unit'), unit)
description = """
<table border="0" width="100%%">
<tr><td><b>%s</b>: </td><td>%s</td></tr>
<tr><td><b>%s</b>: </td><td>%s</td></tr>
%s
%s
<tr><td><b>%s</b>: </td><td>... | geom_type = layer_geometry_polygon['key'] |
Using the snippet: <|code_start|>
def layer_description_html(layer, keywords=None):
"""Form a html description of a given layer based on the layer
parameters and keywords if provided
:param layer: The layer to get the description
:type layer: QgsMapLayer
:param keywords: The layer keywords
... | elif purpose == layer_purpose_exposure['key']: |
Predict the next line after this snippet: <|code_start|> extent_b = (coord_transform.transform(
extent_b, QgsCoordinateTransform.ReverseTransform))
return extent_a.intersects(extent_b)
def layer_description_html(layer, keywords=None):
"""Form a html description of a given layer based on the... | if purpose == layer_purpose_hazard['key']: |
Here is a snippet: <|code_start|>
layer_purpose_nearby_places = {
'key': 'nearby_places',
'name': tr('Nearby Places'),
'description': tr('Lorem ipsum on the nearby places layers.'),
'allowed_geometries': [layer_geometry_point],
'citations': [
{
'text': None,
'link': N... | 'description': property_layer_purpose['description'], |
Continue the code snippet: <|code_start|> should accept params 'current' (int), 'maximum' (int) and 'step' (str).
Defaults to None.
:type callback: function
:return: The buffered vector layer.
:rtype: QgsVectorLayer
"""
# Layer output
output_layer_name = buffer_steps['output_laye... | get_utm_epsg(center.x(), center.y(), input_crs)) |
Next line prediction: <|code_start|>
# We add the hazard value name to the attribute table.
attributes.append(radii[radius])
# We add the value of buffer distance to the attribute table.
attributes.append(radius)
circle = geom.buffer(radius, 30)
... | buffered.keywords['layer_purpose'] = layer_purpose_hazard['key'] |
Next line prediction: <|code_start|>__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '$Format:%H$'
class TestMultiBuffering(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_multi_buffer_points(self):
"""Test we can multi buff... | result = multi_buffering( |
Predict the next line after this snippet: <|code_start|> analysis_layer.keywords[inasafe_keyword_version_key] = (
inasafe_keyword_version)
analysis_layer.keywords['inasafe_fields'] = {
analysis_name_field['key']: analysis_name_field['field_name']
}
return analysis_layer
def create_prof... | tabular.keywords['layer_purpose'] = layer_purpose_profiling['key'] |
Given the following code snippet before the placeholder: <|code_start|>@profile
def create_virtual_aggregation(geometry, crs):
"""Function to create aggregation layer based on extent.
:param geometry: The geometry to use as an extent.
:type geometry: QgsGeometry
:param crs: The Coordinate Reference Sy... | layer_purpose_aggregation['key']) |
Given the code snippet: <|code_start|>
:param analysis_extent: The analysis extent.
:type analysis_extent: QgsGeometry
:param crs: The CRS to use.
:type crs: QgsCoordinateReferenceSystem
:param name: The name of the analysis.
:type name: basestring
:returns: A polygon layer with exposure'... | layer_purpose_analysis_impacted['key']) |
Continue the code snippet: <|code_start|>
:param geometry: The geometry to use as an extent.
:type geometry: QgsGeometry
:param crs: The Coordinate Reference System to use for the layer.
:type crs: QgsCoordinateReferenceSystem
:returns: A polygon layer with exposure's crs.
:rtype: QgsVectorLay... | inasafe_keyword_version) |
Given snippet: <|code_start|> msg = '%s not found in %s' % (
size_field['key'], layer.keywords['title'])
raise InvalidKeywordsForProcessingAlgorithm(msg)
indexes = []
absolute_field_keys = [f['key'] for f in count_fields]
for field, field_name in list(fields.items()):
if ... | new_size = size( |
Given the code snippet: <|code_start|> 'key': 'earthquake_mmi_scale',
'name': tr('Earthquake MMI scale'),
'description': tr(
'This scale, composed of increasing levels of intensity that range '
'from imperceptible shaking to catastrophic destruction, is '
'designated by Roman numerals... | 'fatality_rate': earthquake_fatality_rate(10), |
Next line prediction: <|code_start|> 'numeric_default_max': 2,
'citations': [
{
'text': None,
'link': None
}
],
}
],
'exposures': [
exposure_land_cover,
exposure_place,
expo... | 'Options.' % current_earthquake_model_name()), |
Given the code snippet: <|code_start|> summary_field['field_name'])
# Only add absolute value if there is no summarization / no exposure
# classification
if not summarization_dicts:
# For each absolute values
for absolute_field in list(absolute_values.keys()):
field_d... | if hazard_affected[hazard_class] == not_exposed_class['key']: |
Given the following code snippet before the placeholder: <|code_start|> total += value
attributes.append(total_affected)
attributes.append(total_not_affected)
attributes.append(total_not_exposed)
attributes.append(total)
if summarization_dicts:
for key in... | tabular.keywords['title'] = layer_purpose_exposure_summary_table['name'] |
Based on the snippet: <|code_start|> :return: The new tabular table, without geometry.
:rtype: QgsVectorLayer
.. versionadded:: 4.0
"""
output_layer_name = summary_4_exposure_summary_table_steps[
'output_layer_name']
source_fields = aggregate_hazard.keywords['inasafe_fields']
sourc... | flat_table = FlatTable('hazard_class', 'exposure_class') |
Continue the code snippet: <|code_start|> self.action_multi_exposure = None
self.action_function_centric_wizard = None
self.action_import_dialog = None
self.action_keywords_wizard = None
self.action_minimum_needs = None
self.action_minimum_needs_config = None
self.... | inasafe_release_status == 'final' and not developer_mode) |
Predict the next line for this snippet: <|code_start|> # import here only so that it is AFTER i18n set up
dialog = NeedsManagerDialog(
parent=self.iface.mainWindow(),
dock=self.dock_widget)
dialog.exec_() # modal
def show_options(self):
"""Show the options d... | current_version = StrictVersion(inasafe_version) |
Predict the next line after this snippet: <|code_start|> """
if not layer:
enable_keyword_wizard = False
elif not hasattr(layer, 'providerType'):
enable_keyword_wizard = False
elif layer.providerType() == 'wms':
enable_keyword_wizard = False
els... | if layer_purpose == layer_purpose_exposure['key']: |
Given the following code snippet before the placeholder: <|code_start|> enable_keyword_wizard = False
elif not hasattr(layer, 'providerType'):
enable_keyword_wizard = False
elif layer.providerType() == 'wms':
enable_keyword_wizard = False
else:
enab... | elif layer_purpose == layer_purpose_hazard['key']: |
Continue the code snippet: <|code_start|> """Test translations work."""
def setUp(self):
"""Runs before each test."""
if 'LANG' in iter(list(os.environ.keys())):
os.environ.__delitem__('LANG')
def tearDown(self):
"""Runs after each test."""
if 'LANG' in iter(list... | file_path = safe_dir('i18n/inasafe_id.qm') |
Next line prediction: <|code_start|>
"""Try to make a layer valid."""
__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '$Format:%H$'
@profile
def clean_layer(layer):
"""Clean a vector layer.
:param layer: The vector layer.
... | initialize_processing() |
Continue the code snippet: <|code_start|>
__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '$Format:%H$'
@profile
def clean_layer(layer):
"""Clean a vector layer.
:param layer: The vector layer.
:type layer: qgis.core.QgsVe... | feedback = create_processing_feedback() |
Given the code snippet: <|code_start|>
__copyright__ = "Copyright 2016, The InaSAFE Project"
__license__ = "GPL version 3"
__email__ = "info@inasafe.org"
__revision__ = '$Format:%H$'
@profile
def clean_layer(layer):
"""Clean a vector layer.
:param layer: The vector layer.
:type layer: qgis.core.QgsVector... | context = create_processing_context(feedback=feedback) |
Next line prediction: <|code_start|>
# This postprocessor function is also used in the aggregation_summary
def post_processor_affected_function(
exposure=None, hazard=None, classification=None, hazard_class=None):
"""Private function used in the affected postprocessor.
It returns a boolean if it's affe... | for hazard in hazard_classes_all: |
Using the snippet: <|code_start|>
:param hazard: The hazard to use.
:type hazard: str
:param classification: The hazard classification to use.
:type classification: str
:param hazard_class: The hazard class of the feature.
:type hazard_class: str
:return: If this hazard class is affected ... | affected = not_exposed_class['key'] |
Given the following code snippet before the placeholder: <|code_start|> help_text = ''
def __init__(self, subcommand_creator):
# keep a local copy of the config file which is useful during
# autocompletion
self.config = None
# set up the subcommand options
self.subcomma... | self.task_graph = load_task_graph(config=config) |
Here is a snippet: <|code_start|> self.subcommand_creator = subcommand_creator
self.option_parser = self.subcommand_creator.add_parser(
self.get_command_name(),
help=self.help_text,
description=self.help_text,
)
self.add_command_line_options()
def ... | return get_task_kwargs_list(config=self.config) |
Using the snippet: <|code_start|> self.option_parser = self.subcommand_creator.add_parser(
self.get_command_name(),
help=self.help_text,
description=self.help_text,
)
self.add_command_line_options()
def get_command_name(self):
"""The command name d... | except (ConfigurationNotFound, YamlError): |
Using the snippet: <|code_start|> self.option_parser = self.subcommand_creator.add_parser(
self.get_command_name(),
help=self.help_text,
description=self.help_text,
)
self.add_command_line_options()
def get_command_name(self):
"""The command name d... | except (ConfigurationNotFound, YamlError): |
Given snippet: <|code_start|>
class memoize(object):
"""Decorator. Caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned
(not reevaluated).
adapted from https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
"""
de... | frozen_kwargs = FrozenDict(kwargs) |
Given snippet: <|code_start|>
Returns:
np.ndarray: A TPM with the same number of dimensions, with the nodes
marginalized out.
"""
return tpm.sum(tuple(node_indices), keepdims=True) / (
np.array(tpm.shape)[list(node_indices)].prod()
)
def infer_edge(tpm, a, b, contexts):
"""... | a_off = context[:a] + OFF + context[a:] |
Based on the snippet: <|code_start|> Returns:
np.ndarray: A TPM with the same number of dimensions, with the nodes
marginalized out.
"""
return tpm.sum(tuple(node_indices), keepdims=True) / (
np.array(tpm.shape)[list(node_indices)].prod()
)
def infer_edge(tpm, a, b, contexts):
... | a_on = context[:a] + ON + context[a:] |
Next line prediction: <|code_start|>
Args:
tpm (np.ndarray): The TPM in state-by-node, multidimensional form.
a (int): The index of the putative source node.
b (int): The index of the putative sink node.
Returns:
bool: ``True`` if the edge |A -> B| exists, ``False`` otherwise.
... | all_contexts = tuple(all_states(network_size - 1)) |
Predict the next line after this snippet: <|code_start|> [0., 0., 0., 0., 1., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 1.],
[0., 0., 0., 0., 0., 1., 0., 0.]])
>>> tpm = np.array([[0.1, 0.3, 0.7],
... [0.3, 0.9, 0.2],
... | if is_deterministic(tpm): |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# test/test_utils.py
def test_all_states():
assert list(utils.all_states(0)) == []
assert list(utils.all_states(1)) == [(0,), (1,)]
states = [
(0, 0, 0),
(1, 0, 0),
(0, 1, 0),
(1, 1, 0),
... | close_enough = phi - constants.EPSILON / 2 |
Given the code snippet: <|code_start|> assert np.array_equal(
distribution.marginal(repertoire, 0), np.array([[[0.5]], [[0.5]]])
)
assert np.array_equal(distribution.marginal(repertoire, 1), np.array([[[0], [1]]]))
assert np.array_equal(distribution.marginal(repertoire, 2), np.array([[[0, 1]]]))
... | mechanisms = powerset(s.node_indices) |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# test/test_connectivity/test_connectivity.py
def test_get_inputs_from_cm():
# fmt: off
cm = np.array([
[0, 1, 0],
[1, 1, 1],
[0, 0, 0],
])
# fmt: on
<|code_end|>
, predict the immediate next l... | assert connectivity.get_inputs_from_cm(0, cm) == (1,) |
Here is a snippet: <|code_start|> [0.375, 0.375, 0.125, 0.125],
])
)
# fmt: on
partition = ((0,), (1, 2))
grouping = (((0,), (1,)), ((0, 1), (2,)))
coarse_grain = macro.CoarseGrain(partition, grouping)
assert np.array_equal(coarse_grain.make_mapping(), [0, 1, 0, 1, 0, 1, 2, 3]... | with pytest.raises(ConditionallyDependentError): |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# test_subsystem_cause_effect_info.py
def test_cause_info(s):
mechanism = (0, 1)
purview = (0, 2)
<|code_end|>
. Write the next line using the current file imports:
from pyphi.distance import hamming_emd
and context from other ... | answer = hamming_emd( |
Next line prediction: <|code_start|> return None
order = "C" if big_endian else "F"
# For efficiency, use `ravel` (which returns a view of the array) instead
# of `np.flatten` (which copies the whole array).
return repertoire.squeeze().ravel(order=order)
def unflatten(repertoire, purview, N, b... | @cache(cache={}, maxmem=None) |
Based on the snippet: <|code_start|>
def dumps(obj, **user_kwargs):
"""Serialize ``obj`` as JSON-formatted stream."""
return json.dumps(obj, **_encoder_kwargs(user_kwargs))
def dump(obj, fp, **user_kwargs):
"""Serialize ``obj`` as a JSON-formatted stream and write to ``fp`` (a
``.write()``-supporting... | class _ObjectCache(cache.DictCache): |
Using the snippet: <|code_start|> [1, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 0, 0],
[0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1]]
cm2 = [
[1, 1, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, ... | utils.block_cm(self.cm) |
Here is a snippet: <|code_start|> """Default label for a node."""
return "n{}".format(index)
def default_labels(indices):
"""Default labels for serveral nodes."""
return tuple(default_label(i) for i in indices)
class NodeLabels(collections.abc.Sequence):
"""Text labels for nodes in a network.
... | validate.node_labels(self.labels, node_indices) |
Here is a snippet: <|code_start|> """
def __init__(self, labels, node_indices):
if labels is None:
labels = default_labels(node_indices)
self.labels = tuple(label for label in labels)
self.node_indices = node_indices
validate.node_labels(self.labels, node_indices)
... | @cmp.sametype |
Here is a snippet: <|code_start|> wait_for(is_init,timeout=60 * 10, sleep_duration=1)
if self.is_replicaset_initialized():
log_info("Successfully initiated replica set cluster '%s'!" %
self.id)
else:
msg = ("Timeout error: Init... | users.setup_cluster_users(self, primary_server) |
Next line prediction: <|code_start|> def can_become_primary(self):
return not self.is_arbiter() and self.get_priority() != 0
###########################################################################
def get_member_repl_config(self):
# create the member repl config with host
membe... | tag_mapping = get_cluster_member_alt_address_mapping() |
Based on the snippet: <|code_start|>
ignore = ['host', 'server']
for key,value in self.__document__.items():
if key not in ignore :
member_conf[key] = value
self._apply_alt_address_mapping(member_conf)
return member_conf
###############################... | log_verbose("No alt address tag value created for alt address" |
Given snippet: <|code_start|> # set the alt address if it is different than host
if alt_address and alt_address != member_conf['host']:
tags[tag_name] = alt_address
else:
log_verbose("No alt address tag value created for alt address"
... | log_error("%s" % e) |
Predict the next line for this snippet: <|code_start|>
return False
###########################################################################
def initialize_replicaset(self, suggested_primary_server=None):
log_info("Initializing replica set cluster '%s' %s..." %
(self.id,
... | log_db_command(init_cmd) |
Given snippet: <|code_start|>__author__ = 'abdul'
###############################################################################
# list clusters command
###############################################################################
def list_clusters_command(parsed_options):
clusters = repository.lookup_all_clus... | log_info("No clusters configured") |
Given snippet: <|code_start|>__author__ = 'abdul'
###############################################################################
# list clusters command
###############################################################################
def list_clusters_command(parsed_options):
clusters = repository.lookup_all_clus... | desc = to_string(cluster.get_description()) |
Continue the code snippet: <|code_start|>###############################################################################
# This is mongodb's default dbpath
DEFAULT_DBPATH='/data/db'
LOCK_FILE_NAME = "mongod.lock"
###############################################################################
# MongodServer Class
###... | return resolve_path(dbpath) |
Next line prediction: <|code_start|> ###########################################################################
def get_repl_lag(self, master_status):
"""
Given two 'members' elements from rs.status(),
return lag between their optimes (in secs).
"""
member_status ... | return self.is_wired_tiger() and version < make_version_info("3.2.10") and system_memory_size_gbs() < 30 |
Predict the next line after this snippet: <|code_start|> return member
except (Exception,RuntimeError), e:
log_debug("Cannot get member rs status from server '%s'."
" cause: %s" % (self.id, e))
log_exception(e)
... | log_verbose("isMaster command failed on server '%s'. Cause %s" % |
Based on the snippet: <|code_start|> def command_needs_auth(self, dbname, cmd):
# isMaster command does not need auth
if "isMaster" in cmd or "ismaster" in cmd:
return False
if 'shutdown' in cmd and self.is_arbiter_server():
return False
# otherwise use defaul... | log_debug("Cannot get rs status from server '%s'. cause: %s" % |
Next line prediction: <|code_start|> if "isMaster" in cmd or "ismaster" in cmd:
return False
if 'shutdown' in cmd and self.is_arbiter_server():
return False
# otherwise use default behavior
return super(MongodServer, self).command_needs_auth(dbname, cmd)
####... | log_exception(e) |
Given snippet: <|code_start|>
###########################################################################
def has_joined_replica(self):
master_result = self.is_master_command()
if master_result:
return (master_result.get("ismaster") or
master_result.get("arbiterOn... | log_info("Defaulting TCMALLOC_AGGRESSIVE_DECOMMIT=y") |
Predict the next line for this snippet: <|code_start|> return master_result.get("secondary")
###########################################################################
def is_master_command(self):
try:
if self.is_online():
result = self.db_command({"isMaster" : 1... | raise MongoctlException("Unable to determine replicaset status for" |
Continue the code snippet: <|code_start|> ###########################################################################
def get_repl_lag(self, master_status):
"""
Given two 'members' elements from rs.status(),
return lag between their optimes (in secs).
"""
member_st... | return self.is_wired_tiger() and version < make_version_info("3.2.10") and system_memory_size_gbs() < 30 |
Predict the next line after this snippet: <|code_start|>__author__ = 'abdul'
###############################################################################
# list servers command
###############################################################################
def list_servers_command(parsed_options):
servers = rep... | log_info("No servers have been configured.") |
Here is a snippet: <|code_start|>__author__ = 'abdul'
###############################################################################
# list servers command
###############################################################################
def list_servers_command(parsed_options):
servers = repository.lookup_all_serv... | to_string(server.get_description()), |
Given the code snippet: <|code_start|>__author__ = 'abdul'
###############################################################################
# print uri command
###############################################################################
def print_uri_command(parsed_options):
id = parsed_options.id
db = parse... | raise MongoctlException("Cannot find a server or a cluster with" |
Given the following code snippet before the placeholder: <|code_start|> shutdown_success = mongo_stop_server(server, pid, force=False)
if not can_stop_mongoly or not shutdown_success:
log_verbose(" ... taking more forceful measures ... ")
shutdown_success = \
prompt_or_force_sto... | document_pretty_string(shutdown_cmd))) |
Given the code snippet: <|code_start|> try_mongo_force=can_stop_mongoly)
if shutdown_success:
log_info("Server '%s' has stopped." % server.id)
else:
raise MongoctlException("Unable to stop server '%s'." %
server.id)
#######... | wait_for(stop_pred,timeout=MAX_SHUTDOWN_WAIT) |
Given snippet: <|code_start|> return False
else:
return True
except Exception, e:
log_exception(e)
log_error("Failed to gracefully stop server '%s'. Cause: %s" %
(server.id, e))
return False
###################################################... | kill_process(pid, force=True) |
Predict the next line for this snippet: <|code_start|> log_error("Failed to gracefully stop server '%s'. Cause: %s" %
(server.id, e))
return False
###############################################################################
def force_stop_server(server, pid, try_mongo_force=True):
... | if not is_pid_alive(pid): |
Next line prediction: <|code_start|> elif server.is_server_pid_alive():
log_info("Unable to issue 'shutdown' command to server '%s'. The server is not responding." % server.id)
can_stop_mongoly = False
else:
log_info("Server '%s' is not running." %
... | raise MongoctlException("Unable to stop server '%s'." % |
Here is a snippet: <|code_start|># The MIT License
# Copyright (c) 2012 ObjectLabs Corporation
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limit... | self.assertTrue(make_version_info("1.2.0") < make_version_info("1.2.1")) |
Given the code snippet: <|code_start|># a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permi... | self.assertTrue(is_valid_version("1.0.1")) |
Continue the code snippet: <|code_start|> shard_member.get_server().id == shard_id)
or (shard_member.get_cluster() and
shard_member.get_cluster().id == shard_id)):
return shard_member
################################################... | log_info("Shard cluster already configured. Will only be adding" |
Based on the snippet: <|code_start|> cluster_member_addresses.append(
cluster_member.get_server().get_address())
return "%s/%s" % (shard_member.get_cluster().id,
",".join(cluster_member_addresses))
#######################################... | document_pretty_string(configured_shards)) |
Given the following code snippet before the placeholder: <|code_start|>class VersionPreference(object):
EXACT = "EXACT"
MAJOR_GE = "MAJOR_GE"
LATEST_STABLE = "LATEST_STABLE"
EXACT_OR_MINOR = "EXACT_OR_MINOR"
LATEST_MINOR = "LATEST_MINOR"
DEFAULT = "DEFAULT"
def extract_mongo_exe_options(parsed_... | mongo_installs_dir = config.get_mongodb_installs_dir() |
Predict the next line for this snippet: <|code_start|> exe_version_tuples = find_all_executables(executable_name)
if len(exe_version_tuples) > 0:
selected_exe = best_executable_match(executable_name,
exe_version_tuples,
... | raise MongoctlException("Unable to find a compatible '%s' executable." % executable_name) |
Given the following code snippet before the placeholder: <|code_start|> # Return nothing if nothing compatible
if len(compatible_exes) == 0:
return None
# find the best fit
compatible_exes.sort(key=lambda t: t[1])
exe = compatible_exes[-1]
return mongo_exe_object(exe[0], exe[1])
####... | return path is not None and is_exe(path) |
Using the snippet: <|code_start|> log_info("Using %s at '%s' version '%s'..." %
(executable_name,
selected_exe.path,
selected_exe.version))
return selected_exe
## ok nothing found at all
log_error("Unable to find a compatib... | path_executable = which(executable_name) |
Given the following code snippet before the placeholder: <|code_start|> "for version %s (edition %s). You may need to run 'mongoctl "
"install-mongodb %s %s' to install it.\n\n"
"Here is your enviroment:\n\n"
"$PATH=%s\n\n"
"$MONGO_HOME=%s\n\n"
"mongoDBIn... | mongo_home = resolve_path(mongo_home) |
Here is a snippet: <|code_start|> exe_version = mongo_exe_version(mongo_exe)
exe_ver_tuples.append((mongo_exe, exe_version))
except Exception, e:
log_exception(e)
log_verbose("Skipping executable '%s': %s" % (mongo_exe, e))
return exe_ver_tuples
#############... | vers_spew = execute_command([mongod_path, "--version"]) |
Using the snippet: <|code_start|> return "\n".join(strs)
###############################################################################
def is_valid_mongo_exe(path):
return path is not None and is_exe(path)
###############################################################################
def get_mongo_home_exe... | result = make_version_info(full_version, edition=edition) |
Predict the next line after this snippet: <|code_start|> LATEST_STABLE = "LATEST_STABLE"
EXACT_OR_MINOR = "EXACT_OR_MINOR"
LATEST_MINOR = "LATEST_MINOR"
DEFAULT = "DEFAULT"
def extract_mongo_exe_options(parsed_args, supported_options):
options_extract = {}
# Iterating over parsed options dict
... | MongoDBEdition.COMMUNITY) |
Predict the next line for this snippet: <|code_start|>__author__ = 'abdul'
###############################################################################
# Document Wrapper Class
###############################################################################
class DocumentWrapper(object):
#######################... | return document_pretty_string(self.__document__) |
Using the snippet: <|code_start|>__author__ = 'abdul'
###############################################################################
# CONSTS
###############################################################################
DEFAULT_TAIL_LINES = 15
#####################################################################... | server = repository.lookup_server(parsed_options.server) |
Continue the code snippet: <|code_start|>__author__ = 'abdul'
###############################################################################
# CONSTS
###############################################################################
DEFAULT_TAIL_LINES = 15
#############################################################... | execute_command(["touch", logpath]) |
Continue the code snippet: <|code_start|> if not self._group_message_proc:
self._group_message_proc = Process(target=_write_message,
args=(
self._group_message_queue,
... | encryptor = Encryptor(encrypt_key, IV) |
Using the snippet: <|code_start|> root = get_project_root()
conf_path = os.path.join(root, "conf", "blizzard.conf")
if not os.path.exists(conf_path):
self._init_config(conf_path)
with open(conf_path,"rb") as conf:
configs = conf.read()
config_dict = dic... | get_single_msg_dir(), |
Predict the next line after this snippet: <|code_start|>
def saveSingleMsg(self, sender, receiver, msg):
if sender and receiver and isinstance(msg, list) and msg[0] and msg[1]:
users = "&&".join(sorted([sender,receiver]))
self._single_message_queue.put((sender,users,msg))
... | get_group_msg_dir(), |
Given the following code snippet before the placeholder: <|code_start|> )
)
self._single_message_proc.start()
return True
else:
return False
def saveGroupMsg(self, sender, group_... | path = os.path.join(get_picture_dir(),pic_name+"."+format_) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding:utf-8 -*-
class MessageSaver(object):
def __init__(self):
self._single_message_queue = Queue()
self._group_message_queue = Queue()
self._get_config()
self._terminator = "\nquit\n"
self._singl... | root = get_project_root() |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
#coding:utf-8
"""
Author: --<alen-alex>
Purpose: provide a message content retrieval interface to web server,
retrieve from /data directory
Created: 2014/11/4
"""
#----------------------------------------------------------------------
d... | encryptor = Encryptor(key,IV) |
Here is a snippet: <|code_start|> try:
query_year, query_month, query_day = date.split("-")
except ValueError:
return ("Wrong date format", 404)
file_ = os.path.join(directory,query_year,query_month,query_day+".bin")
if not os.path.exists(file_):
return ("File does not exist", 404... | root = get_project_root() |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
def authorized(func):
@wraps(func)
def action(*args, **kwargs):
token = request.headers.get('token', None)
account = session.get('account', None)
if token and account:
<|code_end|>
, determine the next line of code. You have impo... | db_session = get_session() |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
def authorized(func):
@wraps(func)
def action(*args, **kwargs):
token = request.headers.get('token', None)
account = session.get('account', None)
if token and account:
db_session ... | auth = db_session.query(UserAuth).filter(UserAuth.account == account).one() |
Predict the next line for this snippet: <|code_start|>
class SignerTest(TestCase):
fixtures = ["cybersource-test.yaml"]
def test_sign(self):
profile = get_sa_profile()
<|code_end|>
with the help of current file imports:
from django.test import TestCase
from django.test.client import RequestFactory
f... | signer = SecureAcceptanceSigner(profile.secret_key) |
Given the following code snippet before the placeholder: <|code_start|>
class SignerTest(TestCase):
fixtures = ["cybersource-test.yaml"]
def test_sign(self):
<|code_end|>
, predict the next line using imports from the current file:
from django.test import TestCase
from django.test.client import RequestFactor... | profile = get_sa_profile() |
Given snippet: <|code_start|> "req_transaction_uuid": str(randrange(100000000000, 999999999999)),
"request_token": "Ahj/7wSR8sYxolZgxwyeIkG7lw3ZNnDmLNjMqcSPOS4lfDoTAFLiV8OhM0glqN4vpQyaSZbpAd0+3AnI+WMY0SswY4ZPAAAALRaM",
"req_merchant_secure_data4": encrypt_session_id(session_id),
"score_bi... | SecureAcceptanceSigner(profile.secret_key).sign(data, fields).decode("utf8") |
Continue the code snippet: <|code_start|> self.assertEqual(lines.count(), 1)
line = lines[0]
self.assertEqual(line.quantity, quantity)
self.assertEqual(line.product_id, product_id)
payment_events = order.payment_events.filter(event_type__name="Authorise")
self.assertEqual... | if status == DECISION_REVIEW: |
Continue the code snippet: <|code_start|> # Mask Card data
token_resp_data["req_card_number"] = (
"xxxxxxxxxxxx" + token_resp_data["req_card_number"][-4:]
)
token_resp_data.pop("req_card_cvn", None)
# Add auth fields
token_resp_data["auth_amount"] = token_reque... | self, number, product_id, quantity=1, status=DECISION_ACCEPT, card_last4="1111" |
Given the following code snippet before the placeholder: <|code_start|> req_bill_to_surname = NullCharField(max_length=255)
req_card_expiry_date = NullCharField(max_length=10)
req_reference_number = NullCharField(max_length=128)
req_transaction_type = NullCharField(max_length=20)
req_transaction_uuid... | return DECISION_ACCEPT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.