Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> teams = [movesets[:6], movesets[6:12], [movesets[i] for i in (1, 12, 3, 4, 5, 6)], [movesets[i] for i in (3, 5, 6, 8, 9, 13)]] logs = [lg.generate_log(players[:2], teams[:2]), lg.generate_log(players[2:4], teams[2:]), lg.generate_log((players[1], players[4]), (teams[1], teams[0]))] tmpdir.mkdir('tj') for i, log in enumerate(logs): json.dump(log, open('{2}/tj/battle-{1}-{0}.log.json' .format(i + 1, log['p1rating']['formatid'], tmpdir.strpath), 'w+')) def check(self, processor, result): assert 3 == result assert 14 == len(processor.moveset_sink.sids) assert 5 == len(processor.battle_info_sink.pids) assert 4 == len(processor.battle_info_sink.tids) assert {'uu', 'ou'} == set(processor.battle_info_sink.battles.keys()) assert 2 == len(processor.battle_info_sink.battles['uu']) assert 1 == len(processor.battle_info_sink.battles['ou']) @pytest.mark.usefixtures("generate_logs") def test_one_log_at_a_time(self, tmpdir, p): <|code_end|> , predict the next line using imports from the current file: import json import pytest from collections import defaultdict from onix.backend.sql.sinks import compute_tid from onix import contexts from onix.collection import log_reader as lr from onix.collection import log_processor as lp from onix.collection import sinks from onix.scripts import log_generator as lg and context including class names, function names, and sometimes code from other files: # Path: onix/backend/sql/sinks.py # def compute_tid(team, sanitizer=None): # """ # Computes the Team ID for the given group of movesets # # Args: # team (:obj:`iterable` of :obj:`Moveset` or :obj:`str`) : # the team for which to compute the TID, represented either by their # movesets or by their SIDs # sanitizer (:obj:`onix.utilities.Sanitizer`, optional): # if no sanitizer is provided, movesets are assumed to be already # sanitized. Otherwise, the provided ``Sanitizer`` is used to sanitize # the movesets. # # Returns: # str: the corresponding Team ID # # Examples: # >>> from onix.model import Moveset, Forme, PokeStats # >>> from onix.backend.sql.sinks import compute_tid # >>> delphox = Moveset([Forme('delphox', 'magician', # ... PokeStats(282, 158, 222, 257, 220, 265))], # ... 'f', 'lifeorb', ['calmmind', 'psychic'], 100, 255) # >>> ditto = Moveset([Forme('ditto', 'imposter', # ... PokeStats(259, 164, 98, 134, 126, 123))], # ... 'u', 'focussash', ['transform'], 100, 255) # >>> print(compute_tid([delphox, ditto])) #doctest: +ELLIPSIS # 4e49b0eb... # """ # if isinstance(team[0], Moveset): # sids = [compute_sid(moveset, sanitizer) for moveset in team] # elif isinstance(team[0], str): # sids = team # else: # raise TypeError('team is neither an iterable of movesets nor SIDs') # sids = sorted(sids) # team_hash = hashlib.sha512(repr(sids).encode('utf-8')).hexdigest() # # # may eventually want to truncate hash, e.g. # # team_hash = team_hash[:16] # # return team_hash # # Path: onix/contexts.py # class Context(object): # class ResourceMissingError(Exception): # def __init__(self, **resources): # def __init__(self, resource): # def require(context, *resources): # def _get_context(commit, force_refresh): # def get_standard_context(force_refresh=False): # def get_historical_context(timestamp): # # Path: onix/collection/log_reader.py # class ParsingError(Exception): # class LogReader(with_metaclass(abc.ABCMeta, object)): # class JsonFileLogReader(LogReader): # def __init__(self, log_ref, message): # def get_all_formes(species, ability, item, moves, # context, hackmons=False, any_ability=False): # def rating_dict_to_model(rating_dict): # def normalize_hidden_power(moves, ivs): # def __init__(self, context): # def _parse_log(self, log_ref): # def parse_log(self, log_ref): # def _parse_moveset(self, moveset_dict, hackmons, any_ability, # mega_rayquaza_allowed, default_level): # def __init__(self, context): # def _parse_log(self, log_ref): # # Path: onix/collection/log_processor.py # class LogProcessor(object): # def __init__(self, moveset_sink, battle_info_sink, battle_sink, # force_context_refresh=False): # def _get_log_reader(self, log_ref): # def process_logs(self, logs, ref_type='folder', error_handling='raise'): # def _process_single_log(self, log_ref): # # Path: onix/collection/sinks.py # class _Sink(with_metaclass(abc.ABCMeta, object)): # class MovesetSink(_Sink): # class BattleInfoSink(_Sink): # class BattleSink(_Sink): # def flush(self): # def close(self): # def __enter__(self): # def __exit__(self, *exc): # def store_movesets(self, movesets): # def store_battle_info(self, battle_info): # def store_battle(self, battle): # # Path: onix/scripts/log_generator.py # def _generate_random_ev_list(): # def generate_pokemon(species, context, # level=100, hackmons=False, any_ability=False): # def generate_player(name, **ratings): # def generate_log(players, teams, turns=None, end_type=None): . Output only the next line.
result = 0
Predict the next line for this snippet: <|code_start|> for username in ['Alice', 'Bob']] movesets = [lg.generate_pokemon(species, context)[0] for species in ['alakazammega', 'bisharp', 'cacturne', 'delphox', 'electabuzz', 'flygon', 'gogoat', 'hariyama', 'infernape', 'jumpluff', 'bisharp']] teams = [movesets[:6], movesets[5:]] log = lg.generate_log(players, teams) log_ref = '{0}/battle-ou-195629539.log.json'.format(tmpdir.strpath) json.dump(log, open(log_ref, 'w+')) result = p.process_logs(log_ref, ref_type='file') assert 1 == result assert 11 == len(moveset_sink.sids) assert 2 == len(battle_info_sink.pids) assert 2 == len(battle_info_sink.tids) <|code_end|> with the help of current file imports: import json import pytest from collections import defaultdict from onix.backend.sql.sinks import compute_tid from onix import contexts from onix.collection import log_reader as lr from onix.collection import log_processor as lp from onix.collection import sinks from onix.scripts import log_generator as lg and context from other files: # Path: onix/backend/sql/sinks.py # def compute_tid(team, sanitizer=None): # """ # Computes the Team ID for the given group of movesets # # Args: # team (:obj:`iterable` of :obj:`Moveset` or :obj:`str`) : # the team for which to compute the TID, represented either by their # movesets or by their SIDs # sanitizer (:obj:`onix.utilities.Sanitizer`, optional): # if no sanitizer is provided, movesets are assumed to be already # sanitized. Otherwise, the provided ``Sanitizer`` is used to sanitize # the movesets. # # Returns: # str: the corresponding Team ID # # Examples: # >>> from onix.model import Moveset, Forme, PokeStats # >>> from onix.backend.sql.sinks import compute_tid # >>> delphox = Moveset([Forme('delphox', 'magician', # ... PokeStats(282, 158, 222, 257, 220, 265))], # ... 'f', 'lifeorb', ['calmmind', 'psychic'], 100, 255) # >>> ditto = Moveset([Forme('ditto', 'imposter', # ... PokeStats(259, 164, 98, 134, 126, 123))], # ... 'u', 'focussash', ['transform'], 100, 255) # >>> print(compute_tid([delphox, ditto])) #doctest: +ELLIPSIS # 4e49b0eb... # """ # if isinstance(team[0], Moveset): # sids = [compute_sid(moveset, sanitizer) for moveset in team] # elif isinstance(team[0], str): # sids = team # else: # raise TypeError('team is neither an iterable of movesets nor SIDs') # sids = sorted(sids) # team_hash = hashlib.sha512(repr(sids).encode('utf-8')).hexdigest() # # # may eventually want to truncate hash, e.g. # # team_hash = team_hash[:16] # # return team_hash # # Path: onix/contexts.py # class Context(object): # class ResourceMissingError(Exception): # def __init__(self, **resources): # def __init__(self, resource): # def require(context, *resources): # def _get_context(commit, force_refresh): # def get_standard_context(force_refresh=False): # def get_historical_context(timestamp): # # Path: onix/collection/log_reader.py # class ParsingError(Exception): # class LogReader(with_metaclass(abc.ABCMeta, object)): # class JsonFileLogReader(LogReader): # def __init__(self, log_ref, message): # def get_all_formes(species, ability, item, moves, # context, hackmons=False, any_ability=False): # def rating_dict_to_model(rating_dict): # def normalize_hidden_power(moves, ivs): # def __init__(self, context): # def _parse_log(self, log_ref): # def parse_log(self, log_ref): # def _parse_moveset(self, moveset_dict, hackmons, any_ability, # mega_rayquaza_allowed, default_level): # def __init__(self, context): # def _parse_log(self, log_ref): # # Path: onix/collection/log_processor.py # class LogProcessor(object): # def __init__(self, moveset_sink, battle_info_sink, battle_sink, # force_context_refresh=False): # def _get_log_reader(self, log_ref): # def process_logs(self, logs, ref_type='folder', error_handling='raise'): # def _process_single_log(self, log_ref): # # Path: onix/collection/sinks.py # class _Sink(with_metaclass(abc.ABCMeta, object)): # class MovesetSink(_Sink): # class BattleInfoSink(_Sink): # class BattleSink(_Sink): # def flush(self): # def close(self): # def __enter__(self): # def __exit__(self, *exc): # def store_movesets(self, movesets): # def store_battle_info(self, battle_info): # def store_battle(self, battle): # # Path: onix/scripts/log_generator.py # def _generate_random_ev_list(): # def generate_pokemon(species, context, # level=100, hackmons=False, any_ability=False): # def generate_player(name, **ratings): # def generate_log(players, teams, turns=None, end_type=None): , which may contain function names, class names, or code. Output only the next line.
assert {'ou'} == set(battle_info_sink.battles.keys())
Here is a snippet: <|code_start|> 'flygon', 'gogoat', 'hariyama', 'infernape', 'jumpluff', 'kangaskhan', 'lucario', 'bisharp', 'lucariomega')] teams = [movesets[:6], movesets[6:12], [movesets[i] for i in (1, 12, 3, 4, 5, 6)], [movesets[i] for i in (3, 5, 6, 8, 9, 13)]] logs = [lg.generate_log(players[:2], teams[:2]), lg.generate_log(players[2:4], teams[2:]), lg.generate_log((players[1], players[4]), (teams[1], teams[0]))] tmpdir.mkdir('tj') for i, log in enumerate(logs): json.dump(log, open('{2}/tj/battle-{1}-{0}.log.json' .format(i + 1, log['p1rating']['formatid'], tmpdir.strpath), 'w+')) def check(self, processor, result): assert 3 == result assert 14 == len(processor.moveset_sink.sids) <|code_end|> . Write the next line using the current file imports: import json import pytest from collections import defaultdict from onix.backend.sql.sinks import compute_tid from onix import contexts from onix.collection import log_reader as lr from onix.collection import log_processor as lp from onix.collection import sinks from onix.scripts import log_generator as lg and context from other files: # Path: onix/backend/sql/sinks.py # def compute_tid(team, sanitizer=None): # """ # Computes the Team ID for the given group of movesets # # Args: # team (:obj:`iterable` of :obj:`Moveset` or :obj:`str`) : # the team for which to compute the TID, represented either by their # movesets or by their SIDs # sanitizer (:obj:`onix.utilities.Sanitizer`, optional): # if no sanitizer is provided, movesets are assumed to be already # sanitized. Otherwise, the provided ``Sanitizer`` is used to sanitize # the movesets. # # Returns: # str: the corresponding Team ID # # Examples: # >>> from onix.model import Moveset, Forme, PokeStats # >>> from onix.backend.sql.sinks import compute_tid # >>> delphox = Moveset([Forme('delphox', 'magician', # ... PokeStats(282, 158, 222, 257, 220, 265))], # ... 'f', 'lifeorb', ['calmmind', 'psychic'], 100, 255) # >>> ditto = Moveset([Forme('ditto', 'imposter', # ... PokeStats(259, 164, 98, 134, 126, 123))], # ... 'u', 'focussash', ['transform'], 100, 255) # >>> print(compute_tid([delphox, ditto])) #doctest: +ELLIPSIS # 4e49b0eb... # """ # if isinstance(team[0], Moveset): # sids = [compute_sid(moveset, sanitizer) for moveset in team] # elif isinstance(team[0], str): # sids = team # else: # raise TypeError('team is neither an iterable of movesets nor SIDs') # sids = sorted(sids) # team_hash = hashlib.sha512(repr(sids).encode('utf-8')).hexdigest() # # # may eventually want to truncate hash, e.g. # # team_hash = team_hash[:16] # # return team_hash # # Path: onix/contexts.py # class Context(object): # class ResourceMissingError(Exception): # def __init__(self, **resources): # def __init__(self, resource): # def require(context, *resources): # def _get_context(commit, force_refresh): # def get_standard_context(force_refresh=False): # def get_historical_context(timestamp): # # Path: onix/collection/log_reader.py # class ParsingError(Exception): # class LogReader(with_metaclass(abc.ABCMeta, object)): # class JsonFileLogReader(LogReader): # def __init__(self, log_ref, message): # def get_all_formes(species, ability, item, moves, # context, hackmons=False, any_ability=False): # def rating_dict_to_model(rating_dict): # def normalize_hidden_power(moves, ivs): # def __init__(self, context): # def _parse_log(self, log_ref): # def parse_log(self, log_ref): # def _parse_moveset(self, moveset_dict, hackmons, any_ability, # mega_rayquaza_allowed, default_level): # def __init__(self, context): # def _parse_log(self, log_ref): # # Path: onix/collection/log_processor.py # class LogProcessor(object): # def __init__(self, moveset_sink, battle_info_sink, battle_sink, # force_context_refresh=False): # def _get_log_reader(self, log_ref): # def process_logs(self, logs, ref_type='folder', error_handling='raise'): # def _process_single_log(self, log_ref): # # Path: onix/collection/sinks.py # class _Sink(with_metaclass(abc.ABCMeta, object)): # class MovesetSink(_Sink): # class BattleInfoSink(_Sink): # class BattleSink(_Sink): # def flush(self): # def close(self): # def __enter__(self): # def __exit__(self, *exc): # def store_movesets(self, movesets): # def store_battle_info(self, battle_info): # def store_battle(self, battle): # # Path: onix/scripts/log_generator.py # def _generate_random_ev_list(): # def generate_pokemon(species, context, # level=100, hackmons=False, any_ability=False): # def generate_player(name, **ratings): # def generate_log(players, teams, turns=None, end_type=None): , which may include functions, classes, or code. Output only the next line.
assert 5 == len(processor.battle_info_sink.pids)
Given snippet: <|code_start|> [movesets[i] for i in (3, 5, 6, 8, 9, 13)]] logs = [lg.generate_log(players[:2], teams[:2]), lg.generate_log(players[2:4], teams[2:]), lg.generate_log((players[1], players[4]), (teams[1], teams[0]))] tmpdir.mkdir('tj') for i, log in enumerate(logs): json.dump(log, open('{2}/tj/battle-{1}-{0}.log.json' .format(i + 1, log['p1rating']['formatid'], tmpdir.strpath), 'w+')) def check(self, processor, result): assert 3 == result assert 14 == len(processor.moveset_sink.sids) assert 5 == len(processor.battle_info_sink.pids) assert 4 == len(processor.battle_info_sink.tids) assert {'uu', 'ou'} == set(processor.battle_info_sink.battles.keys()) assert 2 == len(processor.battle_info_sink.battles['uu']) assert 1 == len(processor.battle_info_sink.battles['ou']) @pytest.mark.usefixtures("generate_logs") def test_one_log_at_a_time(self, tmpdir, p): result = 0 result += p.process_logs('{0}/tj/battle-uu-1.log.json'.format( tmpdir.strpath), ref_type='file') result += p.process_logs('{0}/tj/battle-ou-2.log.json'.format( <|code_end|> , continue by predicting the next line. Consider current file imports: import json import pytest from collections import defaultdict from onix.backend.sql.sinks import compute_tid from onix import contexts from onix.collection import log_reader as lr from onix.collection import log_processor as lp from onix.collection import sinks from onix.scripts import log_generator as lg and context: # Path: onix/backend/sql/sinks.py # def compute_tid(team, sanitizer=None): # """ # Computes the Team ID for the given group of movesets # # Args: # team (:obj:`iterable` of :obj:`Moveset` or :obj:`str`) : # the team for which to compute the TID, represented either by their # movesets or by their SIDs # sanitizer (:obj:`onix.utilities.Sanitizer`, optional): # if no sanitizer is provided, movesets are assumed to be already # sanitized. Otherwise, the provided ``Sanitizer`` is used to sanitize # the movesets. # # Returns: # str: the corresponding Team ID # # Examples: # >>> from onix.model import Moveset, Forme, PokeStats # >>> from onix.backend.sql.sinks import compute_tid # >>> delphox = Moveset([Forme('delphox', 'magician', # ... PokeStats(282, 158, 222, 257, 220, 265))], # ... 'f', 'lifeorb', ['calmmind', 'psychic'], 100, 255) # >>> ditto = Moveset([Forme('ditto', 'imposter', # ... PokeStats(259, 164, 98, 134, 126, 123))], # ... 'u', 'focussash', ['transform'], 100, 255) # >>> print(compute_tid([delphox, ditto])) #doctest: +ELLIPSIS # 4e49b0eb... # """ # if isinstance(team[0], Moveset): # sids = [compute_sid(moveset, sanitizer) for moveset in team] # elif isinstance(team[0], str): # sids = team # else: # raise TypeError('team is neither an iterable of movesets nor SIDs') # sids = sorted(sids) # team_hash = hashlib.sha512(repr(sids).encode('utf-8')).hexdigest() # # # may eventually want to truncate hash, e.g. # # team_hash = team_hash[:16] # # return team_hash # # Path: onix/contexts.py # class Context(object): # class ResourceMissingError(Exception): # def __init__(self, **resources): # def __init__(self, resource): # def require(context, *resources): # def _get_context(commit, force_refresh): # def get_standard_context(force_refresh=False): # def get_historical_context(timestamp): # # Path: onix/collection/log_reader.py # class ParsingError(Exception): # class LogReader(with_metaclass(abc.ABCMeta, object)): # class JsonFileLogReader(LogReader): # def __init__(self, log_ref, message): # def get_all_formes(species, ability, item, moves, # context, hackmons=False, any_ability=False): # def rating_dict_to_model(rating_dict): # def normalize_hidden_power(moves, ivs): # def __init__(self, context): # def _parse_log(self, log_ref): # def parse_log(self, log_ref): # def _parse_moveset(self, moveset_dict, hackmons, any_ability, # mega_rayquaza_allowed, default_level): # def __init__(self, context): # def _parse_log(self, log_ref): # # Path: onix/collection/log_processor.py # class LogProcessor(object): # def __init__(self, moveset_sink, battle_info_sink, battle_sink, # force_context_refresh=False): # def _get_log_reader(self, log_ref): # def process_logs(self, logs, ref_type='folder', error_handling='raise'): # def _process_single_log(self, log_ref): # # Path: onix/collection/sinks.py # class _Sink(with_metaclass(abc.ABCMeta, object)): # class MovesetSink(_Sink): # class BattleInfoSink(_Sink): # class BattleSink(_Sink): # def flush(self): # def close(self): # def __enter__(self): # def __exit__(self, *exc): # def store_movesets(self, movesets): # def store_battle_info(self, battle_info): # def store_battle(self, battle): # # Path: onix/scripts/log_generator.py # def _generate_random_ev_list(): # def generate_pokemon(species, context, # level=100, hackmons=False, any_ability=False): # def generate_player(name, **ratings): # def generate_log(players, teams, turns=None, end_type=None): which might include code, classes, or functions. Output only the next line.
tmpdir.strpath), ref_type='file')
Predict the next line for this snippet: <|code_start|> 'w+')) def check(self, processor, result): assert 3 == result assert 14 == len(processor.moveset_sink.sids) assert 5 == len(processor.battle_info_sink.pids) assert 4 == len(processor.battle_info_sink.tids) assert {'uu', 'ou'} == set(processor.battle_info_sink.battles.keys()) assert 2 == len(processor.battle_info_sink.battles['uu']) assert 1 == len(processor.battle_info_sink.battles['ou']) @pytest.mark.usefixtures("generate_logs") def test_one_log_at_a_time(self, tmpdir, p): result = 0 result += p.process_logs('{0}/tj/battle-uu-1.log.json'.format( tmpdir.strpath), ref_type='file') result += p.process_logs('{0}/tj/battle-ou-2.log.json'.format( tmpdir.strpath), ref_type='file') result += p.process_logs('{0}/tj/battle-uu-3.log.json'.format( tmpdir.strpath), ref_type='file') self.check(p, result) @pytest.mark.usefixtures("generate_logs") def test_with_list_of_files(self, tmpdir, p): result = p.process_logs(('{0}/tj/battle-uu-1.log.json'.format( tmpdir.strpath), '{0}/tj/battle-ou-2.log.json'.format( tmpdir.strpath), <|code_end|> with the help of current file imports: import json import pytest from collections import defaultdict from onix.backend.sql.sinks import compute_tid from onix import contexts from onix.collection import log_reader as lr from onix.collection import log_processor as lp from onix.collection import sinks from onix.scripts import log_generator as lg and context from other files: # Path: onix/backend/sql/sinks.py # def compute_tid(team, sanitizer=None): # """ # Computes the Team ID for the given group of movesets # # Args: # team (:obj:`iterable` of :obj:`Moveset` or :obj:`str`) : # the team for which to compute the TID, represented either by their # movesets or by their SIDs # sanitizer (:obj:`onix.utilities.Sanitizer`, optional): # if no sanitizer is provided, movesets are assumed to be already # sanitized. Otherwise, the provided ``Sanitizer`` is used to sanitize # the movesets. # # Returns: # str: the corresponding Team ID # # Examples: # >>> from onix.model import Moveset, Forme, PokeStats # >>> from onix.backend.sql.sinks import compute_tid # >>> delphox = Moveset([Forme('delphox', 'magician', # ... PokeStats(282, 158, 222, 257, 220, 265))], # ... 'f', 'lifeorb', ['calmmind', 'psychic'], 100, 255) # >>> ditto = Moveset([Forme('ditto', 'imposter', # ... PokeStats(259, 164, 98, 134, 126, 123))], # ... 'u', 'focussash', ['transform'], 100, 255) # >>> print(compute_tid([delphox, ditto])) #doctest: +ELLIPSIS # 4e49b0eb... # """ # if isinstance(team[0], Moveset): # sids = [compute_sid(moveset, sanitizer) for moveset in team] # elif isinstance(team[0], str): # sids = team # else: # raise TypeError('team is neither an iterable of movesets nor SIDs') # sids = sorted(sids) # team_hash = hashlib.sha512(repr(sids).encode('utf-8')).hexdigest() # # # may eventually want to truncate hash, e.g. # # team_hash = team_hash[:16] # # return team_hash # # Path: onix/contexts.py # class Context(object): # class ResourceMissingError(Exception): # def __init__(self, **resources): # def __init__(self, resource): # def require(context, *resources): # def _get_context(commit, force_refresh): # def get_standard_context(force_refresh=False): # def get_historical_context(timestamp): # # Path: onix/collection/log_reader.py # class ParsingError(Exception): # class LogReader(with_metaclass(abc.ABCMeta, object)): # class JsonFileLogReader(LogReader): # def __init__(self, log_ref, message): # def get_all_formes(species, ability, item, moves, # context, hackmons=False, any_ability=False): # def rating_dict_to_model(rating_dict): # def normalize_hidden_power(moves, ivs): # def __init__(self, context): # def _parse_log(self, log_ref): # def parse_log(self, log_ref): # def _parse_moveset(self, moveset_dict, hackmons, any_ability, # mega_rayquaza_allowed, default_level): # def __init__(self, context): # def _parse_log(self, log_ref): # # Path: onix/collection/log_processor.py # class LogProcessor(object): # def __init__(self, moveset_sink, battle_info_sink, battle_sink, # force_context_refresh=False): # def _get_log_reader(self, log_ref): # def process_logs(self, logs, ref_type='folder', error_handling='raise'): # def _process_single_log(self, log_ref): # # Path: onix/collection/sinks.py # class _Sink(with_metaclass(abc.ABCMeta, object)): # class MovesetSink(_Sink): # class BattleInfoSink(_Sink): # class BattleSink(_Sink): # def flush(self): # def close(self): # def __enter__(self): # def __exit__(self, *exc): # def store_movesets(self, movesets): # def store_battle_info(self, battle_info): # def store_battle(self, battle): # # Path: onix/scripts/log_generator.py # def _generate_random_ev_list(): # def generate_pokemon(species, context, # level=100, hackmons=False, any_ability=False): # def generate_player(name, **ratings): # def generate_log(players, teams, turns=None, end_type=None): , which may contain function names, class names, or code. Output only the next line.
'{0}/tj/battle-uu-3.log.json'.format(
Given the following code snippet before the placeholder: <|code_start|>"""Tests for the metrics module""" class TestVictoryChance(object): def test_elo(self): """Glicko formula should reduce to Elo if d1=d2=0 Using http://bzstats.strayer.de/bzinfo/elo/ to test against""" assert .76 == round(metrics.victory_chance(1200, 0, 1000, 0), 2) def test_elo_lower_rating_first(self): assert .24 == round(metrics.victory_chance(1000, 0, 1200, 0), 2) <|code_end|> , predict the next line using imports from the current file: from onix import metrics and context including class names, function names, and sometimes code from other files: # Path: onix/metrics.py # def victory_chance(r1, d1, r2, d2): # def gxe(r, d, d0=130.0): # def skill_chance(r, d, baseline): . Output only the next line.
def test_elo_all_that_matters_is_rating_difference(self):
Based on the snippet: <|code_start|>"""Generate the config file that lists which Pokemon can change formes. While we're at it, generate the species lookup dictionary that handles prettifying species names, labelling forme-concatenations and combining appearance-only formes""" <|code_end|> , predict the immediate next line with the help of imports: import json import re from collections import defaultdict from future.utils import iteritems from onix import scrapers from onix.utilities import sanitize_string and context (classes, functions, sometimes code) from other files: # Path: onix/scrapers.py # def get_commit_from_timestamp(timestamp): # def _write(data, destination_filename): # def _scrape(url, entry, commit=None, destination_filename=None): # def scrape_battle_formats_data(commit=None): # def scrape_battle_pokedex(commit=None): # def scrape_battle_aliases(commit=None): # def scrape_battle_items(commit=None): # def scrape_battle_movedex(commit=None): # def scrape_formats(commit=None): # # Path: onix/utilities.py # def sanitize_string(input_string): # """ # Strips all non-alphanumeric characters and puts everything in lowercase # # Args: # input_string (str) : string to be sanitized # # Returns: # str : the sanitized string # # Examples: # >>> from onix.utilities import sanitize_string # >>> print(sanitize_string('Hello World')) # helloworld # # """ # return re.compile(r'[^A-Za-z0-9]').sub('', input_string).lower() . Output only the next line.
def generate_single_forme_species_lookup():
Based on the snippet: <|code_start|>"""Generate the config file that lists which Pokemon can change formes. While we're at it, generate the species lookup dictionary that handles prettifying species names, labelling forme-concatenations and combining appearance-only formes""" <|code_end|> , predict the immediate next line with the help of imports: import json import re from collections import defaultdict from future.utils import iteritems from onix import scrapers from onix.utilities import sanitize_string and context (classes, functions, sometimes code) from other files: # Path: onix/scrapers.py # def get_commit_from_timestamp(timestamp): # def _write(data, destination_filename): # def _scrape(url, entry, commit=None, destination_filename=None): # def scrape_battle_formats_data(commit=None): # def scrape_battle_pokedex(commit=None): # def scrape_battle_aliases(commit=None): # def scrape_battle_items(commit=None): # def scrape_battle_movedex(commit=None): # def scrape_formats(commit=None): # # Path: onix/utilities.py # def sanitize_string(input_string): # """ # Strips all non-alphanumeric characters and puts everything in lowercase # # Args: # input_string (str) : string to be sanitized # # Returns: # str : the sanitized string # # Examples: # >>> from onix.utilities import sanitize_string # >>> print(sanitize_string('Hello World')) # helloworld # # """ # return re.compile(r'[^A-Za-z0-9]').sub('', input_string).lower() . Output only the next line.
def generate_single_forme_species_lookup():
Predict the next line after this snippet: <|code_start|> def current_variable_declaration_scope(self): return self.scope_stack[-1][1] def current_scope_is_strict(self): return bool(self.scope_stack) and self.scope_stack[-1][2] def visit_VariableDeclaration(self, node): scope = self.current_variable_declaration_scope() scope.append(node) self.visit(node.value) def visit_FunctionDeclaration(self, node): strict = self.is_strict(node.body) scope = self.current_function_declaration_scope() scope.append(node) self.enter_scope(strict) self.visit(node.body) function_scope = self.leave_scope() self.node_scopes[node] = function_scope def visit_FunctionExpression(self, node): strict = self.is_strict(node.body) self.enter_scope(strict) self.visit(node.body) function_scope = self.leave_scope() self.node_scopes[node] = function_scope def visit_Program(self, node): strict = self.is_strict(node.statements) self.enter_scope(strict) <|code_end|> using the current file's imports: from ..parser.ast import ExpressionStatement, StringLiteral from ..parser.visitor import NodeVisitor and any relevant context from other files: # Path: bigrig/parser/ast.py # class ExpressionStatement(Statement): # abstract = False # fields = ('expression',) # # class StringLiteral(Literal): # abstract = False # fields = ('value',) # # Path: bigrig/parser/visitor.py # class NodeVisitor(object): # """ # Walks the abstract syntax tree, calling the visitor function for every # subtree found. # """ # def __init__(self): # self._visitor_cache = {} # # def get_visitor(self, node): # node_class = node.__class__ # visitor = self._visitor_cache.get(node_class) # if visitor is None: # method = 'visit_%s' % node_class.__name__ # visitor = getattr(self, method, self.generic_visit) # self._visitor_cache[node_class] = visitor # return visitor # # def visit(self, node): # visitor = self.get_visitor(node) # return visitor(node) # # def generic_visit(self, node): # if isinstance(node, Node): # self.visit_node(node) # # def visit_node(self, node): # for child in node.iter_children(): # self.visit(child) # # def visit_list(self, node): # for element in node: # self.visit(element) . Output only the next line.
self.visit(node.statements)
Here is a snippet: <|code_start|> def current_variable_declaration_scope(self): return self.scope_stack[-1][1] def current_scope_is_strict(self): return bool(self.scope_stack) and self.scope_stack[-1][2] def visit_VariableDeclaration(self, node): scope = self.current_variable_declaration_scope() scope.append(node) self.visit(node.value) def visit_FunctionDeclaration(self, node): strict = self.is_strict(node.body) scope = self.current_function_declaration_scope() scope.append(node) self.enter_scope(strict) self.visit(node.body) function_scope = self.leave_scope() self.node_scopes[node] = function_scope def visit_FunctionExpression(self, node): strict = self.is_strict(node.body) self.enter_scope(strict) self.visit(node.body) function_scope = self.leave_scope() self.node_scopes[node] = function_scope def visit_Program(self, node): strict = self.is_strict(node.statements) self.enter_scope(strict) <|code_end|> . Write the next line using the current file imports: from ..parser.ast import ExpressionStatement, StringLiteral from ..parser.visitor import NodeVisitor and context from other files: # Path: bigrig/parser/ast.py # class ExpressionStatement(Statement): # abstract = False # fields = ('expression',) # # class StringLiteral(Literal): # abstract = False # fields = ('value',) # # Path: bigrig/parser/visitor.py # class NodeVisitor(object): # """ # Walks the abstract syntax tree, calling the visitor function for every # subtree found. # """ # def __init__(self): # self._visitor_cache = {} # # def get_visitor(self, node): # node_class = node.__class__ # visitor = self._visitor_cache.get(node_class) # if visitor is None: # method = 'visit_%s' % node_class.__name__ # visitor = getattr(self, method, self.generic_visit) # self._visitor_cache[node_class] = visitor # return visitor # # def visit(self, node): # visitor = self.get_visitor(node) # return visitor(node) # # def generic_visit(self, node): # if isinstance(node, Node): # self.visit_node(node) # # def visit_node(self, node): # for child in node.iter_children(): # self.visit(child) # # def visit_list(self, node): # for element in node: # self.visit(element) , which may include functions, classes, or code. Output only the next line.
self.visit(node.statements)
Predict the next line after this snippet: <|code_start|> if not code: return False strict = False for node in code: if not isinstance(node, ExpressionStatement): break elif not isinstance(node.expression, StringLiteral): break if node.expression.value[1:-1] == 'use strict': strict = True break return strict class DeclarationVisitor(NodeVisitor): def __init__(self): super(DeclarationVisitor, self).__init__() self.scope_stack = None self.node_scopes = None def is_strict(self, code): return self.current_scope_is_strict() or code_is_strict(code) def enter_scope(self, strict=False): new_scope = ([], [], strict) self.scope_stack.append(new_scope) def leave_scope(self): return self.scope_stack.pop() <|code_end|> using the current file's imports: from ..parser.ast import ExpressionStatement, StringLiteral from ..parser.visitor import NodeVisitor and any relevant context from other files: # Path: bigrig/parser/ast.py # class ExpressionStatement(Statement): # abstract = False # fields = ('expression',) # # class StringLiteral(Literal): # abstract = False # fields = ('value',) # # Path: bigrig/parser/visitor.py # class NodeVisitor(object): # """ # Walks the abstract syntax tree, calling the visitor function for every # subtree found. # """ # def __init__(self): # self._visitor_cache = {} # # def get_visitor(self, node): # node_class = node.__class__ # visitor = self._visitor_cache.get(node_class) # if visitor is None: # method = 'visit_%s' % node_class.__name__ # visitor = getattr(self, method, self.generic_visit) # self._visitor_cache[node_class] = visitor # return visitor # # def visit(self, node): # visitor = self.get_visitor(node) # return visitor(node) # # def generic_visit(self, node): # if isinstance(node, Node): # self.visit_node(node) # # def visit_node(self, node): # for child in node.iter_children(): # self.visit(child) # # def visit_list(self, node): # for element in node: # self.visit(element) . Output only the next line.
def current_function_declaration_scope(self):
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- # Copyright (C) 2016, Maximilian Köhl <mail@koehlma.de> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License version 3 as published by # the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A # PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License along # with this program. If not, see <http://www.gnu.org/licenses/>. from __future__ import print_function, unicode_literals, division, absolute_import if os.environ.get('PYTHON_MOCK_LIBUV', None) == 'True': # pragma: no cover uvcffi = ModuleType('uvcffi') uvcffi.__version__ = __version__ uvcffi.ffi = Mock() <|code_end|> , predict the immediate next line with the help of imports: import collections import os import sys import weakref import uvcffi from . import __version__ from types import ModuleType from .helpers.mock import Mock from .helpers.tracer import LIBTracer, FFITracer and context (classes, functions, sometimes code) from other files: # Path: uv/metadata.py . Output only the next line.
uvcffi.lib = Mock()
Continue the code snippet: <|code_start|> searchable = True name = String() user = RelatedObjects(backref=True) plugins = Dict() class User(RiakObject): """A user of the service""" bucket_name = 'users' api_key = String() credentials = Dict() messaging_driver = String() messaging_address = String() def pre_save(self): if not hasattr(self, 'api_key'): self.api_key = utils.generate_key() class LogEntry(RiakObject): """A log entry holding one or more metrics A log entry "belongs" to a single Service. Each LogEntry can hold multiple metrics, but all LogEntry's must have the same set of metrics.""" bucket_name = 'log_entries' timestamp = Integer() <|code_end|> . Use current file imports: from riakalchemy import RiakObject from riakalchemy.types import Integer, String, Dict, RelatedObjects from surveilr import utils and context (classes, functions, or code) from other files: # Path: surveilr/utils.py # def truncate(number, rounding_factor): # def generate_key(): # def enhance_data_point(data_point): . Output only the next line.
metrics = Dict()
Given snippet: <|code_start|> class Configuration(Resource): def __init__(self): super(Configuration, self).__init__() self.resourceName = 'configuration' self.route('GET', (), self.get) @access.public @autoDescribeRoute( Description('Get the deployment configuration.') ) def get(self): notebooks = Setting().get(Features.NOTEBOOKS) if notebooks is None: notebooks = True site = Setting().get(Deployment.SITE) if site is None: site = '' return { 'features': { 'notebooks': notebooks <|code_end|> , continue by predicting the next line. Consider current file imports: from girder.api import access from girder.api.describe import Description, autoDescribeRoute from girder.api.rest import Resource, RestException from girder.constants import AccessType, TokenScope from girder.models.setting import Setting from .constants import Features, Deployment, Branding and context: # Path: girder/app/app/constants.py # class Features: # NOTEBOOKS = 'app.features.notebooks' # # class Deployment: # SITE = 'app.deployment.site' # # class Branding: # PRIVACY = 'app.configuration.privacy' # LICENSE = 'app.configuration.license' # HEADER_LOGO_ID = 'app.configuration.header.logo.file.id' # FOOTER_LOGO_ID = 'app.configuration.footer.logo.file.id' # FOOTER_LOGO_URL = 'app.configuration.footer.logo.url', # FAVICON_ID = 'app.configuration.favicon.file.id' which might include code, classes, or functions. Output only the next line.
},
Continue the code snippet: <|code_start|> @access.public @autoDescribeRoute( Description('Get the deployment configuration.') ) def get(self): notebooks = Setting().get(Features.NOTEBOOKS) if notebooks is None: notebooks = True site = Setting().get(Deployment.SITE) if site is None: site = '' return { 'features': { 'notebooks': notebooks }, 'deployment': { 'site': site }, 'branding': { 'license': Setting().get(Branding.LICENSE), 'privacy': Setting().get(Branding.PRIVACY), 'headerLogoFileId': Setting().get(Branding.HEADER_LOGO_ID), 'footerLogoFileId': Setting().get(Branding.FOOTER_LOGO_ID), 'footerLogoUrl': Setting().get(Branding.FOOTER_LOGO_URL), 'faviconFileId': Setting().get(Branding.FAVICON_ID) <|code_end|> . Use current file imports: from girder.api import access from girder.api.describe import Description, autoDescribeRoute from girder.api.rest import Resource, RestException from girder.constants import AccessType, TokenScope from girder.models.setting import Setting from .constants import Features, Deployment, Branding and context (classes, functions, or code) from other files: # Path: girder/app/app/constants.py # class Features: # NOTEBOOKS = 'app.features.notebooks' # # class Deployment: # SITE = 'app.deployment.site' # # class Branding: # PRIVACY = 'app.configuration.privacy' # LICENSE = 'app.configuration.license' # HEADER_LOGO_ID = 'app.configuration.header.logo.file.id' # FOOTER_LOGO_ID = 'app.configuration.footer.logo.file.id' # FOOTER_LOGO_URL = 'app.configuration.footer.logo.url', # FAVICON_ID = 'app.configuration.favicon.file.id' . Output only the next line.
}
Next line prediction: <|code_start|> @access.public @autoDescribeRoute( Description('Get the deployment configuration.') ) def get(self): notebooks = Setting().get(Features.NOTEBOOKS) if notebooks is None: notebooks = True site = Setting().get(Deployment.SITE) if site is None: site = '' return { 'features': { 'notebooks': notebooks }, 'deployment': { 'site': site }, 'branding': { 'license': Setting().get(Branding.LICENSE), 'privacy': Setting().get(Branding.PRIVACY), 'headerLogoFileId': Setting().get(Branding.HEADER_LOGO_ID), 'footerLogoFileId': Setting().get(Branding.FOOTER_LOGO_ID), 'footerLogoUrl': Setting().get(Branding.FOOTER_LOGO_URL), 'faviconFileId': Setting().get(Branding.FAVICON_ID) } <|code_end|> . Use current file imports: (from girder.api import access from girder.api.describe import Description, autoDescribeRoute from girder.api.rest import Resource, RestException from girder.constants import AccessType, TokenScope from girder.models.setting import Setting from .constants import Features, Deployment, Branding) and context including class names, function names, or small code snippets from other files: # Path: girder/app/app/constants.py # class Features: # NOTEBOOKS = 'app.features.notebooks' # # class Deployment: # SITE = 'app.deployment.site' # # class Branding: # PRIVACY = 'app.configuration.privacy' # LICENSE = 'app.configuration.license' # HEADER_LOGO_ID = 'app.configuration.header.logo.file.id' # FOOTER_LOGO_ID = 'app.configuration.footer.logo.file.id' # FOOTER_LOGO_URL = 'app.configuration.footer.logo.url', # FAVICON_ID = 'app.configuration.favicon.file.id' . Output only the next line.
}
Given snippet: <|code_start|> Request_ = namedtuple('Request', 'request, method, url, args, kwargs, ordering, session, skwargs, error') Response = namedtuple('Response', 'req, res, err') methods = { 'GET': requests.get, 'OPTIONS': requests.options, 'HEAD': requests.head, 'POST': requests.post, 'PUT': requests.put, <|code_end|> , continue by predicting the next line. Consider current file imports: import sublime import re from urllib import parse from concurrent import futures from collections import namedtuple, deque from ..deps import requests from .parsers import PREFIX from .helpers import truncate, prepend_scheme, is_instance, is_auxiliary_view from ..commands.download import Download from ..commands.upload import Upload and context: # Path: core/parsers.py # PREFIX = r'[\w_][\w\d_]*\.' # # Path: core/helpers.py # def truncate(s, l, ellipsis='…'): # """Truncates string to length `l` if need be and adds `ellipsis`. # """ # try: # _l = len(s) # except: # return s # # if _l > l: # try: # return s[:l] + ellipsis # in case s is a byte string # except: # return s[:l] # return s # # def prepend_scheme(url): # """Prepend scheme to URL if necessary. # """ # if isinstance(url, str) and len(url.split('://')) == 1: # scheme = sublime.load_settings('Requester.sublime-settings').get('scheme', 'http') # return scheme + '://' + url # return url # # def is_instance(obj, s): # """Is object an instance of class named `s`? # """ # return s in str(type(obj)) # # def is_auxiliary_view(view): # """Was view opened by a Requester command? This is useful, e.g., to # avoid resetting `env_file` and `env_string` on these views. # """ # if view.settings().get('requester.response_view', False): # return True # if view.settings().get('requester.test_view', False): # return True # return False which might include code, classes, or functions. Output only the next line.
'PATCH': requests.patch,
Given the code snippet: <|code_start|> Request_ = namedtuple('Request', 'request, method, url, args, kwargs, ordering, session, skwargs, error') Response = namedtuple('Response', 'req, res, err') methods = { 'GET': requests.get, 'OPTIONS': requests.options, 'HEAD': requests.head, 'POST': requests.post, 'PUT': requests.put, 'PATCH': requests.patch, <|code_end|> , generate the next line using the imports in this file: import sublime import re from urllib import parse from concurrent import futures from collections import namedtuple, deque from ..deps import requests from .parsers import PREFIX from .helpers import truncate, prepend_scheme, is_instance, is_auxiliary_view from ..commands.download import Download from ..commands.upload import Upload and context (functions, classes, or occasionally code) from other files: # Path: core/parsers.py # PREFIX = r'[\w_][\w\d_]*\.' # # Path: core/helpers.py # def truncate(s, l, ellipsis='…'): # """Truncates string to length `l` if need be and adds `ellipsis`. # """ # try: # _l = len(s) # except: # return s # # if _l > l: # try: # return s[:l] + ellipsis # in case s is a byte string # except: # return s[:l] # return s # # def prepend_scheme(url): # """Prepend scheme to URL if necessary. # """ # if isinstance(url, str) and len(url.split('://')) == 1: # scheme = sublime.load_settings('Requester.sublime-settings').get('scheme', 'http') # return scheme + '://' + url # return url # # def is_instance(obj, s): # """Is object an instance of class named `s`? # """ # return s in str(type(obj)) # # def is_auxiliary_view(view): # """Was view opened by a Requester command? This is useful, e.g., to # avoid resetting `env_file` and `env_string` on these views. # """ # if view.settings().get('requester.response_view', False): # return True # if view.settings().get('requester.test_view', False): # return True # return False . Output only the next line.
'DELETE': requests.delete,
Continue the code snippet: <|code_start|> Request_ = namedtuple('Request', 'request, method, url, args, kwargs, ordering, session, skwargs, error') Response = namedtuple('Response', 'req, res, err') methods = { 'GET': requests.get, 'OPTIONS': requests.options, 'HEAD': requests.head, <|code_end|> . Use current file imports: import sublime import re from urllib import parse from concurrent import futures from collections import namedtuple, deque from ..deps import requests from .parsers import PREFIX from .helpers import truncate, prepend_scheme, is_instance, is_auxiliary_view from ..commands.download import Download from ..commands.upload import Upload and context (classes, functions, or code) from other files: # Path: core/parsers.py # PREFIX = r'[\w_][\w\d_]*\.' # # Path: core/helpers.py # def truncate(s, l, ellipsis='…'): # """Truncates string to length `l` if need be and adds `ellipsis`. # """ # try: # _l = len(s) # except: # return s # # if _l > l: # try: # return s[:l] + ellipsis # in case s is a byte string # except: # return s[:l] # return s # # def prepend_scheme(url): # """Prepend scheme to URL if necessary. # """ # if isinstance(url, str) and len(url.split('://')) == 1: # scheme = sublime.load_settings('Requester.sublime-settings').get('scheme', 'http') # return scheme + '://' + url # return url # # def is_instance(obj, s): # """Is object an instance of class named `s`? # """ # return s in str(type(obj)) # # def is_auxiliary_view(view): # """Was view opened by a Requester command? This is useful, e.g., to # avoid resetting `env_file` and `env_string` on these views. # """ # if view.settings().get('requester.response_view', False): # return True # if view.settings().get('requester.test_view', False): # return True # return False . Output only the next line.
'POST': requests.post,
Based on the snippet: <|code_start|> fields = [ "first_name", "last_name", "organization", "keyserver_url", "public_key", "fingerprint", "timezone", "language" ] widgets = { 'keyserver_url': forms.TextInput(attrs={'placeholder': _("https://example.com/key.asc")}), 'public_key': forms.Textarea(attrs={'placeholder': _("-----BEGIN PGP PUBLIC KEY BLOCK-----\nVersion: SKS 1.1.1\n<PGP KEY>\n-----END PGP PUBLIC KEY BLOCK-----")}) } current_password = forms.CharField(label=_('Current password'), required=False, widget=forms.PasswordInput) new_password1 = forms.CharField(label=_('New password'), required=False, widget=forms.PasswordInput) new_password2 = forms.CharField(label=_('New password confirmation'), required=False, widget=forms.PasswordInput) def __init__(self, *args, **kwargs): # Flag to let the save method know when to call set_password self.change_password = False self.pub_key = None <|code_end|> , predict the immediate next line with the help of imports: from django.forms import ModelForm from django import forms from django.contrib.auth.password_validation import validate_password from django.utils.translation import ugettext_lazy as _ from allauth.account.forms import LoginForm as BaseLoginForm from allauth.account.forms import SignupForm as BaseSignupForm from .models import User from .utils import key_state import requests and context (classes, functions, sometimes code) from other files: # Path: humans/models.py # class User(AbstractUser): # """ # Project's base user model # """ # LANGUAGE_CHOICES = ( # ('en-us', 'English'), # ('pt-pt', _('Portuguese')), # ) # # organization = models.CharField( # null=True, blank=True, max_length=80, verbose_name=_('Organization')) # public_key = models.TextField( # blank=True, null=True, verbose_name=_('Public key')) # fingerprint = models.CharField( # null=True, blank=True, max_length=50, verbose_name=_('Fingerprint')) # keyserver_url = models.URLField( # null=True, blank=True, verbose_name=_('Key server URL')) # timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone')) # language = models.CharField( # default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language')) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.base_fingerprint = self.fingerprint # # def save(self, *args, **kwargs): # ip = kwargs.pop('ip', None) # agent = kwargs.pop('agent', '') # with transaction.atomic(): # super().save(*args, **kwargs) # if self.base_fingerprint != self.fingerprint: # self.keychanges.create(user=self, # prev_fingerprint=self.base_fingerprint, # to_fingerprint=self.fingerprint, # ip_address=ip, # agent=agent) # self.base_fingerprint = self.fingerprint # # def has_setup_complete(self): # if self.public_key and self.fingerprint: # return True # return False # # @property # def has_github_login(self): # return self.socialaccount_set.filter(provider='github').count() >= 1 # # @property # def has_public_key(self): # return True if self.public_key else False # # @property # def has_keyserver_url(self): # return True if self.keyserver_url else False # # Path: humans/utils.py # @with_gpg_obj # def key_state(key, gpg): # INVALID = (None, "invalid", -1) # if not key: # return INVALID # results = gpg.import_keys(key).results # if not results: # return INVALID # # Key data is present in the last element of the list # key_fingerprint = results[-1].get("fingerprint") # if not key_fingerprint: # return INVALID # # # Since the keyring is exclusive for this import # # only the imported key exists in it. # key = gpg.list_keys()[0] # exp_timestamp = int(key["expires"]) if key["expires"] else 0 # expires = datetime.fromtimestamp(exp_timestamp, timezone.utc) # to_expire = expires - timezone.now() # days_to_expire = to_expire.days # # if key["trust"] == "r": # state = "revoked" # elif exp_timestamp and expires < timezone.now(): # state = "expired" # else: # state = "valid" # # return key_fingerprint, state, days_to_expire . Output only the next line.
return super().__init__(*args, **kwargs)
Given snippet: <|code_start|> class UpdateUserInfoForm(ModelForm): class Meta: model = User fields = [ "first_name", "last_name", "organization", "keyserver_url", "public_key", "fingerprint", "timezone", "language" ] widgets = { 'keyserver_url': forms.TextInput(attrs={'placeholder': _("https://example.com/key.asc")}), 'public_key': forms.Textarea(attrs={'placeholder': _("-----BEGIN PGP PUBLIC KEY BLOCK-----\nVersion: SKS 1.1.1\n<PGP KEY>\n-----END PGP PUBLIC KEY BLOCK-----")}) } current_password = forms.CharField(label=_('Current password'), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.forms import ModelForm from django import forms from django.contrib.auth.password_validation import validate_password from django.utils.translation import ugettext_lazy as _ from allauth.account.forms import LoginForm as BaseLoginForm from allauth.account.forms import SignupForm as BaseSignupForm from .models import User from .utils import key_state import requests and context: # Path: humans/models.py # class User(AbstractUser): # """ # Project's base user model # """ # LANGUAGE_CHOICES = ( # ('en-us', 'English'), # ('pt-pt', _('Portuguese')), # ) # # organization = models.CharField( # null=True, blank=True, max_length=80, verbose_name=_('Organization')) # public_key = models.TextField( # blank=True, null=True, verbose_name=_('Public key')) # fingerprint = models.CharField( # null=True, blank=True, max_length=50, verbose_name=_('Fingerprint')) # keyserver_url = models.URLField( # null=True, blank=True, verbose_name=_('Key server URL')) # timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone')) # language = models.CharField( # default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language')) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.base_fingerprint = self.fingerprint # # def save(self, *args, **kwargs): # ip = kwargs.pop('ip', None) # agent = kwargs.pop('agent', '') # with transaction.atomic(): # super().save(*args, **kwargs) # if self.base_fingerprint != self.fingerprint: # self.keychanges.create(user=self, # prev_fingerprint=self.base_fingerprint, # to_fingerprint=self.fingerprint, # ip_address=ip, # agent=agent) # self.base_fingerprint = self.fingerprint # # def has_setup_complete(self): # if self.public_key and self.fingerprint: # return True # return False # # @property # def has_github_login(self): # return self.socialaccount_set.filter(provider='github').count() >= 1 # # @property # def has_public_key(self): # return True if self.public_key else False # # @property # def has_keyserver_url(self): # return True if self.keyserver_url else False # # Path: humans/utils.py # @with_gpg_obj # def key_state(key, gpg): # INVALID = (None, "invalid", -1) # if not key: # return INVALID # results = gpg.import_keys(key).results # if not results: # return INVALID # # Key data is present in the last element of the list # key_fingerprint = results[-1].get("fingerprint") # if not key_fingerprint: # return INVALID # # # Since the keyring is exclusive for this import # # only the imported key exists in it. # key = gpg.list_keys()[0] # exp_timestamp = int(key["expires"]) if key["expires"] else 0 # expires = datetime.fromtimestamp(exp_timestamp, timezone.utc) # to_expire = expires - timezone.now() # days_to_expire = to_expire.days # # if key["trust"] == "r": # state = "revoked" # elif exp_timestamp and expires < timezone.now(): # state = "expired" # else: # state = "valid" # # return key_fingerprint, state, days_to_expire which might include code, classes, or functions. Output only the next line.
required=False,
Next line prediction: <|code_start|> class MessageInline(admin.TabularInline): model = Message extra = 0 @admin.register(Box) class BoxAdmin(admin.ModelAdmin): list_display = ('name', 'owner', 'created_at', 'expires_at') list_filter = ('status', 'created_at', 'expires_at') search_fields = ['name', 'owner__email'] inlines = [MessageInline] @admin.register(Membership) class MembershipAdmin(admin.ModelAdmin): list_display = ('user', 'box', 'access', 'created_at') list_filter = ('access', 'created_at',) search_fields = ['box__name', 'user__email'] @admin.register(Message) class MessageAdmin(admin.ModelAdmin): list_display = ('box', 'status', 'created_at', 'sent_at') <|code_end|> . Use current file imports: (from django.contrib import admin from .models import Box, Membership, Message) and context including class names, function names, or small code snippets from other files: # Path: boxes/models.py # class Box(models.Model): # # OPEN = 10 # EXPIRED = 20 # DONE = 30 # CLOSED = 40 # # STATUSES = ( # (OPEN, _('Open')), # (EXPIRED, _('Expired')), # (DONE, _('Done')), # (CLOSED, _('Closed')) # ) # # name = models.CharField(max_length=128, verbose_name=_('Name')) # description = models.TextField(null=True, blank=True, # verbose_name=_('Description')) # uuid = models.UUIDField(default=uuid.uuid4, editable=False, # verbose_name=_('Unique ID')) # # owner = models.ForeignKey(settings.AUTH_USER_MODEL, # on_delete=models.CASCADE, # related_name='own_boxes', # verbose_name=_('Owner')) # # recipients = models.ManyToManyField(settings.AUTH_USER_MODEL, # related_name='boxes', # through='Membership', # through_fields=('box', 'user'), # verbose_name=_('Recipients')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # expires_at = models.DateTimeField(null=True, blank=True, # verbose_name=_('Expires at')) # # status = models.IntegerField(choices=STATUSES, default=OPEN, # verbose_name=_('Status')) # max_messages = models.PositiveIntegerField(default=1, validators=[ # MinValueValidator(1)], # verbose_name=_('Max. messages')) # # last_sent_at = models.DateTimeField(null=True, # verbose_name=_('Last sent at')) # # class Meta: # verbose_name = _('Box') # verbose_name_plural = _('Boxes') # # def __str__(self): # return self.name # # @staticmethod # def get_status(name): # return { # "Open": Box.OPEN, # "Expired": Box.EXPIRED, # "Done": Box.DONE, # "Closed": Box.CLOSED # }.get(name, Box.OPEN) # # class Membership(models.Model): # # KNOWLEDGE = 10 # NOTIFICATION = 20 # FULL = 30 # # LEVELS = ( # (KNOWLEDGE, _('Knowledge of existence')), # (NOTIFICATION, _('Activity notifications')), # (FULL, _('Full access to content')), # ) # # access = models.IntegerField(choices=LEVELS, default=FULL, # verbose_name=_('Rights')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # box = models.ForeignKey("Box", on_delete=models.CASCADE) # user = models.ForeignKey(settings.AUTH_USER_MODEL, # on_delete=models.CASCADE) # # class Meta: # verbose_name = _('Membership') # verbose_name_plural = _('Memberships') # # def __str__(self): # return "{}.{}".format(self.id, self.get_access_display()) # # class Message(models.Model): # # ONQUEUE = 10 # SENT = 20 # FAILED = 30 # # STATUSES = ( # (ONQUEUE, _('OnQueue')), # (SENT, _('Sent')), # (FAILED, _('Failed')) # ) # # box = models.ForeignKey( # "Box", on_delete=models.CASCADE, related_name='messages') # status = models.IntegerField(choices=STATUSES, default=ONQUEUE, # verbose_name=_('Status')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # sent_at = models.DateTimeField(null=True, blank=True, # verbose_name=_('Sent at')) . Output only the next line.
list_filter = ('status', 'created_at', 'sent_at')
Predict the next line for this snippet: <|code_start|> class MessageInline(admin.TabularInline): model = Message extra = 0 @admin.register(Box) class BoxAdmin(admin.ModelAdmin): list_display = ('name', 'owner', 'created_at', 'expires_at') list_filter = ('status', 'created_at', 'expires_at') search_fields = ['name', 'owner__email'] <|code_end|> with the help of current file imports: from django.contrib import admin from .models import Box, Membership, Message and context from other files: # Path: boxes/models.py # class Box(models.Model): # # OPEN = 10 # EXPIRED = 20 # DONE = 30 # CLOSED = 40 # # STATUSES = ( # (OPEN, _('Open')), # (EXPIRED, _('Expired')), # (DONE, _('Done')), # (CLOSED, _('Closed')) # ) # # name = models.CharField(max_length=128, verbose_name=_('Name')) # description = models.TextField(null=True, blank=True, # verbose_name=_('Description')) # uuid = models.UUIDField(default=uuid.uuid4, editable=False, # verbose_name=_('Unique ID')) # # owner = models.ForeignKey(settings.AUTH_USER_MODEL, # on_delete=models.CASCADE, # related_name='own_boxes', # verbose_name=_('Owner')) # # recipients = models.ManyToManyField(settings.AUTH_USER_MODEL, # related_name='boxes', # through='Membership', # through_fields=('box', 'user'), # verbose_name=_('Recipients')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # expires_at = models.DateTimeField(null=True, blank=True, # verbose_name=_('Expires at')) # # status = models.IntegerField(choices=STATUSES, default=OPEN, # verbose_name=_('Status')) # max_messages = models.PositiveIntegerField(default=1, validators=[ # MinValueValidator(1)], # verbose_name=_('Max. messages')) # # last_sent_at = models.DateTimeField(null=True, # verbose_name=_('Last sent at')) # # class Meta: # verbose_name = _('Box') # verbose_name_plural = _('Boxes') # # def __str__(self): # return self.name # # @staticmethod # def get_status(name): # return { # "Open": Box.OPEN, # "Expired": Box.EXPIRED, # "Done": Box.DONE, # "Closed": Box.CLOSED # }.get(name, Box.OPEN) # # class Membership(models.Model): # # KNOWLEDGE = 10 # NOTIFICATION = 20 # FULL = 30 # # LEVELS = ( # (KNOWLEDGE, _('Knowledge of existence')), # (NOTIFICATION, _('Activity notifications')), # (FULL, _('Full access to content')), # ) # # access = models.IntegerField(choices=LEVELS, default=FULL, # verbose_name=_('Rights')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # box = models.ForeignKey("Box", on_delete=models.CASCADE) # user = models.ForeignKey(settings.AUTH_USER_MODEL, # on_delete=models.CASCADE) # # class Meta: # verbose_name = _('Membership') # verbose_name_plural = _('Memberships') # # def __str__(self): # return "{}.{}".format(self.id, self.get_access_display()) # # class Message(models.Model): # # ONQUEUE = 10 # SENT = 20 # FAILED = 30 # # STATUSES = ( # (ONQUEUE, _('OnQueue')), # (SENT, _('Sent')), # (FAILED, _('Failed')) # ) # # box = models.ForeignKey( # "Box", on_delete=models.CASCADE, related_name='messages') # status = models.IntegerField(choices=STATUSES, default=ONQUEUE, # verbose_name=_('Status')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # sent_at = models.DateTimeField(null=True, blank=True, # verbose_name=_('Sent at')) , which may contain function names, class names, or code. Output only the next line.
inlines = [MessageInline]
Using the snippet: <|code_start|> class MessageInline(admin.TabularInline): model = Message extra = 0 @admin.register(Box) class BoxAdmin(admin.ModelAdmin): list_display = ('name', 'owner', 'created_at', 'expires_at') list_filter = ('status', 'created_at', 'expires_at') search_fields = ['name', 'owner__email'] inlines = [MessageInline] @admin.register(Membership) class MembershipAdmin(admin.ModelAdmin): list_display = ('user', 'box', 'access', 'created_at') <|code_end|> , determine the next line of code. You have imports: from django.contrib import admin from .models import Box, Membership, Message and context (class names, function names, or code) available: # Path: boxes/models.py # class Box(models.Model): # # OPEN = 10 # EXPIRED = 20 # DONE = 30 # CLOSED = 40 # # STATUSES = ( # (OPEN, _('Open')), # (EXPIRED, _('Expired')), # (DONE, _('Done')), # (CLOSED, _('Closed')) # ) # # name = models.CharField(max_length=128, verbose_name=_('Name')) # description = models.TextField(null=True, blank=True, # verbose_name=_('Description')) # uuid = models.UUIDField(default=uuid.uuid4, editable=False, # verbose_name=_('Unique ID')) # # owner = models.ForeignKey(settings.AUTH_USER_MODEL, # on_delete=models.CASCADE, # related_name='own_boxes', # verbose_name=_('Owner')) # # recipients = models.ManyToManyField(settings.AUTH_USER_MODEL, # related_name='boxes', # through='Membership', # through_fields=('box', 'user'), # verbose_name=_('Recipients')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # expires_at = models.DateTimeField(null=True, blank=True, # verbose_name=_('Expires at')) # # status = models.IntegerField(choices=STATUSES, default=OPEN, # verbose_name=_('Status')) # max_messages = models.PositiveIntegerField(default=1, validators=[ # MinValueValidator(1)], # verbose_name=_('Max. messages')) # # last_sent_at = models.DateTimeField(null=True, # verbose_name=_('Last sent at')) # # class Meta: # verbose_name = _('Box') # verbose_name_plural = _('Boxes') # # def __str__(self): # return self.name # # @staticmethod # def get_status(name): # return { # "Open": Box.OPEN, # "Expired": Box.EXPIRED, # "Done": Box.DONE, # "Closed": Box.CLOSED # }.get(name, Box.OPEN) # # class Membership(models.Model): # # KNOWLEDGE = 10 # NOTIFICATION = 20 # FULL = 30 # # LEVELS = ( # (KNOWLEDGE, _('Knowledge of existence')), # (NOTIFICATION, _('Activity notifications')), # (FULL, _('Full access to content')), # ) # # access = models.IntegerField(choices=LEVELS, default=FULL, # verbose_name=_('Rights')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # box = models.ForeignKey("Box", on_delete=models.CASCADE) # user = models.ForeignKey(settings.AUTH_USER_MODEL, # on_delete=models.CASCADE) # # class Meta: # verbose_name = _('Membership') # verbose_name_plural = _('Memberships') # # def __str__(self): # return "{}.{}".format(self.id, self.get_access_display()) # # class Message(models.Model): # # ONQUEUE = 10 # SENT = 20 # FAILED = 30 # # STATUSES = ( # (ONQUEUE, _('OnQueue')), # (SENT, _('Sent')), # (FAILED, _('Failed')) # ) # # box = models.ForeignKey( # "Box", on_delete=models.CASCADE, related_name='messages') # status = models.IntegerField(choices=STATUSES, default=ONQUEUE, # verbose_name=_('Status')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # sent_at = models.DateTimeField(null=True, blank=True, # verbose_name=_('Sent at')) . Output only the next line.
list_filter = ('access', 'created_at',)
Next line prediction: <|code_start|>from __future__ import absolute_import @shared_task def process_email(message_id, form_data, sent_by=None): message = Message.objects.get(id=message_id) box = message.box msg = form_data["message"] file_name = form_data.get("file_name", "") subject = _('New submission to your box: {}').format(box) reply_to = [sent_by] if sent_by else [] if file_name: body = _("The submitted file can be found in the attachments.") email = EmailMultiAlternatives( subject, <|code_end|> . Use current file imports: (from django.core.mail import EmailMultiAlternatives from django.conf import settings from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from .models import Message from celery import shared_task) and context including class names, function names, or small code snippets from other files: # Path: boxes/models.py # class Message(models.Model): # # ONQUEUE = 10 # SENT = 20 # FAILED = 30 # # STATUSES = ( # (ONQUEUE, _('OnQueue')), # (SENT, _('Sent')), # (FAILED, _('Failed')) # ) # # box = models.ForeignKey( # "Box", on_delete=models.CASCADE, related_name='messages') # status = models.IntegerField(choices=STATUSES, default=ONQUEUE, # verbose_name=_('Status')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # sent_at = models.DateTimeField(null=True, blank=True, # verbose_name=_('Sent at')) . Output only the next line.
body,
Given the following code snippet before the placeholder: <|code_start|> "description", "expires_at", "max_messages"] def clean_expires_at(self): # Validate the expiration date expires_at = self.cleaned_data.get("expires_at", "") never_expires = self.cleaned_data.get("never_expires", "") current_tz = timezone.get_current_timezone() if never_expires: expires_at = None self.cleaned_data["expires_at"] = expires_at if expires_at: # Check if the expiration date is a past date if timezone.localtime(timezone.now(), current_tz) > expires_at: self.add_error('expires_at', _('The date must be on the future.')) if not expires_at and not never_expires: self.add_error('expires_at', _('This field is required, unless box is set to ' 'never expire.')) return expires_at def clean(self): cleaned_data = super().clean() cleaned_data.pop("never_expires") return cleaned_data class SubmitBoxForm(Form): message = CharField(widget=Textarea, required=True) <|code_end|> , predict the next line using imports from the current file: from django.forms import ModelForm, Form, CharField, Textarea, BooleanField from .models import Box from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from sys import getsizeof and context including class names, function names, and sometimes code from other files: # Path: boxes/models.py # class Box(models.Model): # # OPEN = 10 # EXPIRED = 20 # DONE = 30 # CLOSED = 40 # # STATUSES = ( # (OPEN, _('Open')), # (EXPIRED, _('Expired')), # (DONE, _('Done')), # (CLOSED, _('Closed')) # ) # # name = models.CharField(max_length=128, verbose_name=_('Name')) # description = models.TextField(null=True, blank=True, # verbose_name=_('Description')) # uuid = models.UUIDField(default=uuid.uuid4, editable=False, # verbose_name=_('Unique ID')) # # owner = models.ForeignKey(settings.AUTH_USER_MODEL, # on_delete=models.CASCADE, # related_name='own_boxes', # verbose_name=_('Owner')) # # recipients = models.ManyToManyField(settings.AUTH_USER_MODEL, # related_name='boxes', # through='Membership', # through_fields=('box', 'user'), # verbose_name=_('Recipients')) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # updated_at = models.DateTimeField(auto_now=True, # verbose_name=_('Updated at')) # expires_at = models.DateTimeField(null=True, blank=True, # verbose_name=_('Expires at')) # # status = models.IntegerField(choices=STATUSES, default=OPEN, # verbose_name=_('Status')) # max_messages = models.PositiveIntegerField(default=1, validators=[ # MinValueValidator(1)], # verbose_name=_('Max. messages')) # # last_sent_at = models.DateTimeField(null=True, # verbose_name=_('Last sent at')) # # class Meta: # verbose_name = _('Box') # verbose_name_plural = _('Boxes') # # def __str__(self): # return self.name # # @staticmethod # def get_status(name): # return { # "Open": Box.OPEN, # "Expired": Box.EXPIRED, # "Done": Box.DONE, # "Closed": Box.CLOSED # }.get(name, Box.OPEN) . Output only the next line.
file_name = CharField(required=False)
Using the snippet: <|code_start|> Q(public_key__isnull=True) | Q(public_key__exact='')) logger.info(_('Start validating user keys')) for user in users: logger.info(_('Working on user: {}').format(user.email)) key = user.public_key # Check key fingerprint, *state = key_state(key) if state[0] == "expired": # Email user and disable/remove key send_email(user, _('Hawkpost: {} key').format(state[0]), "humans/emails/key_{}.txt".format(state[0])) user.fingerprint = "" user.public_key = "" user.save() elif state[0] == "valid": # Checks if key is about to expire days_to_expire = state[1] if days_to_expire == 7 or days_to_expire == 1: # Warns user if key about to expire send_email(user, _('Hawkpost: Key will expire in {} day(s)').format(days_to_expire), "humans/emails/key_will_expire.txt") @shared_task def send_email_notification(subject, body, email): email = EmailMultiAlternatives(subject, body, settings.DEFAULT_FROM_EMAIL, <|code_end|> , determine the next line of code. You have imports: from celery.task.schedules import crontab from celery.decorators import periodic_task from celery import shared_task from celery.utils.log import get_task_logger from django.core.mail import EmailMultiAlternatives from django.conf import settings from django.db.models import Q from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from .models import User, Notification from .utils import key_state import requests and context (class names, function names, or code) available: # Path: humans/models.py # class User(AbstractUser): # """ # Project's base user model # """ # LANGUAGE_CHOICES = ( # ('en-us', 'English'), # ('pt-pt', _('Portuguese')), # ) # # organization = models.CharField( # null=True, blank=True, max_length=80, verbose_name=_('Organization')) # public_key = models.TextField( # blank=True, null=True, verbose_name=_('Public key')) # fingerprint = models.CharField( # null=True, blank=True, max_length=50, verbose_name=_('Fingerprint')) # keyserver_url = models.URLField( # null=True, blank=True, verbose_name=_('Key server URL')) # timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone')) # language = models.CharField( # default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language')) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.base_fingerprint = self.fingerprint # # def save(self, *args, **kwargs): # ip = kwargs.pop('ip', None) # agent = kwargs.pop('agent', '') # with transaction.atomic(): # super().save(*args, **kwargs) # if self.base_fingerprint != self.fingerprint: # self.keychanges.create(user=self, # prev_fingerprint=self.base_fingerprint, # to_fingerprint=self.fingerprint, # ip_address=ip, # agent=agent) # self.base_fingerprint = self.fingerprint # # def has_setup_complete(self): # if self.public_key and self.fingerprint: # return True # return False # # @property # def has_github_login(self): # return self.socialaccount_set.filter(provider='github').count() >= 1 # # @property # def has_public_key(self): # return True if self.public_key else False # # @property # def has_keyserver_url(self): # return True if self.keyserver_url else False # # class Notification(models.Model): # """ These notifications are emails sent to all users (or some subset) # by an Administrator. Just once. # """ # # subject = models.CharField( # null=False, blank=False, max_length=150, verbose_name=_('Subject')) # body = models.TextField(null=False, blank=False, verbose_name=_('Body')) # # created_at = models.DateTimeField( # auto_now_add=True, verbose_name=_('Created at')) # updated_at = models.DateTimeField( # auto_now=True, verbose_name=_('Updated at')) # # sent_at = models.DateTimeField(null=True, verbose_name=_('Sent at')) # send_to = models.ForeignKey( # Group, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('Send to')) # # class Meta: # verbose_name = _('Notification') # verbose_name_plural = _('Notifications') # # def __str__(self): # return self.subject # # def delete(self): # return super().delete() if not self.sent_at else False # # Path: humans/utils.py # @with_gpg_obj # def key_state(key, gpg): # INVALID = (None, "invalid", -1) # if not key: # return INVALID # results = gpg.import_keys(key).results # if not results: # return INVALID # # Key data is present in the last element of the list # key_fingerprint = results[-1].get("fingerprint") # if not key_fingerprint: # return INVALID # # # Since the keyring is exclusive for this import # # only the imported key exists in it. # key = gpg.list_keys()[0] # exp_timestamp = int(key["expires"]) if key["expires"] else 0 # expires = datetime.fromtimestamp(exp_timestamp, timezone.utc) # to_expire = expires - timezone.now() # days_to_expire = to_expire.days # # if key["trust"] == "r": # state = "revoked" # elif exp_timestamp and expires < timezone.now(): # state = "expired" # else: # state = "valid" # # return key_fingerprint, state, days_to_expire . Output only the next line.
[email])
Continue the code snippet: <|code_start|> user.fingerprint = "" user.public_key = "" user.save() elif state[0] == "valid": # Checks if key is about to expire days_to_expire = state[1] if days_to_expire == 7 or days_to_expire == 1: # Warns user if key about to expire send_email(user, _('Hawkpost: Key will expire in {} day(s)').format(days_to_expire), "humans/emails/key_will_expire.txt") @shared_task def send_email_notification(subject, body, email): email = EmailMultiAlternatives(subject, body, settings.DEFAULT_FROM_EMAIL, [email]) email.send() @shared_task def enqueue_email_notifications(notification_id, group_id): notification = Notification.objects.get(id=notification_id) if group_id: users = User.objects.filter(groups__id=group_id) else: users = User.objects.all() <|code_end|> . Use current file imports: from celery.task.schedules import crontab from celery.decorators import periodic_task from celery import shared_task from celery.utils.log import get_task_logger from django.core.mail import EmailMultiAlternatives from django.conf import settings from django.db.models import Q from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from .models import User, Notification from .utils import key_state import requests and context (classes, functions, or code) from other files: # Path: humans/models.py # class User(AbstractUser): # """ # Project's base user model # """ # LANGUAGE_CHOICES = ( # ('en-us', 'English'), # ('pt-pt', _('Portuguese')), # ) # # organization = models.CharField( # null=True, blank=True, max_length=80, verbose_name=_('Organization')) # public_key = models.TextField( # blank=True, null=True, verbose_name=_('Public key')) # fingerprint = models.CharField( # null=True, blank=True, max_length=50, verbose_name=_('Fingerprint')) # keyserver_url = models.URLField( # null=True, blank=True, verbose_name=_('Key server URL')) # timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone')) # language = models.CharField( # default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language')) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.base_fingerprint = self.fingerprint # # def save(self, *args, **kwargs): # ip = kwargs.pop('ip', None) # agent = kwargs.pop('agent', '') # with transaction.atomic(): # super().save(*args, **kwargs) # if self.base_fingerprint != self.fingerprint: # self.keychanges.create(user=self, # prev_fingerprint=self.base_fingerprint, # to_fingerprint=self.fingerprint, # ip_address=ip, # agent=agent) # self.base_fingerprint = self.fingerprint # # def has_setup_complete(self): # if self.public_key and self.fingerprint: # return True # return False # # @property # def has_github_login(self): # return self.socialaccount_set.filter(provider='github').count() >= 1 # # @property # def has_public_key(self): # return True if self.public_key else False # # @property # def has_keyserver_url(self): # return True if self.keyserver_url else False # # class Notification(models.Model): # """ These notifications are emails sent to all users (or some subset) # by an Administrator. Just once. # """ # # subject = models.CharField( # null=False, blank=False, max_length=150, verbose_name=_('Subject')) # body = models.TextField(null=False, blank=False, verbose_name=_('Body')) # # created_at = models.DateTimeField( # auto_now_add=True, verbose_name=_('Created at')) # updated_at = models.DateTimeField( # auto_now=True, verbose_name=_('Updated at')) # # sent_at = models.DateTimeField(null=True, verbose_name=_('Sent at')) # send_to = models.ForeignKey( # Group, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('Send to')) # # class Meta: # verbose_name = _('Notification') # verbose_name_plural = _('Notifications') # # def __str__(self): # return self.subject # # def delete(self): # return super().delete() if not self.sent_at else False # # Path: humans/utils.py # @with_gpg_obj # def key_state(key, gpg): # INVALID = (None, "invalid", -1) # if not key: # return INVALID # results = gpg.import_keys(key).results # if not results: # return INVALID # # Key data is present in the last element of the list # key_fingerprint = results[-1].get("fingerprint") # if not key_fingerprint: # return INVALID # # # Since the keyring is exclusive for this import # # only the imported key exists in it. # key = gpg.list_keys()[0] # exp_timestamp = int(key["expires"]) if key["expires"] else 0 # expires = datetime.fromtimestamp(exp_timestamp, timezone.utc) # to_expire = expires - timezone.now() # days_to_expire = to_expire.days # # if key["trust"] == "r": # state = "revoked" # elif exp_timestamp and expires < timezone.now(): # state = "expired" # else: # state = "valid" # # return key_fingerprint, state, days_to_expire . Output only the next line.
for user in users:
Given snippet: <|code_start|># Every day at 4 AM UTC @periodic_task(run_every=(crontab(minute=0, hour=4)), ignore_result=True) def update_public_keys(): users = User.objects.exclude( Q(keyserver_url__isnull=True) | Q(keyserver_url__exact='')) logger.info(_('Start updating user keys')) for user in users: logger.info(_('Working on user: {}').format(user.email)) logger.info(_('URL: {}').format(user.keyserver_url)) try: key = fetch_key(user.keyserver_url) except: logger.error(_('Unable to fetch new key')) continue # Check key fingerprint, *state = key_state(key) if state[0] in ["expired", "revoked"]: # Email user and disable/remove key send_email(user, _('Hawkpost: {} key').format(state[0]), "humans/emails/key_{}.txt".format(state[0])) user.fingerprint = "" user.public_key = "" user.keyserver_url = "" user.save() elif state[0] == "invalid": # Alert the user and remove keyserver_url send_email(user, _('Hawkpost: Keyserver Url providing an invalid key'), <|code_end|> , continue by predicting the next line. Consider current file imports: from celery.task.schedules import crontab from celery.decorators import periodic_task from celery import shared_task from celery.utils.log import get_task_logger from django.core.mail import EmailMultiAlternatives from django.conf import settings from django.db.models import Q from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from .models import User, Notification from .utils import key_state import requests and context: # Path: humans/models.py # class User(AbstractUser): # """ # Project's base user model # """ # LANGUAGE_CHOICES = ( # ('en-us', 'English'), # ('pt-pt', _('Portuguese')), # ) # # organization = models.CharField( # null=True, blank=True, max_length=80, verbose_name=_('Organization')) # public_key = models.TextField( # blank=True, null=True, verbose_name=_('Public key')) # fingerprint = models.CharField( # null=True, blank=True, max_length=50, verbose_name=_('Fingerprint')) # keyserver_url = models.URLField( # null=True, blank=True, verbose_name=_('Key server URL')) # timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone')) # language = models.CharField( # default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language')) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.base_fingerprint = self.fingerprint # # def save(self, *args, **kwargs): # ip = kwargs.pop('ip', None) # agent = kwargs.pop('agent', '') # with transaction.atomic(): # super().save(*args, **kwargs) # if self.base_fingerprint != self.fingerprint: # self.keychanges.create(user=self, # prev_fingerprint=self.base_fingerprint, # to_fingerprint=self.fingerprint, # ip_address=ip, # agent=agent) # self.base_fingerprint = self.fingerprint # # def has_setup_complete(self): # if self.public_key and self.fingerprint: # return True # return False # # @property # def has_github_login(self): # return self.socialaccount_set.filter(provider='github').count() >= 1 # # @property # def has_public_key(self): # return True if self.public_key else False # # @property # def has_keyserver_url(self): # return True if self.keyserver_url else False # # class Notification(models.Model): # """ These notifications are emails sent to all users (or some subset) # by an Administrator. Just once. # """ # # subject = models.CharField( # null=False, blank=False, max_length=150, verbose_name=_('Subject')) # body = models.TextField(null=False, blank=False, verbose_name=_('Body')) # # created_at = models.DateTimeField( # auto_now_add=True, verbose_name=_('Created at')) # updated_at = models.DateTimeField( # auto_now=True, verbose_name=_('Updated at')) # # sent_at = models.DateTimeField(null=True, verbose_name=_('Sent at')) # send_to = models.ForeignKey( # Group, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('Send to')) # # class Meta: # verbose_name = _('Notification') # verbose_name_plural = _('Notifications') # # def __str__(self): # return self.subject # # def delete(self): # return super().delete() if not self.sent_at else False # # Path: humans/utils.py # @with_gpg_obj # def key_state(key, gpg): # INVALID = (None, "invalid", -1) # if not key: # return INVALID # results = gpg.import_keys(key).results # if not results: # return INVALID # # Key data is present in the last element of the list # key_fingerprint = results[-1].get("fingerprint") # if not key_fingerprint: # return INVALID # # # Since the keyring is exclusive for this import # # only the imported key exists in it. # key = gpg.list_keys()[0] # exp_timestamp = int(key["expires"]) if key["expires"] else 0 # expires = datetime.fromtimestamp(exp_timestamp, timezone.utc) # to_expire = expires - timezone.now() # days_to_expire = to_expire.days # # if key["trust"] == "r": # state = "revoked" # elif exp_timestamp and expires < timezone.now(): # state = "expired" # else: # state = "valid" # # return key_fingerprint, state, days_to_expire which might include code, classes, or functions. Output only the next line.
"humans/emails/key_invalid.txt")
Using the snippet: <|code_start|> list_display = ('username', 'email', "first_name", "last_name", "is_staff", "has_public_key", "has_keyserver_url") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fieldsets += ((_('Key options'), { 'classes': ('collapse',), 'fields': ('fingerprint', 'keyserver_url', 'public_key'), }),) @admin.register(Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('subject', 'sent_at', 'send_to') list_filter = ('send_to', 'sent_at') fields = ["subject", "body", "send_to"] search_fields = ['subject', 'body'] actions = ["send_notification"] def delete_model(self, request, obj): if obj.sent_at: <|code_end|> , determine the next line of code. You have imports: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin from django.contrib import messages from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from .models import User, Notification, KeyChangeRecord from .tasks import enqueue_email_notifications and context (class names, function names, or code) available: # Path: humans/models.py # class User(AbstractUser): # """ # Project's base user model # """ # LANGUAGE_CHOICES = ( # ('en-us', 'English'), # ('pt-pt', _('Portuguese')), # ) # # organization = models.CharField( # null=True, blank=True, max_length=80, verbose_name=_('Organization')) # public_key = models.TextField( # blank=True, null=True, verbose_name=_('Public key')) # fingerprint = models.CharField( # null=True, blank=True, max_length=50, verbose_name=_('Fingerprint')) # keyserver_url = models.URLField( # null=True, blank=True, verbose_name=_('Key server URL')) # timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone')) # language = models.CharField( # default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language')) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.base_fingerprint = self.fingerprint # # def save(self, *args, **kwargs): # ip = kwargs.pop('ip', None) # agent = kwargs.pop('agent', '') # with transaction.atomic(): # super().save(*args, **kwargs) # if self.base_fingerprint != self.fingerprint: # self.keychanges.create(user=self, # prev_fingerprint=self.base_fingerprint, # to_fingerprint=self.fingerprint, # ip_address=ip, # agent=agent) # self.base_fingerprint = self.fingerprint # # def has_setup_complete(self): # if self.public_key and self.fingerprint: # return True # return False # # @property # def has_github_login(self): # return self.socialaccount_set.filter(provider='github').count() >= 1 # # @property # def has_public_key(self): # return True if self.public_key else False # # @property # def has_keyserver_url(self): # return True if self.keyserver_url else False # # class Notification(models.Model): # """ These notifications are emails sent to all users (or some subset) # by an Administrator. Just once. # """ # # subject = models.CharField( # null=False, blank=False, max_length=150, verbose_name=_('Subject')) # body = models.TextField(null=False, blank=False, verbose_name=_('Body')) # # created_at = models.DateTimeField( # auto_now_add=True, verbose_name=_('Created at')) # updated_at = models.DateTimeField( # auto_now=True, verbose_name=_('Updated at')) # # sent_at = models.DateTimeField(null=True, verbose_name=_('Sent at')) # send_to = models.ForeignKey( # Group, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('Send to')) # # class Meta: # verbose_name = _('Notification') # verbose_name_plural = _('Notifications') # # def __str__(self): # return self.subject # # def delete(self): # return super().delete() if not self.sent_at else False # # class KeyChangeRecord(models.Model): # """ Records the information about the change of a key by the user. # This allows the user to be aware of any suspicious activity # """ # user = models.ForeignKey(User, # on_delete=models.CASCADE, # related_name='keychanges', # verbose_name=_('User')) # prev_fingerprint = models.CharField(null=True, # blank=True, # max_length=50, # verbose_name=_('Previous Fingerprint')) # to_fingerprint = models.CharField(null=True, # blank=True, # max_length=50, # verbose_name=_('To Fingerprint')) # ip_address = models.GenericIPAddressField(blank=True, null=True) # agent = models.TextField(blank=True) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # # class Meta: # verbose_name = _('KeyChangeRecord') # verbose_name_plural = _('KeyChangeRecords') # # Path: humans/tasks.py # @shared_task # def enqueue_email_notifications(notification_id, group_id): # notification = Notification.objects.get(id=notification_id) # if group_id: # users = User.objects.filter(groups__id=group_id) # else: # users = User.objects.all() # # for user in users: # send_email_notification.delay(notification.subject, # notification.body, # user.email) . Output only the next line.
msg = _('Cannot delete "{}", the notification was already sent')
Continue the code snippet: <|code_start|> @admin.register(User) class UserAdmin(DefaultUserAdmin): list_display = ('username', 'email', "first_name", "last_name", "is_staff", "has_public_key", "has_keyserver_url") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) <|code_end|> . Use current file imports: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin from django.contrib import messages from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from .models import User, Notification, KeyChangeRecord from .tasks import enqueue_email_notifications and context (classes, functions, or code) from other files: # Path: humans/models.py # class User(AbstractUser): # """ # Project's base user model # """ # LANGUAGE_CHOICES = ( # ('en-us', 'English'), # ('pt-pt', _('Portuguese')), # ) # # organization = models.CharField( # null=True, blank=True, max_length=80, verbose_name=_('Organization')) # public_key = models.TextField( # blank=True, null=True, verbose_name=_('Public key')) # fingerprint = models.CharField( # null=True, blank=True, max_length=50, verbose_name=_('Fingerprint')) # keyserver_url = models.URLField( # null=True, blank=True, verbose_name=_('Key server URL')) # timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone')) # language = models.CharField( # default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language')) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.base_fingerprint = self.fingerprint # # def save(self, *args, **kwargs): # ip = kwargs.pop('ip', None) # agent = kwargs.pop('agent', '') # with transaction.atomic(): # super().save(*args, **kwargs) # if self.base_fingerprint != self.fingerprint: # self.keychanges.create(user=self, # prev_fingerprint=self.base_fingerprint, # to_fingerprint=self.fingerprint, # ip_address=ip, # agent=agent) # self.base_fingerprint = self.fingerprint # # def has_setup_complete(self): # if self.public_key and self.fingerprint: # return True # return False # # @property # def has_github_login(self): # return self.socialaccount_set.filter(provider='github').count() >= 1 # # @property # def has_public_key(self): # return True if self.public_key else False # # @property # def has_keyserver_url(self): # return True if self.keyserver_url else False # # class Notification(models.Model): # """ These notifications are emails sent to all users (or some subset) # by an Administrator. Just once. # """ # # subject = models.CharField( # null=False, blank=False, max_length=150, verbose_name=_('Subject')) # body = models.TextField(null=False, blank=False, verbose_name=_('Body')) # # created_at = models.DateTimeField( # auto_now_add=True, verbose_name=_('Created at')) # updated_at = models.DateTimeField( # auto_now=True, verbose_name=_('Updated at')) # # sent_at = models.DateTimeField(null=True, verbose_name=_('Sent at')) # send_to = models.ForeignKey( # Group, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('Send to')) # # class Meta: # verbose_name = _('Notification') # verbose_name_plural = _('Notifications') # # def __str__(self): # return self.subject # # def delete(self): # return super().delete() if not self.sent_at else False # # class KeyChangeRecord(models.Model): # """ Records the information about the change of a key by the user. # This allows the user to be aware of any suspicious activity # """ # user = models.ForeignKey(User, # on_delete=models.CASCADE, # related_name='keychanges', # verbose_name=_('User')) # prev_fingerprint = models.CharField(null=True, # blank=True, # max_length=50, # verbose_name=_('Previous Fingerprint')) # to_fingerprint = models.CharField(null=True, # blank=True, # max_length=50, # verbose_name=_('To Fingerprint')) # ip_address = models.GenericIPAddressField(blank=True, null=True) # agent = models.TextField(blank=True) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # # class Meta: # verbose_name = _('KeyChangeRecord') # verbose_name_plural = _('KeyChangeRecords') # # Path: humans/tasks.py # @shared_task # def enqueue_email_notifications(notification_id, group_id): # notification = Notification.objects.get(id=notification_id) # if group_id: # users = User.objects.filter(groups__id=group_id) # else: # users = User.objects.all() # # for user in users: # send_email_notification.delay(notification.subject, # notification.body, # user.email) . Output only the next line.
self.fieldsets += ((_('Key options'), {
Here is a snippet: <|code_start|>class UserAdmin(DefaultUserAdmin): list_display = ('username', 'email', "first_name", "last_name", "is_staff", "has_public_key", "has_keyserver_url") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fieldsets += ((_('Key options'), { 'classes': ('collapse',), 'fields': ('fingerprint', 'keyserver_url', 'public_key'), }),) @admin.register(Notification) class NotificationAdmin(admin.ModelAdmin): list_display = ('subject', 'sent_at', 'send_to') list_filter = ('send_to', 'sent_at') fields = ["subject", "body", "send_to"] search_fields = ['subject', 'body'] actions = ["send_notification"] def delete_model(self, request, obj): <|code_end|> . Write the next line using the current file imports: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin from django.contrib import messages from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from .models import User, Notification, KeyChangeRecord from .tasks import enqueue_email_notifications and context from other files: # Path: humans/models.py # class User(AbstractUser): # """ # Project's base user model # """ # LANGUAGE_CHOICES = ( # ('en-us', 'English'), # ('pt-pt', _('Portuguese')), # ) # # organization = models.CharField( # null=True, blank=True, max_length=80, verbose_name=_('Organization')) # public_key = models.TextField( # blank=True, null=True, verbose_name=_('Public key')) # fingerprint = models.CharField( # null=True, blank=True, max_length=50, verbose_name=_('Fingerprint')) # keyserver_url = models.URLField( # null=True, blank=True, verbose_name=_('Key server URL')) # timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone')) # language = models.CharField( # default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language')) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.base_fingerprint = self.fingerprint # # def save(self, *args, **kwargs): # ip = kwargs.pop('ip', None) # agent = kwargs.pop('agent', '') # with transaction.atomic(): # super().save(*args, **kwargs) # if self.base_fingerprint != self.fingerprint: # self.keychanges.create(user=self, # prev_fingerprint=self.base_fingerprint, # to_fingerprint=self.fingerprint, # ip_address=ip, # agent=agent) # self.base_fingerprint = self.fingerprint # # def has_setup_complete(self): # if self.public_key and self.fingerprint: # return True # return False # # @property # def has_github_login(self): # return self.socialaccount_set.filter(provider='github').count() >= 1 # # @property # def has_public_key(self): # return True if self.public_key else False # # @property # def has_keyserver_url(self): # return True if self.keyserver_url else False # # class Notification(models.Model): # """ These notifications are emails sent to all users (or some subset) # by an Administrator. Just once. # """ # # subject = models.CharField( # null=False, blank=False, max_length=150, verbose_name=_('Subject')) # body = models.TextField(null=False, blank=False, verbose_name=_('Body')) # # created_at = models.DateTimeField( # auto_now_add=True, verbose_name=_('Created at')) # updated_at = models.DateTimeField( # auto_now=True, verbose_name=_('Updated at')) # # sent_at = models.DateTimeField(null=True, verbose_name=_('Sent at')) # send_to = models.ForeignKey( # Group, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('Send to')) # # class Meta: # verbose_name = _('Notification') # verbose_name_plural = _('Notifications') # # def __str__(self): # return self.subject # # def delete(self): # return super().delete() if not self.sent_at else False # # class KeyChangeRecord(models.Model): # """ Records the information about the change of a key by the user. # This allows the user to be aware of any suspicious activity # """ # user = models.ForeignKey(User, # on_delete=models.CASCADE, # related_name='keychanges', # verbose_name=_('User')) # prev_fingerprint = models.CharField(null=True, # blank=True, # max_length=50, # verbose_name=_('Previous Fingerprint')) # to_fingerprint = models.CharField(null=True, # blank=True, # max_length=50, # verbose_name=_('To Fingerprint')) # ip_address = models.GenericIPAddressField(blank=True, null=True) # agent = models.TextField(blank=True) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # # class Meta: # verbose_name = _('KeyChangeRecord') # verbose_name_plural = _('KeyChangeRecords') # # Path: humans/tasks.py # @shared_task # def enqueue_email_notifications(notification_id, group_id): # notification = Notification.objects.get(id=notification_id) # if group_id: # users = User.objects.filter(groups__id=group_id) # else: # users = User.objects.all() # # for user in users: # send_email_notification.delay(notification.subject, # notification.body, # user.email) , which may include functions, classes, or code. Output only the next line.
if obj.sent_at:
Given the following code snippet before the placeholder: <|code_start|> @admin.register(User) class UserAdmin(DefaultUserAdmin): list_display = ('username', 'email', "first_name", "last_name", <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DefaultUserAdmin from django.contrib import messages from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from .models import User, Notification, KeyChangeRecord from .tasks import enqueue_email_notifications and context including class names, function names, and sometimes code from other files: # Path: humans/models.py # class User(AbstractUser): # """ # Project's base user model # """ # LANGUAGE_CHOICES = ( # ('en-us', 'English'), # ('pt-pt', _('Portuguese')), # ) # # organization = models.CharField( # null=True, blank=True, max_length=80, verbose_name=_('Organization')) # public_key = models.TextField( # blank=True, null=True, verbose_name=_('Public key')) # fingerprint = models.CharField( # null=True, blank=True, max_length=50, verbose_name=_('Fingerprint')) # keyserver_url = models.URLField( # null=True, blank=True, verbose_name=_('Key server URL')) # timezone = TimeZoneField(default='UTC', verbose_name=_('Timezone')) # language = models.CharField( # default="en-us", max_length=16, choices=LANGUAGE_CHOICES, verbose_name=_('Language')) # # def __init__(self, *args, **kwargs): # super().__init__(*args, **kwargs) # self.base_fingerprint = self.fingerprint # # def save(self, *args, **kwargs): # ip = kwargs.pop('ip', None) # agent = kwargs.pop('agent', '') # with transaction.atomic(): # super().save(*args, **kwargs) # if self.base_fingerprint != self.fingerprint: # self.keychanges.create(user=self, # prev_fingerprint=self.base_fingerprint, # to_fingerprint=self.fingerprint, # ip_address=ip, # agent=agent) # self.base_fingerprint = self.fingerprint # # def has_setup_complete(self): # if self.public_key and self.fingerprint: # return True # return False # # @property # def has_github_login(self): # return self.socialaccount_set.filter(provider='github').count() >= 1 # # @property # def has_public_key(self): # return True if self.public_key else False # # @property # def has_keyserver_url(self): # return True if self.keyserver_url else False # # class Notification(models.Model): # """ These notifications are emails sent to all users (or some subset) # by an Administrator. Just once. # """ # # subject = models.CharField( # null=False, blank=False, max_length=150, verbose_name=_('Subject')) # body = models.TextField(null=False, blank=False, verbose_name=_('Body')) # # created_at = models.DateTimeField( # auto_now_add=True, verbose_name=_('Created at')) # updated_at = models.DateTimeField( # auto_now=True, verbose_name=_('Updated at')) # # sent_at = models.DateTimeField(null=True, verbose_name=_('Sent at')) # send_to = models.ForeignKey( # Group, null=True, blank=True, on_delete=models.CASCADE, verbose_name=_('Send to')) # # class Meta: # verbose_name = _('Notification') # verbose_name_plural = _('Notifications') # # def __str__(self): # return self.subject # # def delete(self): # return super().delete() if not self.sent_at else False # # class KeyChangeRecord(models.Model): # """ Records the information about the change of a key by the user. # This allows the user to be aware of any suspicious activity # """ # user = models.ForeignKey(User, # on_delete=models.CASCADE, # related_name='keychanges', # verbose_name=_('User')) # prev_fingerprint = models.CharField(null=True, # blank=True, # max_length=50, # verbose_name=_('Previous Fingerprint')) # to_fingerprint = models.CharField(null=True, # blank=True, # max_length=50, # verbose_name=_('To Fingerprint')) # ip_address = models.GenericIPAddressField(blank=True, null=True) # agent = models.TextField(blank=True) # created_at = models.DateTimeField(auto_now_add=True, # verbose_name=_('Created at')) # # class Meta: # verbose_name = _('KeyChangeRecord') # verbose_name_plural = _('KeyChangeRecords') # # Path: humans/tasks.py # @shared_task # def enqueue_email_notifications(notification_id, group_id): # notification = Notification.objects.get(id=notification_id) # if group_id: # users = User.objects.filter(groups__id=group_id) # else: # users = User.objects.all() # # for user in users: # send_email_notification.delay(notification.subject, # notification.body, # user.email) . Output only the next line.
"is_staff",
Here is a snippet: <|code_start|> urlpatterns = [ url(r'^$', HomeView.as_view(), name="pages_index"), url(r'^about$', AboutView.as_view(), name="pages_about"), url(r'^help$', HelpView.as_view(), name="pages_help") <|code_end|> . Write the next line using the current file imports: from django.conf.urls import url from .views import HomeView, AboutView, HelpView and context from other files: # Path: pages/views.py # class HomeView(AuthMixin, TemplateView): # """View for the Index page of the website""" # template_name = "pages/index.html" # # class AboutView(AuthMixin, TemplateView): # """View for the About page of the website""" # template_name = "pages/about.html" # # def get_context_data(self, **kwargs): # context = super().get_context_data(**kwargs) # context["admin_name"] = settings.SUPPORT_NAME # context["admin_email"] = settings.SUPPORT_EMAIL # context["description"] = settings.INSTANCE_DESCRIPTION # context["version"] = settings.VERSION # return context # # class HelpView(AuthMixin, TemplateView): # """View for the About page of the website""" # template_name = "pages/help.html" # # def get_context_data(self, **kwargs): # context = super().get_context_data(**kwargs) # context["support_email"] = settings.SUPPORT_EMAIL # return context , which may include functions, classes, or code. Output only the next line.
]
Given the following code snippet before the placeholder: <|code_start|># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Miscellaneous functions for use by System Storage Manager from __future__ import print_function if sys.version < '3': def __next__(iter): return iter.next() else: def __next__(iter): return next(iter) # List of temporary mount points which should be cleaned up # before exiting TMP_MOUNTED = [] # A debug flag, because we can't reach to main.py from here VERBOSE_VV_FLAG = False VERBOSE_VVV_FLAG = False if sys.version < '3': def __str__(x): if x is not None: return str(x) <|code_end|> , predict the next line using imports from the current file: import os import re import sys import stat import tempfile import threading import subprocess import fcntl import termios import struct from ssmlib import problem from base64 import encode and context including class names, function names, and sometimes code from other files: # Path: ssmlib/problem.py # PROMPT_NONE = 0 # PROMPT_UNMOUNT = 1 # PROMPT_SET_DEFAULT = 2 # PROMPT_IGNORE = 3 # PROMPT_REMOVE = 4 # PROMPT_ADJUST = 5 # PROMPT_USE = 6 # PROMPT_CONTINUE = 7 # PROMPT_CREATE = 8 # PROMPT_MSG = [ # None, # 'Unmount', # 'Set default', # 'Ignore', # 'Remove', # 'Adjust', # 'Use anyway', # 'Continue', # 'Create', # ] # FL_NONE = 0 # FL_MSG_ONLY = 2 # FL_VERBOSE_ONLY = (4 | FL_MSG_ONLY) # FL_DEBUG_ONLY = (8 | FL_MSG_ONLY) # FL_DEFAULT_NO = 16 # FL_SILENT = 32 # FL_EXIT_ON_NO = 64 # FL_EXIT_ON_YES = 128 # FL_NO_MESSAGE = 256 # FL_FORCE_YES = 512 # FL_FORCE_NO = 1024 # FL_FATAL = (2048 | FL_NO_MESSAGE) # class SsmError(Exception): # class GeneralError(SsmError): # class ProgrammingError(SsmError): # class FsMounted(SsmError): # class BadEnvVariable(SsmError): # class NotEnoughSpace(SsmError): # class ResizeMatch(SsmError): # class FsNotSpecified(SsmError): # class DeviceUsed(SsmError): # class NoDevices(SsmError): # class ToolMissing(SsmError): # class ToolMissingPrompt(SsmError): # class CanNotRun(SsmError): # class CommandFailed(SsmError): # class UserInterrupted(SsmError): # class NotSupported(SsmError): # class ExistingFilesystem(SsmError): # class NotImplemented(SsmError): # class WeakPassword(SsmError): # class ExistingSignature(SsmError): # class DuplicateTarget(SsmError): # class ProblemSet(object): # def __init__(self, msg, errcode=None): # def __str__(self): # def __init__(self, msg, errcode=2001): # def __init__(self, msg, errcode=2002): # def __init__(self, msg, errcode=2003): # def __init__(self, msg, errcode=2004): # def __init__(self, msg, errcode=2005): # def __init__(self, msg, errcode=2006): # def __init__(self, msg, errcode=2007): # def __init__(self, msg, errcode=2008): # def __init__(self, msg, errcode=2009): # def __init__(self, msg, errcode=2010): # def __init__(self, msg, errcode=2010): # def __init__(self, msg, errcode=2011): # def __init__(self, msg, errcode=2012, exitcode=-1): # def __init__(self, msg, errcode=2013): # def __init__(self, msg, errcode=2014): # def __init__(self, msg, errcode=2015): # def __init__(self, msg, errcode=2016): # def __init__(self, msg, errcode=2017): # def __init__(self, msg, errcode=2018): # def __init__(self, msg, errcode=2019): # def __init__(self, options): # def set_options(self, options): # def init_problem_set(self): # def _can_print_message(self, flags): # def _read_char(self): # def _ask_question(self, flags): # def check(self, problem, args): # def error(self, args): # def info(self, args): # def warn(self, args): # def not_supported(self, args): . Output only the next line.
else:
Given the code snippet: <|code_start|>MDADM = "mdadm" class MdRaid(template.Backend): def __init__(self, *args, **kwargs): super(MdRaid, self).__init__(*args, **kwargs) self.type = 'dm' self._vol = {} self._pool = {} self._dev = {} self.hostname = socket.gethostname() self._binary = misc.check_binary(MDADM) self.default_pool_name = SSM_DM_DEFAULT_POOL self.attrs = ['dev_name', 'pool_name', 'dev_free', 'dev_used', 'dev_size'] if not self._binary: return self.mounts = misc.get_mounts('/dev/md') mdnumber = misc.get_dmnumber("md") for line in misc.get_partitions(): devname = line[3] devsize = int(line[2]) if line[0] == mdnumber: self._vol[devname] = self.get_volume_data(devname) for dev in misc.get_slaves(os.path.basename(devname)): <|code_end|> , generate the next line using the imports in this file: import os import socket from ssmlib import misc from ssmlib.backends import template and context (functions, classes, or occasionally code) from other files: # Path: ssmlib/misc.py # def __next__(iter): # def __next__(iter): # def __str__(x): # def __str__(x): # def get_unit_size(string): # def is_number(string): # def get_real_size(size): # def get_perc_size_argument(string): # def get_slaves(devname): # def send_udev_event(device, event): # def udev_settle(): # def get_device_by_uuid(uuid): # def get_major_minor(device): # def get_file_size(path): # def check_binary(name): # def do_mount(device, directory, options=None): # def do_umount(mpoint, all_targets=False): # def temp_mount(device, options=None): # def temp_umount(mpoint=None): # def do_cleanup(): # def get_signature(device, types=None): # def get_fs_type(device): # def get_real_device(device): # def get_swaps(): # def get_partitions(): # def get_mountinfo(regex=".*"): # def get_mounts_old(regex=".*"): # def get_mounts(regex=".*"): # def get_dmnumber(name): # def udev_checkpoint(devices): # def wipefs(devices, signatures): # def humanize_size(arg): # def run(cmd, show_cmd=False, stdout=False, stderr=True, can_fail=False, # stdin_data=None, return_stdout=True): # def chain(*iterables): # def izip(*iterables): # def izip(*iterables): # def compress(data, selectors): # def permutations(iterable, r=None): # def terminal_size(default=(25, 80)): # def _ioctl_GWINSZ(fd): # def is_bdevice(path): # def get_device_size(device): # def ptable(data, table_header=None): # def __init__(self): # def neighbours(self): # def parents(self): # def children(self): # def add_neighbour(self, node): # def add_children(self, node): # def add_parent(self, node): # def get_roots(self): # def find_node(name, node_cls): # TMP_MOUNTED = [] # VERBOSE_VV_FLAG = False # VERBOSE_VVV_FLAG = False # class Node(object): # # Path: ssmlib/backends/template.py # SSM_TEMPLATE_DEFAULT_POOL = os.environ['SSM_TEMPLATE_DEFAULT_POOL'] # SSM_TEMPLATE_DEFAULT_POOL = "template_pool" # class Backend(object): # class BackendPool(Backend): # class BackendVolume(Backend): # class BackendDevice(Backend): # def __init__(self, options, data=None): # def __str__(self): # def __iter__(self): # def __getitem__(self, key): # def __init__(self, *args, **kwargs): # def reduce(self, pool, device): # def new(self, pool, devices): # def extend(self, pool, devices): # def remove(self, pool): # def create(self, pool, size=None, name=None, devs=None, # options=None): # def migrate(self, pool, sources, targets=None): # def __init__(self, *args, **kwargs): # def remove(self, volume): # def resize(self, volume, size, resize_fs=True): # def __init__(self, *args, **kwargs): # def remove(self, devices): . Output only the next line.
self._dev[dev] = self.get_device_data(dev, devsize)
Given the code snippet: <|code_start|> def get_device_data(self, devname, devsize): data = {} data['dev_name'] = devname data['hide'] = False command = [MDADM, '--examine', devname] output = misc.run(command, stderr=False)[1].split("\n") for line in output: array = line.split(":") if len(array) < 2: continue item = array[0].strip() if item == "Name": data['pool_name'] = SSM_DM_DEFAULT_POOL data['dev_used'] = data['dev_size'] = devsize data['dev_free'] = 0 return data def get_volume_data(self, devname): data = {} data['dev_name'] = devname data['real_dev'] = devname data['pool_name'] = SSM_DM_DEFAULT_POOL if data['dev_name'] in self.mounts: data['mount'] = self.mounts[data['dev_name']]['mp'] command = [MDADM, '--detail', devname] for line in misc.run(command, stderr=False)[1].split("\n"): array = line.split(":") if len(array) < 2: continue <|code_end|> , generate the next line using the imports in this file: import os import socket from ssmlib import misc from ssmlib.backends import template and context (functions, classes, or occasionally code) from other files: # Path: ssmlib/misc.py # def __next__(iter): # def __next__(iter): # def __str__(x): # def __str__(x): # def get_unit_size(string): # def is_number(string): # def get_real_size(size): # def get_perc_size_argument(string): # def get_slaves(devname): # def send_udev_event(device, event): # def udev_settle(): # def get_device_by_uuid(uuid): # def get_major_minor(device): # def get_file_size(path): # def check_binary(name): # def do_mount(device, directory, options=None): # def do_umount(mpoint, all_targets=False): # def temp_mount(device, options=None): # def temp_umount(mpoint=None): # def do_cleanup(): # def get_signature(device, types=None): # def get_fs_type(device): # def get_real_device(device): # def get_swaps(): # def get_partitions(): # def get_mountinfo(regex=".*"): # def get_mounts_old(regex=".*"): # def get_mounts(regex=".*"): # def get_dmnumber(name): # def udev_checkpoint(devices): # def wipefs(devices, signatures): # def humanize_size(arg): # def run(cmd, show_cmd=False, stdout=False, stderr=True, can_fail=False, # stdin_data=None, return_stdout=True): # def chain(*iterables): # def izip(*iterables): # def izip(*iterables): # def compress(data, selectors): # def permutations(iterable, r=None): # def terminal_size(default=(25, 80)): # def _ioctl_GWINSZ(fd): # def is_bdevice(path): # def get_device_size(device): # def ptable(data, table_header=None): # def __init__(self): # def neighbours(self): # def parents(self): # def children(self): # def add_neighbour(self, node): # def add_children(self, node): # def add_parent(self, node): # def get_roots(self): # def find_node(name, node_cls): # TMP_MOUNTED = [] # VERBOSE_VV_FLAG = False # VERBOSE_VVV_FLAG = False # class Node(object): # # Path: ssmlib/backends/template.py # SSM_TEMPLATE_DEFAULT_POOL = os.environ['SSM_TEMPLATE_DEFAULT_POOL'] # SSM_TEMPLATE_DEFAULT_POOL = "template_pool" # class Backend(object): # class BackendPool(Backend): # class BackendVolume(Backend): # class BackendDevice(Backend): # def __init__(self, options, data=None): # def __str__(self): # def __iter__(self): # def __getitem__(self, key): # def __init__(self, *args, **kwargs): # def reduce(self, pool, device): # def new(self, pool, devices): # def extend(self, pool, devices): # def remove(self, pool): # def create(self, pool, size=None, name=None, devs=None, # options=None): # def migrate(self, pool, sources, targets=None): # def __init__(self, *args, **kwargs): # def remove(self, volume): # def resize(self, volume, size, resize_fs=True): # def __init__(self, *args, **kwargs): # def remove(self, devices): . Output only the next line.
item = array[0].strip()
Given the code snippet: <|code_start|> VERSION=main.VERSION DOC_BUILD='doc/_build/' NAME="system-storage-manager" if sys.version < '2.6': print("Python version 2.6 or higher is required " + "for System Storage Manager to run correctly!") sys.exit(1) setup( name=NAME, version=VERSION, author='Lukas Czerner', author_email='lczerner@redhat.com', <|code_end|> , generate the next line using the imports in this file: import os import sys from distutils.core import setup from ssmlib import main and context (functions, classes, or occasionally code) from other files: # Path: ssmlib/main.py # def main(args=None): # # if args: # sys.argv = args.split() # # options = Options() # PR.set_options(options) # storage = StorageHandle(options) # ssm_parser = SsmParser(storage) # args = ssm_parser.parse() # # # Check create command dependency # if args.func == storage.create: # if not args.raid: # if (args.stripesize): # err = "You can not specify --stripesize without specifying" + \ # " RAID level!" # ssm_parser.parser_create.error(err) # if (args.stripes): # err = "You can not specify --stripes without specifying" + \ # " RAID level!" # ssm_parser.parser_create.error(err) # # This should be changed to be future proofed and every time we add # # new options to any of the commands it would need to be enabled # # in each backend if appropriate # if args.virtual_size and args.pool.type not in ["lvm", "thin"]: # err = "Backed '{0}' does not".format(args.pool.type) + \ # " support --virtual-size option!" # ssm_parser.parser_create.error(err) # # options.verbose = args.verbose # options.force = args.force # # if args.vv or args.vvv: # options.verbose = True # options.vv = True # # if args.vvv: # options.vvv = True # # # #storage.set_globals(args.force, args.verbose, args.yes, args.config) # storage.set_globals(options) # # # Register clean-up function on exit # atexit.register(misc.do_cleanup) # # if args.dry_run: # return 0 # # try: # args.func(args) # except argparse.ArgumentTypeError as ex: # ssm_parser.parser.error(ex) # # return 0 . Output only the next line.
maintainer='Lukas Czerner',
Predict the next line after this snippet: <|code_start|> if item in self.mounts: new['mount'] = self.mounts[item]['mp'] # Subvolume is mounted directly new['direct_mount'] = True else: # If subvolume is not mounted try to find whether parent # subvolume is mounted found = re.findall(r'^(.*)/([^/]*)$', new['path']) if found: parent_path, path = found[0] # try previously loaded subvolumes for prev_sv in self._subvolumes: # if subvolumes are mounted, use that mp if self._subvolumes[prev_sv]['path'] == parent_path: # if parent subvolume is not mounted this # subvolume is not mounted as well if self._subvolumes[prev_sv]['mount'] == '': new['mount'] = '' else: new['mount'] = "{0}/{1}".format( self._subvolumes[prev_sv]['mount'], path) break # if parent volume is not mounted, use root subvolume # if mounted else: if 'mount' in vol: new['mount'] = "{0}/{1}".format(vol['mount'], new['path']) <|code_end|> using the current file's imports: import re import os import datetime from ssmlib import misc from ssmlib.backends import template and any relevant context from other files: # Path: ssmlib/misc.py # def __next__(iter): # def __next__(iter): # def __str__(x): # def __str__(x): # def get_unit_size(string): # def is_number(string): # def get_real_size(size): # def get_perc_size_argument(string): # def get_slaves(devname): # def send_udev_event(device, event): # def udev_settle(): # def get_device_by_uuid(uuid): # def get_major_minor(device): # def get_file_size(path): # def check_binary(name): # def do_mount(device, directory, options=None): # def do_umount(mpoint, all_targets=False): # def temp_mount(device, options=None): # def temp_umount(mpoint=None): # def do_cleanup(): # def get_signature(device, types=None): # def get_fs_type(device): # def get_real_device(device): # def get_swaps(): # def get_partitions(): # def get_mountinfo(regex=".*"): # def get_mounts_old(regex=".*"): # def get_mounts(regex=".*"): # def get_dmnumber(name): # def udev_checkpoint(devices): # def wipefs(devices, signatures): # def humanize_size(arg): # def run(cmd, show_cmd=False, stdout=False, stderr=True, can_fail=False, # stdin_data=None, return_stdout=True): # def chain(*iterables): # def izip(*iterables): # def izip(*iterables): # def compress(data, selectors): # def permutations(iterable, r=None): # def terminal_size(default=(25, 80)): # def _ioctl_GWINSZ(fd): # def is_bdevice(path): # def get_device_size(device): # def ptable(data, table_header=None): # def __init__(self): # def neighbours(self): # def parents(self): # def children(self): # def add_neighbour(self, node): # def add_children(self, node): # def add_parent(self, node): # def get_roots(self): # def find_node(name, node_cls): # TMP_MOUNTED = [] # VERBOSE_VV_FLAG = False # VERBOSE_VVV_FLAG = False # class Node(object): # # Path: ssmlib/backends/template.py # SSM_TEMPLATE_DEFAULT_POOL = os.environ['SSM_TEMPLATE_DEFAULT_POOL'] # SSM_TEMPLATE_DEFAULT_POOL = "template_pool" # class Backend(object): # class BackendPool(Backend): # class BackendVolume(Backend): # class BackendDevice(Backend): # def __init__(self, options, data=None): # def __str__(self): # def __iter__(self): # def __getitem__(self, key): # def __init__(self, *args, **kwargs): # def reduce(self, pool, device): # def new(self, pool, devices): # def extend(self, pool, devices): # def remove(self, pool): # def create(self, pool, size=None, name=None, devs=None, # options=None): # def migrate(self, pool, sources, targets=None): # def __init__(self, *args, **kwargs): # def remove(self, volume): # def resize(self, volume, size, resize_fs=True): # def __init__(self, *args, **kwargs): # def remove(self, devices): . Output only the next line.
new['hide'] = False
Given the code snippet: <|code_start|> # Store snapshot info if 'mount' in new and \ re.match(r"snap-\d{4}-\d{2}-\d{2}-T\d{6}", os.path.basename(new['mount'])): new['snap_name'] = "{0}:{1}".format(name, os.path.basename(new['path'])) new['snap_path'] = new['mount'] if volume['path'] in snapshots: new['hide'] = True self._subvolumes[new['dev_name']] = new def _parse_subvolumes(self, output): volume = {} for line in output.strip().split("\n"): if not line: continue # For the version with screwed 'subvolume list' command line = re.sub("<FS_TREE>/*", "", line) volume['ID'] = re.search(r'(?<=ID )\d+', line).group(0) volume['top_level'] = re.search(r'(?<=top level )\d+', line).group(0) volume['path'] = re.search('(?<=path ).*$', line).group(0) volume['subvolume'] = True yield volume def _find_uniq_pool_name(self, label, dev): if len(label) < 3 or label == "none": label = "btrfs_{0}".format(os.path.basename(dev)) if label not in self._pool: return label <|code_end|> , generate the next line using the imports in this file: import re import os import datetime from ssmlib import misc from ssmlib.backends import template and context (functions, classes, or occasionally code) from other files: # Path: ssmlib/misc.py # def __next__(iter): # def __next__(iter): # def __str__(x): # def __str__(x): # def get_unit_size(string): # def is_number(string): # def get_real_size(size): # def get_perc_size_argument(string): # def get_slaves(devname): # def send_udev_event(device, event): # def udev_settle(): # def get_device_by_uuid(uuid): # def get_major_minor(device): # def get_file_size(path): # def check_binary(name): # def do_mount(device, directory, options=None): # def do_umount(mpoint, all_targets=False): # def temp_mount(device, options=None): # def temp_umount(mpoint=None): # def do_cleanup(): # def get_signature(device, types=None): # def get_fs_type(device): # def get_real_device(device): # def get_swaps(): # def get_partitions(): # def get_mountinfo(regex=".*"): # def get_mounts_old(regex=".*"): # def get_mounts(regex=".*"): # def get_dmnumber(name): # def udev_checkpoint(devices): # def wipefs(devices, signatures): # def humanize_size(arg): # def run(cmd, show_cmd=False, stdout=False, stderr=True, can_fail=False, # stdin_data=None, return_stdout=True): # def chain(*iterables): # def izip(*iterables): # def izip(*iterables): # def compress(data, selectors): # def permutations(iterable, r=None): # def terminal_size(default=(25, 80)): # def _ioctl_GWINSZ(fd): # def is_bdevice(path): # def get_device_size(device): # def ptable(data, table_header=None): # def __init__(self): # def neighbours(self): # def parents(self): # def children(self): # def add_neighbour(self, node): # def add_children(self, node): # def add_parent(self, node): # def get_roots(self): # def find_node(name, node_cls): # TMP_MOUNTED = [] # VERBOSE_VV_FLAG = False # VERBOSE_VVV_FLAG = False # class Node(object): # # Path: ssmlib/backends/template.py # SSM_TEMPLATE_DEFAULT_POOL = os.environ['SSM_TEMPLATE_DEFAULT_POOL'] # SSM_TEMPLATE_DEFAULT_POOL = "template_pool" # class Backend(object): # class BackendPool(Backend): # class BackendVolume(Backend): # class BackendDevice(Backend): # def __init__(self, options, data=None): # def __str__(self): # def __iter__(self): # def __getitem__(self, key): # def __init__(self, *args, **kwargs): # def reduce(self, pool, device): # def new(self, pool, devices): # def extend(self, pool, devices): # def remove(self, pool): # def create(self, pool, size=None, name=None, devs=None, # options=None): # def migrate(self, pool, sources, targets=None): # def __init__(self, *args, **kwargs): # def remove(self, volume): # def resize(self, volume, size, resize_fs=True): # def __init__(self, *args, **kwargs): # def remove(self, devices): . Output only the next line.
return os.path.basename(dev)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python # # (C)2011 Red Hat, Inc., Lukas Czerner <lczerner@redhat.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Common classes for unit testing class MyStdout(object): def __init__(self): self.output = "" self.stdout = sys.stdout def write(self, s): self.output += s <|code_end|> with the help of current file imports: import sys import unittest import argparse from ssmlib import main from ssmlib import misc and context from other files: # Path: ssmlib/main.py # def main(args=None): # # if args: # sys.argv = args.split() # # options = Options() # PR.set_options(options) # storage = StorageHandle(options) # ssm_parser = SsmParser(storage) # args = ssm_parser.parse() # # # Check create command dependency # if args.func == storage.create: # if not args.raid: # if (args.stripesize): # err = "You can not specify --stripesize without specifying" + \ # " RAID level!" # ssm_parser.parser_create.error(err) # if (args.stripes): # err = "You can not specify --stripes without specifying" + \ # " RAID level!" # ssm_parser.parser_create.error(err) # # This should be changed to be future proofed and every time we add # # new options to any of the commands it would need to be enabled # # in each backend if appropriate # if args.virtual_size and args.pool.type not in ["lvm", "thin"]: # err = "Backed '{0}' does not".format(args.pool.type) + \ # " support --virtual-size option!" # ssm_parser.parser_create.error(err) # # options.verbose = args.verbose # options.force = args.force # # if args.vv or args.vvv: # options.verbose = True # options.vv = True # # if args.vvv: # options.vvv = True # # # #storage.set_globals(args.force, args.verbose, args.yes, args.config) # storage.set_globals(options) # # # Register clean-up function on exit # atexit.register(misc.do_cleanup) # # if args.dry_run: # return 0 # # try: # args.func(args) # except argparse.ArgumentTypeError as ex: # ssm_parser.parser.error(ex) # # return 0 # # Path: ssmlib/misc.py # def __next__(iter): # def __next__(iter): # def __str__(x): # def __str__(x): # def get_unit_size(string): # def is_number(string): # def get_real_size(size): # def get_perc_size_argument(string): # def get_slaves(devname): # def send_udev_event(device, event): # def udev_settle(): # def get_device_by_uuid(uuid): # def get_major_minor(device): # def get_file_size(path): # def check_binary(name): # def do_mount(device, directory, options=None): # def do_umount(mpoint, all_targets=False): # def temp_mount(device, options=None): # def temp_umount(mpoint=None): # def do_cleanup(): # def get_signature(device, types=None): # def get_fs_type(device): # def get_real_device(device): # def get_swaps(): # def get_partitions(): # def get_mountinfo(regex=".*"): # def get_mounts_old(regex=".*"): # def get_mounts(regex=".*"): # def get_dmnumber(name): # def udev_checkpoint(devices): # def wipefs(devices, signatures): # def humanize_size(arg): # def run(cmd, show_cmd=False, stdout=False, stderr=True, can_fail=False, # stdin_data=None, return_stdout=True): # def chain(*iterables): # def izip(*iterables): # def izip(*iterables): # def compress(data, selectors): # def permutations(iterable, r=None): # def terminal_size(default=(25, 80)): # def _ioctl_GWINSZ(fd): # def is_bdevice(path): # def get_device_size(device): # def ptable(data, table_header=None): # def __init__(self): # def neighbours(self): # def parents(self): # def children(self): # def add_neighbour(self, node): # def add_children(self, node): # def add_parent(self, node): # def get_roots(self): # def find_node(name, node_cls): # TMP_MOUNTED = [] # VERBOSE_VV_FLAG = False # VERBOSE_VVV_FLAG = False # class Node(object): , which may contain function names, class names, or code. Output only the next line.
class BaseStorageHandleInit(unittest.TestCase):
Based on the snippet: <|code_start|> def format_synopsis(self, parser): return "{0}\n\n".format(self._parse_usage(parser.format_usage())) def write_ssm_usage(self): message = self.format_synopsis(self.ssm_parser.parser) self._write_message(message, SSM_USAGE_INC) def write_create_usage(self): message = self.format_synopsis(self.ssm_parser.parser_create) self._write_message(message, CREATE_USAGE_INC) def write_info_usage(self): message = self.format_synopsis(self.ssm_parser.parser_info) self._write_message(message, INFO_USAGE_INC) def write_list_usage(self): message = self.format_synopsis(self.ssm_parser.parser_list) self._write_message(message, LIST_USAGE_INC) def write_remove_usage(self): message = self.format_synopsis(self.ssm_parser.parser_remove) self._write_message(message, REMOVE_USAGE_INC) def write_resize_usage(self): message = self.format_synopsis(self.ssm_parser.parser_resize) self._write_message(message, RESIZE_USAGE_INC) def write_check_usage(self): message = self.format_synopsis(self.ssm_parser.parser_check) <|code_end|> , predict the immediate next line with the help of imports: import re import sys, os from ssmlib import main and context (classes, functions, sometimes code) from other files: # Path: ssmlib/main.py # def main(args=None): # # if args: # sys.argv = args.split() # # options = Options() # PR.set_options(options) # storage = StorageHandle(options) # ssm_parser = SsmParser(storage) # args = ssm_parser.parse() # # # Check create command dependency # if args.func == storage.create: # if not args.raid: # if (args.stripesize): # err = "You can not specify --stripesize without specifying" + \ # " RAID level!" # ssm_parser.parser_create.error(err) # if (args.stripes): # err = "You can not specify --stripes without specifying" + \ # " RAID level!" # ssm_parser.parser_create.error(err) # # This should be changed to be future proofed and every time we add # # new options to any of the commands it would need to be enabled # # in each backend if appropriate # if args.virtual_size and args.pool.type not in ["lvm", "thin"]: # err = "Backed '{0}' does not".format(args.pool.type) + \ # " support --virtual-size option!" # ssm_parser.parser_create.error(err) # # options.verbose = args.verbose # options.force = args.force # # if args.vv or args.vvv: # options.verbose = True # options.vv = True # # if args.vvv: # options.vvv = True # # # #storage.set_globals(args.force, args.verbose, args.yes, args.config) # storage.set_globals(options) # # # Register clean-up function on exit # atexit.register(misc.do_cleanup) # # if args.dry_run: # return 0 # # try: # args.func(args) # except argparse.ArgumentTypeError as ex: # ssm_parser.parser.error(ex) # # return 0 . Output only the next line.
self._write_message(message, CHECK_USAGE_INC)
Predict the next line after this snippet: <|code_start|># Copyright 2009 Yusuf Simonson # This file is part of Snowball. # # Snowball is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # Snowball is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License # along with Snowball. If not, see <http://www.gnu.org/licenses/>. REALM = 'Administrator Control Panel' def admin_auth(req, realm, name, password): if realm != REALM or name != 'admin': return False <|code_end|> using the current file's imports: from web import * from web import util from web.serialization import * from oz.handler import * import model and any relevant context from other files: # Path: web/util.py # REALM = 'Snowball' # def auth(req, realm, name, password): # def assert_string(name, value, max_length): # def check_tags(tag_arg): # def check_datetime(datetime_arg): # def assert_direction(direction): # def check_weight(weight): # def error_handler(func): # def func_replacement(self, *args, **kwargs): # def get_dynamic_setting(db, name): # def save_dynamic_setting(db, name, value): # def __init__(self, *args, **kwargs): # class SnowballHandler(OzHandler): . Output only the next line.
return password == req.settings['admin_pass']
Here is a snippet: <|code_start|>from __future__ import absolute_import from __future__ import print_function def write_AWIPS_netcdf_grid(outfile, t_start, t, xloc, yloc, lon_for_x, lat_for_y, ctr_lat, ctr_lon, grid, grid_var_name, grid_description, format='i', <|code_end|> . Write the next line using the current file imports: import datetime import scipy.io.netcdf as nc import glob from .make_grids import grid_h5flashfiles and context from other files: # Path: lmatools/grid/make_grids.py # def grid_h5flashfiles(h5_filenames, start_time, end_time, **kwargs): # """ Grid LMA data contianed in HDF5-format LMA files. Keyword arguments to this function # are those to the FlashGridder class and its functions. # # This function is provided as a convenience for compatibility with earlier # implementations of flash gridding. # """ # # process_flash_kwargs = {} # for prock in ('min_points_per_flash',): # if prock in kwargs: # process_flash_kwargs[prock] = kwargs.pop(prock) # # out_kwargs = {} # for outk in ('outpath', 'output_writer', 'output_writer_3d', # 'output_kwargs', 'output_filename_prefix'): # if outk in kwargs: # out_kwargs[outk] = kwargs.pop(outk) # # gridder = FlashGridder(start_time, end_time, **kwargs) # gridder.process_flashes(h5_filenames, **process_flash_kwargs) # output = gridder.write_grids(**out_kwargs) # return output , which may include functions, classes, or code. Output only the next line.
refresh_minutes = 1, grid_units = 'dimensionless'):
Given snippet: <|code_start|> y = Re * (np.radians(latavg) - np.radians(lat)) z = altavg - alt # r_sq = x**2.0 + y**2.0 + z**2.0 # sigma_sq = r_sq.sum()/r_sq.shape[0] # sigma = np.std(r_sq) separation = np.abs(np.percentile(alt,73) - np.percentile(alt,27)) flash_init_idx = np.argmin(flash.points['time']) zinit = alt[flash_init_idx] #in meters area = 0.0 eta = 0.01 if flash.pointCount > 2: try: # find the convex hull and calculate its area cvh = ConvexHull(np.vstack((x,y)).T) # NOT cvh.area - it is the perimeter in 2D. # cvh.area is the surface area in 3D. area = cvh.volume except IndexError: # tends to happen when a duplicate point causes the point count to # drop to 2, leading to a degenerate polygon with no area logger.warning('Setting area to 0 for flash with points %s, %s' % (x, y)) area=0.0 except KeyError: # hull indexing has problems here logger.warning('Setting area to 0 for flash with points %s, %s' % (x, y)) area=0.0 if area == 0.0: <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np import logging import re from scipy.spatial import Delaunay, ConvexHull from scipy.special import factorial from scipy.spatial.qhull import QhullError from lmatools.lasso import empirical_charge_density as cd and context: # Path: lmatools/lasso/empirical_charge_density.py # class rho_retrieve(object): # def __init__(self, area, d, zinit, separation, constant=False, arbitrary_rho=0.4e-9): # def rho_br(self, z, separation): # def energy_estimation(self, rho, d, area): # def calculate(self): which might include code, classes, or functions. Output only the next line.
energy_estimate = 0.
Continue the code snippet: <|code_start|># geoProj = GeographicSystem() # while True: # lon, lat, alt = (yield) # x,y,z = self.mapProj.fromECEF( # *self.geoProj.toECEF(lon, lat, alt) # ) # target.send((x,y,z)) # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- @coroutine def flash_count_log(logfile, format_string="%s flashes in frame starting at %s"): """ Write flash count for some frame to a file-like object. File open/close should be handled by the calling routine.""" # Track flash count for each frame frame_times = {} try: while True: # Receive list of flashes, frame start time flashes, frame_start_time = (yield) n_flashes = len(flashes) try: frame_times[frame_start_time] += n_flashes except KeyError: # Key doesn't exist, so can't increment flash count <|code_end|> . Use current file imports: import glob import gc import numpy as np import logging from lmatools.stream.subset import coroutine from lmatools.density_tools import unique_vectors and context (classes, functions, or code) from other files: # Path: lmatools/stream/subset.py # def coroutine(func): # def start(*args,**kwargs): # cr = func(*args,**kwargs) # next(cr) # return cr # return start # # Path: lmatools/density_tools.py # def unique_vectors(*args, **kwargs): # """ Given D, N-element arrays of vector components return the # unique vectors as a (D, N_reduced) array. If return_indices_only=True # is true (the default) then return the N_reduced indices of the original # arrays corresponding to the unique vectors. # # args: x0_i, x1_i, x2_i, ... # where each x0, x1, etc. are discretized (bin index) values of point # locations. # """ # try: # return_indices_only=kwargs['return_indices_only'] # except KeyError: # return_indices_only=True # # vector_len = len(args) # itemsize = max((x_i.itemsize for x_i in args)) # inttype = 'i{0:d}'.format(itemsize) # # vec_cast = tuple((x_i.astype(inttype) for x_i in args)) # # # Because we do casting below, ascontiguousarray is important # locs = np.ascontiguousarray(np.vstack(vec_cast).T) # # # Find unique rows (unique grid cells occupied per flash) by casting to a set # # of strings comprised of the bytes that make up the rows. Strings are not serialized, just ints cast to byte strings. # # Based on the example at # # http://www.mail-archive.com/numpy-discussion@scipy.org/msg04176.html # # which doesn't quite get it right: it returns unique elements. # vectorbytes = 'S{0:d}'.format(itemsize*vector_len) # unq, unq_index = np.unique(locs.view(vectorbytes), return_index=True) # # if return_indices_only==True: # return unq_index # else: # # this is unnecessary if we only need the row indices # unq_restored = unq.view(inttype).reshape(unq.shape[0],vector_len) # return unq_restored, unq_index . Output only the next line.
frame_times[frame_start_time] = n_flashes
Next line prediction: <|code_start|># *self.geoProj.toECEF(lon, lat, alt) # ) # target.send((x,y,z)) # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- @coroutine def flash_count_log(logfile, format_string="%s flashes in frame starting at %s"): """ Write flash count for some frame to a file-like object. File open/close should be handled by the calling routine.""" # Track flash count for each frame frame_times = {} try: while True: # Receive list of flashes, frame start time flashes, frame_start_time = (yield) n_flashes = len(flashes) try: frame_times[frame_start_time] += n_flashes except KeyError: # Key doesn't exist, so can't increment flash count frame_times[frame_start_time] = n_flashes except GeneratorExit: all_times = list(frame_times.keys()) all_times.sort() <|code_end|> . Use current file imports: (import glob import gc import numpy as np import logging from lmatools.stream.subset import coroutine from lmatools.density_tools import unique_vectors) and context including class names, function names, or small code snippets from other files: # Path: lmatools/stream/subset.py # def coroutine(func): # def start(*args,**kwargs): # cr = func(*args,**kwargs) # next(cr) # return cr # return start # # Path: lmatools/density_tools.py # def unique_vectors(*args, **kwargs): # """ Given D, N-element arrays of vector components return the # unique vectors as a (D, N_reduced) array. If return_indices_only=True # is true (the default) then return the N_reduced indices of the original # arrays corresponding to the unique vectors. # # args: x0_i, x1_i, x2_i, ... # where each x0, x1, etc. are discretized (bin index) values of point # locations. # """ # try: # return_indices_only=kwargs['return_indices_only'] # except KeyError: # return_indices_only=True # # vector_len = len(args) # itemsize = max((x_i.itemsize for x_i in args)) # inttype = 'i{0:d}'.format(itemsize) # # vec_cast = tuple((x_i.astype(inttype) for x_i in args)) # # # Because we do casting below, ascontiguousarray is important # locs = np.ascontiguousarray(np.vstack(vec_cast).T) # # # Find unique rows (unique grid cells occupied per flash) by casting to a set # # of strings comprised of the bytes that make up the rows. Strings are not serialized, just ints cast to byte strings. # # Based on the example at # # http://www.mail-archive.com/numpy-discussion@scipy.org/msg04176.html # # which doesn't quite get it right: it returns unique elements. # vectorbytes = 'S{0:d}'.format(itemsize*vector_len) # unq, unq_index = np.unique(locs.view(vectorbytes), return_index=True) # # if return_indices_only==True: # return unq_index # else: # # this is unnecessary if we only need the row indices # unq_restored = unq.view(inttype).reshape(unq.shape[0],vector_len) # return unq_restored, unq_index . Output only the next line.
for frame_start_time in all_times:
Based on the snippet: <|code_start|> name_to_idx = dict((k, i) for i, k in enumerate(grid_dims)) grid_t_idx = name_to_idx[t.dimensions[0]] grid_x_idx = name_to_idx[x.dimensions[0]] grid_y_idx = name_to_idx[y.dimensions[0]] xedge = centers_to_edges(x) yedge = centers_to_edges(y) indexer[grid_t_idx] = i density = grid[indexer].transpose() out = xedge, yedge, density if return_nc: out += (f,) else: f.close() return out def _all_times(self): for f in self._filenames: for t in self._frame_times_for_file(f): yield t def _frame_times_for_file(self, fname): """ Called once by init to set up frame lookup tables and yield the frame start times. _frame_lookup goes from datetime->(nc file, frame index)""" f = NetCDFFile(fname) data = f.variables # dictionary of variable names to nc_var objects dims = f.dimensions # dictionary of dimension names to sizes <|code_end|> , predict the immediate next line with the help of imports: import glob import itertools import numpy as np from datetime import datetime, timedelta from netCDF4 import Dataset as NetCDFFile from scipy.io.netcdf import NetCDFFile from lmatools.vis.multiples_nc import centers_to_edges from lmatools.coordinateSystems import GeographicSystem, MapProjection and context (classes, functions, sometimes code) from other files: # Path: lmatools/vis/multiples_nc.py # def centers_to_edges(x): # xedge=np.zeros(x.shape[0]+1) # xedge[1:-1] = (x[:-1] + x[1:])/2.0 # dx = np.mean(np.abs(xedge[2:-1] - xedge[1:-2])) # xedge[0] = xedge[1] - dx # xedge[-1] = xedge[-2] + dx # return xedge . Output only the next line.
t = data[self.t_name]
Continue the code snippet: <|code_start|> 'frame_id':self.frame_id, 'frame_time':self.t.isoformat(), 'filename':fname} self.logger.info(json.dumps(lass_verts, cls=NumpyAwareJSONEncoder)) # self.logger.info(lass_verts) # return self.y, self.z, self.v, self.vel def data_table(self): '''If desired, this function takes the PolyLasso vertices drawn, and returns a Pandas Dataframe containing data for each radar field constrained within the Polygon.''' # mask_shape, xvert, yvert = self.mask() mask_shape, xvert, yvert = self.masked_data() poly_velocities = (self.vel[mask_shape]) poly_ref = (self.ref[mask_shape]) poly_sw = (self.sw[mask_shape]) titles = ['Velocities', 'Reflectivity', 'Spectrum Width'] table = pd.DataFrame([poly_velocities, poly_ref, poly_sw]).T table.columns = titles return table <|code_end|> . Use current file imports: import netCDF4 import numpy as np import pandas as pd import scipy as sci import matplotlib import matplotlib.pyplot as plt import logging, json from matplotlib.lines import Line2D from matplotlib.widgets import Widget from matplotlib.colors import LogNorm, Normalize from lmatools.coordinateSystems import GeographicSystem, MapProjection from ipywidgets import widgets from lmatools.vis import ctables as ct from matplotlib.path import Path and context (classes, functions, or code) from other files: # Path: lmatools/coordinateSystems.py # class GeographicSystem(CoordinateSystem): # """ # Coordinate system defined on the surface of the earth using latitude, # longitude, and altitude, referenced by default to the WGS84 ellipse. # # Alternately, specify the ellipse shape using an ellipse known # to pyproj, or [NOT IMPLEMENTED] specify r_equator and r_pole directly. # """ # def __init__(self, ellipse='WGS84', datum='WGS84', # r_equator=None, r_pole=None): # if (r_equator is not None) | (r_pole is not None): # if r_pole is None: # r_pole=r_equator # self.ERSlla = proj4.Proj(proj='latlong', a=r_equator, b=r_pole) # else: # # lat lon alt in some earth reference system # self.ERSlla = proj4.Proj(proj='latlong', ellps=ellipse, datum=datum) # self.ERSxyz = proj4.Proj(proj='geocent', ellps=ellipse, datum=datum) # def toECEF(self, lon, lat, alt): # lat = atleast_1d(lat) # proj doesn't like scalars # lon = atleast_1d(lon) # alt = atleast_1d(alt) # if (lat.shape[0] == 0): return lon, lat, alt # proj doesn't like empties # projectedData = array(proj4.transform(self.ERSlla, self.ERSxyz, lon, lat, alt )) # if len(projectedData.shape) == 1: # return projectedData[0], projectedData[1], projectedData[2] # else: # return projectedData[0,:], projectedData[1,:], projectedData[2,:] # # def fromECEF(self, x, y, z): # x = atleast_1d(x) # proj doesn't like scalars # y = atleast_1d(y) # z = atleast_1d(z) # if (x.shape[0] == 0): return x, y, z # proj doesn't like empties # projectedData = array(proj4.transform(self.ERSxyz, self.ERSlla, x, y, z )) # if len(projectedData.shape) == 1: # return projectedData[0], projectedData[1], projectedData[2] # else: # return projectedData[0,:], projectedData[1,:], projectedData[2,:] # # class MapProjection(CoordinateSystem): # """Map projection coordinate system. Wraps proj4, and uses its projecion names. Defaults to # equidistant cylindrical projection # """ # # def __init__(self, projection='eqc', ctrLat=None, ctrLon=None, ellipse='WGS84', datum='WGS84', **kwargs): # self.ERSxyz = proj4.Proj(proj='geocent', ellps=ellipse, datum=datum) # self.projection = proj4.Proj(proj=projection, ellps=ellipse, datum=datum, **kwargs) # self.ctrLat=ctrLat # self.ctrLon=ctrLon # self.ctrAlt=0.0 # self.geoCS = GeographicSystem() # self.cx, self.cy, self.cz = 0, 0, 0 # self.cx, self.cy, self.cz = self.ctrPosition() # # def ctrPosition(self): # if (self.ctrLat != None) & (self.ctrLon != None): # ex, ey, ez = self.geoCS.toECEF(self.ctrLon, self.ctrLat, self.ctrAlt) # cx, cy, cz = self.fromECEF(ex, ey, ez) # else: # cx, cy, cz = 0, 0, 0 # return cx, cy, cz # # def toECEF(self, x, y, z): # x += self.cx # y += self.cy # z += self.cz # projectedData = array(proj4.transform(self.projection, self.ERSxyz, x, y, z )) # if len(projectedData.shape) == 1: # px, py, pz = projectedData[0], projectedData[1], projectedData[2] # else: # px, py, pz = projectedData[0,:], projectedData[1,:], projectedData[2,:] # return px, py, pz # # def fromECEF(self, x, y, z): # projectedData = array(proj4.transform(self.ERSxyz, self.projection, x, y, z )) # if len(projectedData.shape) == 1: # px, py, pz = projectedData[0], projectedData[1], projectedData[2] # else: # px, py, pz = projectedData[0,:], projectedData[1,:], projectedData[2,:] # return px-self.cx, py-self.cy, pz-self.cz # # Path: lmatools/vis/ctables.py # LUTSIZE = mpl.rcParams['image.lut'] # def get_cmap(name, lut=None): # def cmap_map(function,cmap): . Output only the next line.
def gridLassoOverplotDefault(lasso_widget, ax):
Next line prediction: <|code_start|> # from scipy.spatial import * geosys = GeographicSystem() # from IPython.display import HTML # from IPython.display import Javascript # from IPython.display import display # from http://stackoverflow.com/questions/3488934/simplejson-and-numpy-array/24375113#24375113 class NumpyAwareJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): # and obj.ndim == 1: <|code_end|> . Use current file imports: (import netCDF4 import numpy as np import pandas as pd import scipy as sci import matplotlib import matplotlib.pyplot as plt import logging, json from matplotlib.lines import Line2D from matplotlib.widgets import Widget from matplotlib.colors import LogNorm, Normalize from lmatools.coordinateSystems import GeographicSystem, MapProjection from ipywidgets import widgets from lmatools.vis import ctables as ct from matplotlib.path import Path) and context including class names, function names, or small code snippets from other files: # Path: lmatools/coordinateSystems.py # class GeographicSystem(CoordinateSystem): # """ # Coordinate system defined on the surface of the earth using latitude, # longitude, and altitude, referenced by default to the WGS84 ellipse. # # Alternately, specify the ellipse shape using an ellipse known # to pyproj, or [NOT IMPLEMENTED] specify r_equator and r_pole directly. # """ # def __init__(self, ellipse='WGS84', datum='WGS84', # r_equator=None, r_pole=None): # if (r_equator is not None) | (r_pole is not None): # if r_pole is None: # r_pole=r_equator # self.ERSlla = proj4.Proj(proj='latlong', a=r_equator, b=r_pole) # else: # # lat lon alt in some earth reference system # self.ERSlla = proj4.Proj(proj='latlong', ellps=ellipse, datum=datum) # self.ERSxyz = proj4.Proj(proj='geocent', ellps=ellipse, datum=datum) # def toECEF(self, lon, lat, alt): # lat = atleast_1d(lat) # proj doesn't like scalars # lon = atleast_1d(lon) # alt = atleast_1d(alt) # if (lat.shape[0] == 0): return lon, lat, alt # proj doesn't like empties # projectedData = array(proj4.transform(self.ERSlla, self.ERSxyz, lon, lat, alt )) # if len(projectedData.shape) == 1: # return projectedData[0], projectedData[1], projectedData[2] # else: # return projectedData[0,:], projectedData[1,:], projectedData[2,:] # # def fromECEF(self, x, y, z): # x = atleast_1d(x) # proj doesn't like scalars # y = atleast_1d(y) # z = atleast_1d(z) # if (x.shape[0] == 0): return x, y, z # proj doesn't like empties # projectedData = array(proj4.transform(self.ERSxyz, self.ERSlla, x, y, z )) # if len(projectedData.shape) == 1: # return projectedData[0], projectedData[1], projectedData[2] # else: # return projectedData[0,:], projectedData[1,:], projectedData[2,:] # # class MapProjection(CoordinateSystem): # """Map projection coordinate system. Wraps proj4, and uses its projecion names. Defaults to # equidistant cylindrical projection # """ # # def __init__(self, projection='eqc', ctrLat=None, ctrLon=None, ellipse='WGS84', datum='WGS84', **kwargs): # self.ERSxyz = proj4.Proj(proj='geocent', ellps=ellipse, datum=datum) # self.projection = proj4.Proj(proj=projection, ellps=ellipse, datum=datum, **kwargs) # self.ctrLat=ctrLat # self.ctrLon=ctrLon # self.ctrAlt=0.0 # self.geoCS = GeographicSystem() # self.cx, self.cy, self.cz = 0, 0, 0 # self.cx, self.cy, self.cz = self.ctrPosition() # # def ctrPosition(self): # if (self.ctrLat != None) & (self.ctrLon != None): # ex, ey, ez = self.geoCS.toECEF(self.ctrLon, self.ctrLat, self.ctrAlt) # cx, cy, cz = self.fromECEF(ex, ey, ez) # else: # cx, cy, cz = 0, 0, 0 # return cx, cy, cz # # def toECEF(self, x, y, z): # x += self.cx # y += self.cy # z += self.cz # projectedData = array(proj4.transform(self.projection, self.ERSxyz, x, y, z )) # if len(projectedData.shape) == 1: # px, py, pz = projectedData[0], projectedData[1], projectedData[2] # else: # px, py, pz = projectedData[0,:], projectedData[1,:], projectedData[2,:] # return px, py, pz # # def fromECEF(self, x, y, z): # projectedData = array(proj4.transform(self.ERSxyz, self.projection, x, y, z )) # if len(projectedData.shape) == 1: # px, py, pz = projectedData[0], projectedData[1], projectedData[2] # else: # px, py, pz = projectedData[0,:], projectedData[1,:], projectedData[2,:] # return px-self.cx, py-self.cy, pz-self.cz # # Path: lmatools/vis/ctables.py # LUTSIZE = mpl.rcParams['image.lut'] # def get_cmap(name, lut=None): # def cmap_map(function,cmap): . Output only the next line.
return obj.tolist()
Using the snippet: <|code_start|> kilo_formatter = FuncFormatter(kilo) # # /* DC LMA */ # DClat = 38.8888500 # falls church / western tip of arlington, rough centroid of stations # DClon = -77.1685800 # kounLat = 35.23833 # kounLon = -97.46028 # kounAlt = 377.0 # radarLat=kounLat # radarLon=kounLon # radarAlt=0.0 # # ARMOR # radarLat = 34.6461 # radarLon = -86.7714 # radarAlt = 180.0 # mapProj = MapProjection(projection='eqc', ctrLat=radarLat, ctrLon=radarLon, lat_ts=radarLat, lon_0=radarLon) # geoProj = GeographicSystem() def centers_to_edges(x): xedge=np.zeros(x.shape[0]+1) xedge[1:-1] = (x[:-1] + x[1:])/2.0 dx = np.mean(np.abs(xedge[2:-1] - xedge[1:-2])) xedge[0] = xedge[1] - dx xedge[-1] = xedge[-2] + dx return xedge <|code_end|> , determine the next line of code. You have imports: from .small_multiples import small_multiples_plot from datetime import datetime, timedelta from netCDF4 import Dataset as NetCDFFile from scipy.io.netcdf import NetCDFFile from matplotlib.figure import figaspect, Figure from matplotlib.colorbar import ColorbarBase from matplotlib.cm import get_cmap from matplotlib.ticker import FuncFormatter from matplotlib.dates import mx2num, date2num, DateFormatter from matplotlib.backends.backend_agg import FigureCanvasAgg from math import ceil from hotshot import stats import os import gc import numpy as np import matplotlib import hotshot import sys and context (class names, function names, or code) available: # Path: lmatools/vis/small_multiples.py # class small_multiples_plot(object): # # def __init__(self, fig=None, *args, **kwargs): # if fig is None: # raise AssertionError("A valid figure must be passed in.") # # fig = figure() # self.fig = fig # self.fig.subplots_adjust(bottom=0.20, left = 0.1, right=0.9, top=0.9) # self.colorbar_ax = fig.add_axes((0.1, 0.1, 0.8, 0.05)) # self.multiples = small_multiples(self.fig, **kwargs) # # def label_edges(self, bool_val): # m = self.multiples # leftside = m[:,0] # for ax in leftside: # ax.yaxis.tick_left() # ax.yaxis.set_visible(bool_val) # # #last row # bottomedge = m[-1,:] # for ax in bottomedge: # ax.xaxis.tick_bottom() # ax.xaxis.set_visible(bool_val) . Output only the next line.
def multiples_figaspect(n_rows, n_cols, x_range, y_range, fig_width=None, max_height=None):
Here is a snippet: <|code_start|> width=10, taper_width=2.0, wg_sep=3, port=(1750, 0), direction="WEST", ) tk.add(top, mmi2) (xtop, ytop) = mmi1.portlist["output_top"]["port"] wg2 = pc.Waveguide( [ (xtop, ytop), (xtop + 100, ytop), (xtop + 100, ytop + 200), (xtop + 200, ytop + 200), ], wgt, ) tk.add(top, wg2) sp = pc.Spiral(wgt, 800.0, 8000.0, parity=-1, **wg2.portlist["output"]) tk.add(top, sp) (xtop_out, ytop_out) = sp.portlist["output"]["port"] (xmmi_top, ymmi_top) = mmi2.portlist["output_bot"]["port"] wg_spiral_out = pc.Waveguide( [ (xtop_out, ytop_out), (xmmi_top - 100, ytop_out), (xmmi_top - 100, ytop_out - 200), <|code_end|> . Write the next line using the current file imports: import gdspy import picwriter.components as pc from picwriter import toolkit as tk and context from other files: # Path: picwriter/toolkit.py # TOL = 1e-6 # CURRENT_CELLS = {} # CURRENT_CELL_NAMES = {} # CURRENT_CELLS = {} # CURRENT_CELL_NAMES = {} # def add(top_cell, component_cell, center=(0, 0), x_reflection=False): # def reset_database(): # def getCellName(name): # def build_mask(cell, wgt, final_layer=None, final_datatype=None): # def get_trace_length(trace, wgt): # def get_keys(cell): # def get_angle(pt1, pt2): # def get_exact_angle(pt1, pt2): # def dist(pt1, pt2): # def get_direction(pt1, pt2): # def get_turn(dir1, dir2): # def flip_direction(direction): # def translate_point(pt, length, direction, height=0.0): # def normalize_angle(angle): # def get_curve_length(func, start, end, grid=0.001): # def get_cur_length(pt_list): # def build_waveguide_polygon( # func, wg_width, start_direction, end_direction, start_val=0, end_val=1, grid=0.001 # ): # def get_path_points( # func, wg_width, num_pts, start_direction, end_direction, start_val=0, end_val=1 # ): # def check_path(path, grid): # def __init__(self, name, *args): # def _auto_transform_(self): # def _hash_cell_(self, *args): # def __get_cell(self): # def __direction_to_rotation(self, direction): # def add(self, element, origin=(0, 0), rotation=0.0, x_reflection=False): # def addto(self, top_cell, x_reflection=False): # class Component: , which may include functions, classes, or code. Output only the next line.
(xmmi_top, ytop_out - 200),
Continue the code snippet: <|code_start|> top = gdspy.Cell("top") top.add(gdspy.Rectangle((0, 0), (1000, 1000), layer=100, datatype=0)) wgt = pc.WaveguideTemplate( wg_width=0.45, clad_width=10.0, bend_radius=100, resist="+", fab="ETCH", wg_layer=1, wg_datatype=0, clad_layer=2, clad_datatype=0, ) wg = pc.Waveguide( [(25, 25), (975, 25), (975, 500), (25, 500), (25, 975), (975, 975)], wgt ) tk.add(top, wg) tk.build_mask(top, wgt, final_layer=3, final_datatype=0) <|code_end|> . Use current file imports: import gdspy import picwriter.components as pc from picwriter import toolkit as tk and context (classes, functions, or code) from other files: # Path: picwriter/toolkit.py # TOL = 1e-6 # CURRENT_CELLS = {} # CURRENT_CELL_NAMES = {} # CURRENT_CELLS = {} # CURRENT_CELL_NAMES = {} # def add(top_cell, component_cell, center=(0, 0), x_reflection=False): # def reset_database(): # def getCellName(name): # def build_mask(cell, wgt, final_layer=None, final_datatype=None): # def get_trace_length(trace, wgt): # def get_keys(cell): # def get_angle(pt1, pt2): # def get_exact_angle(pt1, pt2): # def dist(pt1, pt2): # def get_direction(pt1, pt2): # def get_turn(dir1, dir2): # def flip_direction(direction): # def translate_point(pt, length, direction, height=0.0): # def normalize_angle(angle): # def get_curve_length(func, start, end, grid=0.001): # def get_cur_length(pt_list): # def build_waveguide_polygon( # func, wg_width, start_direction, end_direction, start_val=0, end_val=1, grid=0.001 # ): # def get_path_points( # func, wg_width, num_pts, start_direction, end_direction, start_val=0, end_val=1 # ): # def check_path(path, grid): # def __init__(self, name, *args): # def _auto_transform_(self): # def _hash_cell_(self, *args): # def __get_cell(self): # def __direction_to_rotation(self, direction): # def add(self, element, origin=(0, 0), rotation=0.0, x_reflection=False): # def addto(self, top_cell, x_reflection=False): # class Component: . Output only the next line.
gdspy.LayoutViewer()
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- """ @author: DerekK88 """ X_SIZE, Y_SIZE = 15000, 15000 exclusion_region = 2000.0 # region where no devices are to be fabricated x0, y0 = X_SIZE / 2.0, Y_SIZE / 2.0 # define origin of the die step = 100.0 # standard spacing between components """ Top level Cell that contains everything """ top = gdspy.Cell("top") wgt = WaveguideTemplate( wg_width=0.45, clad_width=10.0, bend_radius=100, resist="+", fab="ETCH", wg_layer=1, wg_datatype=0, clad_layer=2, clad_datatype=0, ) """ Add a die outline, with exclusion, from gdspy geometries found at http://gdspy.readthedocs.io/en/latest/""" top.add(gdspy.Rectangle((0, 0), (X_SIZE, Y_SIZE), layer=6, datatype=0)) <|code_end|> , predict the next line using imports from the current file: import numpy as np import gdspy from picwriter import toolkit as tk from picwriter.components import * and context including class names, function names, and sometimes code from other files: # Path: picwriter/toolkit.py # TOL = 1e-6 # CURRENT_CELLS = {} # CURRENT_CELL_NAMES = {} # CURRENT_CELLS = {} # CURRENT_CELL_NAMES = {} # def add(top_cell, component_cell, center=(0, 0), x_reflection=False): # def reset_database(): # def getCellName(name): # def build_mask(cell, wgt, final_layer=None, final_datatype=None): # def get_trace_length(trace, wgt): # def get_keys(cell): # def get_angle(pt1, pt2): # def get_exact_angle(pt1, pt2): # def dist(pt1, pt2): # def get_direction(pt1, pt2): # def get_turn(dir1, dir2): # def flip_direction(direction): # def translate_point(pt, length, direction, height=0.0): # def normalize_angle(angle): # def get_curve_length(func, start, end, grid=0.001): # def get_cur_length(pt_list): # def build_waveguide_polygon( # func, wg_width, start_direction, end_direction, start_val=0, end_val=1, grid=0.001 # ): # def get_path_points( # func, wg_width, num_pts, start_direction, end_direction, start_val=0, end_val=1 # ): # def check_path(path, grid): # def __init__(self, name, *args): # def _auto_transform_(self): # def _hash_cell_(self, *args): # def __get_cell(self): # def __direction_to_rotation(self, direction): # def add(self, element, origin=(0, 0), rotation=0.0, x_reflection=False): # def addto(self, top_cell, x_reflection=False): # class Component: . Output only the next line.
top.add(
Given the following code snippet before the placeholder: <|code_start|># encoding: utf-8 log = __import__('logging').getLogger(__name__) class ContentmentDispatch: __slots__ = [] def __repr__(self): return "{self.__class__.__name__}(0x{id})".format(self=self, id=id(self)) def __call__(self, context, obj, path): # TODO: Move into web.dispatch.meta as "FallbackDispatch". # First, try with object dispatch. This handles custom root controller attachments such as statics. try: result = list(context.dispatch['object'](context, obj, path)) except LookupError: pass else: if result and result[-1][2] and isroutine(result[-1][1]): # Endpoint found. yield from result return <|code_end|> , predict the next line using imports from the current file: from inspect import isroutine from ..component.asset.model import Asset and context including class names, function names, and sometimes code from other files: # Path: web/component/asset/model.py # class Asset(Taxonomy): # meta = dict( # collection = 'asset', # ordering = ['parent', 'order'], # allow_inheritance = True, # index_cls = False, # queryset_class = TaxonomyQuerySet, # # indexes = [ # ] # ) # # # Basic Properties # # title = MapField( # TODO: TranslatedField # StringField(), # default = dict, # simple = False, # read = True, # write = True, # ) # # description = MapField( # TODO: TranslatedField # StringField(), # default = dict, # simple = False, # read = True, # write = True, # ) # # tags = ListField( # StringField(), # default = list, # read = True, # write = True, # ) # # # Magic Properties # # properties = EmbeddedDocumentField( # Properties, # default = Properties, # simple = False, # read = True, # write = True, # ) # # acl = ListField( # EmbeddedDocumentField(ACLRule), # default = list, # simple = False, # read = False, # write = False, # ) # # handler = StringField(read=True, write=True) # TODO: PythonReferenceField('web.component') | URLPath allowing relative # # # Metadata # created = DateTimeField(default=utcnow, simple=False, read=True, write=False) # modified = DateTimeField(default=utcnow, simple=False, read=True, write=False) # # # Controller Lookup # # _controller_cache = PluginCache('web.component') # # @property # def controller(self): # TODO: Move this into PythonReferencefield. # if not self.handler: # return self, self._controller_cache['web.component.asset:AssetController'] # # if ':' in self.handler: # return self, self._controller_cache[self.handler] # # handler = self.children.named(self.handler).get() # return handler.controller # # def __page_panel__(self, context, wrap=False): # return render_asset_panel(context, self, wrap) # # __icon__ = 'folder-o' # # # Python Methods # # def __str__(self): # return D_(self.title) # # def __repr__(self): # return "{0.__class__.__name__}({2}, {1!r}, {0.handler}, {0.properties!r})".format(self, D_(self.title), self.path or self.name) # # # Data Portability # # def __xml__(self, recursive=False): # """Return an XML representation for this Asset.""" # # return export_document(self, recursive, root=True) # # as_xml = property(lambda self: self.__xml__(recursive=False)) # # def __json__(self): # """Return a JSON-safe (and YAML-safe) representation for this Asset.""" # return dict( # id = str(self.id), # title = self.title, # description = self.description, # tags = [i for i in self.tags if ':' not in i], # created = self.created, # modified = self.modified # ) # # as_json = property(lambda self: self.__json__()) # # def __html_stream__(self): # """Return a cinje-compatible template representing the HTML version of this Asset.""" # return [] # # as_stream = property(lambda self: self.__html_stream__) # Note: doesn't call! # # def __html__(self): # """Return the rendered HTML representation of this Asset.""" # return "".join(self.__html_stream__()) # # as_html = property(lambda self: self.__html__()) # # def __html_format__(self, spec=None): # """Special handler for use in MarkupSafe formatting and %{} cinje replacements. # # For example: # # %{"{:link}" some_page} # # """ # # if spec == 'link': # return self.path # # elif spec: # raise ValueError("Invalid format specification for Asset: " + spec) # # return self.__html__() # # def __text__(self): # """Return the full content of the page as a single block of text. # # This is principally used for full-text content extraction as part of the indexing process. # """ # return "" # # as_text = property(lambda self: self.__text__()) . Output only the next line.
del result
Given the following code snippet before the placeholder: <|code_start|># encoding: utf-8 class TestAsset(Asset): data = ListField(IntField(), custom_data=Properties(simple=True)) props = ListField(EmbeddedDocumentField(Properties), custom_data=Properties(simple=False)) # __xml_exporters__ = { # 'props': list_field, # } @classmethod <|code_end|> , predict the next line using imports from the current file: import random from mongoengine import ListField, IntField, EmbeddedDocumentField from web.component.asset.model import Asset from web.contentment.util.model import Properties and context including class names, function names, and sometimes code from other files: # Path: web/component/asset/model.py # class Asset(Taxonomy): # meta = dict( # collection = 'asset', # ordering = ['parent', 'order'], # allow_inheritance = True, # index_cls = False, # queryset_class = TaxonomyQuerySet, # # indexes = [ # ] # ) # # # Basic Properties # # title = MapField( # TODO: TranslatedField # StringField(), # default = dict, # simple = False, # read = True, # write = True, # ) # # description = MapField( # TODO: TranslatedField # StringField(), # default = dict, # simple = False, # read = True, # write = True, # ) # # tags = ListField( # StringField(), # default = list, # read = True, # write = True, # ) # # # Magic Properties # # properties = EmbeddedDocumentField( # Properties, # default = Properties, # simple = False, # read = True, # write = True, # ) # # acl = ListField( # EmbeddedDocumentField(ACLRule), # default = list, # simple = False, # read = False, # write = False, # ) # # handler = StringField(read=True, write=True) # TODO: PythonReferenceField('web.component') | URLPath allowing relative # # # Metadata # created = DateTimeField(default=utcnow, simple=False, read=True, write=False) # modified = DateTimeField(default=utcnow, simple=False, read=True, write=False) # # # Controller Lookup # # _controller_cache = PluginCache('web.component') # # @property # def controller(self): # TODO: Move this into PythonReferencefield. # if not self.handler: # return self, self._controller_cache['web.component.asset:AssetController'] # # if ':' in self.handler: # return self, self._controller_cache[self.handler] # # handler = self.children.named(self.handler).get() # return handler.controller # # def __page_panel__(self, context, wrap=False): # return render_asset_panel(context, self, wrap) # # __icon__ = 'folder-o' # # # Python Methods # # def __str__(self): # return D_(self.title) # # def __repr__(self): # return "{0.__class__.__name__}({2}, {1!r}, {0.handler}, {0.properties!r})".format(self, D_(self.title), self.path or self.name) # # # Data Portability # # def __xml__(self, recursive=False): # """Return an XML representation for this Asset.""" # # return export_document(self, recursive, root=True) # # as_xml = property(lambda self: self.__xml__(recursive=False)) # # def __json__(self): # """Return a JSON-safe (and YAML-safe) representation for this Asset.""" # return dict( # id = str(self.id), # title = self.title, # description = self.description, # tags = [i for i in self.tags if ':' not in i], # created = self.created, # modified = self.modified # ) # # as_json = property(lambda self: self.__json__()) # # def __html_stream__(self): # """Return a cinje-compatible template representing the HTML version of this Asset.""" # return [] # # as_stream = property(lambda self: self.__html_stream__) # Note: doesn't call! # # def __html__(self): # """Return the rendered HTML representation of this Asset.""" # return "".join(self.__html_stream__()) # # as_html = property(lambda self: self.__html__()) # # def __html_format__(self, spec=None): # """Special handler for use in MarkupSafe formatting and %{} cinje replacements. # # For example: # # %{"{:link}" some_page} # # """ # # if spec == 'link': # return self.path # # elif spec: # raise ValueError("Invalid format specification for Asset: " + spec) # # return self.__html__() # # def __text__(self): # """Return the full content of the page as a single block of text. # # This is principally used for full-text content extraction as part of the indexing process. # """ # return "" # # as_text = property(lambda self: self.__text__()) # # Path: web/contentment/util/model.py # class Properties(DynamicEmbeddedDocument): # def __repr__(self): # return repr({f: getattr(self, f) for f in self._dynamic_fields}) # # def get(self, name, default=None): # if name not in self: return default # return getattr(self, name) # # @classmethod # def __xml_importer__(cls, element): # if not element.text or not element.text.strip(): # return cls(**element.attrib) # # from marrow.package.loader import load # # if element.get('type'): # return cls(**{element.get('name'): load(element.get('type'))(element.text)}) # # return cls(**{element.get('name'): element.text}) # # __xml__ = properties . Output only the next line.
def test(cls):
Predict the next line after this snippet: <|code_start|># encoding: utf-8 class TestAsset(Asset): data = ListField(IntField(), custom_data=Properties(simple=True)) props = ListField(EmbeddedDocumentField(Properties), custom_data=Properties(simple=False)) # __xml_exporters__ = { # 'props': list_field, # } <|code_end|> using the current file's imports: import random from mongoengine import ListField, IntField, EmbeddedDocumentField from web.component.asset.model import Asset from web.contentment.util.model import Properties and any relevant context from other files: # Path: web/component/asset/model.py # class Asset(Taxonomy): # meta = dict( # collection = 'asset', # ordering = ['parent', 'order'], # allow_inheritance = True, # index_cls = False, # queryset_class = TaxonomyQuerySet, # # indexes = [ # ] # ) # # # Basic Properties # # title = MapField( # TODO: TranslatedField # StringField(), # default = dict, # simple = False, # read = True, # write = True, # ) # # description = MapField( # TODO: TranslatedField # StringField(), # default = dict, # simple = False, # read = True, # write = True, # ) # # tags = ListField( # StringField(), # default = list, # read = True, # write = True, # ) # # # Magic Properties # # properties = EmbeddedDocumentField( # Properties, # default = Properties, # simple = False, # read = True, # write = True, # ) # # acl = ListField( # EmbeddedDocumentField(ACLRule), # default = list, # simple = False, # read = False, # write = False, # ) # # handler = StringField(read=True, write=True) # TODO: PythonReferenceField('web.component') | URLPath allowing relative # # # Metadata # created = DateTimeField(default=utcnow, simple=False, read=True, write=False) # modified = DateTimeField(default=utcnow, simple=False, read=True, write=False) # # # Controller Lookup # # _controller_cache = PluginCache('web.component') # # @property # def controller(self): # TODO: Move this into PythonReferencefield. # if not self.handler: # return self, self._controller_cache['web.component.asset:AssetController'] # # if ':' in self.handler: # return self, self._controller_cache[self.handler] # # handler = self.children.named(self.handler).get() # return handler.controller # # def __page_panel__(self, context, wrap=False): # return render_asset_panel(context, self, wrap) # # __icon__ = 'folder-o' # # # Python Methods # # def __str__(self): # return D_(self.title) # # def __repr__(self): # return "{0.__class__.__name__}({2}, {1!r}, {0.handler}, {0.properties!r})".format(self, D_(self.title), self.path or self.name) # # # Data Portability # # def __xml__(self, recursive=False): # """Return an XML representation for this Asset.""" # # return export_document(self, recursive, root=True) # # as_xml = property(lambda self: self.__xml__(recursive=False)) # # def __json__(self): # """Return a JSON-safe (and YAML-safe) representation for this Asset.""" # return dict( # id = str(self.id), # title = self.title, # description = self.description, # tags = [i for i in self.tags if ':' not in i], # created = self.created, # modified = self.modified # ) # # as_json = property(lambda self: self.__json__()) # # def __html_stream__(self): # """Return a cinje-compatible template representing the HTML version of this Asset.""" # return [] # # as_stream = property(lambda self: self.__html_stream__) # Note: doesn't call! # # def __html__(self): # """Return the rendered HTML representation of this Asset.""" # return "".join(self.__html_stream__()) # # as_html = property(lambda self: self.__html__()) # # def __html_format__(self, spec=None): # """Special handler for use in MarkupSafe formatting and %{} cinje replacements. # # For example: # # %{"{:link}" some_page} # # """ # # if spec == 'link': # return self.path # # elif spec: # raise ValueError("Invalid format specification for Asset: " + spec) # # return self.__html__() # # def __text__(self): # """Return the full content of the page as a single block of text. # # This is principally used for full-text content extraction as part of the indexing process. # """ # return "" # # as_text = property(lambda self: self.__text__()) # # Path: web/contentment/util/model.py # class Properties(DynamicEmbeddedDocument): # def __repr__(self): # return repr({f: getattr(self, f) for f in self._dynamic_fields}) # # def get(self, name, default=None): # if name not in self: return default # return getattr(self, name) # # @classmethod # def __xml_importer__(cls, element): # if not element.text or not element.text.strip(): # return cls(**element.attrib) # # from marrow.package.loader import load # # if element.get('type'): # return cls(**{element.get('name'): load(element.get('type'))(element.text)}) # # return cls(**{element.get('name'): element.text}) # # __xml__ = properties . Output only the next line.
@classmethod
Given the code snippet: <|code_start|># encoding: utf-8 log = __import__('logging').getLogger(__name__) class AssetController: __dispatch__ = 'resource' def __init__(self, context, document, reference=None): self._ctx = context self._doc = document log.info("Loaded asset.", extra=dict(asset=repr(document.id))) def post(self, kind, name, title): if not self._ctx.uid: return dict(ok=False, message="Unauthorized.") <|code_end|> , generate the next line using the imports in this file: from webob.exc import HTTPNotFound from markupsafe import Markup, escape from .model import Asset from web.component.page.model import Page from web.component.page.block.reference import ReferenceBlock from web.component.page.block.content import TextBlock and context (functions, classes, or occasionally code) from other files: # Path: web/component/asset/model.py # class Asset(Taxonomy): # meta = dict( # collection = 'asset', # ordering = ['parent', 'order'], # allow_inheritance = True, # index_cls = False, # queryset_class = TaxonomyQuerySet, # # indexes = [ # ] # ) # # # Basic Properties # # title = MapField( # TODO: TranslatedField # StringField(), # default = dict, # simple = False, # read = True, # write = True, # ) # # description = MapField( # TODO: TranslatedField # StringField(), # default = dict, # simple = False, # read = True, # write = True, # ) # # tags = ListField( # StringField(), # default = list, # read = True, # write = True, # ) # # # Magic Properties # # properties = EmbeddedDocumentField( # Properties, # default = Properties, # simple = False, # read = True, # write = True, # ) # # acl = ListField( # EmbeddedDocumentField(ACLRule), # default = list, # simple = False, # read = False, # write = False, # ) # # handler = StringField(read=True, write=True) # TODO: PythonReferenceField('web.component') | URLPath allowing relative # # # Metadata # created = DateTimeField(default=utcnow, simple=False, read=True, write=False) # modified = DateTimeField(default=utcnow, simple=False, read=True, write=False) # # # Controller Lookup # # _controller_cache = PluginCache('web.component') # # @property # def controller(self): # TODO: Move this into PythonReferencefield. # if not self.handler: # return self, self._controller_cache['web.component.asset:AssetController'] # # if ':' in self.handler: # return self, self._controller_cache[self.handler] # # handler = self.children.named(self.handler).get() # return handler.controller # # def __page_panel__(self, context, wrap=False): # return render_asset_panel(context, self, wrap) # # __icon__ = 'folder-o' # # # Python Methods # # def __str__(self): # return D_(self.title) # # def __repr__(self): # return "{0.__class__.__name__}({2}, {1!r}, {0.handler}, {0.properties!r})".format(self, D_(self.title), self.path or self.name) # # # Data Portability # # def __xml__(self, recursive=False): # """Return an XML representation for this Asset.""" # # return export_document(self, recursive, root=True) # # as_xml = property(lambda self: self.__xml__(recursive=False)) # # def __json__(self): # """Return a JSON-safe (and YAML-safe) representation for this Asset.""" # return dict( # id = str(self.id), # title = self.title, # description = self.description, # tags = [i for i in self.tags if ':' not in i], # created = self.created, # modified = self.modified # ) # # as_json = property(lambda self: self.__json__()) # # def __html_stream__(self): # """Return a cinje-compatible template representing the HTML version of this Asset.""" # return [] # # as_stream = property(lambda self: self.__html_stream__) # Note: doesn't call! # # def __html__(self): # """Return the rendered HTML representation of this Asset.""" # return "".join(self.__html_stream__()) # # as_html = property(lambda self: self.__html__()) # # def __html_format__(self, spec=None): # """Special handler for use in MarkupSafe formatting and %{} cinje replacements. # # For example: # # %{"{:link}" some_page} # # """ # # if spec == 'link': # return self.path # # elif spec: # raise ValueError("Invalid format specification for Asset: " + spec) # # return self.__html__() # # def __text__(self): # """Return the full content of the page as a single block of text. # # This is principally used for full-text content extraction as part of the indexing process. # """ # return "" # # as_text = property(lambda self: self.__text__()) . Output only the next line.
parent = self._doc
Given the code snippet: <|code_start|># encoding: utf-8 log = __import__('logging').getLogger(__name__) @signal(pre_delete) def remove_children(sender, document, **kw): <|code_end|> , generate the next line using the imports in this file: from itertools import chain from operator import __or__ from functools import reduce from bson import ObjectId, DBRef, SON from mongoengine import QuerySet, Q from mongoengine import Document, ListField, StringField, IntField, ObjectIdField from mongoengine import ReferenceField from mongoengine.signals import pre_delete from mongoengine.common import _import_class from mongoengine.base.fields import ComplexBaseField from mongoengine.base.datastructures import EmbeddedDocumentList, BaseList, BaseDict from mongoengine import EmbeddedDocument from mongoengine.dereference import DeReference from mongoengine.base import get_document, TopLevelDocumentMetaclass from .util.model import signal from operator import __or__ from functools import reduce from operator import __or__ from functools import reduce from operator import __or__ from functools import reduce from operator import __or__ from functools import reduce from web.component.asset import Asset and context (functions, classes, or occasionally code) from other files: # Path: web/contentment/util/model.py # def signal(event): # def decorator(fn): # def signal_inner(cls): # event.connect(fn, sender=cls) # return cls # # fn.signal = signal_inner # return fn # # return decorator . Output only the next line.
document.empty()
Given the following code snippet before the placeholder: <|code_start|> def test_dehumming_improve_snr(): # Test that dehumming removes the added noise rng = np.random.RandomState(0) fs = 250. enf = 50. <|code_end|> , predict the next line using imports from the current file: import numpy as np from pactools.utils.dehummer import dehummer from pactools.utils.maths import norm from pactools.utils.testing import assert_greater from pactools.utils.testing import assert_array_equal from pactools.utils.testing import assert_raises and context including class names, function names, and sometimes code from other files: # Path: pactools/utils/dehummer.py # def dehummer(sig, fs, enf=50.0, hmax=5, block_length=2048, draw='', # progress_bar=True): # """Removes the ENF signal and its harmonics # # sig : input 1D signal # fs : sampling frequency # enf : electrical network frequency # hmax : maximum number of harmonics # block_length : length of FFTs # draw : list of plots # # returns the denoised signal # """ # hmax = min(hmax, int(0.5 * fs / enf)) # if sig.ndim > 2 or (sig.ndim == 2 and min(sig.shape) > 1): # raise ValueError('Input signal should be 1D. Got %s.' % (sig.shape, )) # input_shape = sig.shape # sig = np.ravel(sig) # # block_length = min(block_length, sig.size) # block_length_o2 = block_length // 2 # # # -------- the window and its shift by block_length/2 must sum to 1.0 # window = np.hamming(block_length) # window[0:block_length_o2] /= ( # window[0:block_length_o2] + window[block_length_o2:block_length]) # window[block_length_o2:block_length] = np.flipud(window[0:block_length_o2]) # # if hmax == 0: # return sig # result = np.zeros_like(sig) # # # -------- prepare an array with estimated frequencies # tmax = len(sig) # freq = np.zeros(2 + 2 * tmax // block_length) # kf = 0 # if progress_bar: # bar = ProgressBar(max_value=len(freq), title='dehumming %.0f Hz' % enf) # # # -------- process successive blocks # for tmid in range(0, tmax + block_length_o2, block_length_o2): # # -------- initial and final blocks are truncated # tstart = tmid - block_length_o2 # if tstart < 0: # wstart = -tstart # tstart = 0 # else: # wstart = 0 # tstop = tmid + block_length_o2 # if tstop > tmax: # wstop = block_length + tmax - tstop # tstop = tmax # else: # wstop = block_length # # # -------- search for the frequency # f0 = enf # sigenf = single_estimate(sig[tstart:tstop], f0, fs, hmax) # best_f = f0 # best_sigout = sig[tstart:tstop] - sigenf # best_energy = np.dot(best_sigout.T, best_sigout) # for delta in {0.1, 0.01}: # shift_max = 9 if delta == 0.01 else 9 # shifts = np.arange(1, shift_max + 1) # shifts = np.r_[-shifts[::-1], shifts] # # for shift in shifts: # f = f0 + shift * delta # sigenf = single_estimate(sig[tstart:tstop], f, fs, hmax) # sigout = sig[tstart:tstop] - sigenf # energy = np.dot(sigout.T, sigout) # # we keep the frequency f that removes the most energy # if energy < best_energy: # best_f = f # best_sigout = sigout # best_energy = energy # f0 = best_f # # # -------- this block has been processed, save it # result[tstart:tstop] += best_sigout * window[wstart:wstop] # # freq[kf] = best_f # kf += 1 # if progress_bar and kf % 10 == 0: # bar.update(kf) # if progress_bar: # bar.update(bar.max_value) # # # -------- plot estimated electrical network frequency # if 'f' in draw or 'z' in draw: # t = np.linspace(0, tmax / fs, len(freq)) # plt.figure('Estimated electrical network frequency') # plt.title('Estimated electrical network frequency') # # plt.plot(t, freq / enf, label='%.0fHz' % enf) # plt.ylabel('ENF fluctuation'), # plt.xlabel('Time (sec)') # plt.legend(loc=0) # # # -------- plot long term spectum of noisy and denoised signals # if 'd' in draw or 'z' in draw: # sp = Spectrum(block_length=block_length, fs=fs, donorm=True, # wfunc=np.blackman) # sp.periodogram(sig) # sp.periodogram(result, hold=True) # sp.plot('Power spectral density before/after dehumming', fscale='lin') # # return result.reshape(input_shape) # # Path: pactools/utils/maths.py # def norm(x): # """Compute the Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). More precise than sqrt(squared_norm(x)). # """ # x = np.asarray(x) # # if np.any(np.iscomplex(x)): # return np.sqrt(squared_norm(x)) # else: # nrm2, = linalg.get_blas_funcs(['nrm2'], [x]) # return nrm2(x) # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): . Output only the next line.
clean = rng.randn(512)
Here is a snippet: <|code_start|> def test_dehumming_improve_snr(): # Test that dehumming removes the added noise rng = np.random.RandomState(0) fs = 250. enf = 50. clean = rng.randn(512) noisy = clean.copy() # add ENF noise time = np.arange(512) / float(fs) for harmonic in (1, 2): <|code_end|> . Write the next line using the current file imports: import numpy as np from pactools.utils.dehummer import dehummer from pactools.utils.maths import norm from pactools.utils.testing import assert_greater from pactools.utils.testing import assert_array_equal from pactools.utils.testing import assert_raises and context from other files: # Path: pactools/utils/dehummer.py # def dehummer(sig, fs, enf=50.0, hmax=5, block_length=2048, draw='', # progress_bar=True): # """Removes the ENF signal and its harmonics # # sig : input 1D signal # fs : sampling frequency # enf : electrical network frequency # hmax : maximum number of harmonics # block_length : length of FFTs # draw : list of plots # # returns the denoised signal # """ # hmax = min(hmax, int(0.5 * fs / enf)) # if sig.ndim > 2 or (sig.ndim == 2 and min(sig.shape) > 1): # raise ValueError('Input signal should be 1D. Got %s.' % (sig.shape, )) # input_shape = sig.shape # sig = np.ravel(sig) # # block_length = min(block_length, sig.size) # block_length_o2 = block_length // 2 # # # -------- the window and its shift by block_length/2 must sum to 1.0 # window = np.hamming(block_length) # window[0:block_length_o2] /= ( # window[0:block_length_o2] + window[block_length_o2:block_length]) # window[block_length_o2:block_length] = np.flipud(window[0:block_length_o2]) # # if hmax == 0: # return sig # result = np.zeros_like(sig) # # # -------- prepare an array with estimated frequencies # tmax = len(sig) # freq = np.zeros(2 + 2 * tmax // block_length) # kf = 0 # if progress_bar: # bar = ProgressBar(max_value=len(freq), title='dehumming %.0f Hz' % enf) # # # -------- process successive blocks # for tmid in range(0, tmax + block_length_o2, block_length_o2): # # -------- initial and final blocks are truncated # tstart = tmid - block_length_o2 # if tstart < 0: # wstart = -tstart # tstart = 0 # else: # wstart = 0 # tstop = tmid + block_length_o2 # if tstop > tmax: # wstop = block_length + tmax - tstop # tstop = tmax # else: # wstop = block_length # # # -------- search for the frequency # f0 = enf # sigenf = single_estimate(sig[tstart:tstop], f0, fs, hmax) # best_f = f0 # best_sigout = sig[tstart:tstop] - sigenf # best_energy = np.dot(best_sigout.T, best_sigout) # for delta in {0.1, 0.01}: # shift_max = 9 if delta == 0.01 else 9 # shifts = np.arange(1, shift_max + 1) # shifts = np.r_[-shifts[::-1], shifts] # # for shift in shifts: # f = f0 + shift * delta # sigenf = single_estimate(sig[tstart:tstop], f, fs, hmax) # sigout = sig[tstart:tstop] - sigenf # energy = np.dot(sigout.T, sigout) # # we keep the frequency f that removes the most energy # if energy < best_energy: # best_f = f # best_sigout = sigout # best_energy = energy # f0 = best_f # # # -------- this block has been processed, save it # result[tstart:tstop] += best_sigout * window[wstart:wstop] # # freq[kf] = best_f # kf += 1 # if progress_bar and kf % 10 == 0: # bar.update(kf) # if progress_bar: # bar.update(bar.max_value) # # # -------- plot estimated electrical network frequency # if 'f' in draw or 'z' in draw: # t = np.linspace(0, tmax / fs, len(freq)) # plt.figure('Estimated electrical network frequency') # plt.title('Estimated electrical network frequency') # # plt.plot(t, freq / enf, label='%.0fHz' % enf) # plt.ylabel('ENF fluctuation'), # plt.xlabel('Time (sec)') # plt.legend(loc=0) # # # -------- plot long term spectum of noisy and denoised signals # if 'd' in draw or 'z' in draw: # sp = Spectrum(block_length=block_length, fs=fs, donorm=True, # wfunc=np.blackman) # sp.periodogram(sig) # sp.periodogram(result, hold=True) # sp.plot('Power spectral density before/after dehumming', fscale='lin') # # return result.reshape(input_shape) # # Path: pactools/utils/maths.py # def norm(x): # """Compute the Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). More precise than sqrt(squared_norm(x)). # """ # x = np.asarray(x) # # if np.any(np.iscomplex(x)): # return np.sqrt(squared_norm(x)) # else: # nrm2, = linalg.get_blas_funcs(['nrm2'], [x]) # return nrm2(x) # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): , which may include functions, classes, or code. Output only the next line.
noisy += np.sin(time * 2 * np.pi * enf * harmonic) / harmonic
Next line prediction: <|code_start|> def test_dehumming_improve_snr(): # Test that dehumming removes the added noise rng = np.random.RandomState(0) fs = 250. enf = 50. clean = rng.randn(512) noisy = clean.copy() # add ENF noise <|code_end|> . Use current file imports: (import numpy as np from pactools.utils.dehummer import dehummer from pactools.utils.maths import norm from pactools.utils.testing import assert_greater from pactools.utils.testing import assert_array_equal from pactools.utils.testing import assert_raises) and context including class names, function names, or small code snippets from other files: # Path: pactools/utils/dehummer.py # def dehummer(sig, fs, enf=50.0, hmax=5, block_length=2048, draw='', # progress_bar=True): # """Removes the ENF signal and its harmonics # # sig : input 1D signal # fs : sampling frequency # enf : electrical network frequency # hmax : maximum number of harmonics # block_length : length of FFTs # draw : list of plots # # returns the denoised signal # """ # hmax = min(hmax, int(0.5 * fs / enf)) # if sig.ndim > 2 or (sig.ndim == 2 and min(sig.shape) > 1): # raise ValueError('Input signal should be 1D. Got %s.' % (sig.shape, )) # input_shape = sig.shape # sig = np.ravel(sig) # # block_length = min(block_length, sig.size) # block_length_o2 = block_length // 2 # # # -------- the window and its shift by block_length/2 must sum to 1.0 # window = np.hamming(block_length) # window[0:block_length_o2] /= ( # window[0:block_length_o2] + window[block_length_o2:block_length]) # window[block_length_o2:block_length] = np.flipud(window[0:block_length_o2]) # # if hmax == 0: # return sig # result = np.zeros_like(sig) # # # -------- prepare an array with estimated frequencies # tmax = len(sig) # freq = np.zeros(2 + 2 * tmax // block_length) # kf = 0 # if progress_bar: # bar = ProgressBar(max_value=len(freq), title='dehumming %.0f Hz' % enf) # # # -------- process successive blocks # for tmid in range(0, tmax + block_length_o2, block_length_o2): # # -------- initial and final blocks are truncated # tstart = tmid - block_length_o2 # if tstart < 0: # wstart = -tstart # tstart = 0 # else: # wstart = 0 # tstop = tmid + block_length_o2 # if tstop > tmax: # wstop = block_length + tmax - tstop # tstop = tmax # else: # wstop = block_length # # # -------- search for the frequency # f0 = enf # sigenf = single_estimate(sig[tstart:tstop], f0, fs, hmax) # best_f = f0 # best_sigout = sig[tstart:tstop] - sigenf # best_energy = np.dot(best_sigout.T, best_sigout) # for delta in {0.1, 0.01}: # shift_max = 9 if delta == 0.01 else 9 # shifts = np.arange(1, shift_max + 1) # shifts = np.r_[-shifts[::-1], shifts] # # for shift in shifts: # f = f0 + shift * delta # sigenf = single_estimate(sig[tstart:tstop], f, fs, hmax) # sigout = sig[tstart:tstop] - sigenf # energy = np.dot(sigout.T, sigout) # # we keep the frequency f that removes the most energy # if energy < best_energy: # best_f = f # best_sigout = sigout # best_energy = energy # f0 = best_f # # # -------- this block has been processed, save it # result[tstart:tstop] += best_sigout * window[wstart:wstop] # # freq[kf] = best_f # kf += 1 # if progress_bar and kf % 10 == 0: # bar.update(kf) # if progress_bar: # bar.update(bar.max_value) # # # -------- plot estimated electrical network frequency # if 'f' in draw or 'z' in draw: # t = np.linspace(0, tmax / fs, len(freq)) # plt.figure('Estimated electrical network frequency') # plt.title('Estimated electrical network frequency') # # plt.plot(t, freq / enf, label='%.0fHz' % enf) # plt.ylabel('ENF fluctuation'), # plt.xlabel('Time (sec)') # plt.legend(loc=0) # # # -------- plot long term spectum of noisy and denoised signals # if 'd' in draw or 'z' in draw: # sp = Spectrum(block_length=block_length, fs=fs, donorm=True, # wfunc=np.blackman) # sp.periodogram(sig) # sp.periodogram(result, hold=True) # sp.plot('Power spectral density before/after dehumming', fscale='lin') # # return result.reshape(input_shape) # # Path: pactools/utils/maths.py # def norm(x): # """Compute the Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). More precise than sqrt(squared_norm(x)). # """ # x = np.asarray(x) # # if np.any(np.iscomplex(x)): # return np.sqrt(squared_norm(x)) # else: # nrm2, = linalg.get_blas_funcs(['nrm2'], [x]) # return nrm2(x) # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): . Output only the next line.
time = np.arange(512) / float(fs)
Predict the next line after this snippet: <|code_start|> def twice(a): return 2 * a def test_fake_parallel(): # Test that _FakeParallel does nothing but unrolling the generator generator = (twice(b) for b in range(10)) results = _FakeParallel(n_jobs=1)(generator) reference = [twice(b) for b in range(10)] assert_array_equal(np.array(results), np.array(reference)) # test fake parameters _FakeParallel(n_jobs=1, foo='bar', baz=42) <|code_end|> using the current file's imports: import numpy as np from pactools.utils.parallel import _FakeParallel, _fake_delayed from pactools.utils.testing import assert_array_equal, assert_equal and any relevant context from other files: # Path: pactools/utils/parallel.py # class _FakeParallel(object): # """Useless decorator that is used like Parallel""" # def __init__(self, n_jobs=1, *args, **kwargs): # if n_jobs != 1: # warnings.warn( # "You have set n_jobs=%s to use parallel processing, " # "but it has currently no effect. Please install joblib or " # "scikit-learn to use it." # % (n_jobs, )) # # def __call__(self, iterable): # # return list(iterable) # # def _fake_delayed(func): # return func # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): . Output only the next line.
def test_fake_delayed():
Given the code snippet: <|code_start|> def twice(a): return 2 * a def test_fake_parallel(): # Test that _FakeParallel does nothing but unrolling the generator generator = (twice(b) for b in range(10)) results = _FakeParallel(n_jobs=1)(generator) reference = [twice(b) for b in range(10)] assert_array_equal(np.array(results), np.array(reference)) # test fake parameters _FakeParallel(n_jobs=1, foo='bar', baz=42) <|code_end|> , generate the next line using the imports in this file: import numpy as np from pactools.utils.parallel import _FakeParallel, _fake_delayed from pactools.utils.testing import assert_array_equal, assert_equal and context (functions, classes, or occasionally code) from other files: # Path: pactools/utils/parallel.py # class _FakeParallel(object): # """Useless decorator that is used like Parallel""" # def __init__(self, n_jobs=1, *args, **kwargs): # if n_jobs != 1: # warnings.warn( # "You have set n_jobs=%s to use parallel processing, " # "but it has currently no effect. Please install joblib or " # "scikit-learn to use it." # % (n_jobs, )) # # def __call__(self, iterable): # # return list(iterable) # # def _fake_delayed(func): # return func # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): . Output only the next line.
def test_fake_delayed():
Given snippet: <|code_start|> def twice(a): return 2 * a def test_fake_parallel(): # Test that _FakeParallel does nothing but unrolling the generator <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from pactools.utils.parallel import _FakeParallel, _fake_delayed from pactools.utils.testing import assert_array_equal, assert_equal and context: # Path: pactools/utils/parallel.py # class _FakeParallel(object): # """Useless decorator that is used like Parallel""" # def __init__(self, n_jobs=1, *args, **kwargs): # if n_jobs != 1: # warnings.warn( # "You have set n_jobs=%s to use parallel processing, " # "but it has currently no effect. Please install joblib or " # "scikit-learn to use it." # % (n_jobs, )) # # def __call__(self, iterable): # # return list(iterable) # # def _fake_delayed(func): # return func # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): which might include code, classes, or functions. Output only the next line.
generator = (twice(b) for b in range(10))
Here is a snippet: <|code_start|> low_fq_range = [1., 3., 5., 7.] high_fq_range = [25., 50., 75.] n_low = len(low_fq_range) n_high = len(high_fq_range) n_points = 1024 def simulate_pac_default(n_points=128, fs=200., high_fq=50., low_fq=3., low_fq_width=1., noise_level=0.1, random_state=42, <|code_end|> . Write the next line using the current file imports: import numpy as np from pactools.utils.testing import assert_equal, assert_raises from pactools.utils.testing import assert_array_almost_equal from pactools.utils.testing import assert_array_equal, assert_almost_equal from pactools.simulate_pac import simulate_pac and context from other files: # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/simulate_pac.py # def simulate_pac(n_points, fs, high_fq, low_fq, low_fq_width, noise_level, # high_fq_amp=0.5, low_fq_amp=0.5, random_state=None, # sigmoid_sharpness=6, phi_0=0., delay=0., return_driver=False): # """Simulate a 1D signal with artificial phase amplitude coupling (PAC). # # Parameters # ---------- # n_points : int # Number of points in the signal # # fs : float # Sampling frequency of the signal # # high_fq : float # Frequency of the fast oscillation which is modulated in amplitude # # low_fq : float # Center frequency of the slow oscillation which controls the modulation # # low_fq_width : float # Bandwidth of the slow oscillation which controls the modulation # # noise_level : float # Level of the Gaussian additive white noise # # high_fq_amp : float # Amplitude of the fast oscillation # # low_fq_amp : float # Amplitude of the slow oscillation # # random_state : int seed, RandomState instance, or None (default) # The seed of the pseudo random number generator. # # sigmoid_sharpness : float # Sharpness of the sigmoid used to define the modulation # # phi_0 : float # Preferred phase of the coupling: phase of the slow oscillation which # corresponds to the maximum amplitude of the fast oscillations # # delay : float # Delay between the slow oscillation and the modulation # # return_driver : boolean # If True, return the complex driver instead of the full signal # # Returns # ------- # signal : array, shape (n_points, ) # Signal with artifical PAC # # """ # n_points = int(n_points) # fs = float(fs) # rng = check_random_state(random_state) # if high_fq >= fs / 2 or low_fq >= fs / 2: # raise ValueError('Frequency is larger or equal to half ' # 'the sampling frequency.') # if high_fq < 0 or low_fq < 0 or fs < 0: # raise ValueError('Invalid negative frequency') # # fir = BandPassFilter(fs=fs, fc=low_fq, n_cycles=None, # bandwidth=low_fq_width, extract_complex=True) # driver_real, driver_imag = fir.transform(rng.randn(n_points)) # driver = driver_real + 1j * driver_imag # # We scale by sqrt(2) to have correct amplitude in the real-valued driver # driver *= 1. / driver.std() * np.sqrt(2) # if return_driver: # return driver # # # decay of sigdriv for continuity after np.roll # if delay != 0: # n_decay = max(int(0.5 * fs / low_fq), 5) # window = np.blackman(n_decay * 2 - 1)[:n_decay] # driver[:n_decay] *= window # driver[-n_decay:] *= window[::-1] # # # create the fast oscillation # time = np.arange(n_points) / float(fs) # carrier = np.sin(2 * np.pi * high_fq * time) # carrier *= high_fq_amp / carrier.std() # # # create the modulation, with a sigmoid, and a phase lag # phase = np.exp(1j * phi_0) # sigmoid_sharpness = sigmoid_sharpness # modulation = sigmoid(np.real(driver * phase), sharpness=sigmoid_sharpness) # # # the slow oscillation is not phased lag # theta = np.real(driver) * low_fq_amp # # # add a delay to the slow oscillation theta # delay_point = int(delay * fs) # theta = np.roll(theta, delay_point) # # # apply modulation # gamma = carrier * modulation # # create noise # noise = rng.randn(n_points) * noise_level # # add all oscillations # signal = gamma + theta + noise # # return signal , which may include functions, classes, or code. Output only the next line.
*args, **kwargs):
Continue the code snippet: <|code_start|> low_fq_range = [1., 3., 5., 7.] high_fq_range = [25., 50., 75.] n_low = len(low_fq_range) n_high = len(high_fq_range) n_points = 1024 def simulate_pac_default(n_points=128, fs=200., high_fq=50., low_fq=3., low_fq_width=1., noise_level=0.1, random_state=42, <|code_end|> . Use current file imports: import numpy as np from pactools.utils.testing import assert_equal, assert_raises from pactools.utils.testing import assert_array_almost_equal from pactools.utils.testing import assert_array_equal, assert_almost_equal from pactools.simulate_pac import simulate_pac and context (classes, functions, or code) from other files: # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/simulate_pac.py # def simulate_pac(n_points, fs, high_fq, low_fq, low_fq_width, noise_level, # high_fq_amp=0.5, low_fq_amp=0.5, random_state=None, # sigmoid_sharpness=6, phi_0=0., delay=0., return_driver=False): # """Simulate a 1D signal with artificial phase amplitude coupling (PAC). # # Parameters # ---------- # n_points : int # Number of points in the signal # # fs : float # Sampling frequency of the signal # # high_fq : float # Frequency of the fast oscillation which is modulated in amplitude # # low_fq : float # Center frequency of the slow oscillation which controls the modulation # # low_fq_width : float # Bandwidth of the slow oscillation which controls the modulation # # noise_level : float # Level of the Gaussian additive white noise # # high_fq_amp : float # Amplitude of the fast oscillation # # low_fq_amp : float # Amplitude of the slow oscillation # # random_state : int seed, RandomState instance, or None (default) # The seed of the pseudo random number generator. # # sigmoid_sharpness : float # Sharpness of the sigmoid used to define the modulation # # phi_0 : float # Preferred phase of the coupling: phase of the slow oscillation which # corresponds to the maximum amplitude of the fast oscillations # # delay : float # Delay between the slow oscillation and the modulation # # return_driver : boolean # If True, return the complex driver instead of the full signal # # Returns # ------- # signal : array, shape (n_points, ) # Signal with artifical PAC # # """ # n_points = int(n_points) # fs = float(fs) # rng = check_random_state(random_state) # if high_fq >= fs / 2 or low_fq >= fs / 2: # raise ValueError('Frequency is larger or equal to half ' # 'the sampling frequency.') # if high_fq < 0 or low_fq < 0 or fs < 0: # raise ValueError('Invalid negative frequency') # # fir = BandPassFilter(fs=fs, fc=low_fq, n_cycles=None, # bandwidth=low_fq_width, extract_complex=True) # driver_real, driver_imag = fir.transform(rng.randn(n_points)) # driver = driver_real + 1j * driver_imag # # We scale by sqrt(2) to have correct amplitude in the real-valued driver # driver *= 1. / driver.std() * np.sqrt(2) # if return_driver: # return driver # # # decay of sigdriv for continuity after np.roll # if delay != 0: # n_decay = max(int(0.5 * fs / low_fq), 5) # window = np.blackman(n_decay * 2 - 1)[:n_decay] # driver[:n_decay] *= window # driver[-n_decay:] *= window[::-1] # # # create the fast oscillation # time = np.arange(n_points) / float(fs) # carrier = np.sin(2 * np.pi * high_fq * time) # carrier *= high_fq_amp / carrier.std() # # # create the modulation, with a sigmoid, and a phase lag # phase = np.exp(1j * phi_0) # sigmoid_sharpness = sigmoid_sharpness # modulation = sigmoid(np.real(driver * phase), sharpness=sigmoid_sharpness) # # # the slow oscillation is not phased lag # theta = np.real(driver) * low_fq_amp # # # add a delay to the slow oscillation theta # delay_point = int(delay * fs) # theta = np.roll(theta, delay_point) # # # apply modulation # gamma = carrier * modulation # # create noise # noise = rng.randn(n_points) * noise_level # # add all oscillations # signal = gamma + theta + noise # # return signal . Output only the next line.
*args, **kwargs):
Predict the next line after this snippet: <|code_start|> def test_progress_bar(): n = 10 app = ProgressBar(title='Testing progressBar', max_value=n - 1, spinner=True) assert_false(app.closed) for k in range(n): app.update_with_increment_value(1) <|code_end|> using the current file's imports: import time from pactools.utils.testing import assert_true, assert_false from pactools.utils.progress_bar import ProgressBar and any relevant context from other files: # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/progress_bar.py # class ProgressBar(): # """Class for generating a command-line progressbar # Parameters # ---------- # max_value : int # Maximum value of process (e.g. number of samples to process, bytes to # download, etc.). # initial_value : int # Initial value of process, useful when resuming process from a specific # value, defaults to 0. # title : str # Message to include at end of progress bar. # max_chars : int # Number of characters to use for progress bar (be sure to save some room # for the message and % complete as well). # progress_character : char # Character in the progress bar that indicates the portion completed. # spinner : bool # Show a spinner. Useful for long-running processes that may not # increment the progress bar very often. This provides the user with # feedback that the progress has not stalled. # """ # # spinner_symbols = ['|', '/', '-', '\\'] # template = '\r[{0}{1}] {2:.0f}% {3} {4:.02f} sec | {5} ' # # def __init__(self, title='', max_value=1, initial_value=0, max_chars=40, # progress_character='.', spinner=False, verbose_bool=True): # self.cur_value = initial_value # self.max_value = float(max_value) # self.title = title # self.max_chars = max_chars # self.progress_character = progress_character # self.spinner = spinner # self.spinner_index = 0 # self.n_spinner = len(self.spinner_symbols) # self._do_print = verbose_bool # self.start = time.time() # # self.closed = False # self.update(initial_value) # # def update(self, cur_value, title=None): # """Update progressbar with current value of process # Parameters # ---------- # cur_value : number # Current value of process. Should be <= max_value (but this is not # enforced). The percent of the progressbar will be computed as # (cur_value / max_value) * 100 # title : str # Message to display to the right of the progressbar. If None, the # last message provided will be used. To clear the current message, # pass a null string, ''. # """ # # Ensure floating-point division so we can get fractions of a percent # # for the progressbar. # self.cur_value = cur_value # progress = min(float(self.cur_value) / self.max_value, 1.) # num_chars = int(progress * self.max_chars) # num_left = self.max_chars - num_chars # # # Update the message # if title is not None: # self.title = title # # # time from start # duration = time.time() - self.start # # # The \r tells the cursor to return to the beginning of the line rather # # than starting a new line. This allows us to have a progressbar-style # # display in the console window. # bar = self.template.format(self.progress_character * num_chars, # ' ' * num_left, progress * 100, # self.spinner_symbols[self.spinner_index], # duration, self.title) # # Force a flush because sometimes when using bash scripts and pipes, # # the output is not printed until after the program exits. # if self._do_print: # sys.stdout.write(bar) # sys.stdout.flush() # # Increament the spinner # if self.spinner: # self.spinner_index = (self.spinner_index + 1) % self.n_spinner # # if progress == 1: # self.close() # # def update_with_increment_value(self, increment_value, title=None): # """Update progressbar with the value of the increment instead of the # current value of process as in update() # Parameters # ---------- # increment_value : int # Value of the increment of process. The percent of the progressbar # will be computed as # (self.cur_value + increment_value / max_value) * 100 # title : str # Message to display to the right of the progressbar. If None, the # last message provided will be used. To clear the current message, # pass a null string, ''. # """ # self.cur_value += increment_value # self.update(self.cur_value, title) # # def close(self): # if not self.closed: # sys.stdout.write('\n') # sys.stdout.flush() # self.closed = True # # def __call__(self, sequence): # sequence = iter(sequence) # while True: # try: # yield next(sequence) # self.update_with_increment_value(1) # except StopIteration: # return . Output only the next line.
time.sleep(0.001)
Based on the snippet: <|code_start|> def test_progress_bar(): n = 10 app = ProgressBar(title='Testing progressBar', max_value=n - 1, spinner=True) assert_false(app.closed) for k in range(n): app.update_with_increment_value(1) time.sleep(0.001) assert_true(app.closed) <|code_end|> , predict the immediate next line with the help of imports: import time from pactools.utils.testing import assert_true, assert_false from pactools.utils.progress_bar import ProgressBar and context (classes, functions, sometimes code) from other files: # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/progress_bar.py # class ProgressBar(): # """Class for generating a command-line progressbar # Parameters # ---------- # max_value : int # Maximum value of process (e.g. number of samples to process, bytes to # download, etc.). # initial_value : int # Initial value of process, useful when resuming process from a specific # value, defaults to 0. # title : str # Message to include at end of progress bar. # max_chars : int # Number of characters to use for progress bar (be sure to save some room # for the message and % complete as well). # progress_character : char # Character in the progress bar that indicates the portion completed. # spinner : bool # Show a spinner. Useful for long-running processes that may not # increment the progress bar very often. This provides the user with # feedback that the progress has not stalled. # """ # # spinner_symbols = ['|', '/', '-', '\\'] # template = '\r[{0}{1}] {2:.0f}% {3} {4:.02f} sec | {5} ' # # def __init__(self, title='', max_value=1, initial_value=0, max_chars=40, # progress_character='.', spinner=False, verbose_bool=True): # self.cur_value = initial_value # self.max_value = float(max_value) # self.title = title # self.max_chars = max_chars # self.progress_character = progress_character # self.spinner = spinner # self.spinner_index = 0 # self.n_spinner = len(self.spinner_symbols) # self._do_print = verbose_bool # self.start = time.time() # # self.closed = False # self.update(initial_value) # # def update(self, cur_value, title=None): # """Update progressbar with current value of process # Parameters # ---------- # cur_value : number # Current value of process. Should be <= max_value (but this is not # enforced). The percent of the progressbar will be computed as # (cur_value / max_value) * 100 # title : str # Message to display to the right of the progressbar. If None, the # last message provided will be used. To clear the current message, # pass a null string, ''. # """ # # Ensure floating-point division so we can get fractions of a percent # # for the progressbar. # self.cur_value = cur_value # progress = min(float(self.cur_value) / self.max_value, 1.) # num_chars = int(progress * self.max_chars) # num_left = self.max_chars - num_chars # # # Update the message # if title is not None: # self.title = title # # # time from start # duration = time.time() - self.start # # # The \r tells the cursor to return to the beginning of the line rather # # than starting a new line. This allows us to have a progressbar-style # # display in the console window. # bar = self.template.format(self.progress_character * num_chars, # ' ' * num_left, progress * 100, # self.spinner_symbols[self.spinner_index], # duration, self.title) # # Force a flush because sometimes when using bash scripts and pipes, # # the output is not printed until after the program exits. # if self._do_print: # sys.stdout.write(bar) # sys.stdout.flush() # # Increament the spinner # if self.spinner: # self.spinner_index = (self.spinner_index + 1) % self.n_spinner # # if progress == 1: # self.close() # # def update_with_increment_value(self, increment_value, title=None): # """Update progressbar with the value of the increment instead of the # current value of process as in update() # Parameters # ---------- # increment_value : int # Value of the increment of process. The percent of the progressbar # will be computed as # (self.cur_value + increment_value / max_value) * 100 # title : str # Message to display to the right of the progressbar. If None, the # last message provided will be used. To clear the current message, # pass a null string, ''. # """ # self.cur_value += increment_value # self.update(self.cur_value, title) # # def close(self): # if not self.closed: # sys.stdout.write('\n') # sys.stdout.flush() # self.closed = True # # def __call__(self, sequence): # sequence = iter(sequence) # while True: # try: # yield next(sequence) # self.update_with_increment_value(1) # except StopIteration: # return . Output only the next line.
n = 10
Continue the code snippet: <|code_start|> def test_norm(): # Test that norm and squared_norm are consistent rng = np.random.RandomState(0) for sig in (rng.randn(10), rng.randn(4, 3), [1 + 1j, 3, 6], -9): assert_array_almost_equal(norm(sig) ** 2, squared_norm(sig)) def test_argmax_2d(): # Test that argmax_2d gives the correct indices of the max rng = np.random.RandomState(0) a = rng.randn(4, 3) i, j = argmax_2d(a) assert_equal(a[i, j], a.max()) <|code_end|> . Use current file imports: import numpy as np from pactools.utils.maths import norm, squared_norm, argmax_2d, is_power2 from pactools.utils.maths import prime_factors from pactools.utils.testing import assert_equal from pactools.utils.testing import assert_array_almost_equal from pactools.utils.testing import assert_true, assert_false and context (classes, functions, or code) from other files: # Path: pactools/utils/maths.py # def norm(x): # """Compute the Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). More precise than sqrt(squared_norm(x)). # """ # x = np.asarray(x) # # if np.any(np.iscomplex(x)): # return np.sqrt(squared_norm(x)) # else: # nrm2, = linalg.get_blas_funcs(['nrm2'], [x]) # return nrm2(x) # # def squared_norm(x): # """Squared Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). Faster than norm(x) ** 2. # """ # x = np.asarray(x) # x = x.ravel(order='K') # return np.dot(x, np.conj(x)) # # def argmax_2d(a): # """Return the tuple (i, j) where a[i, j] = a.max()""" # return np.unravel_index(np.argmax(a), a.shape) # # def is_power2(num): # """Test if num is a power of 2. (int -> bool)""" # num = int(num) # return num != 0 and ((num & (num - 1)) == 0) # # Path: pactools/utils/maths.py # def prime_factors(num): # """ # Decomposition in prime factor. # Used to find signal length that speed up Hilbert transform. # # Parameters # ---------- # num : int # # Returns # ------- # decomposition : list of int # List of prime factors sorted by ascending order # """ # assert num > 0 # assert isinstance(num, int) # # decomposition = [] # for i in chain([2], range(3, int(np.sqrt(num)) + 1, 2)): # while num % i == 0: # num = num // i # decomposition.append(i) # if num == 1: # break # if num != 1: # decomposition.append(num) # return decomposition # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): . Output only the next line.
def test_is_power2():
Continue the code snippet: <|code_start|> def test_norm(): # Test that norm and squared_norm are consistent rng = np.random.RandomState(0) for sig in (rng.randn(10), rng.randn(4, 3), [1 + 1j, 3, 6], -9): assert_array_almost_equal(norm(sig) ** 2, squared_norm(sig)) def test_argmax_2d(): # Test that argmax_2d gives the correct indices of the max rng = np.random.RandomState(0) <|code_end|> . Use current file imports: import numpy as np from pactools.utils.maths import norm, squared_norm, argmax_2d, is_power2 from pactools.utils.maths import prime_factors from pactools.utils.testing import assert_equal from pactools.utils.testing import assert_array_almost_equal from pactools.utils.testing import assert_true, assert_false and context (classes, functions, or code) from other files: # Path: pactools/utils/maths.py # def norm(x): # """Compute the Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). More precise than sqrt(squared_norm(x)). # """ # x = np.asarray(x) # # if np.any(np.iscomplex(x)): # return np.sqrt(squared_norm(x)) # else: # nrm2, = linalg.get_blas_funcs(['nrm2'], [x]) # return nrm2(x) # # def squared_norm(x): # """Squared Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). Faster than norm(x) ** 2. # """ # x = np.asarray(x) # x = x.ravel(order='K') # return np.dot(x, np.conj(x)) # # def argmax_2d(a): # """Return the tuple (i, j) where a[i, j] = a.max()""" # return np.unravel_index(np.argmax(a), a.shape) # # def is_power2(num): # """Test if num is a power of 2. (int -> bool)""" # num = int(num) # return num != 0 and ((num & (num - 1)) == 0) # # Path: pactools/utils/maths.py # def prime_factors(num): # """ # Decomposition in prime factor. # Used to find signal length that speed up Hilbert transform. # # Parameters # ---------- # num : int # # Returns # ------- # decomposition : list of int # List of prime factors sorted by ascending order # """ # assert num > 0 # assert isinstance(num, int) # # decomposition = [] # for i in chain([2], range(3, int(np.sqrt(num)) + 1, 2)): # while num % i == 0: # num = num // i # decomposition.append(i) # if num == 1: # break # if num != 1: # decomposition.append(num) # return decomposition # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): . Output only the next line.
a = rng.randn(4, 3)
Given snippet: <|code_start|> def test_norm(): # Test that norm and squared_norm are consistent rng = np.random.RandomState(0) for sig in (rng.randn(10), rng.randn(4, 3), [1 + 1j, 3, 6], -9): assert_array_almost_equal(norm(sig) ** 2, squared_norm(sig)) def test_argmax_2d(): # Test that argmax_2d gives the correct indices of the max rng = np.random.RandomState(0) a = rng.randn(4, 3) i, j = argmax_2d(a) assert_equal(a[i, j], a.max()) def test_is_power2(): for i in range(1, 10): assert_true(is_power2(2 ** i)) assert_false(is_power2(2 ** i + 1)) <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from pactools.utils.maths import norm, squared_norm, argmax_2d, is_power2 from pactools.utils.maths import prime_factors from pactools.utils.testing import assert_equal from pactools.utils.testing import assert_array_almost_equal from pactools.utils.testing import assert_true, assert_false and context: # Path: pactools/utils/maths.py # def norm(x): # """Compute the Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). More precise than sqrt(squared_norm(x)). # """ # x = np.asarray(x) # # if np.any(np.iscomplex(x)): # return np.sqrt(squared_norm(x)) # else: # nrm2, = linalg.get_blas_funcs(['nrm2'], [x]) # return nrm2(x) # # def squared_norm(x): # """Squared Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). Faster than norm(x) ** 2. # """ # x = np.asarray(x) # x = x.ravel(order='K') # return np.dot(x, np.conj(x)) # # def argmax_2d(a): # """Return the tuple (i, j) where a[i, j] = a.max()""" # return np.unravel_index(np.argmax(a), a.shape) # # def is_power2(num): # """Test if num is a power of 2. (int -> bool)""" # num = int(num) # return num != 0 and ((num & (num - 1)) == 0) # # Path: pactools/utils/maths.py # def prime_factors(num): # """ # Decomposition in prime factor. # Used to find signal length that speed up Hilbert transform. # # Parameters # ---------- # num : int # # Returns # ------- # decomposition : list of int # List of prime factors sorted by ascending order # """ # assert num > 0 # assert isinstance(num, int) # # decomposition = [] # for i in chain([2], range(3, int(np.sqrt(num)) + 1, 2)): # while num % i == 0: # num = num // i # decomposition.append(i) # if num == 1: # break # if num != 1: # decomposition.append(num) # return decomposition # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): which might include code, classes, or functions. Output only the next line.
def test_prime_factors():
Based on the snippet: <|code_start|> def test_norm(): # Test that norm and squared_norm are consistent rng = np.random.RandomState(0) for sig in (rng.randn(10), rng.randn(4, 3), [1 + 1j, 3, 6], -9): assert_array_almost_equal(norm(sig) ** 2, squared_norm(sig)) def test_argmax_2d(): # Test that argmax_2d gives the correct indices of the max rng = np.random.RandomState(0) a = rng.randn(4, 3) i, j = argmax_2d(a) assert_equal(a[i, j], a.max()) <|code_end|> , predict the immediate next line with the help of imports: import numpy as np from pactools.utils.maths import norm, squared_norm, argmax_2d, is_power2 from pactools.utils.maths import prime_factors from pactools.utils.testing import assert_equal from pactools.utils.testing import assert_array_almost_equal from pactools.utils.testing import assert_true, assert_false and context (classes, functions, sometimes code) from other files: # Path: pactools/utils/maths.py # def norm(x): # """Compute the Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). More precise than sqrt(squared_norm(x)). # """ # x = np.asarray(x) # # if np.any(np.iscomplex(x)): # return np.sqrt(squared_norm(x)) # else: # nrm2, = linalg.get_blas_funcs(['nrm2'], [x]) # return nrm2(x) # # def squared_norm(x): # """Squared Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). Faster than norm(x) ** 2. # """ # x = np.asarray(x) # x = x.ravel(order='K') # return np.dot(x, np.conj(x)) # # def argmax_2d(a): # """Return the tuple (i, j) where a[i, j] = a.max()""" # return np.unravel_index(np.argmax(a), a.shape) # # def is_power2(num): # """Test if num is a power of 2. (int -> bool)""" # num = int(num) # return num != 0 and ((num & (num - 1)) == 0) # # Path: pactools/utils/maths.py # def prime_factors(num): # """ # Decomposition in prime factor. # Used to find signal length that speed up Hilbert transform. # # Parameters # ---------- # num : int # # Returns # ------- # decomposition : list of int # List of prime factors sorted by ascending order # """ # assert num > 0 # assert isinstance(num, int) # # decomposition = [] # for i in chain([2], range(3, int(np.sqrt(num)) + 1, 2)): # while num % i == 0: # num = num // i # decomposition.append(i) # if num == 1: # break # if num != 1: # decomposition.append(num) # return decomposition # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): . Output only the next line.
def test_is_power2():
Continue the code snippet: <|code_start|> def test_norm(): # Test that norm and squared_norm are consistent rng = np.random.RandomState(0) for sig in (rng.randn(10), rng.randn(4, 3), [1 + 1j, 3, 6], -9): assert_array_almost_equal(norm(sig) ** 2, squared_norm(sig)) def test_argmax_2d(): # Test that argmax_2d gives the correct indices of the max rng = np.random.RandomState(0) a = rng.randn(4, 3) i, j = argmax_2d(a) assert_equal(a[i, j], a.max()) <|code_end|> . Use current file imports: import numpy as np from pactools.utils.maths import norm, squared_norm, argmax_2d, is_power2 from pactools.utils.maths import prime_factors from pactools.utils.testing import assert_equal from pactools.utils.testing import assert_array_almost_equal from pactools.utils.testing import assert_true, assert_false and context (classes, functions, or code) from other files: # Path: pactools/utils/maths.py # def norm(x): # """Compute the Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). More precise than sqrt(squared_norm(x)). # """ # x = np.asarray(x) # # if np.any(np.iscomplex(x)): # return np.sqrt(squared_norm(x)) # else: # nrm2, = linalg.get_blas_funcs(['nrm2'], [x]) # return nrm2(x) # # def squared_norm(x): # """Squared Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). Faster than norm(x) ** 2. # """ # x = np.asarray(x) # x = x.ravel(order='K') # return np.dot(x, np.conj(x)) # # def argmax_2d(a): # """Return the tuple (i, j) where a[i, j] = a.max()""" # return np.unravel_index(np.argmax(a), a.shape) # # def is_power2(num): # """Test if num is a power of 2. (int -> bool)""" # num = int(num) # return num != 0 and ((num & (num - 1)) == 0) # # Path: pactools/utils/maths.py # def prime_factors(num): # """ # Decomposition in prime factor. # Used to find signal length that speed up Hilbert transform. # # Parameters # ---------- # num : int # # Returns # ------- # decomposition : list of int # List of prime factors sorted by ascending order # """ # assert num > 0 # assert isinstance(num, int) # # decomposition = [] # for i in chain([2], range(3, int(np.sqrt(num)) + 1, 2)): # while num % i == 0: # num = num // i # decomposition.append(i) # if num == 1: # break # if num != 1: # decomposition.append(num) # return decomposition # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): . Output only the next line.
def test_is_power2():
Using the snippet: <|code_start|> def test_norm(): # Test that norm and squared_norm are consistent rng = np.random.RandomState(0) for sig in (rng.randn(10), rng.randn(4, 3), [1 + 1j, 3, 6], -9): assert_array_almost_equal(norm(sig) ** 2, squared_norm(sig)) def test_argmax_2d(): # Test that argmax_2d gives the correct indices of the max rng = np.random.RandomState(0) a = rng.randn(4, 3) i, j = argmax_2d(a) assert_equal(a[i, j], a.max()) <|code_end|> , determine the next line of code. You have imports: import numpy as np from pactools.utils.maths import norm, squared_norm, argmax_2d, is_power2 from pactools.utils.maths import prime_factors from pactools.utils.testing import assert_equal from pactools.utils.testing import assert_array_almost_equal from pactools.utils.testing import assert_true, assert_false and context (class names, function names, or code) available: # Path: pactools/utils/maths.py # def norm(x): # """Compute the Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). More precise than sqrt(squared_norm(x)). # """ # x = np.asarray(x) # # if np.any(np.iscomplex(x)): # return np.sqrt(squared_norm(x)) # else: # nrm2, = linalg.get_blas_funcs(['nrm2'], [x]) # return nrm2(x) # # def squared_norm(x): # """Squared Euclidean or Frobenius norm of x. # # Returns the Euclidean norm when x is a vector, the Frobenius norm when x # is a matrix (2-d array). Faster than norm(x) ** 2. # """ # x = np.asarray(x) # x = x.ravel(order='K') # return np.dot(x, np.conj(x)) # # def argmax_2d(a): # """Return the tuple (i, j) where a[i, j] = a.max()""" # return np.unravel_index(np.argmax(a), a.shape) # # def is_power2(num): # """Test if num is a power of 2. (int -> bool)""" # num = int(num) # return num != 0 and ((num & (num - 1)) == 0) # # Path: pactools/utils/maths.py # def prime_factors(num): # """ # Decomposition in prime factor. # Used to find signal length that speed up Hilbert transform. # # Parameters # ---------- # num : int # # Returns # ------- # decomposition : list of int # List of prime factors sorted by ascending order # """ # assert num > 0 # assert isinstance(num, int) # # decomposition = [] # for i in chain([2], range(3, int(np.sqrt(num)) + 1, 2)): # while num % i == 0: # num = num // i # decomposition.append(i) # if num == 1: # break # if num != 1: # decomposition.append(num) # return decomposition # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): # # Path: pactools/utils/testing.py # def assert_array_not_almost_equal(*args, **kwargs): # def func(): . Output only the next line.
def test_is_power2():
Using the snippet: <|code_start|> self.assertIsInstance(exception_log, ExceptionLog) try: 0.0 // 0.0 except Exception as e: exception = e self.assertEqual(exception.__class__.__name__, exception_log.type) self.assertEqual(exception.__class__.__module__, exception_log.module) self.assertEqual(str(exception), exception_log.message) self.assertIn('Traceback (most recent call last):', exception_log.traceback) self.assertIn('ZeroDivisionError: float divmod()', exception_log.traceback) def test_log_variable_undefined(self): # Logger().prepare_value(Variable.Undefined()) causes # TypeError: coercing to Unicode: need string or buffer, __proxy__ found Logger().prepare_value(Variable.Undefined()) variable_definition = VariableDefinition.objects.create(name='A') root = variable_assign_value(variable_name='B', variable_definition=variable_definition) context = Context(log=True) result = root.interpret(context) self.assertFalse(ExceptionLog.objects.all()) class ProgramTest(ProgramTestBase): def test_empty_execution(self): result = self.program_version.execute(test_model=self.test_model) <|code_end|> , determine the next line of code. You have imports: from business_logic.models.log import LOG_ENTRY_VALUE_LENGTH from .common import * and context (class names, function names, or code) available: # Path: business_logic/models/log.py # LOG_ENTRY_VALUE_LENGTH = settings.PROGRAM_LOG_ENTRY_VALUE_LENGTH . Output only the next line.
self.assertIsNone(result.execution)
Given the code snippet: <|code_start|> @python_2_unicode_compatible class Operator(NodeAccessor): operator = models.CharField(_('Operator'), null=False, max_length=3) operator_table = {} def _check_operator(self): if self.operator not in self.operator_table: raise TypeError('Incorrect operator "{operator}" for class {cls}'.format( operator=self.operator, cls=self.__class__.__name__)) def __init__(self, *args, **kwargs): super(Operator, self).__init__(*args, **kwargs) if not self.id and self.operator: self._check_operator() def save(self, *args, **kwargs): self._check_operator() return super(Operator, self).save(*args, **kwargs) def __str__(self): return self.operator class Meta: <|code_end|> , generate the next line using the imports in this file: import operator from decimal import Decimal from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from .node import NodeAccessor and context (functions, classes, or occasionally code) from other files: # Path: business_logic/models/node.py # class NodeAccessor(models.Model): # # @property # def node(self): # if hasattr(self, '_node_cache'): # return self._node_cache # # return Node.objects.get(content_type=ContentType.objects.get_for_model(self.__class__), object_id=self.id) # # class Meta: # abstract = True . Output only the next line.
abstract = True
Next line prediction: <|code_start|> fftabs.py -t | --title fftabs.py (-f | --focus) ID fftabs.py --count fftabs.py --current fftabs.py (-c | -k | --close) ID... fftabs.py -r | --raw fftabs.py -h | --help fftabs.py -V | --version Options: -a --all List all tabs in a readable format. -u --url Show URLs. -l --list URL lister. -t --title Show titles. -f --focus Focus on selected tab, where ID is the tab index. --count Number of tabs. --current URL of the current tab. -c -k --close Close (kill) selected tab, where ID is the tab index(es). -r --raw List all tabs in raw format. -h --help Show this screen. -V --version Show version. """ __project__ = 'Firefox Tabs' __version__ = '0.1' INFO = """ <|code_end|> . Use current file imports: (from docopt import docopt from lib import firefox as ff) and context including class names, function names, or small code snippets from other files: # Path: lib/firefox.py # class Mozrepl(object): # HOST = 'localhost' # PORT = 4242 # def __init__(self, ip=HOST, port=PORT): # def __enter__(self): # def __exit__(self, type, value, traceback): # def cmd(self, command): # def get_text_result(self, command, sep=''): # def is_installed(cls): # def open_url_in_curr_tab(url): # def get_curr_tab_url(): # def open_new_empty_tab(): # def put_focus_on_tab(n): # def open_url_in_new_tab(url): # def reload_curr_tab(): # def get_curr_tab_html(): # def close_curr_tab(): # def get_number_of_tabs(): # def get_curr_tab_title(): # def get_tab_list(): . Output only the next line.
A command line program for manipulating Firefox tabs.
Using the snippet: <|code_start|>#!/usr/bin/env python3 """ print the content of the clipboard to the standard output Last update: 2017-01-08 (yyyy-mm-dd) """ fs.check_if_available(cfg.XSEL, "Error: {} is not available!".format(cfg.XSEL)) def print_help(): print(""" Usage: {0} [options] <|code_end|> , determine the next line of code. You have imports: import sys import config as cfg from lib import clipboard as cb from lib import fs from pathlib import Path and context (class names, function names, or code) available: # Path: lib/clipboard.py # def text_to_clipboards(text): # def to_primary(text): # def to_clipboard(text): # def read_primary(): # def read_clipboard(): # def clear_both_clipboards(): # def clear_primary(): # def clear_clipboard(): # # Path: lib/fs.py # def check_if_available(prg, msg): . Output only the next line.
Options:
Here is a snippet: <|code_start|>#!/usr/bin/env python3 """ print the content of the clipboard to the standard output Last update: 2017-01-08 (yyyy-mm-dd) """ fs.check_if_available(cfg.XSEL, "Error: {} is not available!".format(cfg.XSEL)) def print_help(): print(""" Usage: {0} [options] Options: -h, --help this help -1 read from primary clipboard (default) <|code_end|> . Write the next line using the current file imports: import sys import config as cfg from lib import clipboard as cb from lib import fs from pathlib import Path and context from other files: # Path: lib/clipboard.py # def text_to_clipboards(text): # def to_primary(text): # def to_clipboard(text): # def read_primary(): # def read_clipboard(): # def clear_both_clipboards(): # def clear_primary(): # def clear_clipboard(): # # Path: lib/fs.py # def check_if_available(prg, msg): , which may include functions, classes, or code. Output only the next line.
-2 read from secondary clipboard
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python3 """ A simple script that changes the character encoding of the input file to UTF-8. The result is printed to the screen. Last update: 2017-12-16 (yyyy-mm-dd) """ fs.check_if_available(cfg.FILE, "Error: {} is not available!".format(cfg.FILE)) fs.check_if_available(cfg.ICONV, "Error: {} is not available!".format(cfg.ICONV)) force_conversion = False def print_help(): p = Path(sys.argv[0]) print(""" Usage: {0} input.txt [-f] [-h|--help] <|code_end|> using the current file's imports: import os import sys import config as cfg from pathlib import Path from lib import fs from lib.process import get_simple_cmd_output and any relevant context from other files: # Path: lib/fs.py # def check_if_available(prg, msg): # # Path: lib/process.py # def get_simple_cmd_output(cmd, stderr=STDOUT): # """Execute a simple external command and get its output. # # The command contains no pipes. Error messages are # redirected to the standard output by default. # """ # args = shlex.split(cmd) # return Popen(args, stdout=PIPE, stderr=stderr).communicate()[0].decode("utf8") . Output only the next line.
-f force conversion (even if the input is in UTF-8)
Given the code snippet: <|code_start|>#!/usr/bin/env python3 """ A simple script that changes the character encoding of the input file to UTF-8. The result is printed to the screen. Last update: 2017-12-16 (yyyy-mm-dd) """ fs.check_if_available(cfg.FILE, "Error: {} is not available!".format(cfg.FILE)) fs.check_if_available(cfg.ICONV, "Error: {} is not available!".format(cfg.ICONV)) force_conversion = False def print_help(): p = Path(sys.argv[0]) print(""" Usage: {0} input.txt [-f] [-h|--help] -f force conversion (even if the input is in UTF-8) <|code_end|> , generate the next line using the imports in this file: import os import sys import config as cfg from pathlib import Path from lib import fs from lib.process import get_simple_cmd_output and context (functions, classes, or occasionally code) from other files: # Path: lib/fs.py # def check_if_available(prg, msg): # # Path: lib/process.py # def get_simple_cmd_output(cmd, stderr=STDOUT): # """Execute a simple external command and get its output. # # The command contains no pipes. Error messages are # redirected to the standard output by default. # """ # args = shlex.split(cmd) # return Popen(args, stdout=PIPE, stderr=stderr).communicate()[0].decode("utf8") . Output only the next line.
-h, --help this help
Based on the snippet: <|code_start|> return name + 'text' @web.resource def chat(self, room: str): return Chat(room) class Chat(web.Resource): def __init__(self, room): self.room = room @web.endpoint def publish(self, u: User, message: str): return '[{}] {}: {}'.format(self.room, u.id, message) @web.endpoint def get_messages(self): return [self.room + '1', self.room + '2'] self.Root = Root class TestWsock(TestBase): def setUp(self): super().setUp() self.web = web.Websockets(resources=[self.Root()]) def resolve(self, *args): <|code_end|> , predict the immediate next line with the help of imports: import unittest import json import logging from time import time from functools import wraps from collections import namedtuple from zorro import web and context (classes, functions, sometimes code) from other files: # Path: zorro/web.py # _LEAF_METHOD = marker_object('LEAF_METHOD') # _LEAF_WSOCK_METHOD = marker_object('LEAF_WSOCK_METHOD') # _LEAF_HTTP_METHOD = marker_object('LEAF_HTTP_METHOD') # _RESOURCE_METHOD = marker_object('RESOURCE_METHOD') # _RES_WSOCK_METHOD = marker_object('RES_WSOCK_METHOD') # _RES_HTTP_METHOD = marker_object('RES_HTTP_METHOD') # _RESOURCE = marker_object('RESOURCE') # _INTERRUPT = marker_object('INTERRUPT') # _FORM_CTYPE = b'application/x-www-form-urlencoded' # _LEAF_METHODS = {_LEAF_METHOD} # _RES_METHODS = {_RESOURCE_METHOD} # _LEAF_METHODS = {_LEAF_METHOD, _LEAF_HTTP_METHOD} # _RES_METHODS = {_RESOURCE_METHOD, _RES_HTTP_METHOD} # _LEAF_METHODS = {_LEAF_METHOD, _LEAF_HTTP_METHOD} # _RES_METHODS = {_RESOURCE_METHOD, _RES_HTTP_METHOD} # _LEAF_METHODS = {_LEAF_METHOD, _LEAF_WSOCK_METHOD} # _RES_METHODS = {_RESOURCE_METHOD, _RES_WSOCK_METHOD} # MESSAGE = 'message' # CONNECT = 'connect' # DISCONNECT = 'disconnect' # HEARTBEAT = 'heartbeat' # SYNC = 'sync' # class LegacyMultiDict(object): # class Request(object): # class WebException(Exception): # class Forbidden(WebException): # class InternalError(WebException): # class NotFound(WebException): # class MethodNotAllowed(WebException): # class Redirect(WebException): # class CompletionRedirect(Redirect): # class ChildNotFound(Exception): # class NiceError(Exception): # class BaseResolver(metaclass=abc.ABCMeta): # class PathResolver(BaseResolver): # class MethodResolver(BaseResolver): # class WebsockResolver(BaseResolver): # class InternalRedirect(Exception, metaclass=abc.ABCMeta): # class PathRewrite(InternalRedirect): # class ResourceInterface(metaclass=abc.ABCMeta): # class Resource(object): # class DictResource(dict): # class Site(object): # class ReprHack(str): # class Sticker(metaclass=abc.ABCMeta): # class WebsockCall(object): # class Websockets(object): # def __init__(self, pairs=None): # def update(self, pairs): # def getlist(self, k): # def __contains__(self, k): # def __iter__(self): # def __len__(self): # def parsed_uri(self): # def form_arguments(self): # def legacy_arguments(self): # def cookies(self): # def create(cls, resolver): # def default_response(self): # def default_response(self): # def default_response(self): # def default_response(self): # def default_response(self): # def __init__(self, location, status_code, status_text): # def location_header(self): # def headers(self): # def default_response(self): # def __init__(self, location, cookie=None, *, # status_code=303, status_text="See Other"): # def headers(self): # def __init__(self, request, parent=None): # def __next__(self): # def __iter__(self): # def child_fallback(self): # def set_args(self, args): # def resolve(self, root): # def __init__(self, request, parent=None): # def __next__(self): # def set_args(self, args): # def __init__(self, request, parent=None): # def __next__(self): # def child_fallback(self): # def set_args(self, args): # def __init__(self, request, parent=None): # def __next__(self): # def set_args(self, args): # def update_request(self, request): # def __init__(self, new_path): # def update_request(self, request): # def resolve_local(self, name): # def resolve_local(self, name): # def resolve_local(self, name): # def __init__(self, *, request_class, resources=()): # def _resolve(self, request): # def _safe_dispatch(self, request): # def error_page(self, e): # def __call__(self, *args): # def _dispatch_resource(fun, self, resolver): # def __repr__(self): # def _compile_signature(fun, partial): # def resource(fun): # def http_resource(fun): # def websock_resource(fun): # def _dispatch_leaf(fun, self, resolver): # def endpoint(fun): # def page(fun): # def method(fun): # def postprocessor(fun): # def wrapper(proc): # def preprocessor(fun): # def wrapper(proc): # def decorator(fun): # def wrapper(parser): # def callee(self, resolver, *args, **kw): # def callee(self, resolver, *args, **kw): # def create(cls, resolver): # def supersede(cls, sub): # def __init__(self, msgs): # def _init_message(self, cid, body): # def _init_msgfrom(self, cid, cookie, body): # def _init_connect(self, cid): # def _init_disconnect(self, cid, cookie=None): # def _init_heartbeat(self, server_id): # def _init_sync(self, server_id, *users): # def create(cls, resolver): # def __init__(self, *, resources=(), output=None): # def _resolve(self, request): # def _safe_dispatch(self, request): # def __call__(self, *args): . Output only the next line.
data = json.dumps((args[0], {},) + args[1:]).encode('utf-8')
Given the code snippet: <|code_start|> return list(self._dic[k]) def __contains__(self, k): return k in self._dic def __iter__(self): for k in self._dic: yield k def __len__(self): return len(self._dic) class Request(object): __slots__ = ('__dict__', # the excpected property names and names of respective zerogw items 'uri', # !Uri 'content_type', # !Header Content-Type 'cookie', # !Header Cookie 'body', # !PostBody ) @cached_property def parsed_uri(self): return urlparse(self.uri.decode('ascii')) @cached_property def form_arguments(self): arguments = {} if hasattr(self, 'uri'): <|code_end|> , generate the next line using the imports in this file: import abc import json import logging import inspect from http.cookies import SimpleCookie from urllib.parse import urlparse, parse_qsl from itertools import zip_longest from functools import partial from .util import cached_property, marker_object and context (functions, classes, or occasionally code) from other files: # Path: zorro/util.py # class cached_property(object): # # def __init__(self, fun): # self.function = fun # self.name = fun.__name__ # # def __get__(self, obj, cls): # if obj is None: # return self # res = obj.__dict__[self.name] = self.function(obj) # return res # # class marker_object(object): # __slots__ = ('name',) # # def __init__(self, name): # self.name = name # # def __repr__(self): # return '<{}>'.format(self.name) . Output only the next line.
arguments.update(parse_qsl(self.parsed_uri.query))
Predict the next line after this snippet: <|code_start|> def getlist(self, k): return list(self._dic[k]) def __contains__(self, k): return k in self._dic def __iter__(self): for k in self._dic: yield k def __len__(self): return len(self._dic) class Request(object): __slots__ = ('__dict__', # the excpected property names and names of respective zerogw items 'uri', # !Uri 'content_type', # !Header Content-Type 'cookie', # !Header Cookie 'body', # !PostBody ) @cached_property def parsed_uri(self): return urlparse(self.uri.decode('ascii')) @cached_property def form_arguments(self): arguments = {} <|code_end|> using the current file's imports: import abc import json import logging import inspect from http.cookies import SimpleCookie from urllib.parse import urlparse, parse_qsl from itertools import zip_longest from functools import partial from .util import cached_property, marker_object and any relevant context from other files: # Path: zorro/util.py # class cached_property(object): # # def __init__(self, fun): # self.function = fun # self.name = fun.__name__ # # def __get__(self, obj, cls): # if obj is None: # return self # res = obj.__dict__[self.name] = self.function(obj) # return res # # class marker_object(object): # __slots__ = ('name',) # # def __init__(self, name): # self.name = name # # def __repr__(self): # return '<{}>'.format(self.name) . Output only the next line.
if hasattr(self, 'uri'):
Using the snippet: <|code_start|> self.query_data({'hello': 'world'})) self.assertEqual([ {'hello': 'world'}, {'hello': 'anyone'}, ], self.query_data({})) @passive def test_update(self): self.c.clean() self.c.insert({'test1': 1}) self.assertEqual([{'test1': 1}], self.query_data({'test1': 1})) self.c.update({'test1': 1}, {'test1': 2}) self.assertEqual([], self.query_data({'test1': 1})) self.assertEqual([{'test1': 2}], self.query_data({'test1': 2})) @passive def test_save(self): self.c.clean() self.c.insert({'test1': 1}) doc = list(self.c.query({'test1': 1}))[0] doc['test1'] = 3 self.c.save(doc) self.assertEqual([{'test1': 3}], self.query_data({})) if __name__ == '__main__': <|code_end|> , determine the next line of code. You have imports: import socket import zorro.mongodb import unittest from functools import partial from .base import Test, passive and context (class names, function names, or code) available: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping . Output only the next line.
unittest.main()
Using the snippet: <|code_start|> def setUp(self): super().setUp() self.m = zorro.mongodb.Connection() self.c = self.m['test']['test_collection'] def query_data(self, *args, **kw): lst = list(self.c.query(*args, **kw)) for i in lst: i.pop('_id') return lst class Simple(Mongodb): @passive def test_basic(self): self.c.clean() self.c.insert({'hello': 'world'}) self.assertEqual([{'hello': 'world'}], self.query_data({'hello': 'world'})) @passive def test_disconnect(self): self.c.clean() self.c.insert({'hello': 'world'}) fut1 = self.z.Future(partial(self.query_data, {'hello': 'world'})) fut2 = self.z.Future(partial(self.query_data, {'hello': 'world'})) self.c._conn._channel._sock.shutdown(socket.SHUT_RDWR) self.z.sleep(0.01) with self.assertRaises(self.z.channel.PipeError): fut1.get() <|code_end|> , determine the next line of code. You have imports: import socket import zorro.mongodb import unittest from functools import partial from .base import Test, passive and context (class names, function names, or code) available: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping . Output only the next line.
with self.assertRaises(self.z.channel.PipeError):
Given the following code snippet before the placeholder: <|code_start|> self.hub.do_spawn(lambda: f.set('hello')) self.assertEquals(f.get(), 'hello') @passive def test_future_user_to(self): f = self.z.Future() self.hub.do_spawn(lambda: (self.z.sleep(0.1), f.set('hello'))) self.assertEquals(f.get(), 'hello') @passive def test_condition(self): cond = self.z.Condition() r = [] self.hub.do_spawn( lambda: (r.append('hello'), cond.notify())) cond.wait() self.assertEquals(r, ['hello']) @passive def test_both(self): cond = self.z.Condition() f = self.z.Future() self.hub.do_spawn( lambda: (f.set('hello'), cond.notify())) self.assertEquals(f._value , self.z.core.FUTURE_PENDING) cond.wait() self.assertEquals(f._value, 'hello') @passive def test_condition_timeo(self): <|code_end|> , predict the next line using imports from the current file: from .base import Test, passive import unittest and context including class names, function names, and sometimes code from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping . Output only the next line.
cond = self.z.Condition()
Here is a snippet: <|code_start|> class Core(Test): test_timeout = 0.25 @passive def test_future_cb_simple(self): f = self.z.Future(lambda:123) self.assertEquals(f.get(), 123) @passive def test_future_cb_to(self): f = self.z.Future(lambda:(self.z.sleep(0.1),234)) self.assertEquals(f.get(), (None, 234)) @passive def test_future_timeo_ok(self): f = self.z.Future(lambda:(self.z.sleep(0.1),234)) self.assertEquals(f.get(timeout=0.2), (None, 234)) @passive <|code_end|> . Write the next line using the current file imports: from .base import Test, passive import unittest and context from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping , which may include functions, classes, or code. Output only the next line.
def test_future_timeo_raised(self):
Predict the next line for this snippet: <|code_start|> self.wfile.flush() def do_FETCH(self): self.send_response(200) self.send_header('Transfer-Encoding', 'chunked') self.end_headers() self.wfile.write(b'5\r\nHELLO\r\n0\r\n\r\n') self.wfile.flush() class Simple(Test): def do_request(self): self.z.sleep(0.1) cli = self.z.http.HTTPSClient('localhost', 9997) self.got_value = cli.request('/').body @interactive(do_request) def test_req(self): srv = HTTPSServer(('localhost', 9997), RequestHandler) srv.handle_request() self.thread.join(1) self.assertEqual(self.got_value, b'HELLO') def do_fetch(self): self.z.sleep(0.1) cli = self.z.http.HTTPSClient('localhost', 9997) self.fetched_value = cli.request('/', method='FETCH').body @interactive(do_fetch) <|code_end|> with the help of current file imports: import os.path import time import ssl import socket import zorro.http import zorro.http import zorro.http import unittest from socketserver import BaseServer from http.server import HTTPServer, BaseHTTPRequestHandler from .base import Test, interactive and context from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def interactive(zfun): # def wrapper(fun): # @wraps(fun) # def wrapping(self, *a, **kw): # self.hub.add_task(partial(zfun, self, *a, **kw)) # self.thread.start() # fun(self, *a, **kw) # return wrapping # return wrapper , which may contain function names, class names, or code. Output only the next line.
def test_fetch(self):
Given the following code snippet before the placeholder: <|code_start|> self.m = zorro.mysql.Mysql() class Simple(Mysql): @passive def test_basic(self): self.m.execute('drop table if exists test') self.m.execute('create table test (id int)') self.assertEqual(self.m.execute( 'insert into test values (10)'), (0, 1)) self.assertEqual(self.m.execute( 'insert into test values (30),(40)'), (0, 2)) @passive def test_select(self): self.m.execute('drop table if exists test') self.m.execute('create table test (id int, val varchar(10))') self.assertEqual(self.m.execute( 'insert into test values (10, "11")'), (0, 1)) self.assertEqual(set(self.m.query('select * from test').tuples()), set([(10, "11")])) self.assertEqual(list(self.m.query('select * from test').dicts())[0], {'id': 10, 'val': "11"}) @passive def test_nulls(self): self.m.execute('drop table if exists test') self.m.execute('create table test (id int)') self.assertEqual(self.m.execute_prepared('insert into test values (?)' <|code_end|> , predict the next line using imports from the current file: import socket import unittest import datetime import zorro.mysql from functools import partial from .base import Test, passive from zorro.mysql import Formatter from zorro.mysql import Formatter from datetime import date, time, datetime, timedelta from zorro.mysql import Formatter and context including class names, function names, and sometimes code from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping . Output only the next line.
+ ',(?)'*24, *((1,)+(None,)*24)), (0, 25))
Based on the snippet: <|code_start|> ]), ['OK', 11, 1]) @passive def test_keys(self): self.r.execute('DEL', 'test:big') self.assertEqual(self.r.execute('SET', 'test:key1', 'value'), 'OK') self.assertEqual(self.r.execute('SET', 'test:key2', 'value'), 'OK') self.assertEqual(set(map(bytes, self.r.execute('KEYS', '*'))), set([b'test:key1', b'test:key2'])) val = self.r.bulk([('MULTI',), ('GET', 'test:key1'), ('MGET', 'test:key1', 'test:key2'), ('KEYS', '*'), ('EXEC',)]) self.assertEqual(val[0], b'value') self.assertEqual(val[1], [b'value', b'value']) self.assertSetEqual(set(map(bytes, val[2])), set([b'test:key1', b'test:key2'])) self.assertEquals(self.r.execute('DEL', 'test:key1'), 1) self.assertEquals(self.r.execute('DEL', 'test:key2'), 1) class BigTest(Redis): test_timeout = 10 @passive def test_time(self): def get100(): for i in range(100): self.r.execute('GET', 'test:key1') <|code_end|> , predict the immediate next line with the help of imports: import socket import zorro.redis import time import unittest from .base import Test, passive and context (classes, functions, sometimes code) from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping . Output only the next line.
old = time.time()
Predict the next line after this snippet: <|code_start|> def test_bulk(self): self.assertEquals(self.r.bulk([ ('MULTI',), ('SET', 'test:key1', '10'), ('INCR', 'test:key1'), ('DEL', 'test:key1'), ('EXEC',), ]), ['OK', 11, 1]) @passive def test_keys(self): self.r.execute('DEL', 'test:big') self.assertEqual(self.r.execute('SET', 'test:key1', 'value'), 'OK') self.assertEqual(self.r.execute('SET', 'test:key2', 'value'), 'OK') self.assertEqual(set(map(bytes, self.r.execute('KEYS', '*'))), set([b'test:key1', b'test:key2'])) val = self.r.bulk([('MULTI',), ('GET', 'test:key1'), ('MGET', 'test:key1', 'test:key2'), ('KEYS', '*'), ('EXEC',)]) self.assertEqual(val[0], b'value') self.assertEqual(val[1], [b'value', b'value']) self.assertSetEqual(set(map(bytes, val[2])), set([b'test:key1', b'test:key2'])) self.assertEquals(self.r.execute('DEL', 'test:key1'), 1) self.assertEquals(self.r.execute('DEL', 'test:key2'), 1) class BigTest(Redis): <|code_end|> using the current file's imports: import socket import zorro.redis import time import unittest from .base import Test, passive and any relevant context from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def passive(zfun): # @wraps(zfun) # def wrapping(self, *a, **kw): # exc = [] # def catch(): # try: # zfun(self, *a, **kw) # except BaseException as e: # exc.append(e) # self.hub.add_task(catch) # self.thread.start() # try: # self.thread.join(self.test_timeout) # finally: # if exc: # raise exc[0] # return wrapping . Output only the next line.
test_timeout = 10
Predict the next line after this snippet: <|code_start|> class Unix(PipelinedReqChannel): BUFSIZE = 1024 def __init__(self, unixsock='/var/run/collectd-unixsock'): self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self._sock.setblocking(0) self._cur_producing = [] self._todo = 0 try: self._sock.connect(unixsock) except socket.error as e: if e.errno == errno.EINPROGRESS: gethub().do_write(self._sock) else: raise super().__init__() self._start() def produce(self, line): if self._todo: self._cur_producing.append(line) self._todo -= 1 else: num, tail = line.split(b' ', 1) lines = int(num) self._todo = lines self._cur_producing.append(line) if not self._todo: <|code_end|> using the current file's imports: import socket import errno from time import time as current_time from .core import gethub, Lock, Future from .channel import PipelinedReqChannel and any relevant context from other files: # Path: zorro/core.py # def gethub(): # let = greenlet.getcurrent() # return let.hub # # class Lock(Condition): # def __init__(self): # super().__init__() # self._locked = False # # def acquire(self): # while self._locked: # self.wait() # self._locked = True # # def release(self): # self._locked = False # self.notify() # # def __enter__(self): # self.acquire() # # def __exit__(self, exc_type, exc_value, exc_tb): # self.release() # # class Future(object): # def __init__(self, fun=None): # self._listeners = [] # self._value = FUTURE_PENDING # if fun is not None: # def future(): # try: # result = fun() # except Exception as e: # self.throw(e) # else: # self.set(result) # gethub().do_spawn(future) # # def get(self, timeout=None): # val = self._value # if val is not FUTURE_PENDING: # if val is FUTURE_EXCEPTION: # raise self._exception # else: # return val # cur = greenlet.getcurrent() # cur.cleanup.append(self._listeners.remove) # self._listeners.append(cur) # hub = cur.hub # if timeout is not None: # targ = time.time() + timeout # cur.cleanup.append(hub._timeouts.add(targ, cur)) # del cur # no cycles # hub._self.switch() # val = self._value # if val is FUTURE_PENDING: # raise TimeoutError() # if val is FUTURE_EXCEPTION: # raise self._exception # else: # return val # # def set(self, value): # if self._value is not FUTURE_PENDING: # raise RuntimeError("Value is already set") # self._value = value # lst = self._listeners # del self._listeners # hub = gethub() # for one in lst: # hub.queue_task(one) # # def throw(self, exception): # self._value = FUTURE_EXCEPTION # self._exception = exception # lst = self._listeners # del self._listeners # for one in lst: # gethub().queue_task(one) # # def check(self): # return self._value is FUTURE_PENDING # # Path: zorro/channel.py # class PipelinedReqChannel(BaseChannel): # # def __init__(self): # super().__init__() # self._producing = deque() # self._cur_producing = [] # # def _stop_producing(self): # prod = self._producing # del self._producing # for num, fut in prod: # fut.throw(PipeError()) # self._cond.notify() # wake up consumer if it waits for messages # # def produce(self, value): # if not self._alive: # raise ShutdownException() # val = self._cur_producing.append(value) # num = self._producing[0][0] # if num is None: # del self._cur_producing[:] # self._producing.popleft()[1].set(value) # elif len(self._cur_producing) >= num: # res = tuple(self._cur_producing) # del self._cur_producing[:] # self._producing.popleft()[1].set(res) # else: # return # # def request(self, input, num_output=None): # if not self._alive: # raise PipeError() # val = Future() # self._pending.append(input) # self._producing.append((num_output, val)) # self._cond.notify() # return val # # def push(self, input): # """For requests which do not need an answer""" # self._pending.append(input) # self._cond.notify() . Output only the next line.
res = tuple(self._cur_producing)
Continue the code snippet: <|code_start|> elif e.errno in (errno.EPIPE, errno.ECONNRESET): raise EOFError() else: raise while True: idx = buf.find(b'\n', pos) if idx < 0: break line = buf[pos:idx] self.produce(line) pos = idx + 1 class Connection(object): def __init__(self, unixsock='/var/run/collectd-unixsock'): # TODO(tailhook) self.unixsock = unixsock self._channel = None self._channel_lock = Lock() def channel(self): if not self._channel: with self._channel_lock: if not self._channel: self._channel = Unix(unixsock=self.unixsock) return self._channel def putval(self, identifier, values, interval=None, time=None): return self.putval_future(identifier, values, <|code_end|> . Use current file imports: import socket import errno from time import time as current_time from .core import gethub, Lock, Future from .channel import PipelinedReqChannel and context (classes, functions, or code) from other files: # Path: zorro/core.py # def gethub(): # let = greenlet.getcurrent() # return let.hub # # class Lock(Condition): # def __init__(self): # super().__init__() # self._locked = False # # def acquire(self): # while self._locked: # self.wait() # self._locked = True # # def release(self): # self._locked = False # self.notify() # # def __enter__(self): # self.acquire() # # def __exit__(self, exc_type, exc_value, exc_tb): # self.release() # # class Future(object): # def __init__(self, fun=None): # self._listeners = [] # self._value = FUTURE_PENDING # if fun is not None: # def future(): # try: # result = fun() # except Exception as e: # self.throw(e) # else: # self.set(result) # gethub().do_spawn(future) # # def get(self, timeout=None): # val = self._value # if val is not FUTURE_PENDING: # if val is FUTURE_EXCEPTION: # raise self._exception # else: # return val # cur = greenlet.getcurrent() # cur.cleanup.append(self._listeners.remove) # self._listeners.append(cur) # hub = cur.hub # if timeout is not None: # targ = time.time() + timeout # cur.cleanup.append(hub._timeouts.add(targ, cur)) # del cur # no cycles # hub._self.switch() # val = self._value # if val is FUTURE_PENDING: # raise TimeoutError() # if val is FUTURE_EXCEPTION: # raise self._exception # else: # return val # # def set(self, value): # if self._value is not FUTURE_PENDING: # raise RuntimeError("Value is already set") # self._value = value # lst = self._listeners # del self._listeners # hub = gethub() # for one in lst: # hub.queue_task(one) # # def throw(self, exception): # self._value = FUTURE_EXCEPTION # self._exception = exception # lst = self._listeners # del self._listeners # for one in lst: # gethub().queue_task(one) # # def check(self): # return self._value is FUTURE_PENDING # # Path: zorro/channel.py # class PipelinedReqChannel(BaseChannel): # # def __init__(self): # super().__init__() # self._producing = deque() # self._cur_producing = [] # # def _stop_producing(self): # prod = self._producing # del self._producing # for num, fut in prod: # fut.throw(PipeError()) # self._cond.notify() # wake up consumer if it waits for messages # # def produce(self, value): # if not self._alive: # raise ShutdownException() # val = self._cur_producing.append(value) # num = self._producing[0][0] # if num is None: # del self._cur_producing[:] # self._producing.popleft()[1].set(value) # elif len(self._cur_producing) >= num: # res = tuple(self._cur_producing) # del self._cur_producing[:] # self._producing.popleft()[1].set(res) # else: # return # # def request(self, input, num_output=None): # if not self._alive: # raise PipeError() # val = Future() # self._pending.append(input) # self._producing.append((num_output, val)) # self._cond.notify() # return val # # def push(self, input): # """For requests which do not need an answer""" # self._pending.append(input) # self._cond.notify() . Output only the next line.
interval=interval, time=time).get()
Next line prediction: <|code_start|> def channel(self): if not self._channel: with self._channel_lock: if not self._channel: self._channel = Unix(unixsock=self.unixsock) return self._channel def putval(self, identifier, values, interval=None, time=None): return self.putval_future(identifier, values, interval=interval, time=time).get() def putval_future(self, identifier, values, interval=None, time=None): buf = bytearray(b'PUTVAL ') buf += identifier.encode('ascii') if interval is not None: buf += ' interval={0:d}'.format(interval).encode('ascii') for tup in values: if time is None: time = current_time() lst = [str(int(time))] for val in tup: if val is None: lst.append('U') else: lst.append(str(float(val))) buf += b' ' buf += ':'.join(lst).encode('ascii') return self.channel().request(buf) <|code_end|> . Use current file imports: (import socket import errno from time import time as current_time from .core import gethub, Lock, Future from .channel import PipelinedReqChannel) and context including class names, function names, or small code snippets from other files: # Path: zorro/core.py # def gethub(): # let = greenlet.getcurrent() # return let.hub # # class Lock(Condition): # def __init__(self): # super().__init__() # self._locked = False # # def acquire(self): # while self._locked: # self.wait() # self._locked = True # # def release(self): # self._locked = False # self.notify() # # def __enter__(self): # self.acquire() # # def __exit__(self, exc_type, exc_value, exc_tb): # self.release() # # class Future(object): # def __init__(self, fun=None): # self._listeners = [] # self._value = FUTURE_PENDING # if fun is not None: # def future(): # try: # result = fun() # except Exception as e: # self.throw(e) # else: # self.set(result) # gethub().do_spawn(future) # # def get(self, timeout=None): # val = self._value # if val is not FUTURE_PENDING: # if val is FUTURE_EXCEPTION: # raise self._exception # else: # return val # cur = greenlet.getcurrent() # cur.cleanup.append(self._listeners.remove) # self._listeners.append(cur) # hub = cur.hub # if timeout is not None: # targ = time.time() + timeout # cur.cleanup.append(hub._timeouts.add(targ, cur)) # del cur # no cycles # hub._self.switch() # val = self._value # if val is FUTURE_PENDING: # raise TimeoutError() # if val is FUTURE_EXCEPTION: # raise self._exception # else: # return val # # def set(self, value): # if self._value is not FUTURE_PENDING: # raise RuntimeError("Value is already set") # self._value = value # lst = self._listeners # del self._listeners # hub = gethub() # for one in lst: # hub.queue_task(one) # # def throw(self, exception): # self._value = FUTURE_EXCEPTION # self._exception = exception # lst = self._listeners # del self._listeners # for one in lst: # gethub().queue_task(one) # # def check(self): # return self._value is FUTURE_PENDING # # Path: zorro/channel.py # class PipelinedReqChannel(BaseChannel): # # def __init__(self): # super().__init__() # self._producing = deque() # self._cur_producing = [] # # def _stop_producing(self): # prod = self._producing # del self._producing # for num, fut in prod: # fut.throw(PipeError()) # self._cond.notify() # wake up consumer if it waits for messages # # def produce(self, value): # if not self._alive: # raise ShutdownException() # val = self._cur_producing.append(value) # num = self._producing[0][0] # if num is None: # del self._cur_producing[:] # self._producing.popleft()[1].set(value) # elif len(self._cur_producing) >= num: # res = tuple(self._cur_producing) # del self._cur_producing[:] # self._producing.popleft()[1].set(res) # else: # return # # def request(self, input, num_output=None): # if not self._alive: # raise PipeError() # val = Future() # self._pending.append(input) # self._producing.append((num_output, val)) # self._cond.notify() # return val # # def push(self, input): # """For requests which do not need an answer""" # self._pending.append(input) # self._cond.notify() . Output only the next line.
def flush(self, timeout=None, plugin=None, identifier=None):
Predict the next line for this snippet: <|code_start|> self.send_response(200) self.send_header('Transfer-Encoding', 'chunked') self.end_headers() self.wfile.write(b'5\r\nHELLO\r\n0\r\n\r\n') self.wfile.flush() class Simple(Test): def do_request(self): self.z.sleep(0.1) cli = self.z.http.HTTPClient('localhost', 9997) self.got_value = cli.request('/').body @interactive(do_request) def test_req(self): srv = http.server.HTTPServer(('localhost', 9997), RequestHandler) srv.handle_request() self.thread.join(1) self.assertEqual(self.got_value, b'HELLO') def do_fetch(self): self.z.sleep(0.1) cli = self.z.http.HTTPClient('localhost', 9997) self.fetched_value = cli.request('/', method='FETCH').body @interactive(do_fetch) def test_fetch(self): srv = http.server.HTTPServer(('localhost', 9997), RequestHandler) srv.handle_request() <|code_end|> with the help of current file imports: import time import http.server import zorro.http import zorro.http import unittest from .base import Test, interactive and context from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def interactive(zfun): # def wrapper(fun): # @wraps(fun) # def wrapping(self, *a, **kw): # self.hub.add_task(partial(zfun, self, *a, **kw)) # self.thread.start() # fun(self, *a, **kw) # return wrapping # return wrapper , which may contain function names, class names, or code. Output only the next line.
self.thread.join(1)
Continue the code snippet: <|code_start|> class RequestHandler(http.server.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-Length', '5') self.end_headers() self.wfile.write(b'HELLO') self.wfile.flush() def do_FETCH(self): self.send_response(200) self.send_header('Transfer-Encoding', 'chunked') self.end_headers() self.wfile.write(b'5\r\nHELLO\r\n0\r\n\r\n') <|code_end|> . Use current file imports: import time import http.server import zorro.http import zorro.http import unittest from .base import Test, interactive and context (classes, functions, or code) from other files: # Path: tests/base.py # class Test(unittest.TestCase): # test_timeout = 1 # # def setUp(self): # import zorro # from zorro import zmq # self.z = zorro # self.hub = self.z.Hub() # self.thread = threading.Thread(target=self.hub.run) # # def tearDown(self): # if not self.hub.stopping: # self.hub.stop() # self.thread.join(self.test_timeout) # if self.thread.is_alive(): # try: # if not getattr(self, 'should_timeout', False): # raise AssertionError("test timed out") # finally: # self.hub.crash() # self.thread.join() # for key in list(sys.modules.keys()): # if key == 'zorro' or key.startswith('zorro.'): # del sys.modules[key] # # def interactive(zfun): # def wrapper(fun): # @wraps(fun) # def wrapping(self, *a, **kw): # self.hub.add_task(partial(zfun, self, *a, **kw)) # self.thread.start() # fun(self, *a, **kw) # return wrapping # return wrapper . Output only the next line.
self.wfile.flush()
Next line prediction: <|code_start|> class TestBson(unittest.TestCase): def test_loads(self): data = b"\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00" self.assertEqual({"hello": "world"}, bson.loads(data)) data = (b"1\x00\x00\x00\x04BSON\x00&\x00\x00\x00\x020\x00\x08\x00\x00" b"\x00awesome\x00\x011\x00333333\x14@\x102\x00\xc2\x07\x00" b"\x00\x00\x00") self.assertEqual({"BSON": ["awesome", 5.05, 1986]}, bson.loads(data)) def test_dumps(self): data = {"hello": "world"} coded = b"\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00" self.assertEqual(coded, bson.dumps(data)) coded = (b"1\x00\x00\x00\x04BSON\x00&\x00\x00\x00\x020\x00\x08\x00\x00" b"\x00awesome\x00\x011\x00333333\x14@\x102\x00\xc2\x07\x00" b"\x00\x00\x00") <|code_end|> . Use current file imports: (import unittest from zorro.mongodb import bson) and context including class names, function names, or small code snippets from other files: # Path: zorro/mongodb/bson.py # class ObjectID(bytes): # def __repr__(self): # def _unpack(char): # def register(fun): # def _pack(char, typ): # def register(fun): # def unpack_float(buf, idx): # def unpack_string(buf, idx): # def unpack_document(buf, idx): # def unpack_array(buf, idx): # def unpack_objectid(buf, idx): # def unpack_none(buf, idx): # def unpack_int32(buf, idx): # def unpack_int64(buf, idx): # def loads(s): # def iter_load_from(buf, offset=0): # def pack_float(value, buf): # def pack_string(value, buf): # def pack_document(value, buf): # def pack_array(value, buf): # def pack_objectid(value, buf): # def pack_none(value, buf): # def pack_int(value, buf): # def _pack_doc(pairs, buf): # def dumps(obj): # def dump_extend(buf, obj): # def dump_extend_iter(buf, iterable): . Output only the next line.
data = {"BSON": ["awesome", 5.05, 1986]}
Continue the code snippet: <|code_start|> __all__ = [ 'Zorrolet', 'Hub', 'gethub', 'Future', 'Condition', 'Lock', ] FUTURE_EXCEPTION = marker_object('FUTURE_EXCEPTION') FUTURE_PENDING = marker_object('FUTURE_PENDING') os_errors = (IOError, OSError) class TimeoutError(Exception): pass <|code_end|> . Use current file imports: import heapq import time import threading import select import weakref import logging import errno import greenlet from collections import deque, defaultdict from functools import partial from operator import methodcaller from math import ceil from .util import priorityqueue, orderedset, socket_pair, marker_object and context (classes, functions, or code) from other files: # Path: zorro/util.py # class priorityqueue(object): # # def __init__(self): # self.heap = [] # self.counter = 0 # # def add(self, pri, task): # self.counter += 1 # item = [pri, self.counter, task] # heappush(self.heap, item) # def remover(*a): # item[2] = None # return remover # # def min(self): # while self.heap and self.heap[0][2] is None: # heappop(self.heap) # if self.heap: # return self.heap[0][0] # return None # # def pop(self, value): # val = self.min() # if val is not None and val <= value: # return self.heap[0][2] # return None # # def __bool__(self): # return bool(self.heap) # # class orderedset(object): # # def __init__(self): # self.deque = deque() # # def add(self, *val): # self.deque.append(val) # def remover(*a): # self.deque.remove(val) # return remover # # def update(self, value): # self.deque.extend(value) # # def first(self): # if self.deque: # return self.deque[0] # return None # # def remove(self, value): # self.deque.remove(value) # # def __bool__(self): # return bool(self.deque) # # def socket_pair(): # a, b = socketpair() # a.setblocking(0) # b.setblocking(0) # return a, b # # class marker_object(object): # __slots__ = ('name',) # # def __init__(self, name): # self.name = name # # def __repr__(self): # return '<{}>'.format(self.name) . Output only the next line.
class WaitingError(Exception):