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 create_request(query):
""" Creates a GET request to Yarr! server :param query: Free-text search query :returns: Requests object """ |
yarr_url = app.config.get('YARR_URL', False)
if not yarr_url:
raise('No URL to Yarr! server specified in config.')
api_token = app.config.get('YARR_API_TOKEN', False)
headers = {'X-API-KEY': api_token} if api_token else {}
payload = {'q': query}
url = '%s/search' % yarr_url
retur... |
<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_authentication(func):
""" Function decorator that throws an exception if the user is not authenticated, and executes the function normally if the us... |
def _auth(self, *args, **kwargs):
if not self._authenticated:
raise NotAuthenticatedException('Function {} requires'
.format(func.__name__)
+ ' authentication')
else:
... |
<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_user_info(self):
""" Returns a TSquareUser object representing the currently logged in user. Throws a NotAuthenticatedException if the user is not authen... |
response = self._session.get(BASE_URL_TSQUARE + '/user/current.json')
response.raise_for_status() # raises an exception if not 200: OK
user_data = response.json()
del user_data['password'] # tsquare doesn't store passwords
return TSquareUser(**user_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 get_site_by_id(self, id):
""" Looks up a site by ID and returns a TSquareSite representing that object, or throws an exception if no such site is found. @par... |
response = self._session.get(BASE_URL_TSQUARE + '/site/{}.json'.format(id))
response.raise_for_status()
site_data = response.json()
return TSquareSite(**site_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 get_sites(self, filter_func=lambda x: True):
""" Returns a list of TSquareSite objects that represent the sites available to a user. @param filter_func - A f... |
response = self._session.get(BASE_URL_TSQUARE + 'site.json')
response.raise_for_status() # raise an exception if not 200: OK
site_list = response.json()['site_collection']
if not site_list:
# this means that this t-square session expired. It's up
# to the user to... |
<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_announcements(self, site=None, num=10, age=20):
""" Gets announcements from a site if site is not None, or from every site otherwise. Returns a list of T... |
url = BASE_URL_TSQUARE + 'announcement/'
if site:
url += 'site/{}.json?n={}&d={}'.format(site.id, num, age)
else:
url += 'user.json?n={}&d={}'.format(num, age)
request = self._session.get(url)
request.raise_for_status()
announcement_list = request... |
<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_tools(self, site):
""" Gets all tools associated with a site. @param site (TSquareSite) - The site to search for tools @returns A list of dictionaries re... |
# hack - gotta bypass the tsquare REST api because it kinda sucks with tools
url = site.entityURL.replace('direct', 'portal')
response = self._session.get(url)
response.raise_for_status()
# scrape the resulting html
tools_dict_list = self._html_iface.get_tools(response.t... |
<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_grades(self, site):
""" Gets a list of grades associated with a site. The return type is a dictionary whose keys are assignment categories, similar to ho... |
tools = self.get_tools(site)
grade_tool_filter = [x.href for x in tools if x.name == 'gradebook-tool']
if not grade_tool_filter:
return []
response = self._session.get(grade_tool_filter[0])
response.raise_for_status()
iframes = self._html_iface.get_iframes(re... |
<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_syllabus(self, site):
""" Gets the syllabus for a course. The syllabus may or may not contain HTML, depending on the site. TSquare does not enforce wheth... |
tools = self.get_tools(site)
syllabus_filter = [x.href for x in tools if x.name == 'syllabus']
if not syllabus_filter:
return ''
response = self._session.get(syllabus_filter[0])
response.raise_for_status()
iframes = self._html_iface.get_iframes(response.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 setup_app_scope(name, scope):
"""activate plugins accordingly to config""" |
# load plugins
plugins = []
for plugin_name, active in get('settings').get('rw.plugins', {}).items():
plugin = __import__(plugin_name)
plugin_path = plugin_name.split('.')[1:] + ['plugin']
for sub in plugin_path:
plugin = getattr(plugin, sub)
plugins.append(scop... |
<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_section(self, section_name):
"""Add an empty section. """ |
if section_name == "DEFAULT":
raise Exception("'DEFAULT' is reserved section name.")
if section_name in self._sections:
raise Exception(
"Error! %s is already one of the sections" % section_name)
else:
self._sections[section_name] = Section(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 remove_section(self, section_name):
"""Remove a section, it cannot be the DEFAULT section. """ |
if section_name == "DEFAULT":
raise Exception("'DEFAULT' is reserved section name.")
if section_name in self._sections:
del self._sections[section_name]
else:
raise Exception("Error! cannot find section '%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 set_section(self, section):
"""Set a section. If section already exists, overwrite the old one. """ |
if not isinstance(section, Section):
raise Exception("You")
try:
self.remove_section(section.name)
except:
pass
self._sections[section.name] = copy.deepcopy(section) |
<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_logger(log_file, level=logging.DEBUG):
'''One function call to set up logging with some nice logs about the machine'''
cfg = AppBuilder.get_pcfg()
logger = cfg['log_module']
# todo make sure structlog is compliant and that logbook is also the correct name???
assert logger in ("logging", "l... |
<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_windows_permissions(filename):
'''
At least on windows 7 if a file is created on an Admin account,
Other users will not be given execute or full control.
However if a user creates the file himself it will work...
So just always change permissions after creating a file on windows
Change ... |
<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_raven():
'''we setup sentry to get all stuff from our logs'''
pcfg = AppBuilder.get_pcfg()
from raven.handlers.logging import SentryHandler
from raven import Client
from raven.conf import setup_logging
client = Client(pcfg['raven_dsn'])
handler = SentryHandler(client)
# TODO VE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def save(self):
'''saves our config objet to file'''
if self.app.cfg_mode == 'json':
with open(self.app.cfg_file, 'w') as opened_file:
json.dump(self.app.cfg, opened_file)
else:
with open(self.app.cfg_file, 'w')as opened_file:
yaml.dump(sel... |
<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_cfg(self, cfg_file, defaults=None, mode='json'):
'''
set mode to json or yaml? probably remove this option..Todo
Creates the config file for your app with default values
The file will only be created if it doesn't exits
also sets up the first_run attribute.
... |
<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_cfg(self):
'''loads our config object accessible via self.cfg'''
if self.cfg_mode == 'json':
with open(self.cfg_file) as opened_file:
return json.load(opened_file)
else:
with open(self.cfg_file) as ymlfile:
return yaml.safe_load(ym... |
<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_if_open(self, path=None, appdata=False, verbose=False):
'''
Allows only one version of the app to be open at a time.
If you are calling create_cfg() before calling this,
you don't need to give a path. Otherwise a file path must be
given so we can save our file there.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def release_singleton(self):
'''deletes the data that lets our program know if it is
running as singleton when calling check_if_open,
i.e check_if_open will return fals after calling this
'''
with suppress(KeyError):
del self.cfg['is_programming_running_info']
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unpack_int_base128(varint, offset):
"""Implement Perl unpack's 'w' option, aka base 128 decoding.""" |
res = ord(varint[offset])
if ord(varint[offset]) >= 0x80:
offset += 1
res = ((res - 0x80) << 7) + ord(varint[offset])
if ord(varint[offset]) >= 0x80:
offset += 1
res = ((res - 0x80) << 7) + ord(varint[offset])
if ord(va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _unpack_body(self, buff):
""" Parse the response body. After body unpacking its data available as python list of tuples For each request type the response bo... |
# Unpack <return_code> and <count> (how many records affected or selected)
self._return_code = struct_L.unpack_from(buff, offset=0)[0]
# Separate return_code and completion_code
self._completion_status = self._return_code & 0x00ff
self._return_code >>= 8
# In case of ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cast_field(self, cast_to, value):
""" Convert field type from raw bytes to native python type :param cast_to: native python type to cast to :type cast_to: a... |
if cast_to in (int, long, str):
return cast_to(value)
elif cast_to == unicode:
try:
value = value.decode(self.charset, self.errors)
except UnicodeEncodeError, e:
raise InvalidData("Error encoding unicode value '%s': %s" % (repr(value),... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cast_tuple(self, values):
""" Convert values of the tuple from raw bytes to native python types :param values: tuple of the raw database values :type value:... |
result = []
for i, value in enumerate(values):
if i < len(self.field_types):
result.append(self._cast_field(self.field_types[i], value))
else:
result.append(self._cast_field(self.field_types[-1], value))
return tuple(result) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ping(self):
""" send ping packet to tarantool server and receive response with empty body """ |
d = self.replyQueue.get_ping()
packet = RequestPing(self.charset, self.errors)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, self.charset, self.errors, None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert(self, space_no, *args):
""" insert tuple, if primary key exists server will return error """ |
d = self.replyQueue.get()
packet = RequestInsert(self.charset, self.errors, d._ipro_request_id, space_no, Request.TNT_FLAG_ADD, *args)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, self.charset, self.errors, None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, space_no, *args):
""" delete tuple by primary key """ |
d = self.replyQueue.get()
packet = RequestDelete(self.charset, self.errors, d._ipro_request_id, space_no, 0, *args)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, self.charset, self.errors, None) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call(self, proc_name, field_types, *args):
""" call server procedure """ |
d = self.replyQueue.get()
packet = RequestCall(self.charset, self.errors, d._ipro_request_id, proc_name, 0, *args)
self.transport.write(bytes(packet))
return d.addCallback(self.handle_reply, self.charset, self.errors, field_types) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fibs(n, m):
""" Yields Fibonacci numbers starting from ``n`` and ending at ``m``. """ |
a = b = 1
for x in range(3, m + 1):
a, b = b, a + b
if x >= n:
yield b |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unload_fixture(apps, schema_editor):
""" Brutally deleting all 'Country' model entries for reversing operation """ |
appmodel = apps.get_model(APP_LABEL, COUNTRY_MODELNAME)
appmodel.objects.all().delete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def precondition(precond):
""" Runs the callable responsible for making some assertions about the data structure expected for the transformation. If the precondi... |
def decorator(f):
"""`f` can be a reference to a method or function. In
both cases the `data` is expected to be passed as the
first positional argument (obviously respecting the
`self` argument when it is a method).
"""
def decorated(*args):
if len(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 run(self, data, rewrap=False, prefetch=0):
""" Wires the pipeline and returns a lazy object of the transformed data. :param data: must be an iterable, where ... |
if rewrap:
data = [data]
for _filter in self._filters:
_filter.feed(data)
data = _filter
else:
iterable = self._prefetch_callable(data, prefetch) if prefetch else data
for out_data in iterable:
yield out_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 camel_case_to_snake_case(name):
""" HelloWorld -> hello_world """ |
s1 = _FIRST_CAP_RE.sub(r'\1_\2', name)
return _ALL_CAP_RE.sub(r'\1_\2', s1).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 load_builtin_config(name, module_name=__name__, specs_path=specs.__path__):
""" Uses package info magic to find the resource file located in the specs submod... |
config_path = Path(next(iter(specs_path)))
config_path = config_path / PurePath(resource_filename(module_name, name + '.yaml'))
return load_config(config_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 load_config(path):
""" Loads a yaml configuration. :param path: a pathlib Path object pointing to the configuration """ |
with path.open('rb') as fi:
file_bytes = fi.read()
config = yaml.load(file_bytes.decode('utf-8'))
return config |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drag(*args, function = move):
""" Drags the mouse along a specified path :param args: list of arguments passed to function :param function: path to traverse ... |
x, y = win32api.GetCursorPos()
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
function(*args)
x, y = win32api.GetCursorPos()
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 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 add(self, action):
"""Add an action to the execution queue.""" |
self._state_machine.transition_to_add()
self._actions.append(action) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self):
"""Execute all actions, throwing an ExecutionException on failure. Catch the ExecutionException and call rollback() to rollback. """ |
self._state_machine.transition_to_execute()
for action in self._actions:
self._executed_actions.append(action)
self.execute_with_retries(action, lambda a: a.execute())
self._state_machine.transition_to_execute_complete() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rollback(self):
"""Call rollback on executed actions.""" |
self._state_machine.transition_to_rollback()
for action in reversed(self._executed_actions):
try:
self.execute_with_retries(action, lambda a: a.rollback())
except: # pylint: disable=bare-except
pass # on exception, carry on with rollback of othe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute_with_retries(self, action, f):
"""Execute function f with single argument action. Retry if ActionRetryException is raised. """ |
# Run action until either it succeeds or throws an exception
# that's not an ActionRetryException
retry = True
while retry:
retry = False
try:
f(action)
except ActionRetryException as ex: # other exceptions should bubble 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 input_option(message, options="yn", error_message=None):
""" Reads an option from the screen, with a specified prompt. Keeps asking until a valid option is s... |
def _valid(character):
if character not in options:
print(error_message % character)
return input("%s [%s]" % (message, options), _valid, True, lambda a: a.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 safe_unicode(obj, *args):
""" return the unicode representation of obj """ |
try:
return unicode(obj, *args) # noqa for undefined-variable
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
try:
return unicode(ascii_text) # noqa for undefined-variable
except NameError:
# This is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def safe_str(obj):
""" return the byte string representation of obj """ |
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
try:
return unicode(obj).encode('unicode_escape') # noqa for undefined-variable
except NameError:
# This is Python 3, just return the obj as it's already unicode
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crosstalk_correction(pathway_definitions, random_seed=2015, gene_set=set(), all_genes=True, max_iters=1000):
"""A wrapper function around the maximum impact ... |
np.random.seed(seed=random_seed)
genes_in_pathway_definitions = set.union(*pathway_definitions.values())
pathway_column_names = index_element_map(pathway_definitions.keys())
corrected_pathway_defns = {}
if gene_set:
gene_set = gene_set & genes_in_pathway_definitions
if not gene_se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximum_impact_estimation(membership_matrix, max_iters=1000):
"""An expectation maximization technique that produces pathway definitions devoid of crosstalk.... |
# Initialize the probability vector as the sum of each column in the
# membership matrix normalized by the sum of the entire membership matrix.
# The probability at some index j in the vector represents the likelihood
# that a pathway (column) j is defined by the current set of genes (rows)
# in th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize_membership_matrix(gene_row_names, pathway_definitions):
"""Create the binary gene-to-pathway membership matrix that will be considered in the maxi... |
membership = []
for pathway, full_definition in pathway_definitions.items():
pathway_genes = list(full_definition & gene_row_names)
membership.append(np.in1d(list(gene_row_names), pathway_genes))
membership = np.array(membership).astype("float").T
return membership |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index_element_map(arr):
"""Map the indices of the array to the respective elements. Parameters arr : list(a) The array to process, of generic type a Returns ... |
index_to_element = {}
for index, element in enumerate(arr):
index_to_element[index] = element
return index_to_element |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _apply_correction_on_genes(genes, pathway_column_names, pathway_definitions):
"""Helper function to create the gene-to-pathway membership matrix and apply cr... |
gene_row_names = index_element_map(genes)
membership_matrix = initialize_membership_matrix(
genes, pathway_definitions)
crosstalk_corrected_index_map = maximum_impact_estimation(
membership_matrix)
updated_pathway_definitions = _update_pathway_definitions(
crosstalk_corrected_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 _update_probabilities(pr, membership_matrix):
"""Updates the probability vector for each iteration of the expectation maximum algorithm in maximum impact est... |
n, k = membership_matrix.shape
pathway_col_sums = np.sum(membership_matrix, axis=0)
weighted_pathway_col_sums = np.multiply(pathway_col_sums, pr)
sum_of_col_sums = np.sum(weighted_pathway_col_sums)
try:
new_pr = weighted_pathway_col_sums / sum_of_col_sums
except FloatingPointError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _replace_zeros(arr, default_min_value):
"""Substitute 0s in the list with a near-zero value. Parameters arr : numpy.array(float) default_min_value : float If... |
min_nonzero_value = min(default_min_value, np.min(arr[arr > 0]))
closest_to_zero = np.nextafter(min_nonzero_value, min_nonzero_value - 1)
arr[arr == 0] = closest_to_zero
return arr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hdfoutput(outname, frames, dozip=False):
'''Outputs the frames to an hdf file.'''
with h5.File(outname,'a') as f:
for frame in frames:
group=str(frame['step']);
h5w(f, frame, group=group,
compression='lzf' if dozip else None); |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def beds_to_boolean(beds, ref=None, beds_sorted=False, ref_sorted=False, **kwargs):
""" Compare a list of bed files or BedTool objects to a reference bed file an... |
beds = copy.deepcopy(beds)
fns = []
for i,v in enumerate(beds):
if type(v) == str:
fns.append(v)
beds[i] = pbt.BedTool(v)
else:
fns.append(v.fn)
if not beds_sorted:
beds[i] = beds[i].sort()
names = _sample_names(fns, kwargs)
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 combine(beds, beds_sorted=False, postmerge=True):
""" Combine a list of bed files or BedTool objects into a single BedTool object. Parameters beds : list Lis... |
beds = copy.deepcopy(beds)
for i,v in enumerate(beds):
if type(v) == str:
beds[i] = pbt.BedTool(v)
if not beds_sorted:
beds[i] = beds[i].sort()
# For some reason, doing the merging in the reduce statement doesn't work. I
# think this might be a pybedtools bug. 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 strip_chr(bt):
"""Strip 'chr' from chromosomes for BedTool object Parameters bt : pybedtools.BedTool BedTool to strip 'chr' from. Returns ------- out : pybed... |
try:
df = pd.read_table(bt.fn, header=None, dtype=str)
# If the try fails, I assume that's because the file has a trackline. Note
# that I don't preserve the trackline (I'm not sure how pybedtools keeps
# track of it anyway).
except pd.parser.CParserError:
df = pd.read_table(bt.fn, ... |
<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_saved_bts(self):
"""If the AnnotatedInteractions object was saved to a pickle and reloaded, this method remakes the BedTool objects.""" |
if self._bt1_path:
self.bt1 = pbt.BedTool(self._bt1_path)
if self._bt2_path:
self.bt2 = pbt.BedTool(self._bt2_path)
if self._bt_loop_path:
self.bt_loop = pbt.BedTool(self._bt_loop_path)
if self._bt_loop_inner_path:
self.bt_loop_inner = pbt... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
"""Delete the file.""" |
self.close()
if self.does_file_exist():
os.remove(self.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 open(self, mode='read'):
"""Open the file.""" |
if self.file:
self.close()
raise 'Close file before opening.'
if mode == 'write':
self.file = open(self.path, 'w')
elif mode == 'overwrite':
# Delete file if exist.
self.file = open(self.path, 'w+')
else:
# Open fo... |
<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_hit(self, hit):
"""Add a hit to the file.""" |
if not self._csv:
raise 'Open before write'
self._csv.writerow(hit)
self.number_of_hits += 1
# Todo: check performance for timestamp check
# assert self._path == self.get_filename_by_timestamp(timestamp)
timestamp = hit['timestamp']
if self.latest_tim... |
<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_records(self):
""" Get all stored records. """ |
self.close()
with open(self.path, 'r') as filep:
first_line = filep.readline().split(',')
if first_line[0] != self.fields[0]:
yield first_line
for line in filep:
yield line.split(',') |
<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_user(self, uid, nodes, weights):
"""Add a user.""" |
for i, node in enumerate(nodes):
self.file.write("{},{},{}\n".format(uid, node, weights[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 get(self, key, default=None):
"""Get a key.""" |
key = "{0}{1}".format(self.prefix, key)
data = self.redis.get(key)
# Redis returns None not an exception
if data is None:
data = default
else:
data = json.loads(data)
return 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 set(self, key, value):
"""Set a key, value pair.""" |
key = "{0}{1}".format(self.prefix, key)
value = json.dumps(value, cls=NumpyEncoder)
self.redis.set(key, value) |
<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_by_timestamp(self, prefix, timestamp):
"""Get the cache file to a given timestamp.""" |
year, week = get_year_week(timestamp)
return self.get(prefix, year, week) |
<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(self, prefix, year, week):
"""Get the cache file.""" |
filename = self._format_filename(prefix, year, week)
return RawEvents(filename, prefix, year, week) |
<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_user_profiles(self, prefix):
"""Get the user profil from the cache to the given prefix.""" |
filepath = "{}{}".format(self.base_path, prefix)
return UserProfiles(filepath, prefix) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_filename(self, prefix, year, week):
"""Construct the file name based on the path and options.""" |
return "{}{}_{}-{}.csv".format(self.base_path, prefix, year, week) |
<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_recommendation_store(self):
"""Get the configured recommendation store.""" |
return RedisStore(self.config['host'],
self.config['port'],
self.config['db'],
self.config['prefix']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _deleteFile(self,directory,fn,dentry,db,service):
"""Deletets file and changes status to '?' if no more services manages the file """ |
# FIXME : can switch back to only managing once service
# at a time
logger.debug("%s - Deleting"%(fn))
if fn not in db:
print("%s - rm: Not in DB, can't remove !"%(fn))
return False
# Build up list of names
servicenames=db[fn]['services'].keys()... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _uploadFile(self,directory,fn,dentry,db,service):
"""Uploads file and changes status to 'S'. Looks up service name with service string """ |
# Create a hash of the file
if fn not in db:
print("%s - Not in DB, must run 'add' first!"%(fn))
else:
# If already added, see if it's modified, only then
# do another upload
if db[fn]['services'][service]['status']==self.ST_UPTODATE:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _updateToDeleted(self,directory,fn,dentry,db,service):
"""Changes to status to 'D' as long as a handler exists, directory - DIR where stuff is happening fn -... |
# Create a hash of the file
if fn not in db:
print("%s - rm: not in DB, skipping!"%(fn))
return
services=self.sman.GetServices(fn)
# If nobody manages this file, just skip it
if (not services):
print("%s - no manger of this file type found"%(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _updateToAdded(self,directory,fn,dentry,db,service):
"""Changes to status to 'A' as long as a handler exists, also generates a hash directory - DIR where stu... |
services=self.sman.GetServices(fn)
# If nobody manages this file, just skip it
if services is None:
print("%s - No services handle this file" %(fn))
return
# Build up list of names
servicenames=[]
for s in services:
servicenames.appe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _hashfile(self,filename,blocksize=65536):
"""Hashes the file and returns hash""" |
logger.debug("Hashing file %s"%(filename))
hasher=hashlib.sha256()
afile=open(filename,'rb')
buf=afile.read(blocksize)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(blocksize)
return hasher.hexdigest() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def storage(self):
""" Instantiates and returns a storage instance """ |
if self.backend == 'redis':
return RedisBackend(self.prefix, self.secondary_indexes)
if self.backend == 'dynamodb':
return DynamoDBBackend(self.prefix, self.key, self.sort_key,
self.secondary_indexes)
return DictBackend(self.prefix, sel... |
<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_property(self, prop):
"""Access nested value using dot separated keys Args: prop (:obj:`str`):
Property in the form of dot separated keys Returns: Prope... |
prop = prop.split('.')
root = self
for p in prop:
if p in root:
root = root[p]
else:
return None
return root |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dict(cls, val):
"""Creates dict2 object from dict object Args: val (:obj:`dict`):
Value to create from Returns: Equivalent dict2 object. """ |
if isinstance(val, dict2):
return val
elif isinstance(val, dict):
res = cls()
for k, v in val.items():
res[k] = cls.from_dict(v)
return res
elif isinstance(val, list):
res = []
for item in val:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self, val=UNSET):
"""Creates dict object from dict2 object Args: val (:obj:`dict2`):
Value to create from Returns: Equivalent dict object. """ |
if val is UNSET:
val = self
if isinstance(val, dict2) or isinstance(val, dict):
res = dict()
for k, v in val.items():
res[k] = self.to_dict(v)
return res
elif isinstance(val, list):
res = []
for item in val... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def main():
"Process CLI arguments and call appropriate functions."
try:
args = docopt.docopt(__doc__, version=__about__.__version__)
except docopt.DocoptExit:
if len(sys.argv) > 1:
print(f"{Fore.RED}Invalid command syntax, "
f"check help:{Fore.RESET}\n")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""The event's start time, as a timezone-aware datetime object""" |
if self.start_time is None:
time = datetime.time(hour=19, tzinfo=CET)
else:
time = self.start_time.replace(tzinfo=CET)
return datetime.datetime.combine(self.date, time) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next_occurrences(self, n=None, since=None):
"""Yield the next planned occurrences after the date "since" The `since` argument can be either a date or datetim... |
scheme = self.recurrence_scheme
if scheme is None:
return ()
db = Session.object_session(self)
query = db.query(Event)
query = query.filter(Event.series_slug == self.slug)
query = query.order_by(desc(Event.date))
query = query.limit(1)
last_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 do_upgrade():
"""Carry out the upgrade.""" |
op.alter_column(
table_name='knwKBRVAL',
column_name='id_knwKB',
type_=db.MediumInteger(8, unsigned=True),
existing_nullable=False,
existing_server_default='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 spark_string(ints):
"""Returns a spark string from given iterable of ints.""" |
ticks = u'▁▂▃▅▆▇'
ints = [i for i in ints if type(i) == int]
if len(ints) == 0:
return ""
step = (max(ints) / float(len(ticks) - 1)) or 1
return u''.join(
ticks[int(round(i / step))] if type(i) == int else u'.' for i in ints) |
<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_facts_by_name(api_url=None, fact_name=None, verify=False, cert=list()):
""" Returns facts by name :param api_url: Base PuppetDB API url :param fact_name:... |
return utils._make_api_request(api_url, '/facts/{0}'.format(fact_name), verify, cert) |
<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_facts_by_name_and_value(api_url=None, fact_name=None, fact_value=None, verify=False, cert=list()):
""" Returns facts by name and value :param api_url: Ba... |
return utils._make_api_request(api_url, '/facts/{0}/{1}'.format(fact_name, fact_value), verify, cert) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sanitize_config_loglevel(level):
'''
Kinda sorta backport of loglevel sanitization for Python 2.6.
'''
if sys.version_info[:2] != (2, 6) or isinstance(level, (int, long)):
return level
lvl = None
if isinstance(level, basestring):
lvl = logging._levelNames.get(level)
if no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_by_tag(stack, descriptor):
""" Returns the count of currently running or pending instances that match the given stack and deployer combo """ |
ec2_conn = boto.ec2.connection.EC2Connection()
resses = ec2_conn.get_all_instances(
filters={
'tag:stack': stack,
'tag:descriptor': descriptor
})
instance_list_raw = list()
[[instance_list_raw.append(x) for x in res... |
<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_if_unique(self, name):
""" Returns ``True`` on success. Returns ``False`` if the name already exists in the namespace. """ |
with self.lock:
if name not in self.names:
self.names.append(name)
return True
return 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 _add_to_spec(self, name):
"""The spec of the mirrored mock object is updated whenever the mirror gains new attributes""" |
self._spec.add(name)
self._mock.mock_add_spec(list(self._spec), 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_fp_meta(fp):
"""Processes a CMIP3 style file path. The standard CMIP3 directory structure: <experiment>/<variable_name>/<model>/<ensemble_member>/<CMOR f... |
# Copy metadata list then reverse to start at end of path
directory_meta = list(DIR_ATTS)
# Prefer meta extracted from filename
meta = get_dir_meta(fp, directory_meta)
meta.update(get_fname_meta(fp))
return meta |
<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_fname_meta(fp):
"""Processes a CMIP3 style file name. Filename is of pattern: <model>-<experiment>-<variable_name>-<ensemble_member>.nc Arguments: fp (st... |
# Strip directory, extension, then split
if '/' in fp:
fp = os.path.split(fp)[1]
fname = os.path.splitext(fp)[0]
meta = fname.split('-')
res = {}
try:
for key in FNAME_ATTS:
res[key] = meta.pop(0)
except IndexError:
raise PathError(fname)
return r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_user_agent(version):
""" generating the user agent witch will be used for most requests monkey patching system and release functions from platform module... |
def monkey_patch():
"""
small monkey patch
"""
raise IOError
# saving original functions
orig_system = platform.system
orig_release = platform.release
# applying patch
platform.system = monkey_patch
platform.release = monkey_patch
user_agent = requests... |
<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_url_request(self):
""" Consults the authenticator and grant for HTTP request parameters and headers to send with the access token request, builds the r... |
params = {}
headers = {}
self._authenticator(params, headers)
self._grant(params)
return Request(self._endpoint, urlencode(params), headers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, response_decoder=None):
""" Creates and sends a request to the OAuth server, decodes the response and returns the resulting token object. response... |
decoder = loads
if response_decoder is not None and callable(response_decoder):
decoder = response_decoder
request = self.build_url_request()
try:
f = urlopen(request)
except HTTPError as e:
try:
error_resp = e.read()
... |
<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(self, model, **spec):
"""get a single model instance by handle :param model: model :param handle: instance handle :return: """ |
handles = self.__find_handles(model, **spec)
if len(handles) > 1:
raise MultipleObjectsReturned()
if not handles:
raise ObjectDoesNotExist()
return self.get_instance(model, handles[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 get_sha_blob(self):
""" if the current file exists returns the sha blob else returns None """ |
r = requests.get(self.api_url, auth=self.get_auth_details())
try:
return r.json()['sha']
except KeyError:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_post(self):
""" If it's a new file, add it. Else, update it. """ |
payload = {'content': self.content_base64.decode('utf-8')}
sha_blob = self.get_sha_blob()
if sha_blob:
commit_msg = 'ghPublish UPDATE: {}'.format(self.title)
payload.update(sha=sha_blob)
payload.update(message=commit_msg)
else:
commit_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 _gpio_callback(self, gpio):
""" Gets triggered whenever the the gpio state changes :param gpio: Number of gpio that changed :type gpio: int :rtype: None """ |
self.debug(u"Triggered #{}".format(gpio))
try:
index = self.gpios.index(gpio)
except ValueError:
self.error(u"{} not present in GPIO list".format(gpio))
return
with self._people_lock:
person = self.people[index]
read_val = GPIO... |
<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_report(self, with_line_nums=True):
""" Returns a report which includes each distinct error only once, together with a list of the input lines wher... |
templ = '{} ← {}' if with_line_nums else '{}'
return '\n'.join([
templ.format(error.string, ','.join(map(str, sorted(set(lines)))))
for error, lines in self.errors.items()]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self, to, from_, body):
""" Send BODY to TO from FROM as an SMS! """ |
try:
msg = self.client.sms.messages.create(
body=body,
to=to,
from_=from_
)
print msg.sid
except twilio.TwilioRestException as e:
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tar_gzip_dir(directory, destination, base=None):
"""Creates a tar.gz from a directory.""" |
dest_file = tarfile.open(destination, 'w:gz')
abs_dir_path = os.path.abspath(directory)
base_name = abs_dir_path + "/"
base = base or os.path.basename(directory)
for path, dirnames, filenames in os.walk(abs_dir_path):
rel_path = path[len(base_name):]
dir_norm_path = os.path.join(bas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.