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 flatten_urlinfo(urlinfo, shorter_keys=True): """ Takes a urlinfo object and returns a flat dictionary."""
def flatten(value, prefix=""): if is_string(value): _result[prefix[1:]] = value return try: len(value) except (AttributeError, TypeError): # a leaf _result[prefix[1:]] = value return try: items = value.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 response_minify(self, response): """ minify response html to decrease traffic """
if response.content_type == u'text/html; charset=utf-8': endpoint = request.endpoint or '' view_func = current_app.view_functions.get(endpoint, None) name = ( '%s.%s' % (view_func.__module__, view_func.__name__) if view_func 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 exempt(self, obj): """ decorator to mark a view as exempt from htmlmin. """
name = '%s.%s' % (obj.__module__, obj.__name__) @wraps(obj) def __inner(*a, **k): return obj(*a, **k) self._exempt_routes.add(name) return __inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dmql(query): """Client supplied raw DMQL, ensure quote wrap."""
if isinstance(query, dict): raise ValueError("You supplied a dictionary to the dmql_query parameter, but a string is required." " Did you mean to pass this to the search_filter parameter? ") # automatically surround the given query with parentheses if it doe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ids(self, content_ids, object_ids): """Appends the content and object ids how RETS expects them"""
result = [] content_ids = self.split(content_ids, False) object_ids = self.split(object_ids) for cid in content_ids: result.append('{}:{}'.format(cid, ':'.join(object_ids))) return 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 set_value(self, key, value): """ Set key value to the file. The fuction will be make the key and value to dictinary formate. If its exist then it will update...
file_cache = self.read_file() if file_cache: file_cache[key] = value else: file_cache = {} file_cache[key] = value self.update_file(file_cache)
<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_value(self, key): """ Delete the key if the token is expired. Arg: key : cache key """
response = {} response['status'] = False response['msg'] = "key does not exist" file_cache = self.read_file() if key in file_cache: del file_cache[key] self.update_file(file_cache) response['status'] = True response['msg'] = "succ...
<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_file(self, content): """ It will convert json content to json string and update into file. Return: Boolean True/False """
updated_content = json.dumps(content) file_obj = open(self.file, 'r+') file_obj.write(str(updated_content)) file_obj.close() 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 auth(self): """ Auth is used to call the AUTH API of CricketAPI. Access token required for every request call to CricketAPI. Auth functional will post user C...
if not self.store_handler.has_value('access_token'): params = {} params["access_key"] = self.access_key params["secret_key"] = self.secret_key params["app_id"] = self.app_id params["device_id"] = self.device_id auth_url = self.api_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 get_active_token(self): """ Getting the valid access token. Access token expires every 24 hours, It will expires then it will generate a new token. Return: a...
expire_time = self.store_handler.has_value("expires") access_token = self.store_handler.has_value("access_token") if expire_time and access_token: expire_time = self.store_handler.get_value("expires") if not datetime.now() < datetime.fromtimestamp(float(expire_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 get_recent_matches(self, card_type="micro_card"): """ Calling the Recent Matches API. Arg: card_type: optional, default to micro_card. Accepted values are mi...
recent_matches_url = self.api_path + "recent_matches/" params = {} params["card_type"] = card_type response = self.get_response(recent_matches_url, params) return response
<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_recent_season_matches(self, season_key): """ Calling specific season recent matches. Arg: season_key: key of the season. Return: json date """
season_recent_matches_url = self.api_path + "season/" + season_key + "/recent_matches/" response = self.get_response(season_recent_matches_url) return response
<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_recent_seasons(self): """ Calling the Recent Season API. Return: json data """
recent_seasons_url = self.api_path + "recent_seasons/" response = self.get_response(recent_seasons_url) return response
<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_schedule(self, date=None): """ Calling the Schedule API. Return: json data """
schedule_url = self.api_path + "schedule/" params = {} if date: params['date'] = date response = self.get_response(schedule_url, params) return response
<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_season_schedule(self, season_key): """ Calling specific season schedule Arg: season_key: key of the season Return: json data """
schedule_url = self.api_path + "season/" + season_key + "/schedule/" response = self.get_response(schedule_url) return response
<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_season(self, season_key, card_type="micro_card"): """ Calling Season API. Arg: season_key: key of the season card_type: optional, default to micro_card. ...
season_url = self.api_path + "season/" + season_key + "/" params = {} params["card_type"] = card_type response = self.get_response(season_url, params) return response
<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_season_stats(self, season_key): """ Calling Season Stats API. Arg: season_key: key of the season Return: json data """
season_stats_url = self.api_path + "season/" + season_key + "/stats/" response = self.get_response(season_stats_url) return response
<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_season_team(self, season_key, season_team_key,stats_type=None): """ Calling Season teams API Arg: season_key: key of the season Return: json data """
params = {"stats_type": stats_type} season_team_url = self.api_path + 'season/' + season_key + '/team/' + season_team_key + '/' response = self.get_response(season_team_url, params=params) return response
<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_season_points(self, season_key): """ Calling Season Points API. Arg: season_key: key of the season Return: json data """
season_points_url = self.api_path + "season/" + season_key + "/points/" response = self.get_response(season_points_url) return response
<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_season_player_stats(self, season_key, player_key): """ Calling Season Player Stats API. Arg: season_key: key of the season player_key: key of the player ...
season_player_stats_url = self.api_path + "season/" + season_key + "/player/" + player_key + "/stats/" response = self.get_response(season_player_stats_url) return response
<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_overs_summary(self, match_key): """ Calling Overs Summary API Arg: match_key: key of the match Return: json data """
overs_summary_url = self.api_path + "match/" + match_key + "/overs_summary/" response = self.get_response(overs_summary_url) return response
<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_news_aggregation(self): """ Calling News Aggregation API Return: json data """
news_aggregation_url = self.api_path + "news_aggregation" + "/" response = self.get_response(news_aggregation_url) return response
<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_fantasy_credits(self, match_key): """ Calling Fantasy Credit API Arg: match_key: key of the match Return: json data """
fantasy_credit_url = self.api_path_v3 + "fantasy-match-credits/" + match_key + "/" response = self.get_response(fantasy_credit_url) return response
<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_fantasy_points(self, match_key): """ Calling Fantasy Points API Arg: match_key: key of the match Return: json data """
fantasy_points_url = self.api_path_v3 + "fantasy-match-points/" + match_key + "/" response = self.get_response(fantasy_points_url) return response
<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(self): """ Generates an output string by replacing the keywords in the format string with the corresponding values from a submission dictionary. """
self.manage_submissions() out_string = self.options['format'] # Pop until we get something which len(title) <= max-chars length = float('inf') while length > self.options['max_chars']: self.selected_submission = self.submissions.pop() length = len(self.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 login(self): """ Logs into Reddit in order to display a personalised front page. """
data = {'user': self.options['username'], 'passwd': self.options['password'], 'api_type': 'json'} response = self.client.post('http://www.reddit.com/api/login', data=data) self.client.modhash = response.json()['json']['data']['modhash']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def manage_submissions(self): """ If there are no or only one submissions left, get new submissions. This function manages URL creation and the specifics for fro...
if not hasattr(self, 'submissions') or len(self.submissions) == 1: self.submissions = [] if self.options['mode'] == 'front': # If there are no login details, the standard front # page will be displayed. if self.options['password'] and self...
<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_submissions(self, url): """ Connects to Reddit and gets a JSON representation of submissions. This JSON data is then processed and returned. url: A url t...
response = self.client.get(url, params={'limit': self.options['limit']}) submissions = [x['data'] for x in response.json()['data']['children']] return submissions
<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(self): """ A compulsary function that gets the output of the cmus-remote -Q command and converts it to unicode in order for it to be processed and final...
try: # Setting stderr to subprocess.STDOUT seems to stop the error # message returned by the process from being output to STDOUT. cmus_output = subprocess.check_output(['cmus-remote', '-Q'], stderr=subprocess.STDOUT).decode('utf-8') ...
<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_cmus_output(self, cmus_output): """ Change the newline separated string of output data into a dictionary which can then be used to replace the string...
cmus_output = cmus_output.split('\n') cmus_output = [x.replace('tag ', '') for x in cmus_output if not x in ''] cmus_output = [x.replace('set ', '') for x in cmus_output] status = {} partitioned = (item.partition(' ') for item in cmus_output) status = {item[0]: item[2] 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 output(self, full_text, short_text): """ Output all of the options and data for a segment. full_text: A string representing the data that should be output to...
full_text = full_text.replace('\n', '') short_text = short_text.replace('\n', '') self.output_options.update({'full_text': full_text, 'short_text': short_text}) self.output_options = {k: v for k, v in self.output_options.items() if v} return self.output_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 on_click(self, event): """ A function that should be overwritten by a plugin that wishes to react to events, if it wants to perform any action other than run...
if event['button'] == 1 and 'button1' in self.options: subprocess.call(self.options['button1'].split()) elif event['button'] == 2 and 'button2' in self.options: subprocess.call(self.options['button2'].split()) elif event['button'] == 3 and 'button3' in self.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 url_image(request, image_id, thumb_options=None, width=None, height=None): """ Converts a filer image ID in a complete path :param request: Request object :p...
image = File.objects.get(pk=image_id) if getattr(image, 'canonical_url', None): url = image.canonical_url else: url = image.url thumb = _return_thumbnail(image, thumb_options, width, height) if thumb: image = thumb url = image.url data = { 'url': url, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thumbnail_options(request): """ Returns the requested ThumbnailOption as JSON :param request: Request object :return: JSON serialized ThumbnailOption """
response_data = [{'id': opt.pk, 'name': opt.name} for opt in ThumbnailOption.objects.all()] return http.HttpResponse(json.dumps(response_data), content_type="application/json")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serve_image(request, image_id, thumb_options=None, width=None, height=None): """ returns the content of an image sized according to the parameters :param req...
image = File.objects.get(pk=image_id) if getattr(image, 'canonical_url', None): url = image.canonical_url else: url = image.url thumb = _return_thumbnail(image, thumb_options, width, height) if thumb: return server.serve(request, file_obj=thumb, save_as=False) 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 _touch_dir(self, path): """ A helper function to create a directory if it doesn't exist. path: A string containing a full path to the directory to be created...
try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: 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 reload(self): """ Reload the configuration from the file. This is in its own function so that it can be called at any time by another class. """
self._conf = configparser.ConfigParser() # Preserve the case of sections and keys. self._conf.optionxform = str self._conf.read(self.config_file_path) if 'general' not in self._conf.keys(): raise IncompleteConfigurationFile('Missing the general section') gene...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def coerce_retention_period(value): """ Coerce a retention period to a Python value. :param value: A string containing the text 'always', a number or an expressi...
# Numbers pass through untouched. if not isinstance(value, numbers.Number): # Other values are expected to be strings. if not isinstance(value, string_types): msg = "Expected string, got %s instead!" raise ValueError(msg % type(value)) # Check for the literal str...
<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_file(configuration_file=None, expand=True): """ Load a configuration file with backup directories and rotation schemes. :param configuration_file...
expand_notice_given = False if configuration_file: loader = ConfigLoader(available_files=[configuration_file], strict=True) else: loader = ConfigLoader(program_name='rotate-backups', strict=False) for section in loader.section_names: items = dict(loader.get_options(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 rotate_concurrent(self, *locations, **kw): """ Rotate the backups in the given locations concurrently. :param locations: One or more values accepted by :func...
timer = Timer() pool = CommandPool(concurrency=10) logger.info("Scanning %s ..", pluralize(len(locations), "backup location")) for location in locations: for cmd in self.rotate_backups(location, prepare=True, **kw): pool.add(cmd) if pool.num_commands ...
<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_file(self, location): """ Load a rotation scheme and other options from a configuration file. :param location: Any value accepted by :func:`coerc...
location = coerce_location(location) for configured_location, rotation_scheme, options in load_config_file(self.config_file, expand=False): if configured_location.match(location): logger.verbose("Loading configuration for %s ..", location) if rotation_scheme:...
<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_backups(self, location): """ Collect the backups at the given location. :param location: Any value accepted by :func:`coerce_location()`. :returns: A...
backups = [] location = coerce_location(location) logger.info("Scanning %s for backups ..", location) location.ensure_readable() for entry in natsort(location.context.list_entries(location.directory)): match = TIMESTAMP_PATTERN.search(entry) if match: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_preservation_criteria(self, backups_by_frequency): """ Collect the criteria used to decide which backups to preserve. :param backups_by_frequency: A :cl...
backups_to_preserve = collections.defaultdict(list) for frequency, delta in ORDERED_FREQUENCIES: for period in backups_by_frequency[frequency].values(): for backup in period: backups_to_preserve[backup].append(frequency) return backups_to_preserve
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(self, location): """ Check if the given location "matches". :param location: The :class:`Location` object to try to match. :returns: :data:`True` if th...
if self.ssh_alias != location.ssh_alias: # Never match locations on other systems. return False elif self.have_wildcards: # Match filename patterns using fnmatch(). return fnmatch.fnmatch(location.directory, self.directory) else: # Com...
<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_file_logger(filename, formatting, log_level): """ A helper function for creating a file logger. Accepts arguments, as it is used in Status and LoggingW...
logger = logging.getLogger() # If a stream handler has been attached, remove it. if logger.handlers: logger.removeHandler(logger.handlers[0]) handler = logging.FileHandler(filename) logger.addHandler(handler) formatter = logging.Formatter(*formatting) handler.setFormatter(formatter)...
<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_bar(self, message, comma=True): """ Outputs data to stdout, without buffering. message: A string containing the data to be output. comma: Whether o...
if comma: message += ',' sys.stdout.write(message + '\n') sys.stdout.flush()
<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(self): """ Reload the installed plugins and the configuration file. This is called when either the plugins or config get updated. """
logging.debug('Reloading config file as files have been modified.') self.config.plugin, self.config.general = self.config.reload() logging.debug('Reloading plugins as files have been modified.') self.loader = plugin_manager.PluginLoader( self._plugin_path, self.config.plugin...
<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_plugins(self): """ Creates a thread for each plugin and lets the thread_manager handle it. """
for obj in self.loader.objects: # Reserve a slot in the output_dict in order to ensure that the # items are in the correct order. self.output_dict[obj.output_options['name']] = None self.thread_manager.add_thread(obj.main, obj.options['interval'])
<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): """ Monitors if the config file or plugins are updated. Also outputs the JSON data generated by the plugins, without needing to poll the threads. ...
self.run_plugins() while True: # Reload plugins and config if either the config file or plugin # directory are modified. if self._config_mod_time != os.path.getmtime(self._config_file_path) or \ self._plugin_mod_time != os.path.getmtime(self._plug...
<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_empty_output(self): """ If plugins haven't been initialised and therefore not sending output or their output is None, there is no reason to take up e...
output = [] for key in self.output_dict: if self.output_dict[key] is not None and 'full_text' in self.output_dict[key]: output.append(self.output_dict[key]) return 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 handle_events(self): """ An event handler that processes events from stdin and calls the on_click function of the respective object. This function is run in ...
for event in sys.stdin: if event.startswith('['): continue name = json.loads(event.lstrip(','))['name'] for obj in self.loader.objects: if obj.output_options['name'] == name: obj.on_click(json.loads(event.lstrip(',')))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def field_dict(self, model): """ Helper function that returns a dictionary of all fields in the given model. If self.field_filter is set, it only includes the fi...
if self.field_filter: return dict( [(f.name, f) for f in model._meta.fields if self.field_filter(f)] ) else: return dict( [(f.name, f) for f in model._meta.fields if not f.rel and 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 run(self): """ Calls the main function of a plugin and mutates the output dict with its return value. Provides an easy way to change the output whilst not ne...
self.running = True while self.running: ret = self.func() self.output_dict[ret['name']] = ret time.sleep(self.interval) 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 add_thread(self, func, interval): """ Creates a thread, starts it and then adds it to the thread pool. Func: Same as in the Thread class. Interval: Same as i...
t = Thread(func, interval, self.output_dict) t.start() self._thread_pool.append(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 _compile_files(self): """ Compiles python plugin files in order to be processed by the loader. It compiles the plugins if they have been updated or haven't y...
for f in glob.glob(os.path.join(self.dir_path, '*.py')): # Check for compiled Python files that aren't in the __pycache__. if not os.path.isfile(os.path.join(self.dir_path, f + 'c')): compileall.compile_dir(self.dir_path, quiet=True) logging.debug('Compil...
<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_compiled(self, file_path): """ Accepts a path to a compiled plugin and returns a module object. file_path: A string that represents a complete file pat...
name = os.path.splitext(os.path.split(file_path)[-1])[0] plugin_directory = os.sep.join(os.path.split(file_path)[0:-1]) compiled_directory = os.path.join(plugin_directory, '__pycache__') # Use glob to autocomplete the filename. compiled_file = glob.glob(os.path.join(compiled_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 load_objects(self): """ Matches the plugins that have been specified in the config file with the available plugins. Returns instantiated objects based upon t...
objects = [] for settings in self._config: if settings['plugin'] in self.plugins: module = self.plugins[settings['plugin']] # Trusts that the only item in __all__ is the name of the # plugin class. plugin_class = getattr(module...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_files(self): """ Discovers the available plugins and turns each into a module object. This is a seperate function to allow plugins to be updated dyna...
plugins = {} _plugin_files = glob.glob(os.path.join(self.dir_path, '[!_]*.pyc')) for f in glob.glob(os.path.join(self.dir_path, '[!_]*.py')): if not any(os.path.splitext(f)[0] == os.path.splitext(x)[0] for x in _plugin_files): logging.debug('Addin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def model_page(self, request, app_label, model_name, rest_of_url=None): """ Handles the model-specific functionality of the databrowse site, delegating<to the ap...
try: model = get_model(app_label, model_name) except LookupError: model = None if model is None: raise http.Http404("App %r, model %r, not found." % (app_label, model_name)) try: databrowse_class = self.regi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def values(self): """ Returns a list of values for this field for this instance. It's a list so we can accomodate many-to-many fields. """
# This import is deliberately inside the function because it causes # some settings to be imported, and we don't want to do that at the # module level. if self.field.rel: if isinstance(self.field.rel, models.ManyToOneRel): objs = getattr(self.instance.instanc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def field_dict(self, model): """ Helper function that returns a dictionary of all DateFields or DateTimeFields in the given model. If self.field_names is set, it...
if self.field_names is None: return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.DateField)]) else: return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.Da...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def kmer_dag(job, input_file, output_path, kmer_length, spark_conf, workers, cores, memory, sudo): ''' Optionally launches a Spark cluster and then runs ADAM to count k-mers on an input file. :param ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def download_count_upload(job, master_ip, input_file, output_file, kmer_length, spark_conf, memory, sudo): ''' Runs k-mer counting...
<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_gatk_germline_pipeline(job, samples, config): """ Downloads shared files and calls the GATK best practices germline pipeline for a cohort of samples :par...
# Determine the available disk space on a worker node before any jobs have been run. work_dir = job.fileStore.getLocalTempDir() st = os.statvfs(work_dir) config.available_disk = st.f_bavail * st.f_frsize # Check that there is a reasonable number of samples for joint genotyping num_samples = le...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gatk_germline_pipeline(job, samples, config): """ Runs the GATK best practices pipeline for germline SNP and INDEL discovery. Steps in Pipeline 0: Generate a...
require(len(samples) > 0, 'No samples were provided!') # Get total size of genome reference files. This is used for configuring disk size. genome_ref_size = config.genome_fasta.size + config.genome_fai.size + config.genome_dict.size # 0: Generate processed BAM and BAI files for each sample # grou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def joint_genotype_and_filter(job, gvcfs, config): """ Checks for enough disk space for joint genotyping, then calls the genotype and filter pipeline function. :...
# Get the total size of genome reference files genome_ref_size = config.genome_fasta.size + config.genome_fai.size + config.genome_dict.size # Require at least 2.5x the sum of the individual GVCF files cohort_size = sum(gvcf.size for gvcf in gvcfs.values()) require(int(2.5 * cohort_size + genome_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 genotype_and_filter(job, gvcfs, config): """ Genotypes one or more GVCF files and runs either the VQSR or hard filtering pipeline. Uploads the genotyped VCF ...
# Get the total size of the genome reference genome_ref_size = config.genome_fasta.size + config.genome_fai.size + config.genome_dict.size # GenotypeGVCF disk requirement depends on the input GVCF, the genome reference files, and # the output VCF file. The output VCF is smaller than the input GVCF. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annotate_vcfs(job, vcfs, config): """ Runs Oncotator for a group of VCF files. Each sample is annotated individually. :param JobFunctionWrappingJob job: pass...
job.fileStore.logToMaster('Running Oncotator on the following samples:\n%s' % '\n'.join(vcfs.keys())) for uuid, vcf_id in vcfs.iteritems(): # The Oncotator disk requirement depends on the input VCF, the Oncotator database # and the output VCF. The annotated VCF will be significantly larger than...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_manifest(path_to_manifest): """ Parses manifest file for Toil Germline Pipeline :param str path_to_manifest: Path to sample manifest file :return: List...
bam_re = r"^(?P<uuid>\S+)\s(?P<url>\S+[bsc][r]?am)" fq_re = r"^(?P<uuid>\S+)\s(?P<url>\S+)\s(?P<paired_url>\S+)?\s?(?P<rg_line>@RG\S+)" samples = [] with open(path_to_manifest, 'r') as f: for line in f.readlines(): line = line.strip() if line.startswith('#'): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_shared_files(job, config): """ Downloads shared reference files for Toil Germline pipeline :param JobFunctionWrappingJob job: passed automatically b...
job.fileStore.logToMaster('Downloading shared reference files') shared_files = {'genome_fasta', 'genome_fai', 'genome_dict'} nonessential_files = {'genome_fai', 'genome_dict'} # Download necessary files for pipeline configuration if config.run_bwa: shared_files |= {'amb', 'ann', 'bwt', 'pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reference_preprocessing(job, config): """ Creates a genome fasta index and sequence dictionary file if not already present in the pipeline config. :param Job...
job.fileStore.logToMaster('Preparing Reference Files') genome_id = config.genome_fasta if getattr(config, 'genome_fai', None) is None: config.genome_fai = job.addChildJobFn(run_samtools_faidx, genome_id, cor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_bam(job, uuid, url, config, paired_url=None, rg_line=None): """ Prepares BAM file for Toil germline pipeline. Steps in pipeline 0: Download and align...
# 0: Align FASTQ or realign BAM if config.run_bwa: get_bam = job.wrapJobFn(setup_and_run_bwakit, uuid, url, rg_line, config, paired_url=paired_...
<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_and_run_bwakit(job, uuid, url, rg_line, config, paired_url=None): """ Downloads and runs bwakit for BAM or FASTQ files :param JobFunctionWrappingJob jo...
bwa_config = deepcopy(config) bwa_config.uuid = uuid bwa_config.rg_line = rg_line # bwa_alignment uses a different naming convention bwa_config.ref = config.genome_fasta bwa_config.fai = config.genome_fai # Determine if sample is a FASTQ or BAM file using the file extension basename, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gatk_haplotype_caller(job, bam, bai, ref, fai, ref_dict, annotations=None, emit_threshold=10.0, call_threshold=30.0, unsafe_mode=False, hc_output=None): """ ...
job.fileStore.logToMaster('Running GATK HaplotypeCaller') inputs = {'genome.fa': ref, 'genome.fa.fai': fai, 'genome.dict': ref_dict, 'input.bam': bam, 'input.bam.bai': bai} work_dir = job.fileStore.getLocalTempDir() for name, file_store_id in in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def static_dag(job, uuid, rg_line, inputs): """ Prefer this here as it allows us to pull the job functions from other jobs without rewrapping the job functions b...
# get work directory work_dir = job.fileStore.getLocalTempDir() inputs.cpu_count = cpu_count() inputs.maxCores = sys.maxint args = {'uuid': uuid, 's3_bucket': inputs.s3_bucket, 'sequence_dir': inputs.sequence_dir, 'dir_suffix': inputs.dir_suffix} # get hea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_encrypted_file(work_dir, url, key_path, name): """ Downloads encrypted file from S3 Input1: Working directory Input2: S3 URL to be downloaded Input3...
file_path = os.path.join(work_dir, name) key = generate_unique_key(key_path, url) encoded_key = base64.b64encode(key) encoded_key_md5 = base64.b64encode(hashlib.md5(key).digest()) h1 = 'x-amz-server-side-encryption-customer-algorithm:AES256' h2 = 'x-amz-server-side-encryption-customer-key:{}'.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 return_input_paths(job, work_dir, ids, *args): """ Returns the paths of files from the FileStore Input1: Toil job instance Input2: Working directory Input3: ...
paths = OrderedDict() for name in args: if not os.path.exists(os.path.join(work_dir, name)): file_path = job.fileStore.readGlobalFile(ids[name], os.path.join(work_dir, name)) else: file_path = os.path.join(work_dir, name) paths[name] = file_path if len(ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_to_output_dir(work_dir, output_dir, uuid=None, files=list()): """ Moves files from work_dir to output_dir Input1: Working directory Input2: Output direc...
for fname in files: if uuid is None: shutil.move(os.path.join(work_dir, fname), os.path.join(output_dir, fname)) else: shutil.move(os.path.join(work_dir, fname), os.path.join(output_dir, '{}.{}'.format(uuid, fname)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batch_start(job, input_args): """ Downloads shared files that are used by all samples for alignment and places them in the jobstore. """
shared_files = ['ref.fa', 'ref.fa.amb', 'ref.fa.ann', 'ref.fa.bwt', 'ref.fa.pac', 'ref.fa.sa', 'ref.fa.fai'] shared_ids = {} for fname in shared_files: url = input_args[fname] shared_ids[fname] = job.addChildJobFn(download_from_url, url, fname).rv() job.addFollowOnJobFn(spawn_batch_jobs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spawn_batch_jobs(job, shared_ids, input_args): """ Spawns an alignment job for every sample in the input configuration file """
samples = [] config = input_args['config'] with open(config, 'r') as f_in: for line in f_in: line = line.strip().split(',') uuid = line[0] urls = line[1:] samples.append((uuid, urls)) for sample in samples: job.addChildJobFn(alignment, sha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alignment(job, ids, input_args, sample): """ Runs BWA and then Bamsort on the supplied fastqs for this sample Input1: Toil Job instance Input2: jobstore id d...
uuid, urls = sample # ids['bam'] = job.fileStore.getEmptyFileStoreID() work_dir = job.fileStore.getLocalTempDir() output_dir = input_args['output_dir'] key_path = input_args['ssec'] cores = multiprocessing.cpu_count() # I/O return_input_paths(job, work_dir, ids, 'ref.fa', 'ref.fa.amb',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upload_bam_to_s3(job, ids, input_args, sample): """ Uploads output BAM from sample to S3 Input1: Toil Job instance Input2: jobstore id dictionary Input3: Inp...
uuid, urls = sample key_path = input_args['ssec'] work_dir = job.fileStore.getLocalTempDir() # Parse s3_dir to get bucket and s3 path s3_dir = input_args['s3_dir'] bucket_name = s3_dir.lstrip('/').split('/')[0] bucket_dir = '/'.join(s3_dir.lstrip('/').split('/')[1:]) base_url = 'https:/...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tarball_files(work_dir, tar_name, uuid=None, files=None): """ Tars a group of files together into a tarball work_dir: str Current Working Directory tar_name:...
with tarfile.open(os.path.join(work_dir, tar_name), 'w:gz') as f_out: for fname in files: if uuid: f_out.add(os.path.join(work_dir, fname), arcname=uuid + '.' + fname) else: f_out.add(os.path.join(work_dir, fname), arcname=fname)
<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_batch(job, input_args): """ This function will administer 5 jobs at a time then recursively call itself until subset is empty """
samples = parse_sra(input_args['sra']) # for analysis_id in samples: job.addChildJobFn(download_and_transfer_sample, input_args, samples, cores=1, disk='30')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_and_transfer_sample(job, input_args, samples): """ Downloads a sample from dbGaP via SRAToolKit, then uses S3AM to transfer it to S3 input_args: dic...
if len(samples) > 1: a = samples[len(samples)/2:] b = samples[:len(samples)/2] job.addChildJobFn(download_and_transfer_sample, input_args, a, disk='30G') job.addChildJobFn(download_and_transfer_sample, input_args, b, disk='30G') else: analysis_id = samples[0] wor...
<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_file_job(job, filename, file_id, output_dir, s3_key_path=None): """ Uploads a file from the FileStore to an output directory on the local filesystem o...
job.fileStore.logToMaster('Writing {} to {}'.format(filename, output_dir)) work_dir = job.fileStore.getLocalTempDir() filepath = job.fileStore.readGlobalFile(file_id, os.path.join(work_dir, filename)) if urlparse(output_dir).scheme == 's3': s3am_upload(job=job, fpath=os.path.join(work_dir, 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 download_encrypted_file(job, input_args, name): """ Downloads encrypted files from S3 via header injection input_args: dict Input dictionary defined in main(...
work_dir = job.fileStore.getLocalTempDir() key_path = input_args['ssec'] file_path = os.path.join(work_dir, name) url = input_args[name] with open(key_path, 'r') as f: key = f.read() if len(key) != 32: raise RuntimeError('Invalid Key! Must be 32 bytes: {}'.format(key)) key...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_from_url(job, url): """ Simple curl request made for a given url url: str URL to download """
work_dir = job.fileStore.getLocalTempDir() file_path = os.path.join(work_dir, os.path.basename(url)) if not os.path.exists(file_path): if url.startswith('s3:'): download_from_s3_url(file_path, url) else: try: subprocess.check_call(['curl', '-fs', '--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 docker_call(work_dir, tool_parameters, tool, java_opts=None, outfile=None, sudo=False): """ Makes subprocess call of a command to a docker container. tool_pa...
base_docker_call = 'docker run --log-driver=none --rm -v {}:/data'.format(work_dir).split() if sudo: base_docker_call = ['sudo'] + base_docker_call if java_opts: base_docker_call = base_docker_call + ['-e', 'JAVA_OPTS={}'.format(java_opts)] try: if outfile: subproces...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_to_output_dir(work_dir, output_dir, uuid=None, files=list()): """ A list of files to move from work_dir to output_dir. work_dir: str Current working dir...
for fname in files: if uuid is None: shutil.copy(os.path.join(work_dir, fname), os.path.join(output_dir, fname)) else: shutil.copy(os.path.join(work_dir, fname), os.path.join(output_dir, '{}.{}'.format(uuid, fname)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def program_checks(job, input_args): """ Checks that dependency programs are installed. input_args: dict Dictionary of input arguments (from main()) """
# Program checks for program in ['curl', 'docker', 'unzip', 'samtools']: assert which(program), 'Program "{}" must be installed on every node.'.format(program) job.addChildJobFn(download_shared_files, input_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 download_shared_files(job, input_args): """ Downloads and stores shared inputs files in the FileStore input_args: dict Dictionary of input arguments (from ma...
shared_files = ['unc.bed', 'hg19.transcripts.fa', 'composite_exons.bed', 'normalize.pl', 'rsem_ref.zip', 'ebwt.zip', 'chromosomes.zip'] shared_ids = {} for f in shared_files: shared_ids[f] = job.addChildJobFn(download_from_url, input_args[f]).rv() if input_args['config'] or ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_config_file(job, ids, input_args): """ Launches pipeline for each sample. shared_ids: dict Dictionary of fileStore IDs input_args: dict Dictionary of i...
samples = [] config = input_args['config'] with open(config, 'r') as f: for line in f.readlines(): if not line.isspace(): sample = line.strip().split(',') samples.append(sample) for sample in samples: job.addChildJobFn(download_sample, ids, in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def download_sample(job, ids, input_args, sample): """ Defines variables unique to a sample that are used in the rest of the pipelines ids: dict Dictionary of fi...
if len(sample) == 2: uuid, sample_location = sample url1, url2 = None, None else: uuid, url1, url2 = sample sample_location = None # Update values unique to sample sample_input = dict(input_args) sample_input['uuid'] = uuid sample_input['sample.tar'] = sample_loc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def static_dag_launchpoint(job, job_vars): """ Statically define jobs in the pipeline job_vars: tuple Tuple of dictionaries: input_args and ids """
input_args, ids = job_vars if input_args['config_fastq']: cores = input_args['cpu_count'] a = job.wrapJobFn(mapsplice, job_vars, cores=cores, disk='130G').encapsulate() else: a = job.wrapJobFn(merge_fastqs, job_vars, disk='70 G').encapsulate() b = job.wrapJobFn(consolidate_outpu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_fastqs(job, job_vars): """ Unzips input sample and concats the Read1 and Read2 groups together. job_vars: tuple Tuple of dictionaries: input_args and i...
input_args, ids = job_vars work_dir = job.fileStore.getLocalTempDir() cores = input_args['cpu_count'] single_end_reads = input_args['single_end_reads'] # I/O sample = return_input_paths(job, work_dir, ids, 'sample.tar') # Untar File # subprocess.check_call(['unzip', sample, '-d', work_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mapsplice(job, job_vars): """ Maps RNA-Seq reads to a reference genome. job_vars: tuple Tuple of dictionaries: input_args and ids """
# Unpack variables input_args, ids = job_vars work_dir = job.fileStore.getLocalTempDir() cores = input_args['cpu_count'] sudo = input_args['sudo'] single_end_reads = input_args['single_end_reads'] files_to_delete = ['R1.fastq'] # I/O return_input_paths(job, work_dir, ids, 'ebwt.zip'...
<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_read_groups(job, job_vars): """ This function adds read groups to the headers job_vars: tuple Tuple of dictionaries: input_args and ids """
input_args, ids = job_vars work_dir = job.fileStore.getLocalTempDir() sudo = input_args['sudo'] # I/O alignments = return_input_paths(job, work_dir, ids, 'alignments.bam') output = os.path.join(work_dir, 'rg_alignments.bam') # Command and callg parameter = ['AddOrReplaceReadGroups', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bamsort_and_index(job, job_vars): """ Sorts bam file and produces index file job_vars: tuple Tuple of dictionaries: input_args and ids """
# Unpack variables input_args, ids = job_vars work_dir = job.fileStore.getLocalTempDir() sudo = input_args['sudo'] # I/O rg_alignments = return_input_paths(job, work_dir, ids, 'rg_alignments.bam') output = os.path.join(work_dir, 'sorted.bam') # Command -- second argument is "Output Pref...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_bam_by_reference(job, job_vars): """ Sorts the bam by reference job_vars: tuple Tuple of dictionaries: input_args and ids """
# Unpack variables input_args, ids = job_vars work_dir = job.fileStore.getLocalTempDir() # I/O sorted_bam, sorted_bai = return_input_paths(job, work_dir, ids, 'sorted.bam', 'sorted.bam.bai') output = os.path.join(work_dir, 'sort_by_ref.bam') # Call: Samtools ref_seqs = [] handle = s...