Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|> reload(sys) sys.setdefaultencoding('utf-8') # python manage.py runspider -a url=https://item.jd.com/11478178241.html -a name=jd class JDCommentSpider(Spider): name = 'jd_comment' def __init__(self, name = None, **kwargs): super(JDCommentSpider, self).__init__(na...
proxymng.red = self.red
Here is a snippet: <|code_start|># coding=utf-8 logger = logging.getLogger(__name__) class ProxyMiddleware(object): def process_request(self, request, spider): try: request.meta['req_count'] = request.meta.get('req_count', 0) + 1 if request.meta.get('is_proxy', False): <|code_...
request.meta['proxy'] = proxymng.get_proxy()
Continue the code snippet: <|code_start|> main_data = formatted_data_list else: main_data = data_list else: column = get_object_or_404(DataColumn, id = column_id) main_data = column.get_data() if not encode: return main_data # Encode it in the appropr...
@superuser_only
Given snippet: <|code_start|>#!/usr/bin/python setup_environ(settings) while True: ping_hosts = PingHost.objects.filter(active = True) time.sleep(5) for ping_host in ping_hosts: logging.debug(u"Pinging: " + ping_host.hostname) result = pinger.ping(ping_host.hostname) if result...
p_result = PingResult(min_delay = result[0], avg_delay = result[1], max_delay = result[2], stddev = result[3])
Based on the snippet: <|code_start|>#!/usr/bin/env python filename = './test/test/' if len(sys.argv)>1: filename += sys.argv[1] else: print('Please input filename!') exit(1) <|code_end|> , predict the immediate next line with the help of imports: import sys from pingphp.helper import read from pingphp....
lexer = PingLexer(read(filename))
Based on the snippet: <|code_start|>#!/usr/bin/env python filename = './test/test/' if len(sys.argv)>1: filename += sys.argv[1] else: print('Please input filename!') exit(1) <|code_end|> , predict the immediate next line with the help of imports: import sys from pingphp.helper import read from pingphp....
lexer = PingLexer(read(filename))
Using the snippet: <|code_start|> Returns: np.array: Random rotation matrix ``R``. """ if rng is None: rng = np.random.RandomState(42) assert D >= 2 D = int(D) # make sure that the dimension is an integer # induction start: uniform draw from D=2 Haar measure t = 2 * np.pi *...
class quadratic_deep(_quadratic_base):
Using the snippet: <|code_start|> Return the storage.vars[''] variable that contains the values Parameters ---------- cv : :class:`openpathsampling.netcdf.PseudoAttribute` the objectdict you request the attached variable store template : :obj:`openpathsampling.engines...
ValueStore,
Predict the next line for this snippet: <|code_start|> logging.getLogger('openpathsampling.ensemble').setLevel(logging.CRITICAL) logging.getLogger('openpathsampling.netcdfplus').setLevel(logging.CRITICAL) engine_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "external_...
SnaphotClass = ToySnapshot
Given the following code snippet before the placeholder: <|code_start|> def to_dict(self): out = dict() atom_data = [] for atom in self.mdtraj.atoms: if atom.element is None: element_symbol = "" else: element_symbol = atom.element.symbo...
error_if_no_mdtraj("MDTrajTopology")
Next line prediction: <|code_start|> element_symbol = atom.element.symbol if hasattr(atom, 'segment_id'): atom_data.append(( atom.serial, atom.name, element_symbol, int(atom.residue.resSeq), atom.residue.name, atom.r...
md_topology = md.Topology.from_dataframe(atoms, bonds)
Next line prediction: <|code_start|># REPLICA EXCHANGE GENERATORS ############################################################################### class ReplicaExchangeMover(SampleMover): """ A Sample Mover implementing a standard Replica Exchange """ _is_ensemble_change_mover = True def __init__(s...
initialization_logging(logger=init_log, obj=self,
Given the code snippet: <|code_start|> return list(map(PathReversalMover, ensembles)) class Details(StorableObject): """Details of an object. Can contain any data """ def __init__(self, **kwargs): super(Details, self).__init__() for key, value in kwargs.items(): setattr(sel...
@deprecate(MOVE_DETAILS)
Predict the next line for this snippet: <|code_start|>def PathReversalSet(ensembles): return list(map(PathReversalMover, ensembles)) class Details(StorableObject): """Details of an object. Can contain any data """ def __init__(self, **kwargs): super(Details, self).__init__() for key, ...
@has_deprecations
Given the following code snippet before the placeholder: <|code_start|> def __str__(self): # primarily for debugging/interactive use mystr = "" for key in self.__dict__.keys(): obj = self.__dict__[key] if key in self._print_nothing_keys: pass # do noth...
@deprecate(SAMPLE_DETAILS)
Given the following code snippet before the placeholder: <|code_start|> return list(map(PathReversalMover, ensembles)) class Details(StorableObject): """Details of an object. Can contain any data """ def __init__(self, **kwargs): super(Details, self).__init__() for key, value in kwargs...
@deprecate(MOVE_DETAILS)
Predict the next line after this snippet: <|code_start|> def _build_sample( self, input_sample, shooting_index, trial_trajectory, stopping_reason=None, run_details={} ): # TODO OPS 2.0: the passing of run_details is a hack an...
NEW_SNAPSHOT_KWARG_SELECTOR.warn()
Here is a snippet: <|code_start|> # test uses snapshots with different velocities self.initial_snapshots = [toys.Snapshot( coordinates=np.array([[0.0]]), velocities=np.array([[1.0]]), engine=...
self.simulation = SShootingSimulation(
Based on the snippet: <|code_start|> for subtrj in subtrajectories] # ========================================================================== # UTILITY FUNCTIONS # ========================================================================== def to_mdtraj(self, topology=None): ...
error_if_no_mdtraj("Converting to mdtraj")
Next line prediction: <|code_start|> If not None this topology will be used to construct the mdtraj objects otherwise the topology object will be taken from the configurations in the trajectory snapshots. Returns ------- :class:`mdtraj.Trajectory` ...
traj = md.Trajectory(output, topology)
Given the following code snippet before the placeholder: <|code_start|> """ Returns ------- n_degrees_of_freedom: int number of degrees of freedom in this system (after accounting for constraints) """ return snapshot.engine.n_degrees_of_freedom() @property def instantaneous_tempe...
ke_in_energy = state.getKineticEnergy() / u.AVOGADRO_CONSTANT_NA
Given the following code snippet before the placeholder: <|code_start|> cv_requires_lists=cv_requires_lists, cv_wrap_numpy_array=cv_wrap_numpy_array, cv_scalarize_numpy_singletons=cv_scalarize_numpy_singletons, **kwargs ) self.topology = topology def ...
@has_deprecations
Based on the snippet: <|code_start|> cv_wrap_numpy_array=cv_wrap_numpy_array, cv_scalarize_numpy_singletons=cv_scalarize_numpy_singletons, **kwargs ) self.topology = topology def _eval(self, items): trajectory = paths.Trajectory(items) t = trajec...
@deprecate(MSMBUILDER)
Predict the next line after this snippet: <|code_start|> cv_wrap_numpy_array=cv_wrap_numpy_array, cv_scalarize_numpy_singletons=cv_scalarize_numpy_singletons, **kwargs ) self.topology = topology def _eval(self, items): trajectory = paths.Trajectory(items)...
@deprecate(MSMBUILDER)
Next line prediction: <|code_start|>def interpolate_slice(f3d, rot, pfac=2, size=None): nhalf = f3d.shape[0] / 2 if size is None: phalf = nhalf else: phalf = size / 2 qot = rot * pfac # Scaling! px, py, pz = np.meshgrid(np.arange(-phalf, phalf), np.arange(-phalf, phalf), 0) pr =...
fill_ft(ft, ftc, vol.shape[0], normfft=normfft)
Given the following code snippet before the placeholder: <|code_start|> for r in refs: if args.class_3d is not None: refmap = EMData(r) com = Vec3f(*refmap.phase_cog()[:3]) shifts.append(com) else: stack = EMData.read_images(r) for im in sta...
write_star(args.output, star, reindex=True)
Continue the code snippet: <|code_start|>def sc2dq(theta, d, l, m): q = np.zeros((4,), dtype=np.complex128) theta_half = 0.5 * theta sin_theta_half = np.sin(theta_half) cos_theta_half = np.cos(theta_half) d_half = 0.5 * d q.real[0] = cos_theta_half q.real[:1] = sin_theta_half * l q.imag[...
p0 = cross3_sca(l, m)
Using the snippet: <|code_start|> print("No CTF resolution field found in input") return 1 df = df.loc[ind] if args.max_ctf_fom is not None: ind = df["rlnCtfFigureOfMerit"] <= args.max_ctf_fom df = df.loc[ind] if args.min_ctf_fom is not None: ind = df["rl...
write_star(args.output, df)
Continue the code snippet: <|code_start|> assert arr.ndim == 2 if reference is None: mu0 = np.mean(arr, axis=0, keepdims=True) mu = np.mean(arr) else: mu0 = np.mean(reference, axis=0, keepdims=True) mu = np.mean(reference) mu1 = np.mean(arr, axis=1, keepdims=True) if i...
ninterp = np.round(np.rad2deg(2 * distq(keyq[i], keyq[i + 1])) * steps_per_deg)
Continue the code snippet: <|code_start|> mu0 = np.mean(arr, axis=0, keepdims=True) mu = np.mean(arr) else: mu0 = np.mean(reference, axis=0, keepdims=True) mu = np.mean(reference) mu1 = np.mean(arr, axis=1, keepdims=True) if inplace: arr -= mu0 arr -= mu1 ...
qexp.append(qslerp(keyq[i], keyq[i + 1], t))
Predict the next line after this snippet: <|code_start|> qexp = [] for i in range(0, len(keyq) - 1): ninterp = np.round(np.rad2deg(2 * distq(keyq[i], keyq[i + 1])) * steps_per_deg) for t in np.arange(0, 1, 1 / ninterp): qexp.append(qslerp(keyq[i], keyq[i + 1], t)) qexp.append(keyq...
dq.imag = qtimes(dq.imag, dq.real) * 0.5
Using the snippet: <|code_start|> def isrotation(r, tol=1e-6): """Check for valid rotation matrix""" check = np.identity(3, dtype=r.dtype) - np.dot(r.T, r) if tol is None: return check return np.linalg.norm(check) < tol def qslerp_mult_balanced(keyq, steps_per_deg=10): qexp = [] for i ...
kq = meanq(qarr[mask, :][idx == i, :])
Given the following code snippet before the placeholder: <|code_start|> class TestUnordered: class UnorderedSchema(Schema): name = fields.Str() email = fields.Str() class Meta: ordered = False def test_unordered_dump_returns_dict(self): schema = self.UnorderedSc...
u = User("steve", email="steve@steve.steve")
Based on the snippet: <|code_start|>"""Tests for field serialization.""" class DateTimeList: def __init__(self, dtimes): self.dtimes = dtimes class IntegerList: def __init__(self, ints): self.ints = ints class DateTimeIntegerTuple: def __init__(self, dtime_int): self.dtime_i...
return User("Foo", email="foo@bar.com", age=42)
Predict the next line for this snippet: <|code_start|> 'Elements of "tuple_fields" must be subclasses or ' "instances of marshmallow.base.FieldABC." ) with pytest.raises(ValueError, match=expected_msg): fields.Tuple([ASchema]) def test_serialize_does_not_apply_val...
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
Given the code snippet: <|code_start|> name = fields.Field(data_key="") schema = MySchema() assert schema.dump({"name": "Grace"}) == {"": "Grace"} def test_serialize_with_attribute_and_data_key_uses_data_key(self): class ConfusedDumpToAndAttributeSerializer(Schema): ...
central.localize(dt.datetime(2013, 11, 10, 1, 23, 45), is_dst=False),
Continue the code snippet: <|code_start|> assert result.microseconds == 0 field = fields.TimeDelta(fields.TimeDelta.MINUTES) result = field.deserialize(1441) assert isinstance(result, dt.timedelta) assert result.days == 1 assert result.seconds == 60 assert result....
assert_date_equal(result, d)
Given the code snippet: <|code_start|> ), ( "rfc", central, "Sun, 10 Nov 2013 01:23:45 -0300", dt.datetime(2013, 11, 9, 22, 23, 45), ), ], ) def test_naive_datetime_with_timezone(self, fmt, timezone, value...
assert_time_equal(result, t)
Given the code snippet: <|code_start|> field = fields.DateTime(format="%H:%M:%S.%f %Y-%m-%d") assert field.deserialize(datestring) == dt.datetime( 2019, 1, 2, 10, 11, 12, 123456 ) field = fields.NaiveDateTime(format="%H:%M:%S.%f %Y-%m-%d") assert field.deserialize(dat...
central.localize(dt.datetime(2013, 11, 10, 1, 23, 45), is_dst=False),
Predict the next line after this snippet: <|code_start|> def test_is_keyed_tuple(): Point = namedtuple("Point", ["x", "y"]) p = Point(24, 42) assert utils.is_keyed_tuple(p) is True t = (24, 42) assert utils.is_keyed_tuple(t) is False d = {"x": 42, "y": 24} assert utils.is_keyed_tuple(d) is F...
central.localize(dt.datetime(2013, 11, 10, 1, 23, 45), is_dst=False),
Here is a snippet: <|code_start|> ( "2013-11-10T01:23:45+00:00", dt.datetime(2013, 11, 10, 1, 23, 45, tzinfo=dt.timezone.utc), ), ( # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1251 "2013-11-10T01:23:45.123+00:00", ...
assert_time_equal(result, t)
Predict the next line for this snippet: <|code_start|> ), ], ) def test_from_iso_datetime(value, expected): result = utils.from_iso_datetime(value) assert type(result) == dt.datetime assert result == expected def test_from_iso_time_with_microseconds(): t = dt.time(1, 23, 45, 6789) forma...
assert_date_equal(result, d)
Predict the next line after this snippet: <|code_start|> assert schema2.fields["foo"].value_field.root == schema2 # Regression test for https://github.com/marshmallow-code/marshmallow/issues/1357 def test_datetime_list_inner_format(self, schema): class MySchema(Schema): foo = fields....
@pytest.mark.parametrize("FieldClass", ALL_FIELDS)
Given the code snippet: <|code_start|>"""Pytest fixtures that are available in all test modules.""" @pytest.fixture def user(): return User(name="Monty", age=42.3, homepage="http://monty.python.org/") @pytest.fixture def blog(user): col1 = User(name="Mick", age=123) col2 = User(name="Keith", age=456) ...
return UserSchema().dump(user)
Given the following code snippet before the placeholder: <|code_start|>"""Pytest fixtures that are available in all test modules.""" @pytest.fixture def user(): return User(name="Monty", age=42.3, homepage="http://monty.python.org/") @pytest.fixture def blog(user): col1 = User(name="Mick", age=123) col...
return Blog(
Using the snippet: <|code_start|># FIXME: param _raise ?? def merge(repository, ref, msg='automerge', commit_msg='', no_ff=False, _raise=True, _env=None): # msg, commit_msg makes multiline commit message git = git_with_repo(repository) git_merge = git.bake('merge', ref, no_ff=no_ff) if msg: ...
return format_merge_analysis(analysis)
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # FIXME: param _raise ?? def merge(repository, ref, msg='automerge', commit_msg='', no_ff=False, _raise=True, _env=None): # msg, commit_msg makes multiline commit message git = git_w...
return format_index(index)
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- def list_tags(repository, name_only=None): """git tag command, pygit2 wrapper""" tags = [] refs = repository.listall_references() for ref in refs: if ref.startswith("refs/tags/"): if name_only: ...
tags.append(format_tag(tag_obj, repository))
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- def list_tags(repository, name_only=None): """git tag command, pygit2 wrapper""" tags = [] refs = repository.listall_references() for ref in refs: if ref.startswith("refs/tags/"): if name_only: ...
tags.append(format_lw_tag(ref, tag_obj, repository))
Given the code snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- # from ellen.utils.text import highlight_code # no use yet m = magic._get_magic_type(True) magic.magic_setflags(m.cookie, magic.MAGIC_NONE | magic.MAGIC_NO_CHECK_COMPRESS | ...
func_name = 'format_' + PYGIT2_OBJ_TYPE[obj.type]
Using the snippet: <|code_start|> # return hl_lines res = text res = res.splitlines() #hl_lines = _blame_src_highlighted_lines(ref, path) hl_lines = {} blame = [] rev_data = {} new_block = True for line in res: if new_block: sha, old_no, line_no = line.split()[:...
disp_summary = trunc_utf8(
Next line prediction: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- def blame_(repository, ref, path, lineno=None): """ git blame """ git = git_with_repo(repository) if lineno: cmdstr = ('-L %s,%s --porcelain %s -- %s' % (lineno, lineno, ref, path)) # start == end...
result = format_blame(ret['stdout'], repository)
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- def clone_repository(url, path, bare=None, checkout_branch=None, mirror=None, env=None, shared=None): """git clone command NOTE: 因为`git clone`在本机上直接做硬链接,速度比pygit2.clone_repository快 "...
return git.clone(url, path,
Here is a snippet: <|code_start|>#!/usr/bin/env python # -*- coding: utf-8 -*- def clone_repository(url, path, bare=None, checkout_branch=None, mirror=None, env=None, shared=None): """git clone command NOTE: 因为`git clone`在本机上直接做硬链接,速度比pygit2.clone_repository快 """ return git.clone...
git = git_with_repo(repository)
Continue the code snippet: <|code_start|> except (KeyError, ValueError): from_commit = None if max_count: length = max_count + skip if skip else max_count else: length = 0 for c in walker: if all([_check_author(c, author), _check_file_change(c, pat...
return [format_commit(commits_dict[i], repository)
Next line prediction: <|code_start|> here_dir = os.path.dirname(os.path.abspath(__file__)) ec2_mocker = mock_ec2() _OLD_CONTEXT = [] def setUp(): <|code_end|> . Use current file imports: (import os import boto import loadsbroker.aws from mock import Mock, PropertyMock, patch from moto import mock_ec2 from ...
_OLD_CONTEXT[:] = list(clear_boto_context())
Next line prediction: <|code_start|> here_dir = os.path.dirname(os.path.abspath(__file__)) ec2_mocker = mock_ec2() _OLD_CONTEXT = [] def setUp(): _OLD_CONTEXT[:] = list(clear_boto_context()) ec2_mocker.start() create_image() def tearDown(): ec2_mocker.stop() <|code_end|> . Use current file imports...
load_boto_context(*_OLD_CONTEXT)
Given the following code snippet before the placeholder: <|code_start|> here_dir = os.path.dirname(os.path.abspath(__file__)) ec2_mocker = mock_ec2() _OLD_CONTEXT = [] def setUp(): _OLD_CONTEXT[:] = list(clear_boto_context()) ec2_mocker.start() <|code_end|> , predict the next line using imports from the cur...
create_image()
Predict the next line after this snippet: <|code_start|> class TestRetry(unittest.TestCase): def test_retry_on_result(self): attempts = [] <|code_end|> using the current file's imports: import unittest from operator import not_ from loadsbroker.util import retry and any relevant context from other fi...
@retry(attempts=4, on_result=not_)
Continue the code snippet: <|code_start|> s.seek(0) boto.config.clear() return s.read(), endpoints def load_boto_context(config, endpoints=None): s = StringIO() s.write(config) boto.config.clear() boto.config.read(s) if endpoints is not None: os.environ['BOTO_ENDPOINTS'] = endpo...
for region in AWS_REGIONS:
Predict the next line for this snippet: <|code_start|> ec2_mocker = mock_ec2() _OLD_CONTEXT = [] def setUp(): <|code_end|> with the help of current file imports: import unittest import boto import loadsbroker.aws import loadsbroker.aws import loadsbroker.aws import loadsbroker.aws...
_OLD_CONTEXT[:] = list(clear_boto_context())
Here is a snippet: <|code_start|> ec2_mocker = mock_ec2() _OLD_CONTEXT = [] def setUp(): _OLD_CONTEXT[:] = list(clear_boto_context()) ec2_mocker.start() create_image() def tearDown(): ec2_mocker.stop() <|code_end|> . Write the next line using the current file imports: import unittest import boto...
load_boto_context(*_OLD_CONTEXT)
Continue the code snippet: <|code_start|> ec2_mocker = mock_ec2() _OLD_CONTEXT = [] def setUp(): _OLD_CONTEXT[:] = list(clear_boto_context()) ec2_mocker.start() <|code_end|> . Use current file imports: import unittest import boto import loadsbroker.aws import loadsbroker.aws import...
create_image()
Next line prediction: <|code_start|> # Make vocabulary files char_vocab_file_path = mkdir_join(vocab_file_save_path, 'character.txt') char_capital_vocab_file_path = mkdir_join( vocab_file_save_path, 'character_capital_divide.txt') # Reserve some indices char_set.discard(SPACE) char_set....
char2idx = Char2idx(char_vocab_file_path)
Predict the next line after this snippet: <|code_start|> # Check double-letters skip_flag = False for i in range(1, len(word) - 1, 1): if skip_flag: skip_flag = False continue ...
char_vocab_file_path = mkdir_join(vocab_file_save_path, 'character.txt')
Based on the snippet: <|code_start|> char_set (set): char_capital_set (set): word_count_dict (dict): key => word value => the number of words in Fisher corpus """ print('=====> Processing target labels...') speaker_dict = OrderedDict() char_set, char_capita...
transcript = fix_transcript(transcript_original)
Given the following code snippet before the placeholder: <|code_start|> phone61_list = [] with open(label_path, 'r') as f: for line in f: line = line.strip().split(' ') # start_frame = line[0] # end_frame = line[1] phone61_list....
phone2idx_61 = Phone2idx(phone61_vocab_map_file_path)
Here is a snippet: <|code_start|>def read_phone(label_paths, vocab_file_save_path, save_vocab_file=False, is_test=False): """Read phone transcript. Args: label_paths (list): list of paths to label files vocab_file_save_path (string): path to vocabulary files save_vocab_fil...
phone61_vocab_map_file_path = mkdir_join(
Given snippet: <|code_start|> phone39_vocab_map_file_path = mkdir_join( vocab_file_save_path, 'phone39.txt') # Save mapping file if save_vocab_file: with open(phone61_vocab_map_file_path, 'w') as f: for phone in sorted(list(phone61_set)): f.write('%s\n' % phone) ...
phone48_list = map_phone2phone(phone61_list, 'phone48',
Predict the next line after this snippet: <|code_start|> from __future__ import absolute_import from __future__ import division from __future__ import print_function def split_wav(wav_paths, save_path, speaker_dict): """Read WAV files & divide them with respect to each utterance. Args: wav_paths (lis...
wav_utt_save_path = mkdir_join(save_path, speaker)
Continue the code snippet: <|code_start|>#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function sys.path.append('../../') fisher_path = '/n/sd8/inaguma/corpus/swbd/data/fisher' # Search paths to transcript label_pa...
read_trans(label_paths=label_paths, target_speaker='A')
Given the code snippet: <|code_start|>#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function sys.path.append('../../') fisher_path = '/n/sd8/inaguma/corpus/swbd/data/fisher' # Search paths to transcript label_paths...
@measure_time
Based on the snippet: <|code_start|>parser.add_argument('--energy', type=int, help='if 1, add the energy feature') parser.add_argument('--delta', type=int, help='if 1, add the energy feature') parser.add_argument('--deltadelta', type=int, help='if 1, double delta features are also extracted') parser...
save_path = mkdir_join(
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import from __future__ import division from __future__ import print_function sys.path.append('../') parser = argparse.ArgumentParser() parser.add_argument('--wav_save_path', type=str, help='path to audio files') pa...
htk_save_path = mkdir(args.htk_save_path)
Given the following code snippet before the placeholder: <|code_start|> sys.path.append('../') parser = argparse.ArgumentParser() parser.add_argument('--wav_save_path', type=str, help='path to audio files') parser.add_argument('--htk_save_path', type=str, help='path to save htk files') parser.add_argument('--run_root...
save_config(audio_file_type='wav',
Using the snippet: <|code_start|> # HTK settings save_config(audio_file_type='wav', feature_type=args.feature_type, channels=args.channels, config_save_path='./config', sampling_rate=16000, window=args.window, slide=...
save_path = mkdir_join(
Predict the next line after this snippet: <|code_start|>from __future__ import division from __future__ import print_function sys.path.append('../') parser = argparse.ArgumentParser() parser.add_argument('--data_path', type=str, help='path to Librispeech dataset') parser.add_argument('--htk_save_...
htk_save_path = mkdir(args.htk_save_path)
Next line prediction: <|code_start|> sys.path.append('../') parser = argparse.ArgumentParser() parser.add_argument('--data_path', type=str, help='path to Librispeech dataset') parser.add_argument('--htk_save_path', type=str, help='path to save htk files') parser.add_argument('--feature_type', type...
save_config(audio_file_type='wav',
Predict the next line after this snippet: <|code_start|> rpcServerScript = os.path.abspath(__file__).replace("\\", "/") scriptCmd = "python %s --port=%d --logLevel=%d" %(rpcServerScript, self.port, self.logLevel) self.proc = subprocess.Popen(shlex.split(scriptCmd)) self.__lock.release(); ...
sw1 = self.pyscardRpc.c_transmit(hextools.hex2bytes(POLL_STATUS_PATTERN[self.pattern]),
Using the snippet: <|code_start|>startDir = dir def setupLogger(loggingLevel): if not os.path.exists(resultDir): os.makedirs(resultDir) resultFile = os.path.join(resultDir, "result.txt") # create logger with 'root' logger = logging.getLogger() logger.handlers = [] logger.setLevel(loggin...
sim_router.setLoggerExtHandler(extHandler)
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python # LICENSE: GPL2 # (c) 2015 Kamil Wartanowicz # (c) 2015 Mikolaj Bartnicki sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) class TestAuthentication(unittest.TestCase): def test_1_dummy_xor(self): # input: key ...
result = sim_auth.dummyXorHex(key, rand, sqn, amf, None)
Given the code snippet: <|code_start|> except KeyboardInterrupt: pass class DbusProcess(multiprocessing.Process): def __init__(self, taskQueue, resultQueue): multiprocessing.Process.__init__(self) self.taskQueue = taskQueue self.resultQueue = resultQueue @staticmethod de...
class SessionDBus(dbus.service.Object, sim_shell.SimShell):
Given the code snippet: <|code_start|># coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function patch() class ParserTests(unittest.TestCase): def test_parser(self): <|code_end|> , generate the next line using the imports in this file: import unittest from asn1crypto ...
result = parser.parse(b'\x02\x01\x00')
Given the code snippet: <|code_start|># coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function patch() if sys.version_info < (3,): byte_cls = str else: byte_cls = bytes tests_root = os.path.dirname(__file__) fixtures_dir = os.path.join(tests_root, 'fixtures') cl...
request = ocsp.OCSPRequest.load(f.read())
Based on the snippet: <|code_start|> self.assertEqual( 'successful', response['response_status'].native ) self.assertEqual( 'basic_ocsp_response', response_bytes['response_type'].native ) self.assertEqual( 'sha1_rsa', ...
datetime(2015, 5, 22, 16, 24, 8, tzinfo=util.timezone.utc),
Continue the code snippet: <|code_start|>the following items: - iri_to_uri() - uri_to_iri() """ from __future__ import unicode_literals, division, absolute_import, print_function if sys.version_info < (3,): else: def iri_to_uri(value, normalize=False): """ Encodes a unicode IRI into an ASCII byte stri...
raise TypeError(unwrap(
Given the following code snippet before the placeholder: <|code_start|> tag = 0 while True: if data_len < pointer + 1: raise ValueError(_INSUFFICIENT_DATA_MESSAGE % (1, data_len - pointer)) num = ord(encoded_data[pointer]) if _PY2 else encoded_data[pointer] ...
contents_end = pointer + int_from_bytes(encoded_data[pointer - length_octets:pointer], signed=False)
Given the code snippet: <|code_start|> An integer ASN.1 tag value :param contents: A byte string of the encoded byte contents :return: A byte string of the ASN.1 DER header """ header = b'' id_num = 0 id_num |= class_ << 6 id_num |= method << 5 if tag >= 31: ...
length_bytes = int_to_bytes(length)
Given the code snippet: <|code_start|># coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function patch() if sys.version_info < (3,): py2 = True byte_cls = str num_cls = long # noqa else: py2 = False byte_cls = bytes num_cls = int tests_root = os.pa...
utc = util.timezone.utc
Given the following code snippet before the placeholder: <|code_start|># coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function patch() if sys.version_info < (3,): byte_cls = str num_cls = long # noqa else: byte_cls = bytes num_cls = int tests_root = os.p...
certification_request = csr.CertificationRequest.load(f.read())
Given snippet: <|code_start|> patch() if sys.version_info < (3,): byte_cls = str num_cls = long # noqa else: byte_cls = bytes num_cls = int tests_root = os.path.dirname(__file__) fixtures_dir = os.path.join(tests_root, 'fixtures') class CSRTests(unittest.TestCase): def test_parse_csr(self): ...
util.OrderedDict([
Here is a snippet: <|code_start|> DEFAULTSPACING = 1.0 / 10 class Label(BaseControl): """ Text displayer. @rtype : Label """ def __init__(self, left, top, width, text, parent, pinning=PinningEnum.TopLeft, fontSize=10, fontID='default', color=None, ID=None, imgID=None, ...
style = style or DefaultStyle(color)
Based on the snippet: <|code_start|> filename extension and see if an unpacker was registered for that extension. In case none is found, a ValueError is raised. """ if extract_dir is None: extract_dir = os.getcwd() if format is not None: try: ...
class PluginsManager(BaseManager):
Given snippet: <|code_start|> def __init__(self): super(PluginsManager, self).__init__() self._pluginPaths = {} self._tempPluginPaths = {} self._enabled = {} self._plugins = {} def addPlugin(self, ID, pluginPath, isEnabled=True): if ID in self._pluginPaths.keys():...
plugDesc = PluginDescription.fromDisk(tempDir)
Here is a snippet: <|code_start|> self._plugins[ID] = self._injectPlugin(ID, pluginPath) def removePlugin(self, ID): if ID not in self._pluginPaths.keys(): raise RuntimeError('the specified ID ({}) does not exist.'.format(ID)) self._enabled.pop(ID) self._pluginPaths.pop(I...
return _Plugin(plugDesc, mainClass, pluginPath)
Based on the snippet: <|code_start|> self._pluginPaths = {} self._tempPluginPaths = {} self._enabled = {} self._plugins = {} def addPlugin(self, ID, pluginPath, isEnabled=True): if ID in self._pluginPaths.keys(): raise RuntimeError('the specified ID ({}) already e...
mainFilePath = path.join(tempDir, MAINFILENAME)
Continue the code snippet: <|code_start|> self._plugins = {} def addPlugin(self, ID, pluginPath, isEnabled=True): if ID in self._pluginPaths.keys(): raise RuntimeError('the specified ID ({}) already exist.'.format(ID)) self._pluginPaths[ID] = pluginPath self._enabled[ID] ...
mainClass = getattr(plugin_module, MAINCLASSNAME)(self._engine)
Based on the snippet: <|code_start|> def addPlugin(self, ID, pluginPath, isEnabled=True): if ID in self._pluginPaths.keys(): raise RuntimeError('the specified ID ({}) already exist.'.format(ID)) self._pluginPaths[ID] = pluginPath self._enabled[ID] = isEnabled self._plugin...
if not issubclass(type(mainClass), Runnable):
Using the snippet: <|code_start|> class ColorfullStyle(DefaultStyle): def __init__(self): super(ColorfullStyle, self).__init__(RGB1(.5, 0, .5)) self.name = 'Colorfull' self.baseColor = fromRGB1_A(RED / 2.0 + BLUE, 1) self.borderColor = YELLOW self.borderSize = 3 se...
self.gradientType = GradientTypesEnum.LeftCorner
Given the code snippet: <|code_start|> class SoundsManager(Manager): def __init__(self): """ Keeps references to sounds in use. @rtype : SoundsManager """ super(SoundsManager, self).__init__() self._soundIDs = {} self._lastListenerPosition = vec3(0) ...
sound = Sound(parent, self, filePath, isStream, bufferSize, maxBufferNumber)