Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the code snippet: <|code_start|> vi = [ 6, 'minor' ],
vii = [ 7, 'minor' ],
)
class Literal(object):
def __init__(self):
"""
Constructs an interpreter for specific note names or chords.
It doesn't need to know a scale and is pretty basic.
literal = Literal()
roma... | return chord([]) |
Using the snippet: <|code_start|> def do(self, sym):
"""
Accepts symbols like C4-major or C4,E4,G4
or note symbols like 'C4'
"""
# The dash is a bit of a notation hack, it's there because "C4 major"
# would look like two symbols, so we need to have no whitespace
... | elif type(note_or_chord) == Chord: |
Here is a snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless req... | if not isinstance(bus, FxBus): |
Next line prediction: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless ... | notes = [ note('C4'), note('E4'), note('G4')] |
Here is a snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless req... | chord1 = Chord(notes=notes) |
Given the code snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unles... | chord2 = chord(['G4','C4','E4']) |
Given the code snippet: <|code_start|>
self._factory = song
self._patterns = dict()
self._save(patterns)
def _save(self, patterns):
for (name, pattern) in patterns.items():
if isinstance(pattern, str):
pattern = pattern.replace("|","").split()
... | return Endlessly(pattern) |
Predict the next line after this snippet: <|code_start|> return self._patterns
class RandomPatterns(Patterns):
def __init__(self, song, mode=None, patterns=None):
self.mode = mode
super().__init__(song, patterns=patterns)
def create(self, pattern):
return Randomly(pattern, mode... | return Repeatedly(pattern, hold=self.hold) |
Using the snippet: <|code_start|>class Patterns(object):
def __init__(self, song, patterns=None):
assert patterns is not None
self._factory = song
self._patterns = dict()
self._save(patterns)
def _save(self, patterns):
for (name, pattern) in patterns.items():
... | return Randomly(pattern, mode=self.mode) |
Using the snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless req... | class Repeatedly(Selector): |
Here is a snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless req... | scale1 = Scale(root=note('C4'), typ='major') |
Given snippet: <|code_start|>Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distribut... | assert chord(results) == chord(expected) |
Given the following code snippet before the placeholder: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apach... | scale1 = Scale(root=note('C4'), typ='major') |
Predict the next line after this snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/... | scale2 = scale('C4 major') |
Next line prediction: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless ... | class Arp(Member): |
Continue the code snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Un... | class Subdivide(Member): |
Using the snippet: <|code_start|> yield False
else:
yield True
elif mode == 'exhaust':
my_list = alist[:]
while len(my_list) > 0:
print("DRAWING")
length = len(my_list)
index = random... | class Randomly(Selector): |
Based on the snippet: <|code_start|>"""
Copyright 2016, Michael DeHaan <michael.dehaan@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless ... | class Transpose(Member): |
Given snippet: <|code_start|>http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific languag... | if type(instrument) != Instrument: |
Next line prediction: <|code_start|> locrian = [ 1, 'b2', 'b3', 4, 'b5', 'b6', 'b7' ],
lydian = [ 1, 2, 3, 'b4', 5, 6, 7 ],
major_pentatonic = [ 1, 2, 3, 5, 6 ],
melodic_minor_asc = [ 1, 2, 'b3', 4, 5, 'b7', 'b8', 8 ],
melodic_minor_desc = [ 1, 2, 'b3', 4, 5, 'b6', 'b7', 8 ],
... | root = note(root) |
Here is a snippet: <|code_start|>
def summarized_placeholder(name, prefix=None, key=tf.GraphKeys.SUMMARIES):
prefix = '' if not prefix else prefix + '/'
p = tf.placeholder(tf.float32, name=name)
tf.summary.scalar(prefix + name, p, collections=[key])
return p
def resize_area(tensor, like):
_, h, w... | return downsample_ops(tensor, num) |
Here is a snippet: <|code_start|>
DISOCC_THRESH = 0.8
def length_sq(x):
return tf.reduce_sum(tf.square(x), 3, keepdims=True)
def compute_losses(im1, im2, flow_fw, flow_bw,
border_mask=None,
mask_occlusion='',
data_max_distance=1):
losses = {}
i... | disocc_fw = tf.cast(forward_warp(flow_fw) < DISOCC_THRESH, tf.float32) |
Continue the code snippet: <|code_start|>
DISOCC_THRESH = 0.8
def length_sq(x):
return tf.reduce_sum(tf.square(x), 3, keepdims=True)
def compute_losses(im1, im2, flow_fw, flow_bw,
border_mask=None,
mask_occlusion='',
data_max_distance=1):
losses = {... | im2_warped = image_warp(im2, flow_fw) |
Predict the next line after this snippet: <|code_start|>
class ImageWarpTest(tf.test.TestCase):
def _warp_test(self, first, second, flow, debug=False):
num_batch, height, width, channels = second.shape
second_ = tf.placeholder(tf.float32, shape=second.shape, name='im')
flow_ = tf.placehold... | inv_warped_second = image_warp(second_, flow_) |
Predict the next line after this snippet: <|code_start|> fn2 = os.path.join(dir_path, files[i + 1])
filenames.append((fn1, fn2))
random.seed(seed)
random.shuffle(filenames)
print("Training on {} frame pairs.".format(len(filenames)))
filenames_exte... | image_1, image_2 = random_crop([image_1, image_2], [height, width, 3]) |
Continue the code snippet: <|code_start|> eigenvalues = self.get_eig_array()
plt.clf()
if window is not None:
plt.ylim(window[0], window[1])
if self.get_number_of_spins() == 1:
for i in range(self.nbands):
band_i = eigenvalues[i, :] - self.get_ferm... | symbols, positions, cell = read_poscar_and_unsort(filename=filename) |
Based on the snippet: <|code_start|>def read_OUTCAR_energy(outcar='./OUTCAR'):
"""
read energy with out entropy from OUTCAR
"""
[energy_free, energy_zero] = [0, 0]
if all:
energy_free = []
energy_zero = []
for line in open(outcar, 'r'):
# Free energy
if line.lower... | sdict = symbol_number(atoms) |
Next line prediction: <|code_start|>
#!/usr/bin/env python
from __future__ import division, print_function, unicode_literals
def build_structure(name, mag='PM'):
return gen_primitive(name=name, latticeconstant=4, mag_order='PM')
def make_scf_input(atoms,
ecut=26,
xc='LDA'... | structure, magmoms = to_abi_structure(atoms, magmoms=True) |
Given snippet: <|code_start|> freq = evals[i][j]
if label:
mode = label_Gamma(
evec=evec, masses=self.atoms.get_masses())
Gamma_mode_names.append(mode)
else:
Gam... | mode = label_zone_boundary(qname, evec=evec) |
Predict the next line after this snippet: <|code_start|> def get_gamma_modes(self):
"""
return (Freqs, names, evecs)
"""
return self.phonon_mode_freqs['Gamma'], self.phonon_mode_names['Gamma'], self.phonon_mode_evecs['Gamma'],
def get_gamma_mode(self, mode_name):
"""
... | mode = label_Gamma( |
Given the code snippet: <|code_start|> )
#phbst.plot_phbands()
qpoints = phbst.qpoints.frac_coords
print qpoints
nqpts = len(qpoints)
nbranch = 3 * len(numbers)
evals = np.zeros([nqpts, nbranch])
evecs = np.zeros([nqpts, nbranch, nbranch], dtype='complex128')
m = np.sqrt(np.kron(... | ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*27*33.356,weights[:,:].T*0.98+0.01,xticks=[names,[1,2,3,4,5]],style='alpha') |
Predict the next line for this snippet: <|code_start|> # DDK
self.add_dataset(
iscf=-3,
getwfk=1,
kptopt=2,
rfelfd=2,
nqpt=1,
rfphon=0,
tolvrs=0,
tolwfr=tolwfr * 10,
... | qpoints = get_ir_kpts(atoms, qpts) |
Continue the code snippet: <|code_start|> if 'nspden' in self.parameters and self.parameters['nspden']==2:
wannier_input.write_input(prefix=self.prefix, spin=True)
else:
wannier_input.write_input(prefix=self.prefix, spin=False)
self.calculate(atoms=atoms)
wann_dir... | kpath=cubic_kpath()[0], |
Predict the next line after this snippet: <|code_start|> if not self.get_spin_polarized():
magmom = 0.0
else: # only for spinpolarized system Magnetisation is printed
for line in open(join(self.workdir,self.label + '.txt')):
if line.find('Magnetisation') != -1: #... | def get_efermi(self): |
Predict the next line for this snippet: <|code_start|> des = os.path.join(wdir[i], 'abiniti_WFK')
if os.path.exists(des):
os.remove(des)
os.symlink(src, des)
self.set(**relax_params)
self.set(
irdwfk=1,
berryopt=... | kpts=self.get_kpoints() |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python
from __future__ import division, print_function, unicode_literals
def build_structure(name, mag='PM'):
return gen_primitive(name=name, latticeconstant=4, mag_order='PM')
def make_scf_input(atoms,
ec... | structure, magmoms = to_abi_structure(atoms, magmoms=True) |
Continue the code snippet: <|code_start|> #subplot_number=int(str(len(xs))+'1'+str(i+1))
nplot=len(xs)
if i==0:
axes.append(plt.subplot(nplot,1,i+1))
else:
axes.append(plt.subplot(nplot,1,i+1,sharex=axes[0]))
ys=yss[i]
label=labels[i]
for y ... | atom_nums=[x for x in list(symdict.keys()) if symnum_to_sym(x) in element_types] |
Next line prediction: <|code_start|> line_num=6
for line in dos_text:
line_num +=1
if line_num >= nbands+6:
break
e,dos_up,dos_down,idos_up,idos_down=[float(fstr) for fstr in line.split()]
e_norm=e-efermi
if e_norm< epmax and e_norm > epmin:
e_array... | symdict=get_symdict() |
Continue the code snippet: <|code_start|> # DDK
self.add_dataset(
iscf=-3,
getwfk=1,
kptopt=2,
rfelfd=2,
nqpt=1,
rfphon=0,
tolvrs=0,
tolwfr=tolwfr * 10,
... | qpoints = get_ir_kpts(atoms, qpts) |
Given the code snippet: <|code_start|> prtwant=2,
paral_kgb=0,
kptopt=3,
istwfk="%s*1" % nkpts)
self.set(**kwargs)
wannier_input.write_input()
self.calculate(atoms=atoms, )
if not os.path.exists('Wannier'):
os.mkdir('Wannier')
... | kpath=cubic_kpath()[0], |
Predict the next line after this snippet: <|code_start|> """
self.energy=(self._kweights*(self._occupations*self._eigenvals)).sum()
def get_free_energy(self):
pass
#raise NotImplementedError
def get_projection(self,orb,spin=0):
"""
get the projection to nth orb.
... | return plot_band_weight(kslist,ekslist,wkslist=wkslist,efermi=None,yrange=None,output=None,style='alpha',color=color,axis=axis,width=10,xticks=None) |
Using the snippet: <|code_start|> qptbounds=kpath_bounds,
)
#phbst.plot_phbands()
qpoints = phbst.qpoints.frac_coords
nqpts = len(qpoints)
nbranch = 3 * len(numbers)
evals = np.zeros([nqpts, nbranch])
evecs = np.zeros([nqpts, nbranch, nbranch], dtype='complex128')
m = np.sqrt... | ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*27*33.356,weights[:,:].T*0.98+0.01,xticks=[names,[1,2,3,4,5]],style='alpha') |
Given the code snippet: <|code_start|>
m = np.sqrt(np.kron(masses,[1,1,1]))
#positions=np.kron(scaled_positions,[1,1,1])
for iqpt, qpt in enumerate(qpoints):
for ibranch in range(nbranch):
phmode = phbst.get_phmode(qpt, ibranch)
evals[iqpt, ibranch] = phmode.freq
... | ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*8065.6,weights[:,:].T*0.98+0.01,xticks=[knames,xpts],style='alpha') |
Given snippet: <|code_start|>#!/usr/bin/env python
def plot_pdos():
parser=argparse.ArgumentParser(description='Plot the partial dos')
parser.add_argument('-f','--filename',type=str,help='DOSCAR filename',default='DOSCAR')
parser.add_argument('-n','--ispin',type=int,help='number os spins, 1 or 2',default=2... | plot_all_pdos(element_types=args.element,filename=args.filename,ispin=args.ispin,ymin=args.ymin,ymax=args.ymax,xmin=args.xmin,xmax=args.xmax,output_dir=args.output,orbs=args.sites) |
Next line prediction: <|code_start|>#!/usr/bin/env python
if __name__=='__main__':
parser=ArgumentParser(description='sum the DOSCAR valence dos')
parser.add_argument('-o','--output',help='output file name',default='sum_dos.txt')
args=parser.parse_args()
<|code_end|>
. Use current file imports:
(from pyDFT... | write_all_sum_dos(output=args.output) |
Given the following code snippet before the placeholder: <|code_start|>#! /usr/bin/env python
def get_potential():
if not os.path.exists('./vplanar.txt'):
raise IOError('No data vplanar.txt found. Please run work_function')
data=np.loadtxt('vplanar.txt',skiprows=1)
pos=data[:,0]
pot=data[:,1]
... | p=array(peakdetect(data,lookahead=5,delta=0.01)) |
Given the following code snippet before the placeholder: <|code_start|> phfreqs = ds.variables['phfreqs'][:] * 8065.6
phdisps = ds.variables['phdispl_cart'][:]
masses = ds.variables['atomic_mass_units'][:]
masses = list(masses) + [masses[-1]] * 2
IR_modes = label_all(qpoints, phfreqs, phdisps, masse... | kpath = cubic_kpath() |
Based on the snippet: <|code_start|>
def get_vertex(self,direction):
return self.__dict__[direction]
def set_axis(self,x=(1,0,0), y=(0,1,0),z=(0,0,1),axis_type=None):
"""
axis_type: default None, if not None: 'rotate45_xy': means x,y are 45 degree rotated about z
"""
... | self.sym_dict=get_symdict(filename=None,atoms=atoms) |
Given the following code snippet before the placeholder: <|code_start|>
def vec_ang(a,b):
"""angle of two vectors, 0 ~ 180"""
return np.arccos(np.inner(a,b)/(np.linalg.norm(a)*np.linalg.norm(b)))/np.pi*180
def atom_angle(a1,a2,a3):
"""
angle a1-a2-a3
a1 a2 a3 are atom objects
"""
vec1=a2.p... | symdict=symbol_number(atoms) |
Continue the code snippet: <|code_start|>
def atom_angle(a1,a2,a3):
"""
angle a1-a2-a3
a1 a2 a3 are atom objects
"""
vec1=a2.position-a1.position
vec2=a2.position-a3.position
return vec_ang(vec1,vec2)
def even_or_odd_path(atoms,from_symnum,node_sym_list,to_symnum_list=None,first_neighbor_m... | if symnum_to_sym(s) in node_sym_list: |
Given the code snippet: <|code_start|>#!/usr/bin/env python
if __name__=='__main__':
if len(sys.argv)==2:
spin = sys.argv[1]
else:
spin=None
<|code_end|>
, generate the next line using the imports in this file:
from pyDFTutils.queue.commander import zenobe_run_wannier90
import sys
and context ... | zenobe_run_wannier90(spin=spin) |
Here is a snippet: <|code_start|>#! /usr/bin/env python
def run_bader(filename='CHGCAR'):
if os.path.exists('AECCAR0') and os.path.exists('AECCAR2'):
if not os.path.exists('CHGCAR_sum'):
os.system('chgsum AECCAR0 AECCAR2')
os.system('bader %s -ref CHGCAR_sum'%filename)
else:
... | elec_dict=get_electrons() |
Using the snippet: <|code_start|> #plt.show()
def phonon_unfold():
atoms = FaceCenteredCubic(size=(1, 1, 1), symbol="Cu", pbc=True)
symbols = atoms.get_chemical_symbols()
symbols[-1] = 'Ag'
atoms.set_chemical_symbols(symbols)
calc = EMT()
atoms.set_calculator(calc)
phonon = calculate_pho... | ax=plot_band_weight([list(x)]*freqs.shape[1],freqs.T*33.356,weights[:,:].T*0.98+0.01,xticks=[names,X],axis=ax) |
Next line prediction: <|code_start|>def read_unsorted_poscar(filename='CONTCAR'):
s, p, c = read_poscar_and_unsort(filename=filename)
atoms = Atoms(symbols=s, positions=p, cell=c)
return atoms
def get_electrons(filename='POTCAR'):
"""
get dict {symbol: valence} from POTCAR
"""
nelect = dic... | symdict = symbol_number(syms) |
Next line prediction: <|code_start|> if line.startswith(' magnetization (x)'):
start = True
text = ''
if start:
text += line
if line.startswith('tot'):
start = False
return text
def check_converge(filename='log'):
... | print(symnum_to_sym('1')) |
Next line prediction: <|code_start|>#!/usr/bin/env python
def plot_ldos():
parser=argparse.ArgumentParser(description='Plot the local dos')
parser.add_argument('-f','--filename',type=str,help='DOSCAR filename',default='DOSCAR')
parser.add_argument('-n','--ispin',type=int,help='number os spins, 1 or 2',defa... | plot_all_ldos(filename=args.filename,ispin=args.ispin,ymin=args.ymin,ymax=args.ymax,xmin=args.xmin,xmax=args.xmax, has_f=False) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
def test():
parser=argparse.ArgumentParser(description='Decide AFM structure 1 -1')
parser.add_argument('-f','--filename',type=str,help='POSCAR filename',default='POSCAR.vasp')
parser.add_argument('-n','--nodes',type=str,help='symbol of element on th... | symnums,vals= even_or_odd_path(atoms,args.origin,args.nodes,first_neighbor_min=args.xmin,first_neighbor_max=args.xmax) |
Next line prediction: <|code_start|>#!/usr/bin/env python
def test():
parser=argparse.ArgumentParser(description='Decide AFM structure 1 -1')
parser.add_argument('-f','--filename',type=str,help='POSCAR filename',default='POSCAR.vasp')
parser.add_argument('-n','--nodes',type=str,help='symbol of element on th... | if symnum_to_sym(s)==sym: |
Given the following code snippet before the placeholder: <|code_start|>
def cubic_kpath(npoints=500,name=True):
"""
return the kpoint path for cubic
Parameters:
----------------
npoints: int
number of points.
Returns:
-----------------
kpts:
kpoints
xs:
x cor... | def get_ir_kpts(atoms, mesh): |
Given the following code snippet before the placeholder: <|code_start|>
class NextEventsContent(models.Model):
count = models.IntegerField(default=5)
class Meta:
abstract = True
verbose_name = 'Next Events Content'
verbose_name_plural = 'Next Events Contents'
def render(self, **k... | events = Event.objects.pending()[0:self.count] |
Predict the next line after this snippet: <|code_start|>
def invitation_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is an invitee.
"""
actual_decorator = user_passes_test(
lambda u: isinstance(u, Invitee) and u.is_active,
... | lambda u: isinstance(u, Participant) and u.is_active, |
Here is a snippet: <|code_start|>
def invitation_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
Decorator for views that checks that the user is an invitee.
"""
actual_decorator = user_passes_test(
<|code_end|>
. Write the next line using the current file imports:
from django.c... | lambda u: isinstance(u, Invitee) and u.is_active, |
Based on the snippet: <|code_start|>
register = template.Library()
class GetEventPartsNode(template.Node):
def __init__(self, variable_name=None):
self.variable_name = variable_name
def render(self, context):
if self.variable_name is None:
return u''
if 'person' not in con... | event_parts = EventPart.objects.filter(event=event).filter(attendances__participant=person) |
Given the code snippet: <|code_start|>
class WoodstockView(object):
invitation_required = False
registration_required = False
def dispatch(self, request, *args, **kwargs):
if self.invitation_required and not isinstance(request.user, Invitee):
raise PermissionDenied
<|code_end|>
, gener... | if self.registration_required and not isinstance(request.user, Participant): |
Using the snippet: <|code_start|>
class WoodstockView(object):
invitation_required = False
registration_required = False
def dispatch(self, request, *args, **kwargs):
<|code_end|>
, determine the next line of code. You have imports:
from django.core.exceptions import PermissionDenied
from woodstock.model... | if self.invitation_required and not isinstance(request.user, Invitee): |
Predict the next line for this snippet: <|code_start|>
PAGE_PERMISSIONS = (
(0, 'Alle'),
(1, 'Teilnehmer'),
(2, 'Einladungen'),
(3, 'Teilnehmer oder Einladung'),
)
def check_permission_request_processor(self, request):
if self.woodstock_permissions in (1, 3):
<|code_end|>
with the help of curren... | if isinstance(request.user, Participant): |
Using the snippet: <|code_start|>
PAGE_PERMISSIONS = (
(0, 'Alle'),
(1, 'Teilnehmer'),
(2, 'Einladungen'),
(3, 'Teilnehmer oder Einladung'),
)
def check_permission_request_processor(self, request):
if self.woodstock_permissions in (1, 3):
if isinstance(request.user, Participant):
... | if isinstance(request.user, Invitee): |
Here is a snippet: <|code_start|> account=account,
name=self.name.split('/')[-1],
) or self.name
tag = _tag or tag or self.tag
if use_digest:
name = '{name}@{digest}'.format(name=name, digest=tag)
tag = None
return self.__class__(name=name... | repository, tag = docker.utils.parse_repository_tag(image) |
Continue the code snippet: <|code_start|> for part in re.split(r'(?<!\\),', string):
if not part.startswith(option + '='):
continue
value = shlex.split(part.split('=', 1)[-1])
return value and value[0] or None
class ServiceNotFoundError(ServiceError):
pass
class RemovableO... | new_values = utils.OrderedSet(new_values) |
Next line prediction: <|code_start|>class HostOption(RemovableOption):
path = '/Spec/TaskTemplate/ContainerSpec/Hosts/*'
def get_current_values(self, *args, **kwargs):
values = super(HostOption, self).get_current_values(*args, **kwargs)
# 'ip host' => 'host:ip'
return map(lambda value:... | class Service(ManagedService): |
Given the following code snippet before the placeholder: <|code_start|>
def get_option_value(string, option):
"""
get option value from string with nested options
such as "source=from,destination=to"
"""
for part in re.split(r'(?<!\\),', string):
if not part.startswith(option + '='):
... | class RemovableOption(Option): |
Given snippet: <|code_start|> def get_current_values(self, *args, **kwargs):
values = super(HostOption, self).get_current_values(*args, **kwargs)
# 'ip host' => 'host:ip'
return map(lambda value: ':'.join(value.split(' ', 1)[::-1]), values)
class PlacementPrefOption(RemovableOption):
p... | command = Attribute() |
Here is a snippet: <|code_start|>
def get_option_value(string, option):
"""
get option value from string with nested options
such as "source=from,destination=to"
"""
for part in re.split(r'(?<!\\),', string):
if not part.startswith(option + '='):
continue
value = sh... | class ServiceNotFoundError(ServiceError): |
Given the code snippet: <|code_start|># through RabbitMQ. This may be slightly faster than it's twisted-based cousin.
sys.path.append(os.path.dirname(__file__))
if not os.environ.has_key("DJANGO_SETTINGS_MODULE"):
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
logger = pygowave_rpc.logger.setupLogging()
if p... | omc = AmqpMessageProcessor(amqpconn) |
Continue the code snippet: <|code_start|>
class MyRegistrationForm(RegistrationForm):
def clean_username(self):
"""
Validate that the username is at least three characters long.
"""
username = super(MyRegistrationForm, self).clean_username()
if len(username) < 3:
raise forms.ValidationError(_(u'Your... | return AlreadyUploadedFile(path, oldfile, os.path.getsize(path)) |
Given the following code snippet before the placeholder: <|code_start|> if not isinstance(value, AlreadyUploadedFile):
# Add prefix to avoid overwriting of files with the same name
prefix = sha_constructor(str(random())).hexdigest()[:4] + "_"
filename = settings.AVATAR_ROOT + prefix + value.name
destinatio... | model = get_profile_model() |
Predict the next line for this snippet: <|code_start|> if self.cleaned_data["upload"] == "":
raise forms.ValidationError(_(u'You must upload a file or choose "External URL" and enter an URL.'))
# Set URL by uploaded file
self.cleaned_data["url"] = settings.GADGET_URL + self.cleaned_data["upload"]
... | model = Gadget |
Given snippet: <|code_start|>
#
# PyGoWave Server - The Python Google Wave Server
# Copyright 2009 Patrick Schneider <patrick.p2k.schneider@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the Lic... | "form_class": MyRegistrationForm, |
Based on the snippet: <|code_start|>
class UserOnlineMiddleware:
"""
Update the last_contact field of the user's participant object. Used to
determine how many users are online. This also creates a participant object
if it is missing.
"""
def process_request(self, request):
if request.user.is_authenticated(... | profile_obj = Participant.objects.get(user__id=request.user.id) |
Based on the snippet: <|code_start|> @transaction.commit_on_success
def create_and_init_new_wave(self, creator, title):
wave = self.create()
wavelet = Wavelet(wave=wave, creator=creator, title=title, is_root=True)
wavelet.save()
wavelet.participants.add(creator)
blip = Blip(wavelet=wavelet, creator=cre... | self.id = find_random_id(Wave.objects, 10) |
Predict the next line after this snippet: <|code_start|> participant_conns = models.ManyToManyField(ParticipantConn, blank=True, related_name="wavelets", verbose_name=_(u'connections'))
def blipById(self, id):
"""
Returns the Blip object with the given id, if the Blip resides on this
Wavelet. Returns None othe... | return datetime2milliseconds(self.created) |
Using the snippet: <|code_start|> # ET = (Qet / (rho_w * Lv))
#------------------------------------------
# rho_w = 1000d ;[kg/m^3]
# Lv = -2500000d ;[J/kg]
# So (rho_w * Lv) = -2.5e+9 [J/m^3]
#-------------------------------------
ET = (Qet / np.float6... | self.alpha_unit = model_input.open_file(self.alpha_type, self.alpha_file) |
Predict the next line after this snippet: <|code_start|> 'var1, var2 = ${var1}, ${var2}\n',
'More lines\n']
template_unit.writelines( lines )
template_unit.close()
# make_test_template()
#-------------------------------------------------------------------------
def test1( method='RE'... | template_files.replace( cfg_template_file, new_cfg_file, |
Given the code snippet: <|code_start|> # (2/18/13) Previous version of framework class initialized
# and then connected the components in the comp_set using
# embedded references. In this version we will call a
# "get_required_vars()" method within the time loop, which
# will in ... | time_interpolator = time_interpolation.time_interpolator( |
Given snippet: <|code_start|> # needed to convert snowmelt to snow water
# equivalent (swe) in update_swe() in "snow_base.py".
#-------------------------------------------------------------
T_air = self.T_air # (2/3/13, new framework)
#---------------------... | self.c0_unit = model_input.open_file(self.c0_type, self.c0_file) |
Given snippet: <|code_start|> # ALLOW ET TO BE A SCALAR ??
##########################################
## if (size(self.ET) == 1):
## self.ET += np.zeros((self.ny, self.nx), dtype='Float64')
# update_ET_rate()
#-----------------------------------------------------... | self.ET_unit = model_input.open_file(self.ET_type, \ |
Predict the next line after this snippet: <|code_start|> # (2/18/13) Previous version of framework class initialized
# and then connected the components in the comp_set using
# embedded references. In this version we will call a
# "get_required_vars()" method within the time loop, which
... | time_interpolator = time_interpolation.time_interpolator( |
Here is a snippet: <|code_start|> ################################################
#------------------------------------------
# Lf = latent heat of fusion [J/kg]
# Lv = latent heat of vaporization [J/kg]
# ET = (Qet / (rho_w * Lv))
#------------------------------... | self.K_soil_unit = model_input.open_file(self.K_soil_type, self.K_soil_file) |
Here is a snippet: <|code_start|># bobs_erode_test() # Use framework to run Erode.
#
#-----------------------------------------------------------------------
def topoflow_test( driver_comp_name ='topoflow_driver',
cfg_prefix=None, cfg_directory=None,
time_interp_method='Linear'):... | f = emeli.framework() |
Next line prediction: <|code_start|># get_input_var_names() # (5/15/12)
# get_output_var_names() # (5/15/12)
# get_var_name() # (5/15/12)
# get_var_units() # (5/15/12)
# -------------------------
# initialize_layer_vars() # (5/11/10)
# set_computed_inpu... | class infil_component( infil_base.infil_component ): |
Given the code snippet: <|code_start|> ## n = self.time_index
## Green_Ampt_Infil_Rate_v2(self, r, r_last, n)
# update_infil_rate()
#-------------------------------------------------------------------
def open_input_files(self):
#----------------------------------------... | self.Ks_unit.append( model_input.open_file(self.Ks_type[k], self.Ks_file[k]) ) |
Based on the snippet: <|code_start|> #--------------------------------------------
MID_PONDING = ((dIp > 0) and (dIp < (r * self.dt)))
if (MID_PONDING):
print 'MID_PONDING occurred.'
#--------------------------
# For this case: Ip = Ip2
#-------... | TF_Print('tp = ' + str(self.tp)) |
Predict the next line for this snippet: <|code_start|> # reduce dt_too_small.
#-----------------------------------------------------
dt_grid_min = np.nanmin(self.dt_grid)
if (dt_grid_min < dt_too_small):
print '******************************************'
pr... | rtg_files.write_grid( self.dt_grid, RTG_file, self.rti )
|
Next line prediction: <|code_start|> # followed by "n_sources" blocks of the form:
#
# source_ID: (source pixel ID as long integer)
# nt: (number of discharge (Q) values)
# Q: (vector of discharges in m^3/s)
#-----------------... | n_sources = cfg.read_value(file_unit, dtype='Int32') |
Given the code snippet: <|code_start|> #------------------------
# Update internal clock
#------------------------
# print '#### Calling update_time()...'
self.update_time()
self.status = 'updated' # (OpenMI 2.0 convention)
# update()
#-----------------... | FOUND = tf_utils.file_exists( self.source_file ) |
Given the following code snippet before the placeholder: <|code_start|># get_component_name()
# get_attribute() # (10/26/11)
# get_input_var_names() # (10/23/12)
# get_output_var_names() # (10/23/12)
# get_var_name() # (10/23/12)
# get_var_units() # (1... | class infil_component(infil_base.infil_component): |
Here is a snippet: <|code_start|> ## r_last = ???
## n = self.time_index
## Smith_Parlange_Infil_Rate_v2(self, r, r_last, n)
# update_infil_rate()
#-------------------------------------------------------------------
def open_input_files(self):
#-------------------... | self.Ks_unit.append( model_input.open_file(self.Ks_type[k], self.Ks_file[k]) ) |
Using the snippet: <|code_start|> #------------------------------------------
MID_PONDING = np.logical_and((dIp > 0), (dIp < (r * self.dt)))
if (MID_PONDING):
print 'MID_PONDING occurred.'
#------------------------
#For this case: Ip = Ip2
#----... | TF_Print('tp = ' + TF_String(self.tp)) |
Based on the snippet: <|code_start|> #------------------------------------------
MID_PONDING = np.logical_and((dIp > 0), (dIp < (r * self.dt)))
if (MID_PONDING):
print 'MID_PONDING occurred.'
#------------------------
#For this case: Ip = Ip2
#-... | TF_Print('tp = ' + TF_String(self.tp)) |
Given the code snippet: <|code_start|># get_input_var_names() # (5/15/12)
# get_output_var_names() # (5/15/12)
# get_var_name() # (5/15/12)
# get_var_units() # (5/15/12)
# -------------------------
# initialize_layer_vars() # (5/11/10)
# set_computed_in... | class infil_component( infil_base.infil_component ): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.