text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_import(name, is_from, is_star):
"""Use python to resolve an import. Args: name: The fully qualified module name. Returns: The path to the module source file or None. """ |
# Don't try to resolve relative imports or builtins here; they will be
# handled by resolve.Resolver
if name.startswith('.') or is_builtin(name):
return None
ret = _resolve_import(name)
if ret is None and is_from and not is_star:
package, _ = name.rsplit('.', 1)
ret = _resolve_import(package)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_imports(filename):
"""Get all the imports in a file. Each import is a tuple of: (name, alias, is_from, is_star, source_file) """ |
with open(filename, "rb") as f:
src = f.read()
finder = ImportFinder()
finder.visit(ast.parse(src, filename=filename))
imports = []
for i in finder.imports:
name, _, is_from, is_star = i
imports.append(i + (resolve_import(name, is_from, is_star),))
return imports |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_file(self, filename):
"""Add a file and all its immediate dependencies to the graph.""" |
assert not self.final, 'Trying to mutate a final graph.'
self.add_source_file(filename)
resolved, unresolved = self.get_file_deps(filename)
self.graph.add_node(filename)
for f in resolved:
self.graph.add_node(f)
self.graph.add_edge(filename, f)
for imp in unresolved:
self.broken_deps[filename].add(imp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def follow_file(self, f, seen, trim):
"""Whether to recurse into a file's dependencies.""" |
return (f not in self.graph.nodes and
f not in seen and
(not trim or
not isinstance(self.provenance[f],
(resolve.Builtin, resolve.System)))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_file_recursive(self, filename, trim=False):
"""Add a file and all its recursive dependencies to the graph. Args: filename: The name of the file. trim: Whether to trim the dependencies of builtin and system files. """ |
assert not self.final, 'Trying to mutate a final graph.'
self.add_source_file(filename)
queue = collections.deque([filename])
seen = set()
while queue:
filename = queue.popleft()
self.graph.add_node(filename)
try:
deps, broken = self.get_file_deps(filename)
except parsepy.ParseError:
# Python couldn't parse `filename`. If we're sure that it is a
# Python file, we mark it as unreadable and keep the node in the
# graph so importlab's callers can do their own syntax error
# handling if desired.
if filename.endswith('.py'):
self.unreadable_files.add(filename)
else:
self.graph.remove_node(filename)
continue
for f in broken:
self.broken_deps[filename].add(f)
for f in deps:
if self.follow_file(f, seen, trim):
queue.append(f)
seen.add(f)
self.graph.add_node(f)
self.graph.add_edge(filename, f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shrink_to_node(self, scc):
"""Shrink a strongly connected component into a node.""" |
assert not self.final, 'Trying to mutate a final graph.'
self.graph.add_node(scc)
edges = list(self.graph.edges)
for k, v in edges:
if k not in scc and v in scc:
self.graph.remove_edge(k, v)
self.graph.add_edge(k, scc)
elif k in scc and v not in scc:
self.graph.remove_edge(k, v)
self.graph.add_edge(scc, v)
for node in scc.nodes:
self.graph.remove_node(node) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(self):
"""Finalise the graph, after adding all input files to it.""" |
assert not self.final, 'Trying to mutate a final graph.'
# Replace each strongly connected component with a single node `NodeSet`
for scc in sorted(nx.kosaraju_strongly_connected_components(self.graph),
key=len, reverse=True):
if len(scc) == 1:
break
self.shrink_to_node(NodeSet(scc))
self.final = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sorted_source_files(self):
"""Returns a list of targets in topologically sorted order.""" |
assert self.final, 'Call build() before using the graph.'
out = []
for node in nx.topological_sort(self.graph):
if isinstance(node, NodeSet):
out.append(node.nodes)
else:
# add a one-element list for uniformity
out.append([node])
return list(reversed(out)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_all_unresolved(self):
"""Returns a set of all unresolved imports.""" |
assert self.final, 'Call build() before using the graph.'
out = set()
for v in self.broken_deps.values():
out |= v
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(cls, env, filenames, trim=False):
"""Create and return a final graph. Args: env: An environment.Environment object filenames: A list of filenames trim: Whether to trim the dependencies of builtin and system files. Returns: An immutable ImportGraph with the recursive dependencies of all the files in filenames """ |
import_graph = cls(env)
for filename in filenames:
import_graph.add_file_recursive(os.path.abspath(filename), trim)
import_graph.build()
return import_graph |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_source_file_provenance(self, filename):
"""Infer the module name if possible.""" |
module_name = resolve.infer_module_name(filename, self.path)
return resolve.Direct(filename, module_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collect_files(path, extension):
"""Collect all the files with extension in a directory tree.""" |
# We should only call this on an actual directory; callers should do the
# validation.
assert os.path.isdir(path)
out = []
# glob would be faster (see PEP471) but python glob doesn't do **/*
for root, _, files in os.walk(path):
out += [os.path.join(root, f) for f in files if f.endswith(extension)]
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_source_files(filenames, cwd=None):
"""Expand a list of filenames passed in as sources. This is a helper function for handling command line arguments that specify a list of source files and directories. Any directories in filenames will be scanned recursively for .py files. Any files that do not end with ".py" will be dropped. Args: filenames: A list of filenames to process. cwd: An optional working directory to expand relative paths Returns: A list of sorted full paths to .py files """ |
out = []
for f in expand_paths(filenames, cwd):
if os.path.isdir(f):
# If we have a directory, collect all the .py files within it.
out += collect_files(f, ".py")
else:
if f.endswith(".py"):
out.append(f)
return sorted(set(out)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_suffix(string, suffix):
"""Remove a suffix from a string if it exists.""" |
if string.endswith(suffix):
return string[:-(len(suffix))]
return string |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_directory(self, filename):
"""Create a subdirectory in the temporary directory.""" |
path = os.path.join(self.path, filename)
makedirs(path)
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_file(self, filename, indented_data=None):
"""Create a file in the temporary directory. Dedents the contents. """ |
filedir, filename = os.path.split(filename)
if filedir:
self.create_directory(filedir)
path = os.path.join(self.path, filedir, filename)
data = indented_data
if isinstance(data, bytes) and not isinstance(data, str):
# This is binary data rather than text.
mode = 'wb'
else:
mode = 'w'
if data:
data = textwrap.dedent(data)
with open(path, mode) as fi:
if data:
fi.write(data)
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_reply(cls, thread, user, content):
""" Create a new reply for an existing Thread. Mark thread as unread for all other participants, and mark thread as read by replier. """ |
msg = cls.objects.create(thread=thread, sender=user, content=content)
thread.userthread_set.exclude(user=user).update(deleted=False, unread=True)
thread.userthread_set.filter(user=user).update(deleted=False, unread=False)
message_sent.send(sender=cls, message=msg, thread=thread, reply=True)
return msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_message(cls, from_user, to_users, subject, content):
""" Create a new Message and Thread. Mark thread as unread for all recipients, and mark thread as read and deleted from inbox by creator. """ |
thread = Thread.objects.create(subject=subject)
for user in to_users:
thread.userthread_set.create(user=user, deleted=False, unread=True)
thread.userthread_set.create(user=from_user, deleted=True, unread=False)
msg = cls.objects.create(thread=thread, sender=from_user, content=content)
message_sent.send(sender=cls, message=msg, thread=thread, reply=False)
return msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unread(thread, user):
""" Check whether there are any unread messages for a particular thread for a user. """ |
return bool(thread.userthread_set.filter(user=user, unread=True)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split(self, text):
"""Splits text and returns a list of the resulting sentences.""" |
text = cleanup(text)
return self.sent_detector.tokenize(text.strip()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_from_file(path):
""" Return file contents as string. """ |
with open(path) as f:
s = f.read().strip()
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xml_equal(xml_file1, xml_file2):
""" Parse xml and convert to a canonical string representation so we don't have to worry about semantically meaningless differences """ |
def canonical(xml_file):
# poor man's canonicalization, since we don't want to install
# external packages just for unittesting
s = et.tostring(et.parse(xml_file).getroot()).decode("UTF-8")
s = re.sub("[\n|\t]*", "", s)
s = re.sub("\s+", " ", s)
s = "".join(sorted(s)).strip()
return s
return canonical(xml_file1) == canonical(xml_file2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_files(dir_path, recursive=True):
""" Return a list of files in dir_path. """ |
for root, dirs, files in os.walk(dir_path):
file_list = [os.path.join(root, f) for f in files]
if recursive:
for dir in dirs:
dir = os.path.join(root, dir)
file_list.extend(list_files(dir, recursive=True))
return file_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(input_dir, output_dir, function):
""" Apply function to all files in input_dir and save the resulting ouput files in output_dir. """ |
if not os.path.exists(output_dir):
os.makedirs(output_dir)
logger = log.get_global_console_logger()
logger.info("Processing files in {}.".format(input_dir))
input_file_names = os.listdir(input_dir)
for input_file_name in input_file_names:
logger.info("Processing {}.".format(input_file_name))
input_file = os.path.join(input_dir, input_file_name)
with codecs.open(input_file, "r", encoding="UTF-8") as f:
input_string = f.read()
output_string = function(input_string)
output_file = os.path.join(output_dir, input_file_name)
with codecs.open(output_file, "w", encoding="UTF-8") as f:
f.write(output_string)
logger.info("Saved processed files to {}.".format(output_dir)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_sentences(self):
""" ROUGE requires texts split into sentences. In case the texts are not already split, this method can be used. """ |
from pyrouge.utils.sentence_splitter import PunktSentenceSplitter
self.log.info("Splitting sentences.")
ss = PunktSentenceSplitter()
sent_split_to_string = lambda s: "\n".join(ss.split(s))
process_func = partial(
DirectoryProcessor.process, function=sent_split_to_string)
self.__process_summaries(process_func) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_config_static(system_dir, system_filename_pattern, model_dir, model_filename_pattern, config_file_path, system_id=None):
""" Write the ROUGE configuration file, which is basically a list of system summary files and their corresponding model summary files. pyrouge uses regular expressions to automatically find the matching model summary files for a given system summary file (cf. docstrings for system_filename_pattern and model_filename_pattern). system_dir: Path of directory containing system summaries. system_filename_pattern: Regex string for matching system summary filenames. model_dir: Path of directory containing model summaries. model_filename_pattern: Regex string for matching model summary filenames. config_file_path: Path of the configuration file. system_id: Optional system ID string which will appear in the ROUGE output. """ |
system_filenames = [f for f in os.listdir(system_dir)]
system_models_tuples = []
system_filename_pattern = re.compile(system_filename_pattern)
for system_filename in sorted(system_filenames):
match = system_filename_pattern.match(system_filename)
if match:
id = match.groups(0)[0]
model_filenames = Rouge155.__get_model_filenames_for_id(
id, model_dir, model_filename_pattern)
system_models_tuples.append(
(system_filename, sorted(model_filenames)))
if not system_models_tuples:
raise Exception(
"Did not find any files matching the pattern {} "
"in the system summaries directory {}.".format(
system_filename_pattern.pattern, system_dir))
with codecs.open(config_file_path, 'w', encoding='utf-8') as f:
f.write('<ROUGE-EVAL version="1.55">')
for task_id, (system_filename, model_filenames) in enumerate(
system_models_tuples, start=1):
eval_string = Rouge155.__get_eval_string(
task_id, system_id,
system_dir, system_filename,
model_dir, model_filenames)
f.write(eval_string)
f.write("</ROUGE-EVAL>") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_config(self, config_file_path=None, system_id=None):
""" Write the ROUGE configuration file, which is basically a list of system summary files and their matching model summary files. This is a non-static version of write_config_file_static(). config_file_path: Path of the configuration file. system_id: Optional system ID string which will appear in the ROUGE output. """ |
if not system_id:
system_id = 1
if (not config_file_path) or (not self._config_dir):
self._config_dir = mkdtemp()
config_filename = "rouge_conf.xml"
else:
config_dir, config_filename = os.path.split(config_file_path)
verify_dir(config_dir, "configuration file")
self._config_file = os.path.join(self._config_dir, config_filename)
Rouge155.write_config_static(
self._system_dir, self._system_filename_pattern,
self._model_dir, self._model_filename_pattern,
self._config_file, system_id)
self.log.info(
"Written ROUGE configuration to {}".format(self._config_file)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(self, system_id=1, rouge_args=None):
""" Run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. The summaries are assumed to be in the one-sentence-per-line HTML format ROUGE understands. system_id: Optional system ID which will be printed in ROUGE's output. Returns: Rouge output as string. """ |
self.write_config(system_id=system_id)
options = self.__get_options(rouge_args)
command = [self._bin_path] + options
env = None
if hasattr(self, "_home_dir") and self._home_dir:
env = {'ROUGE_EVAL_HOME': self._home_dir}
self.log.info(
"Running ROUGE with command {}".format(" ".join(command)))
rouge_output = check_output(command, env=env).decode("UTF-8")
return rouge_output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_and_evaluate(self, system_id=1, split_sentences=False, rouge_args=None):
""" Convert plain text summaries to ROUGE format and run ROUGE to evaluate the system summaries in system_dir against the model summaries in model_dir. Optionally split texts into sentences in case they aren't already. This is just a convenience method combining convert_summaries_to_rouge_format() and evaluate(). split_sentences: Optional argument specifying if sentences should be split. system_id: Optional system ID which will be printed in ROUGE's output. Returns: ROUGE output as string. """ |
if split_sentences:
self.split_sentences()
self.__write_summaries()
rouge_output = self.evaluate(system_id, rouge_args)
return rouge_output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def output_to_dict(self, output):
""" Convert the ROUGE output into python dictionary for further processing. """ |
#0 ROUGE-1 Average_R: 0.02632 (95%-conf.int. 0.02632 - 0.02632)
pattern = re.compile(
r"(\d+) (ROUGE-\S+) (Average_\w): (\d.\d+) "
r"\(95%-conf.int. (\d.\d+) - (\d.\d+)\)")
results = {}
for line in output.split("\n"):
match = pattern.match(line)
if match:
sys_id, rouge_type, measure, result, conf_begin, conf_end = \
match.groups()
measure = {
'Average_R': 'recall',
'Average_P': 'precision',
'Average_F': 'f_score'
}[measure]
rouge_type = rouge_type.lower().replace("-", '_')
key = "{}_{}".format(rouge_type, measure)
results[key] = float(result)
results["{}_cb".format(key)] = float(conf_begin)
results["{}_ce".format(key)] = float(conf_end)
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __set_rouge_dir(self, home_dir=None):
""" Verfify presence of ROUGE-1.5.5.pl and data folder, and set those paths. """ |
if not home_dir:
self._home_dir = self.__get_rouge_home_dir_from_settings()
else:
self._home_dir = home_dir
self.save_home_dir()
self._bin_path = os.path.join(self._home_dir, 'ROUGE-1.5.5.pl')
self.data_dir = os.path.join(self._home_dir, 'data')
if not os.path.exists(self._bin_path):
raise Exception(
"ROUGE binary not found at {}. Please set the "
"correct path by running pyrouge_set_rouge_path "
"/path/to/rouge/home.".format(self._bin_path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __process_summaries(self, process_func):
""" Helper method that applies process_func to the files in the system and model folders and saves the resulting files to new system and model folders. """ |
temp_dir = mkdtemp()
new_system_dir = os.path.join(temp_dir, "system")
os.mkdir(new_system_dir)
new_model_dir = os.path.join(temp_dir, "model")
os.mkdir(new_model_dir)
self.log.info(
"Processing summaries. Saving system files to {} and "
"model files to {}.".format(new_system_dir, new_model_dir))
process_func(self._system_dir, new_system_dir)
process_func(self._model_dir, new_model_dir)
self._system_dir = new_system_dir
self._model_dir = new_model_dir |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __get_options(self, rouge_args=None):
""" Get supplied command line arguments for ROUGE or use default ones. """ |
if self.args:
options = self.args.split()
elif rouge_args:
options = rouge_args.split()
else:
options = [
'-e', self._data_dir,
'-c', 95,
'-2',
'-1',
'-U',
'-r', 1000,
'-n', 4,
'-w', 1.2,
'-a',
]
options = list(map(str, options))
options = self.__add_config_option(options)
return options |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __create_dir_property(self, dir_name, docstring):
""" Generate getter and setter for a directory property. """ |
property_name = "{}_dir".format(dir_name)
private_name = "_" + property_name
setattr(self, private_name, None)
def fget(self):
return getattr(self, private_name)
def fset(self, path):
verify_dir(path, dir_name)
setattr(self, private_name, path)
p = property(fget=fget, fset=fset, doc=docstring)
setattr(self.__class__, property_name, p) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __set_dir_properties(self):
""" Automatically generate the properties for directories. """ |
directories = [
("home", "The ROUGE home directory."),
("data", "The path of the ROUGE 'data' directory."),
("system", "Path of the directory containing system summaries."),
("model", "Path of the directory containing model summaries."),
]
for (dirname, docstring) in directories:
self.__create_dir_property(dirname, docstring) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __clean_rouge_args(self, rouge_args):
""" Remove enclosing quotation marks, if any. """ |
if not rouge_args:
return
quot_mark_pattern = re.compile('"(.+)"')
match = quot_mark_pattern.match(rouge_args)
if match:
cleaned_args = match.group(1)
return cleaned_args
else:
return rouge_args |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_auth(self, username, password):
''' This function is called to check if a username password combination
is valid. '''
return username == self.queryname and password == self.querypw |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def requires_auth(self, func):
'''
Decorator to prompt for user name and password. Useful for data dumps,
etc. That you don't want to be public.
'''
@wraps(func)
def decorated(*args, **kwargs):
''' Wrapper '''
auth = request.authorization
if not auth or not self.check_auth(auth.username, auth.password):
return self.authenticate()
return func(*args, **kwargs)
return decorated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_exp_error(exception):
"""Handle errors by sending an error page.""" |
app.logger.error(
"%s (%s) %s", exception.value, exception.errornum, str(dict(request.args)))
return exception.error_page(request, CONFIG.get('HIT Configuration',
'contact_email_on_error')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_worker_status():
''' Check worker status route '''
if 'workerId' not in request.args:
resp = {"status": "bad request"}
return jsonify(**resp)
else:
worker_id = request.args['workerId']
assignment_id = request.args['assignmentId']
allow_repeats = CONFIG.getboolean('HIT Configuration', 'allow_repeats')
if allow_repeats: # if you allow repeats focus on current worker/assignment combo
try:
part = Participant.query.\
filter(Participant.workerid == worker_id).\
filter(Participant.assignmentid == assignment_id).one()
status = part.status
except exc.SQLAlchemyError:
status = NOT_ACCEPTED
else: # if you disallow repeats search for highest status of anything by this worker
try:
matches = Participant.query.\
filter(Participant.workerid == worker_id).all()
numrecs = len(matches)
if numrecs==0: # this should be caught by exception, but just to be safe
status = NOT_ACCEPTED
else:
status = max([record.status for record in matches])
except exc.SQLAlchemyError:
status = NOT_ACCEPTED
resp = {"status" : status}
return jsonify(**resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def give_consent():
""" Serves up the consent in the popup window. """ |
if not ('hitId' in request.args and 'assignmentId' in request.args and
'workerId' in request.args):
raise ExperimentError('hit_assign_worker_id_not_set_in_consent')
hit_id = request.args['hitId']
assignment_id = request.args['assignmentId']
worker_id = request.args['workerId']
mode = request.args['mode']
with open('templates/consent.html', 'r') as temp_file:
consent_string = temp_file.read()
consent_string = insert_mode(consent_string, mode)
return render_template_string(
consent_string,
hitid=hit_id,
assignmentid=assignment_id,
workerid=worker_id
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_ad_via_hitid(hit_id):
''' Get ad via HIT id '''
username = CONFIG.get('psiTurk Access', 'psiturk_access_key_id')
password = CONFIG.get('psiTurk Access', 'psiturk_secret_access_id')
try:
req = requests.get('https://api.psiturk.org/api/ad/lookup/' + hit_id,
auth=(username, password))
except:
raise ExperimentError('api_server_not_reachable')
else:
if req.status_code == 200:
return req.json()['ad_id']
else:
return "error" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(uid=None):
""" Load experiment data, which should be a JSON object and will be stored after converting to string. """ |
app.logger.info("GET /sync route with id: %s" % uid)
try:
user = Participant.query.\
filter(Participant.uniqueid == uid).\
one()
except exc.SQLAlchemyError:
app.logger.error("DB error: Unique user not found.")
try:
resp = json.loads(user.datastring)
except:
resp = {
"condition": user.cond,
"counterbalance": user.counterbalance,
"assignmentId": user.assignmentid,
"workerId": user.workerid,
"hitId": user.hitid,
"bonus": user.bonus
}
return jsonify(**resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(uid=None):
""" Save experiment data, which should be a JSON object and will be stored after converting to string. """ |
app.logger.info("PUT /sync route with id: %s" % uid)
try:
user = Participant.query.\
filter(Participant.uniqueid == uid).\
one()
except exc.SQLAlchemyError:
app.logger.error("DB error: Unique user not found.")
if hasattr(request, 'json'):
user.datastring = request.data.decode('utf-8').encode(
'ascii', 'xmlcharrefreplace'
)
db_session.add(user)
db_session.commit()
try:
data = json.loads(user.datastring)
except:
data = {}
trial = data.get("currenttrial", None)
app.logger.info("saved data for %s (current trial: %s)", uid, trial)
resp = {"status": "user data saved"}
return jsonify(**resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def quitter():
""" Mark quitter as such. """ |
unique_id = request.form['uniqueId']
if unique_id[:5] == "debug":
debug_mode = True
else:
debug_mode = False
if debug_mode:
resp = {"status": "didn't mark as quitter since this is debugging"}
return jsonify(**resp)
else:
try:
unique_id = request.form['uniqueId']
app.logger.info("Marking quitter %s" % unique_id)
user = Participant.query.\
filter(Participant.uniqueid == unique_id).\
one()
user.status = QUITEARLY
db_session.add(user)
db_session.commit()
except exc.SQLAlchemyError:
raise ExperimentError('tried_to_quit')
else:
resp = {"status": "marked as quitter"}
return jsonify(**resp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def debug_complete():
''' Debugging route for complete. '''
if not 'uniqueId' in request.args:
raise ExperimentError('improper_inputs')
else:
unique_id = request.args['uniqueId']
mode = request.args['mode']
try:
user = Participant.query.\
filter(Participant.uniqueid == unique_id).one()
user.status = COMPLETED
user.endhit = datetime.datetime.now()
db_session.add(user)
db_session.commit()
except:
raise ExperimentError('error_setting_worker_complete')
else:
if (mode == 'sandbox' or mode == 'live'): # send them back to mturk.
return render_template('closepopup.html')
else:
return render_template('complete.html') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regularpage(foldername=None, pagename=None):
""" Route not found by the other routes above. May point to a static template. """ |
if foldername is None and pagename is None:
raise ExperimentError('page_not_found')
if foldername is None and pagename is not None:
return render_template(pagename)
else:
return render_template(foldername+"/"+pagename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run_webserver():
''' Run web server '''
host = "0.0.0.0"
port = CONFIG.getint('Server Parameters', 'port')
print "Serving on ", "http://" + host + ":" + str(port)
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.jinja_env.auto_reload = True
app.run(debug=True, host=host, port=port) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def random_id_generator(self, size=6, chars=string.ascii_uppercase +
string.digits):
''' Generate random id numbers '''
return ''.join(random.choice(chars) for x in range(size)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_bonus(worker_dict):
" Adds DB-logged worker bonus to worker list data "
try:
unique_id = '{}:{}'.format(worker_dict['workerId'], worker_dict['assignmentId'])
worker = Participant.query.filter(
Participant.uniqueid == unique_id).one()
worker_dict['bonus'] = worker.bonus
except sa.exc.InvalidRequestError:
# assignment is found on mturk but not in local database.
worker_dict['bonus'] = 'N/A'
return worker_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_workers(self, status=None, chosen_hits=None, assignment_ids=None, all_studies=False):
'''
Status, if set, can be one of `Submitted`, `Approved`, or `Rejected`
'''
if assignment_ids:
workers = [self.get_worker(assignment_id) for assignment_id in assignment_ids]
else:
workers = self.amt_services.get_workers(assignment_status=status, chosen_hits=chosen_hits)
if workers is False:
raise Exception('*** failed to get workers')
if not all_studies:
my_hitids = self._get_my_hitids()
workers = [worker for worker in workers if worker['hitId'] in my_hitids]
workers = [self.add_bonus(worker) for worker in workers]
return workers |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hit_extend(self, hit_id, assignments, minutes):
""" Add additional worker assignments or minutes to a HIT. Args: hit_id: A list conaining one hit_id string. assignments: Variable <int> for number of assignments to add. minutes: Variable <int> for number of minutes to add. Returns: A side effect of this function is that the state of a HIT changes on AMT servers. Raises: """ |
assert type(hit_id) is list
assert type(hit_id[0]) is str
if self.amt_services.extend_hit(hit_id[0], assignments, minutes):
print "HIT extended." |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hit_delete(self, all_hits, hit_ids=None):
''' Delete HIT. '''
if all_hits:
hits_data = self.amt_services.get_all_hits()
hit_ids = [hit.options['hitid'] for hit in hits_data if \
hit.options['status'] == "Reviewable"]
for hit in hit_ids:
# Check that the HIT is reviewable
status = self.amt_services.get_hit_status(hit)
if not status:
print "*** Error getting hit status"
return
if self.amt_services.get_hit_status(hit) != "Reviewable":
print("*** This hit is not 'Reviewable' and so can not be "
"deleted")
return
else:
success = self.amt_services.delete_hit(hit)
# self.web_services.delete_ad(hit) # also delete the ad
if success:
if self.sandbox:
print "deleting sandbox HIT", hit
else:
print "deleting live HIT", hit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hit_expire(self, all_hits, hit_ids=None):
''' Expire all HITs. '''
if all_hits:
hits_data = self.get_active_hits()
hit_ids = [hit.options['hitid'] for hit in hits_data]
for hit in hit_ids:
success = self.amt_services.expire_hit(hit)
if success:
if self.sandbox:
print "expiring sandbox HIT", hit
else:
print "expiring live HIT", hit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hit_create(self, numWorkers, reward, duration):
''' Create a HIT '''
if self.sandbox:
mode = 'sandbox'
else:
mode = 'live'
server_loc = str(self.config.get('Server Parameters', 'host'))
use_psiturk_ad_server = self.config.getboolean('Shell Parameters', 'use_psiturk_ad_server')
if use_psiturk_ad_server:
if not self.web_services.check_credentials():
error_msg = '\n'.join(['*****************************',
' Sorry, your psiTurk Credentials are invalid.\n ',
' You cannot create ads and hits until you enter valid credentials in ',
' the \'psiTurk Access\' section of ~/.psiturkconfig. You can obtain your',
' credentials or sign up at https://www.psiturk.org/login.\n'])
raise Exception(error_msg)
if not self.amt_services.verify_aws_login():
error_msg = '\n'.join(['*****************************',
' Sorry, your AWS Credentials are invalid.\n ',
' You cannot create ads and hits until you enter valid credentials in ',
' the \'AWS Access\' section of ~/.psiturkconfig. You can obtain your ',
' credentials via the Amazon AMT requester website.\n'])
raise Exception(error_msg)
ad_id = None
if use_psiturk_ad_server:
ad_id = self.create_psiturk_ad()
create_failed = False
fail_msg = None
if ad_id is not False:
ad_location = self.web_services.get_ad_url(ad_id, int(self.sandbox))
hit_config = self.generate_hit_config(ad_location, numWorkers, reward, duration)
hit_id = self.amt_services.create_hit(hit_config)
if hit_id is not False:
if not self.web_services.set_ad_hitid(ad_id, hit_id, int(self.sandbox)):
create_failed = True
fail_msg = " Unable to update Ad on http://ad.psiturk.org to point at HIT."
else:
create_failed = True
fail_msg = " Unable to create HIT on Amazon Mechanical Turk."
else:
create_failed = True
fail_msg = " Unable to create Ad on http://ad.psiturk.org."
else: # not using psiturk ad server
ad_location = "{}?mode={}".format(self.config.get('Shell Parameters', 'ad_location'), mode )
hit_config = self.generate_hit_config(ad_location, numWorkers, reward, duration)
create_failed = False
hit_id = self.amt_services.create_hit(hit_config)
if hit_id is False:
create_failed = True
fail_msg = " Unable to create HIT on Amazon Mechanical Turk."
if create_failed:
print '\n'.join(['*****************************',
' Sorry, there was an error creating hit and registering ad.'])
if fail_msg is None:
fail_msg = ''
raise Exception(fail_msg)
return (hit_id, ad_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def db_aws_list_regions(self):
''' List AWS DB regions '''
regions = self.db_services.list_regions()
if regions != []:
print "Avaliable AWS regions:"
for reg in regions:
print '\t' + reg,
if reg == self.db_services.get_region():
print "(currently selected)"
else:
print '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def db_aws_set_region(self, region_name):
''' Set AWS region '''
# interactive = False # Not used
if region_name is None:
# interactive = True # Not used
self.db_aws_list_regions()
allowed_regions = self.db_services.list_regions()
region_name = "NONSENSE WORD1234"
tries = 0
while region_name not in allowed_regions:
if tries == 0:
region_name = raw_input('Enter the name of the region you '
'would like to use: ')
else:
print("*** The region name (%s) you entered is not allowed, " \
"please choose from the list printed above (use type 'db " \
"aws_list_regions'." % region_name)
region_name = raw_input('Enter the name of the region you '
'would like to use: ')
tries += 1
if tries > 5:
print("*** Error, region you are requesting not available. "
"No changes made to regions.")
return
self.db_services.set_region(region_name)
print "Region updated to ", region_name
self.config.set('AWS Access', 'aws_region', region_name, True)
if self.server.is_server_running() == 'yes':
self.server_restart() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def db_aws_list_instances(self):
''' List AWS DB instances '''
instances = self.db_services.get_db_instances()
if not instances:
print("There are no DB instances associated with your AWS account " \
"in region " + self.db_services.get_region())
else:
print("Here are the current DB instances associated with your AWS " \
"account in region " + self.db_services.get_region())
for dbinst in instances:
print '\t'+'-'*20
print "\tInstance ID: " + dbinst.id
print "\tStatus: " + dbinst.status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def db_aws_delete_instance(self, instance_id):
''' Delete AWS DB instance '''
interactive = False
if instance_id is None:
interactive = True
instances = self.db_services.get_db_instances()
instance_list = [dbinst.id for dbinst in instances]
if interactive:
valid = False
if len(instances) == 0:
print("There are no instances you can delete currently. Use "
"`db aws_create_instance` to make one.")
return
print "Here are the available instances you can delete:"
for inst in instances:
print "\t ", inst.id, "(", inst.status, ")"
while not valid:
instance_id = raw_input('Enter the instance identity you would '
'like to delete: ')
res = self.db_services.validate_instance_id(instance_id)
if res is True:
valid = True
else:
print(res + " Try again, instance name not valid. Check " \
"for typos.")
if instance_id in instance_list:
valid = True
else:
valid = False
print("Try again, instance not present in this account. "
"Try again checking for typos.")
else:
res = self.db_services.validate_instance_id(instance_id)
if res is not True:
print("*** Error, instance name either not valid. Try again "
"checking for typos.")
return
if instance_id not in instance_list:
print("*** Error, This instance not present in this account. "
"Try again checking for typos. Run `db aws_list_instances` to "
"see valid list.")
return
user_input = raw_input(
"Deleting an instance will erase all your data associated with the "
"database in that instance. Really quit? y or n:"
)
if user_input == 'y':
res = self.db_services.delete_db_instance(instance_id)
if res:
print("AWS RDS database instance %s deleted. Run `db " \
"aws_list_instances` for current status." % instance_id)
else:
print("*** Error deleting database instance %s. " \
"It maybe because it is still being created, deleted, or is " \
"being backed up. Run `db aws_list_instances` for current " \
"status." % instance_id)
else:
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def init(self, *args):
'''init method
Takes our custom options from self.options and creates a config
dict which specifies custom settings.
'''
cfg = {}
for k, v in self.options.items():
if k.lower() in self.cfg.settings and v is not None:
cfg[k.lower()] = v
return cfg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def wait_until_online(function, ip, port):
""" Uses Wait_For_State to wait for the server to come online, then runs the given function. """ |
awaiting_service = Wait_For_State(lambda: not is_port_available(ip, port), function)
awaiting_service.start()
return awaiting_service |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def process():
''' Figure out how we were invoked '''
invoked_as = os.path.basename(sys.argv[0])
if invoked_as == "psiturk":
launch_shell()
elif invoked_as == "psiturk-server":
launch_server()
elif invoked_as == "psiturk-shell":
launch_shell()
elif invoked_as == "psiturk-setup-example":
setup_example()
elif invoked_as == "psiturk-install":
install_from_exchange() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def install_from_exchange():
''' Install from experiment exchange. '''
parser = argparse.ArgumentParser(
description='Download experiment from the psiturk.org experiment\
exchange (http://psiturk.org/ee).'
)
parser.add_argument(
'exp_id', metavar='exp_id', type=str, help='the id number of the\
experiment in the exchange'
)
args = parser.parse_args()
exp_exch = ExperimentExchangeServices()
exp_exch.download_experiment(args.exp_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setup_example():
''' Add commands for testing, etc. '''
parser = argparse.ArgumentParser(
description='Creates a simple default project (stroop) in the current\
directory with the necessary psiTurk files.'
)
# Optional flags
parser.add_argument(
'-v', '--version', help='Print version number.', action="store_true"
)
args = parser.parse_args()
# If requested version just print and quite
if args.version:
print version_number
else:
import psiturk.setup_example as se
se.setup_example() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def colorize(target, color, use_escape=True):
''' Colorize target string. Set use_escape to false when text will not be
interpreted by readline, such as in intro message.'''
def escape(code):
''' Escape character '''
return '\001%s\002' % code
if color == 'purple':
color_code = '\033[95m'
elif color == 'cyan':
color_code = '\033[96m'
elif color == 'darkcyan':
color_code = '\033[36m'
elif color == 'blue':
color_code = '\033[93m'
elif color == 'green':
color_code = '\033[92m'
elif color == 'yellow':
color_code = '\033[93m'
elif color == 'red':
color_code = '\033[91m'
elif color == 'white':
color_code = '\033[37m'
elif color == 'bold':
color_code = '\033[1m'
elif color == 'underline':
color_code = '\033[4m'
else:
color_code = ''
if use_escape:
return escape(color_code) + target + escape('\033[0m')
else:
return color_code + target + '\033[m' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def default(self, cmd):
''' Collect incorrect and mistyped commands '''
choices = ["help", "mode", "psiturk_status", "server", "shortcuts",
"worker", "db", "edit", "open", "config", "show",
"debug", "setup_example", "status", "tunnel", "amt_balance",
"download_datafiles", "exit", "hit", "load", "quit", "save",
"shell", "version"]
print "%s is not a psiTurk command. See 'help'." %(cmd)
print "Did you mean this?\n %s" %(process.extractOne(cmd,
choices)[0]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_offline_configuration(self):
''' Check offline configuration file'''
quit_on_start = False
database_url = self.config.get('Database Parameters', 'database_url')
host = self.config.get('Server Parameters', 'host', 'localhost')
if database_url[:6] != 'sqlite':
print("*** Error: config.txt option 'database_url' set to use "
"mysql://. Please change this sqllite:// while in cabin mode.")
quit_on_start = True
if host != 'localhost':
print("*** Error: config option 'host' is not set to localhost. "
"Please change this to localhost while in cabin mode.")
quit_on_start = True
if quit_on_start:
exit() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_intro_prompt(self):
''' Print cabin mode message '''
sys_status = open(self.help_path + 'cabin.txt', 'r')
server_msg = sys_status.read()
return server_msg + colorize('psiTurk version ' + version_number +
'\nType "help" for more information.',
'green', False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def color_prompt(self):
''' Construct psiTurk shell prompt '''
prompt = '[' + colorize('psiTurk', 'bold')
server_string = ''
server_status = self.server.is_server_running()
if server_status == 'yes':
server_string = colorize('on', 'green')
elif server_status == 'no':
server_string = colorize('off', 'red')
elif server_status == 'maybe':
server_string = colorize('unknown', 'yellow')
elif server_status == 'blocked':
server_string = colorize('blocked', 'red')
prompt += ' server:' + server_string
prompt += ' mode:' + colorize('cabin', 'bold')
prompt += ']$ '
self.prompt = prompt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def preloop(self):
''' Keep persistent command history. '''
if not self.already_prelooped:
self.already_prelooped = True
open('.psiturk_history', 'a').close() # create file if it doesn't exist
readline.read_history_file('.psiturk_history')
for i in range(readline.get_current_history_length()):
if readline.get_history_item(i) is not None:
self.history.append(readline.get_history_item(i)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def onecmd_plus_hooks(self, line):
''' Trigger hooks after command. '''
if not line:
return self.emptyline()
return Cmd.onecmd_plus_hooks(self, line) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def postcmd(self, stop, line):
''' Exit cmd cleanly. '''
self.color_prompt()
return Cmd.postcmd(self, stop, line) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hit_list(self, active_hits, reviewable_hits, all_studies):
''' List hits. '''
if active_hits:
hits_data = self.amt_services_wrapper.get_active_hits(all_studies)
elif reviewable_hits:
hits_data = self.amt_services_wrapper.get_reviewable_hits(all_studies)
else:
hits_data = self.amt_services_wrapper.get_all_hits(all_studies)
if not hits_data:
print '*** no hits retrieved'
else:
for hit in hits_data:
print hit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _confirm_dialog(self, prompt):
''' Prompts for a 'yes' or 'no' to given prompt. '''
response = raw_input(prompt).strip().lower()
valid = {'y': True, 'ye': True, 'yes': True, 'n': False, 'no': False}
while True:
try:
return valid[response]
except:
response = raw_input("Please respond 'y' or 'n': ").strip().lower() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def server_off(self):
''' Stop experiment server '''
if (self.server.is_server_running() == 'yes' or
self.server.is_server_running() == 'maybe'):
self.server.shutdown()
print 'Please wait. This could take a few seconds.'
time.sleep(0.5) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def complete_config(self, text, line, begidx, endidx):
''' Tab-complete config command '''
return [i for i in PsiturkShell.config_commands if i.startswith(text)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def print_config(self, _):
''' Print configuration. '''
for section in self.config.sections():
print '[%s]' % section
items = dict(self.config.items(section))
for k in items:
print "%(a)s=%(b)s" % {'a': k, 'b': items[k]}
print '' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reload_config(self, _):
''' Reload config. '''
restart_server = False
if (self.server.is_server_running() == 'yes' or
self.server.is_server_running() == 'maybe'):
user_input = raw_input("Reloading configuration requires the server "
"to restart. Really reload? y or n: ")
if user_input != 'y':
return
restart_server = True
self.config.load_config()
if restart_server:
self.server_restart() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_status(self, _):
''' Notify user of server status. '''
server_status = self.server.is_server_running()
if server_status == 'yes':
print 'Server: ' + colorize('currently online', 'green')
elif server_status == 'no':
print 'Server: ' + colorize('currently offline', 'red')
elif server_status == 'maybe':
print 'Server: ' + colorize('status unknown', 'yellow')
elif server_status == 'blocked':
print 'Server: ' + colorize('blocked', 'red') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def db_use_local_file(self, arg, filename=None):
''' Use local file for DB. '''
# interactive = False # Never used
if filename is None:
# interactive = True # Never used
filename = raw_input('Enter the filename of the local SQLLite '
'database you would like to use '
'[default=participants.db]: ')
if filename == '':
filename = 'participants.db'
base_url = "sqlite:///" + filename
self.config.set("Database Parameters", "database_url", base_url)
print "Updated database setting (database_url): \n\t", \
self.config.get("Database Parameters", "database_url")
if self.server.is_server_running() == 'yes':
self.server_restart() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_download_datafiles(self, _):
''' Download datafiles. '''
contents = {"trialdata": lambda p: p.get_trial_data(), "eventdata": \
lambda p: p.get_event_data(), "questiondata": lambda p: \
p.get_question_data()}
query = Participant.query.all()
for k in contents:
ret = "".join([contents[k](p) for p in query])
temp_file = open(k + '.csv', 'w')
temp_file.write(ret)
temp_file.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def complete_server(self, text, line, begidx, endidx):
''' Tab-complete server command '''
return [i for i in PsiturkShell.server_commands if i.startswith(text)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_quit(self, _):
'''Override do_quit for network clean up.'''
if (self.server.is_server_running() == 'yes' or
self.server.is_server_running() == 'maybe'):
user_input = raw_input("Quitting shell will shut down experiment "
"server. Really quit? y or n: ")
if user_input == 'y':
self.server_off()
else:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def clean_up(self):
''' Clean up child and orphaned processes. '''
if self.tunnel.is_open:
print 'Closing tunnel...'
self.tunnel.close()
print 'Done.'
else:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_intro_prompt(self):
''' Overloads intro prompt with network-aware version if you can reach
psiTurk.org, request system status message'''
server_msg = self.web_services.get_system_status()
return server_msg + colorize('psiTurk version ' + version_number +
'\nType "help" for more information.',
'green', False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def complete_db(self, text, line, begidx, endidx):
''' Tab-complete db command '''
return [i for i in PsiturkNetworkShell.db_commands if \
i.startswith(text)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def complete_hit(self, text, line, begidx, endidx):
''' Tab-complete hit command. '''
return [i for i in PsiturkNetworkShell.hit_commands if \
i.startswith(text)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def complete_worker(self, text, line, begidx, endidx):
''' Tab-complete worker command. '''
return [i for i in PsiturkNetworkShell.worker_commands if \
i.startswith(text)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_db_instance_info(self, dbid):
''' Get DB instance info '''
if not self.connect_to_aws_rds():
return False
try:
instances = self.rdsc.describe_db_instances(dbid).get('DBInstances')
except:
return False
else:
myinstance = instances[0]
return myinstance |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def allow_access_to_instance(self, _, ip_address):
''' Allow access to instance. '''
if not self.connect_to_aws_rds():
return False
try:
conn = boto.ec2.connect_to_region(
self.region,
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key
)
sgs = conn.get_all_security_groups('default')
default_sg = sgs[0]
default_sg.authorize(ip_protocol='tcp', from_port=3306,
to_port=3306, cidr_ip=str(ip_address)+'/32')
except EC2ResponseError, exception:
if exception.error_code == "InvalidPermission.Duplicate":
return True # ok it already exists
else:
return False
else:
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_instance_id(self, instid):
''' Validate instance ID '''
# 1-63 alphanumeric characters, first must be a letter.
if re.match('[\w-]+$', instid) is not None:
if len(instid) <= 63 and len(instid) >= 1:
if instid[0].isalpha():
return True
return "*** Error: Instance ids must be 1-63 alphanumeric characters, \
first is a letter." |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_instance_username(self, username):
''' Validate instance username '''
# 1-16 alphanumeric characters - first character must be a letter -
# cannot be a reserved MySQL word
if re.match('[\w-]+$', username) is not None:
if len(username) <= 16 and len(username) >= 1:
if username[0].isalpha():
if username not in MYSQL_RESERVED_WORDS:
return True
return '*** Error: Usernames must be 1-16 alphanumeric chracters, \
first a letter, cannot be reserved MySQL word.' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_instance_password(self, password):
''' Validate instance passwords '''
# 1-16 alphanumeric characters - first character must be a letter -
# cannot be a reserved MySQL word
if re.match('[\w-]+$', password) is not None:
if len(password) <= 41 and len(password) >= 8:
return True
return '*** Error: Passwords must be 8-41 alphanumeric characters' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_instance_dbname(self, dbname):
''' Validate instance database name '''
# 1-64 alphanumeric characters, cannot be a reserved MySQL word
if re.match('[\w-]+$', dbname) is not None:
if len(dbname) <= 41 and len(dbname) >= 1:
if dbname.lower() not in MYSQL_RESERVED_WORDS:
return True
return '*** Error: Database names must be 1-64 alphanumeric characters,\
cannot be a reserved MySQL word.' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def create_db_instance(self, params):
''' Create db instance '''
if not self.connect_to_aws_rds():
return False
try:
database = self.rdsc.create_dbinstance(
id=params['id'],
allocated_storage=params['size'],
instance_class='db.t1.micro',
engine='MySQL',
master_username=params['username'],
master_password=params['password'],
db_name=params['dbname'],
multi_az=False
)
except:
return False
else:
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_all_hits(self):
''' Get all HITs '''
if not self.connect_to_turk():
return False
try:
hits = []
paginator = self.mtc.get_paginator('list_hits')
for page in paginator.paginate():
hits.extend(page['HITs'])
except Exception as e:
print e
return False
hits_data = self._hit_xml_to_object(hits)
return hits_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def setup_mturk_connection(self):
''' Connect to turk '''
if ((self.aws_access_key_id == 'YourAccessKeyId') or
(self.aws_secret_access_key == 'YourSecretAccessKey')):
print "AWS access key not set in ~/.psiturkconfig; please enter a valid access key."
assert False
if self.is_sandbox:
endpoint_url = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com'
else:
endpoint_url = 'https://mturk-requester.us-east-1.amazonaws.com'
self.mtc = boto3.client('mturk',
region_name='us-east-1',
aws_access_key_id=self.aws_access_key_id,
aws_secret_access_key=self.aws_secret_access_key,
endpoint_url=endpoint_url)
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_hit_status(self, hitid):
''' Get HIT status '''
hitdata = self.get_hit(hitid)
if not hitdata:
return False
return hitdata['HITStatus'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def query_records_no_auth(self, name, query=''):
''' Query records without authorization '''
#headers = {'key': username, 'secret': password}
req = requests.get(self.api_server + '/api/' + name + "/" + query)
return req |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_tunnel_ad_url(self):
''' Get tunnel hostname from psiturk.org '''
req = requests.get('https://api.psiturk.org/api/tunnel',
auth=(self.access_key, self.secret_key))
if req.status_code in [401, 403, 500]:
print(req.content)
return False
else:
return req.json()['tunnel_hostname'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.