Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Using the snippet: <|code_start|> """
return dot(self.L, self.L.T)
def gradient(self):
"""
Derivative of the covariance matrix over the lower triangular, flat part of L.
It is equal to
∂K/∂Lᵢⱼ = ALᵀ + LAᵀ,
where Aᵢⱼ is an n×m matrix of zeros except at [Aᵢⱼ]ᵢⱼ=1.
Returns
-------
Lu : ndarray
Derivative of K over the lower-triangular, flat part of L.
"""
L = self.L
n = self.L.shape[0]
grad = {"Lu": zeros((n, n, n * self._L.shape[1]))}
for ii in range(self._L.shape[0] * self._L.shape[1]):
row = ii // self._L.shape[1]
col = ii % self._L.shape[1]
grad["Lu"][row, :, ii] = L[:, col]
grad["Lu"][:, row, ii] += L[:, col]
return grad
def __str__(self):
<|code_end|>
, determine the next line of code. You have imports:
from numpy import asarray, dot, ones, zeros
from optimix import Function, Vector
from .._util import format_function
and context (class names, function names, or code) available:
# Path: glimix_core/_util/format.py
# def format_function(func, params, attrs=None):
# if attrs is None:
# attrs = []
# tname = type(func).__name__
# name = func.name
# kwargs_input = [f"{arg}={val}" for arg, val in params.items()]
# input = ", ".join(kwargs_input)
# msg = f"{tname}({input})"
# if name is not None:
# msg += f": {name}"
#
# msg += "\n"
# for a in attrs:
# msg += _format_named_arr(a[0], a[1])
# return msg
. Output only the next line. | return format_function( |
Here is a snippet: <|code_start|>
class Memshark():
def __init__(self, config):
self.wii_u_ip = config.wii_u_ip
self.tcp_gecko = None
self.pokes = []
def connect(self):
if self.is_connected():
self.tcp_gecko.s.close()
try:
<|code_end|>
. Write the next line using the current file imports:
from vendor.tcpgecko import tcpgecko
import time
and context from other files:
# Path: vendor/tcpgecko/tcpgecko.py
# def enum(**enums):
# def __init__(self, *args):
# def readmem(self, address, length): #Number of bytes
# def readkern(self, address): #Only takes 4 bytes, may need to run multiple times
# def writekern(self, address, value): #Only takes 4 bytes, may need to run multiple times
# def pokemem(self, address, value): #Only takes 4 bytes, may need to run multiple times
# def pokemem8(self, address, value):
# def pokemem16(self, address, value):
# def pokemem32(self, address, value):
# def search32(self, address, value, size):
# def getversion(self):
# def writestr(self, address, string):
# def memalign(self, size, align):
# def freemem(self, address):
# def memalloc(self, size, align, noprint=False):
# def freealloc(self, address):
# def createpath(self, path):
# def createstr(self, string):
# def FSInitClient(self):
# def FSInitCmdBlock(self):
# def FSOpenDir(self, path="/"):
# def SAVEOpenDir(self, path="/", slot=255):
# def FSReadDir(self):
# def SAVEOpenFile(self, path="/", mode="r", slot=255):
# def FSReadFile(self):
# def get_symbol(self, rplname, symname, noprint=False, data=0):
# def call(self, address, *args):
# def function(self, rplname, symname, noprint=False, data=0, *args):
# def validrange(self, address, length):
# def validaccess(self, address, length, access):
# def printflags(self, flags, data):
# def printperms(self, perms):
# def hexstr0(data): #0xFFFFFFFF, uppercase hex string
# def __init__(self, address, rpc=None, rplname=None, symname=None, noprint=False):
# def __call__(self, *args):
# class TCPGecko:
# class FileSystem: #TODO: Try to clean this up ????
# class ExportedSymbol(object):
, which may include functions, classes, or code. Output only the next line. | self.tcp_gecko = tcpgecko.TCPGecko(self.wii_u_ip) |
Here is a snippet: <|code_start|>
config = MemsharkConfig('config.json')
games = Games('games')
memshark = memshark.Memshark(config)
exploit_server = server.ExploitServer()
background.schedule(memshark)
background.schedule(exploit_server)
<|code_end|>
. Write the next line using the current file imports:
from memshark_config import MemsharkConfig
from games import Games
from gui import gui
from background import background, memshark, server
and context from other files:
# Path: memshark_config.py
# class MemsharkConfig():
# def __init__(self, configPath):
# with open(configPath) as json_file:
# self.get = json.load(json_file)
# self.wii_u_ip = self.get['wii_u_ip']
# self.window_width = self.get['window_width']
# self.window_height = self.get['window_height']
#
# Path: games.py
# class Games():
# def __init__(self, gamesPath):
# self.games = []
# self.game_lookup = {}
# for root,dirs,files in os.walk(gamesPath):
# for file in files:
# gamePath = os.path.join(root,file)
# game = Game(file, gamePath)
# self.games.append(game)
# self.game_lookup[game.name] = game
#
# Path: gui/gui.py
# class MainApp:
# class MainWindow:
# def __init__(self, config, games, memshark, exploit_server):
# def start(self):
# def __init__(self, master, config, games, memshark, exploit_server):
#
# Path: background/background.py
# def background():
# running = True
# while running:
# task.background()
# item = None
# try:
# item = task.get_queue().get(timeout=1)
# except Exception:
# swallow = True
# if item != None:
# if item == "kill_thread":
# running = False
# else:
# task.handle_message(item)
#
# Path: background/memshark.py
# class Memshark():
# def __init__(self, config):
# def connect(self):
# def disconnect(self):
# def poke(self, target):
# def is_connected(self):
# def handle_message(self, message):
# def background(self):
#
# Path: background/server.py
# class ExploitHandler(BaseHTTPRequestHandler):
# class ExploitServer():
# def do_GET(self):
# def __init__(self):
# def start(self):
# def stop(self):
# def get_listen_url(self):
# def handle_message(self, message):
# def background(self):
, which may include functions, classes, or code. Output only the next line. | app = gui.MainApp(config, games, memshark, exploit_server) |
Given the code snippet: <|code_start|>
config = MemsharkConfig('config.json')
games = Games('games')
memshark = memshark.Memshark(config)
exploit_server = server.ExploitServer()
<|code_end|>
, generate the next line using the imports in this file:
from memshark_config import MemsharkConfig
from games import Games
from gui import gui
from background import background, memshark, server
and context (functions, classes, or occasionally code) from other files:
# Path: memshark_config.py
# class MemsharkConfig():
# def __init__(self, configPath):
# with open(configPath) as json_file:
# self.get = json.load(json_file)
# self.wii_u_ip = self.get['wii_u_ip']
# self.window_width = self.get['window_width']
# self.window_height = self.get['window_height']
#
# Path: games.py
# class Games():
# def __init__(self, gamesPath):
# self.games = []
# self.game_lookup = {}
# for root,dirs,files in os.walk(gamesPath):
# for file in files:
# gamePath = os.path.join(root,file)
# game = Game(file, gamePath)
# self.games.append(game)
# self.game_lookup[game.name] = game
#
# Path: gui/gui.py
# class MainApp:
# class MainWindow:
# def __init__(self, config, games, memshark, exploit_server):
# def start(self):
# def __init__(self, master, config, games, memshark, exploit_server):
#
# Path: background/background.py
# def background():
# running = True
# while running:
# task.background()
# item = None
# try:
# item = task.get_queue().get(timeout=1)
# except Exception:
# swallow = True
# if item != None:
# if item == "kill_thread":
# running = False
# else:
# task.handle_message(item)
#
# Path: background/memshark.py
# class Memshark():
# def __init__(self, config):
# def connect(self):
# def disconnect(self):
# def poke(self, target):
# def is_connected(self):
# def handle_message(self, message):
# def background(self):
#
# Path: background/server.py
# class ExploitHandler(BaseHTTPRequestHandler):
# class ExploitServer():
# def do_GET(self):
# def __init__(self):
# def start(self):
# def stop(self):
# def get_listen_url(self):
# def handle_message(self, message):
# def background(self):
. Output only the next line. | background.schedule(memshark) |
Predict the next line for this snippet: <|code_start|>
config = MemsharkConfig('config.json')
games = Games('games')
memshark = memshark.Memshark(config)
<|code_end|>
with the help of current file imports:
from memshark_config import MemsharkConfig
from games import Games
from gui import gui
from background import background, memshark, server
and context from other files:
# Path: memshark_config.py
# class MemsharkConfig():
# def __init__(self, configPath):
# with open(configPath) as json_file:
# self.get = json.load(json_file)
# self.wii_u_ip = self.get['wii_u_ip']
# self.window_width = self.get['window_width']
# self.window_height = self.get['window_height']
#
# Path: games.py
# class Games():
# def __init__(self, gamesPath):
# self.games = []
# self.game_lookup = {}
# for root,dirs,files in os.walk(gamesPath):
# for file in files:
# gamePath = os.path.join(root,file)
# game = Game(file, gamePath)
# self.games.append(game)
# self.game_lookup[game.name] = game
#
# Path: gui/gui.py
# class MainApp:
# class MainWindow:
# def __init__(self, config, games, memshark, exploit_server):
# def start(self):
# def __init__(self, master, config, games, memshark, exploit_server):
#
# Path: background/background.py
# def background():
# running = True
# while running:
# task.background()
# item = None
# try:
# item = task.get_queue().get(timeout=1)
# except Exception:
# swallow = True
# if item != None:
# if item == "kill_thread":
# running = False
# else:
# task.handle_message(item)
#
# Path: background/memshark.py
# class Memshark():
# def __init__(self, config):
# def connect(self):
# def disconnect(self):
# def poke(self, target):
# def is_connected(self):
# def handle_message(self, message):
# def background(self):
#
# Path: background/server.py
# class ExploitHandler(BaseHTTPRequestHandler):
# class ExploitServer():
# def do_GET(self):
# def __init__(self):
# def start(self):
# def stop(self):
# def get_listen_url(self):
# def handle_message(self, message):
# def background(self):
, which may contain function names, class names, or code. Output only the next line. | exploit_server = server.ExploitServer() |
Given the code snippet: <|code_start|> self.game_selected.set("Choose a game...")
self.game_selected.trace('w', self.change_game_selection)
self.game_list = tk.OptionMenu(self.master, self.game_selected, *self.game_options)
self.game_list.config(width=50, padx=10)
# Calling this before the app is drawn causes it to crash
# self.game_selected.set(self.game_options[0])
self.game_list.grid()
self.game_version = tk.Label(self.master, text='')
self.game_version.grid()
self.check_all_button = tk.Button(self.master, text="Check All", command=self.freeze_all)
self.uncheck_all_button = tk.Button(self.master, text="Uncheck All", command=self.unfreeze_all)
self.check_all_button.grid(padx=(10,0))
self.uncheck_all_button.grid(padx=(10,0), pady=(10,10))
def change_game_selection(self, name, index, mode):
if self.game_actions_frame != None:
self.game_actions_frame.destroy()
self.game_actions_frame = tk.Frame(self.master)
game_name = self.game_selected.get()
game = self.games.game_lookup[game_name]
self.game_version.config(text='Game Version: {}'.format(game.version))
self.game_pokes = [(
'Name',
'Address',
'Value',
'Poke',
'Frozen'
)]
<|code_end|>
, generate the next line using the imports in this file:
import tkinter as tk
import time
import threading
from gui import table_widget
and context (functions, classes, or occasionally code) from other files:
# Path: gui/table_widget.py
# class TableWidget(gui.Frame):
# def __init__(self, parent):
# def set_rows(self, rows):
# def set(self, row, column, value):
. Output only the next line. | self.poke_table = table_widget.TableWidget(self.game_actions_frame) |
Given snippet: <|code_start|>
class MainApp:
def __init__(self, config, games, memshark, exploit_server):
self.root = tk.Tk()
self.mainWindow = MainWindow(self.root, config, games, memshark, exploit_server)
def start(self):
self.root.mainloop()
class MainWindow:
def __init__(self, master, config, games, memshark, exploit_server):
self.master = master
self.master.title("Memshark")
self.container = tk.Frame(self.master)
self.container.grid(padx=(20,20), pady=(20,20))
self.label = tk.Label(self.container, text="Wii U IP Address: {}".format(config.wii_u_ip))
self.notebook = ttk.Notebook(self.container)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import tkinter as tk
import tkinter.ttk as ttk
from gui import exploit_server_frame
from gui import tcp_gecko_frame
from gui import game_actions_frame
and context:
# Path: gui/exploit_server_frame.py
# KILL_THREAD = False
# class ExploitServerFrame():
# def __init__(self, master, exploit_server):
# def start_exploit_server(self):
# def stop_exploit_server(self):
#
# Path: gui/tcp_gecko_frame.py
# class TcpGeckoFrame():
# def __init__(self, master, memshark):
# def connect(self):
# def disconnect(self):
#
# Path: gui/game_actions_frame.py
# class GameActionsFrame():
# KILL_THREAD = False
# def __init__(self, master, games, memshark, config):
# def change_game_selection(self, name, index, mode):
# def poke(self, poke):
# def change_frozen_values(self, name, index, mode):
# def freeze_all(self):
# def unfreeze_all(self):
which might include code, classes, or functions. Output only the next line. | self.server_frame = exploit_server_frame.ExploitServerFrame(self.notebook, exploit_server) |
Using the snippet: <|code_start|>
class MainApp:
def __init__(self, config, games, memshark, exploit_server):
self.root = tk.Tk()
self.mainWindow = MainWindow(self.root, config, games, memshark, exploit_server)
def start(self):
self.root.mainloop()
class MainWindow:
def __init__(self, master, config, games, memshark, exploit_server):
self.master = master
self.master.title("Memshark")
self.container = tk.Frame(self.master)
self.container.grid(padx=(20,20), pady=(20,20))
self.label = tk.Label(self.container, text="Wii U IP Address: {}".format(config.wii_u_ip))
self.notebook = ttk.Notebook(self.container)
self.server_frame = exploit_server_frame.ExploitServerFrame(self.notebook, exploit_server)
<|code_end|>
, determine the next line of code. You have imports:
import tkinter as tk
import tkinter.ttk as ttk
from gui import exploit_server_frame
from gui import tcp_gecko_frame
from gui import game_actions_frame
and context (class names, function names, or code) available:
# Path: gui/exploit_server_frame.py
# KILL_THREAD = False
# class ExploitServerFrame():
# def __init__(self, master, exploit_server):
# def start_exploit_server(self):
# def stop_exploit_server(self):
#
# Path: gui/tcp_gecko_frame.py
# class TcpGeckoFrame():
# def __init__(self, master, memshark):
# def connect(self):
# def disconnect(self):
#
# Path: gui/game_actions_frame.py
# class GameActionsFrame():
# KILL_THREAD = False
# def __init__(self, master, games, memshark, config):
# def change_game_selection(self, name, index, mode):
# def poke(self, poke):
# def change_frozen_values(self, name, index, mode):
# def freeze_all(self):
# def unfreeze_all(self):
. Output only the next line. | self.tcp_gecko_frame = tcp_gecko_frame.TcpGeckoFrame(self.notebook, memshark) |
Based on the snippet: <|code_start|>
class MainApp:
def __init__(self, config, games, memshark, exploit_server):
self.root = tk.Tk()
self.mainWindow = MainWindow(self.root, config, games, memshark, exploit_server)
def start(self):
self.root.mainloop()
class MainWindow:
def __init__(self, master, config, games, memshark, exploit_server):
self.master = master
self.master.title("Memshark")
self.container = tk.Frame(self.master)
self.container.grid(padx=(20,20), pady=(20,20))
self.label = tk.Label(self.container, text="Wii U IP Address: {}".format(config.wii_u_ip))
self.notebook = ttk.Notebook(self.container)
self.server_frame = exploit_server_frame.ExploitServerFrame(self.notebook, exploit_server)
self.tcp_gecko_frame = tcp_gecko_frame.TcpGeckoFrame(self.notebook, memshark)
<|code_end|>
, predict the immediate next line with the help of imports:
import tkinter as tk
import tkinter.ttk as ttk
from gui import exploit_server_frame
from gui import tcp_gecko_frame
from gui import game_actions_frame
and context (classes, functions, sometimes code) from other files:
# Path: gui/exploit_server_frame.py
# KILL_THREAD = False
# class ExploitServerFrame():
# def __init__(self, master, exploit_server):
# def start_exploit_server(self):
# def stop_exploit_server(self):
#
# Path: gui/tcp_gecko_frame.py
# class TcpGeckoFrame():
# def __init__(self, master, memshark):
# def connect(self):
# def disconnect(self):
#
# Path: gui/game_actions_frame.py
# class GameActionsFrame():
# KILL_THREAD = False
# def __init__(self, master, games, memshark, config):
# def change_game_selection(self, name, index, mode):
# def poke(self, poke):
# def change_frozen_values(self, name, index, mode):
# def freeze_all(self):
# def unfreeze_all(self):
. Output only the next line. | self.game_actions_frame = game_actions_frame.GameActionsFrame(self.notebook, games, memshark, config) |
Given snippet: <|code_start|>#
# Revision 1.2 2007/01/05 23:33:55 customdesigned
# Make blacklist an AddrCache
#
# Revision 1.1 2007/01/05 21:25:40 customdesigned
# Move AddrCache to Milter package.
#
# Author: Stuart D. Gathman <stuart@bmsi.com>
# Copyright 2001,2002,2003,2004,2005 Business Management Systems, Inc.
# This code is under the GNU General Public License. See COPYING for details.
from __future__ import print_function
class AddrCache(object):
time_format = '%Y%b%d %H:%M:%S %Z'
def __init__(self,renew=7,fname=None):
self.age = renew
self.cache = {}
self.fname = fname
def load(self,fname,age=0):
"Load address cache from persistent store."
if not age:
age = self.age
self.fname = fname
cache = {}
self.cache = cache
now = time.time()
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
from Milter.plock import PLock
and context:
# Path: Milter/plock.py
# class PLock(object):
# "A simple /etc/passwd style lock,update,rename protocol for updating files."
# def __init__(self,basename):
# self.basename = basename
# self.fp = None
#
# def lock(self,lockname=None,mode=0o660,strict_perms=False):
# "Start an update transaction. Return FILE to write new version."
# self.unlock()
# if not lockname:
# lockname = self.basename + '.lock'
# self.lockname = lockname
# try:
# st = os.stat(self.basename)
# mode |= st.st_mode
# except OSError: pass
# u = os.umask(0o2)
# try:
# fd = os.open(lockname,os.O_WRONLY+os.O_CREAT+os.O_EXCL,mode)
# finally:
# os.umask(u)
# self.fp = os.fdopen(fd,'w')
# try:
# os.chown(self.lockname,-1,st.st_gid)
# except:
# if strict_perms:
# self.unlock()
# raise
# return self.fp
#
# def wlock(self,lockname=None):
# "Wait until lock is free, then start an update transaction."
# while True:
# try:
# return self.lock(lockname)
# except OSError:
# sleep(2)
#
# def commit(self,backname=None):
# "Commit update transaction with optional backup file."
# if not self.fp:
# raise IOError("File not locked")
# self.fp.close()
# self.fp = None
# if backname:
# try:
# os.remove(backname)
# except OSError: pass
# os.link(self.basename,backname)
# os.rename(self.lockname,self.basename)
#
# def unlock(self):
# "Cancel update transaction."
# if self.fp:
# try:
# self.fp.close()
# except: pass
# self.fp = None
# os.remove(self.lockname)
which might include code, classes, or functions. Output only the next line. | lock = PLock(self.fname) |
Given the code snippet: <|code_start|>## Determine if a hostname is internal or not.
# True if internal, False otherwise
def is_internal(hostname):
components = hostname.split(".")
return components.pop() in internal_tlds
# Determine if internal and external hosts are mixed based on a list
# of hostnames
def are_mixed(hostnames):
hostnames_mapped = map(is_internal, hostnames)
# Num internals
num_internal_hosts = hostnames_mapped.count(True)
# Num externals
num_external_hosts = hostnames_mapped.count(False)
return num_external_hosts >= 1 and num_internal_hosts >= 1
class NoMixMilter(Milter.Base):
def __init__(self): # A new instance with each new connection.
self.id = Milter.uniqueID() # Integer incremented with each call.
## def envfrom(self,f,*str):
@Milter.noreply
def envfrom(self, mailfrom, *str):
self.mailfrom = mailfrom
self.domains = []
<|code_end|>
, generate the next line using the imports in this file:
import Milter
import time
import sys
from Milter.utils import parse_addr
and context (functions, classes, or occasionally code) from other files:
# Path: Milter/utils.py
# def parse_addr(t):
# """Split email into user,domain.
#
# >>> parse_addr('user@example.com')
# ['user', 'example.com']
# >>> parse_addr('"user@example.com"')
# ['user@example.com']
# >>> parse_addr('"user@bar"@example.com')
# ['user@bar', 'example.com']
# >>> parse_addr('foo')
# ['foo']
# >>> parse_addr('@mx.example.com:user@example.com')
# ['user', 'example.com']
# >>> parse_addr('@user@example.com')
# ['@user', 'example.com']
# """
# if t.startswith('<') and t.endswith('>'): t = t[1:-1]
# if t.startswith('"'):
# if t.endswith('"'): return [t[1:-1]]
# pos = t.find('"@')
# if pos > 0: return [t[1:pos],t[pos+2:]]
# if t.startswith('@'):
# try: t = t.split(':',1)[1]
# except IndexError: pass
# return t.rsplit('@',1)
. Output only the next line. | t = parse_addr(mailfrom) |
Predict the next line for this snippet: <|code_start|> self.fp = None
self.receiver = self.getsymval('j')
self.log("connect from %s at %s" % (IPname, hostaddr) )
return Milter.CONTINUE
## def hello(self,hostname):
def hello(self, heloname):
# (self, 'mailout17.dallas.texas.example.com')
self.H = heloname
self.log("HELO %s" % heloname)
if heloname.find('.') < 0: # illegal helo name
# NOTE: example only - too many real braindead clients to reject on this
self.setreply('550','5.7.1','Sheesh people! Use a proper helo name!')
return Milter.REJECT
return Milter.CONTINUE
## def envfrom(self,f,*str):
def envfrom(self, mailfrom, *str):
self.F = mailfrom
self.R = [] # list of recipients
self.fromparms = Milter.dictfromlist(str) # ESMTP parms
self.user = self.getsymval('{auth_authen}') # authenticated user
self.log("mail from:", mailfrom, *str)
# NOTE: self.fp is only an *internal* copy of message data. You
# must use addheader, chgheader, replacebody to change the message
# on the MTA.
self.fp = BytesIO()
<|code_end|>
with the help of current file imports:
import Milter
import time
import email
import mimetypes
import os
import sys
from StringIO import StringIO as BytesIO
from io import BytesIO
from email import message_from_binary_file
from email import policy
from socket import AF_INET, AF_INET6
from Milter.utils import parse_addr
from multiprocessing import Process as Thread, Queue
from threading import Thread
from Queue import Queue
and context from other files:
# Path: Milter/utils.py
# def parse_addr(t):
# """Split email into user,domain.
#
# >>> parse_addr('user@example.com')
# ['user', 'example.com']
# >>> parse_addr('"user@example.com"')
# ['user@example.com']
# >>> parse_addr('"user@bar"@example.com')
# ['user@bar', 'example.com']
# >>> parse_addr('foo')
# ['foo']
# >>> parse_addr('@mx.example.com:user@example.com')
# ['user', 'example.com']
# >>> parse_addr('@user@example.com')
# ['@user', 'example.com']
# """
# if t.startswith('<') and t.endswith('>'): t = t[1:-1]
# if t.startswith('"'):
# if t.endswith('"'): return [t[1:-1]]
# pos = t.find('"@')
# if pos > 0: return [t[1:pos],t[pos+2:]]
# if t.startswith('@'):
# try: t = t.split(':',1)[1]
# except IndexError: pass
# return t.rsplit('@',1)
, which may contain function names, class names, or code. Output only the next line. | self.canon_from = '@'.join(parse_addr(mailfrom)) |
Given the code snippet: <|code_start|>#from Milter.greylist import Greylist
class GreylistTestCase(unittest.TestCase):
def setUp(self):
self.fname = 'test.db'
if os.path.isfile(self.fname):
os.remove(self.fname)
def tearDown(self):
#os.remove(self.fname)
pass
def testGrey(self):
<|code_end|>
, generate the next line using the imports in this file:
import unittest
import doctest
import os
from Milter.greysql import Greylist
and context (functions, classes, or occasionally code) from other files:
# Path: Milter/greysql.py
# class Greylist(object):
#
# def __init__(self,dbname,grey_time=10,grey_expire=4,grey_retain=36):
# self.ignoreLastByte = False
# self.greylist_time = grey_time * 60 # minutes
# self.greylist_expire = grey_expire * 3600 # hours
# self.greylist_retain = grey_retain * 24 * 3600 # days
# self.conn = sqlite3.connect(dbname)
# self.conn.row_factory = sqlite3.Row
# try:
# self.conn.execute('''create table greylist(
# ip text , sender text, recipient text,
# firstseen timestamp, lastseen timestamp, cnt integer, umis text,
# primary key (ip,sender,recipient))''')
# except: pass
#
# def import_csv(self,fp):
# import csv
# rdr = csv.reader(fp)
# cur = self.conn.execute('begin immediate')
# try:
# for r in rdr:
# cur.execute('''insert into
# greylist(ip,sender,recipient,firstseen,lastseen,cnt,umis)
# values(?,?,?,?,?,?,?)''', r)
# self.conn.commit()
# finally:
# cur.close();
#
# def clean(self,timeinc=0):
# "Delete records past the retention limit."
# now = time.time() + timeinc - self.greylist_retain
# cur = self.conn.cursor()
# try:
# cur.execute('delete from greylist where lastseen < ?',(now,))
# cnt = cur.rowcount
# self.conn.commit()
# finally: cur.close()
# return cnt
#
# def check(self,ip,sender,recipient,timeinc=0):
# "Return number of allowed messages for greylist triple."
# _db_lock.acquire()
# cur = self.conn.execute('begin immediate')
# try:
# cur.execute('''select firstseen,lastseen,cnt,umis from greylist where
# ip=? and sender=? and recipient=?''',(ip,sender,recipient))
# r = cur.fetchone()
# now = time.time() + timeinc
# cnt = 0
# if not r:
# cur.execute('''insert into
# greylist(ip,sender,recipient,firstseen,lastseen,cnt,umis)
# values(?,?,?,?,?,?,?)''', (ip,sender,recipient,now,now,0,None))
# elif now > r['lastseen'] + self.greylist_retain:
# # expired
# log.debug('Expired greylist: %s:%s:%s',ip,sender,recipient)
# cur.execute('''update greylist set firstseen=?,lastseen=?,cnt=?,umis=?
# where ip=? and sender=? and recipient=?''',
# (now,now,0,None,ip,sender,recipient))
# elif now < r['firstseen'] + self.greylist_time + 5:
# # still greylisted
# log.debug('Early greylist: %s:%s:%s',ip,sender,recipient)
# #r = Record()
# cur.execute('''update greylist set lastseen=?
# where ip=? and sender=? and recipient=?''',
# (now,ip,sender,recipient))
# elif r['cnt'] or now < r['firstseen'] + self.greylist_expire:
# # in greylist window or active
# cnt = r['cnt'] + 1
# cur.execute('''update greylist set lastseen=?,cnt=?
# where ip=? and sender=? and recipient=?''',
# (now,cnt,ip,sender,recipient))
# log.debug('Active greylist(%d): %s:%s:%s',cnt,ip,sender,recipient)
# else:
# # passed greylist window
# log.debug('Late greylist: %s:%s:%s',ip,sender,recipient)
# cur.execute('''update greylist set firstseen=?,lastseen=?,cnt=?,umis=?
# where ip=? and sender=? and recipient=?''',
# (now,now,0,None,ip,sender,recipient))
# self.conn.commit()
# finally:
# cur.close()
# _db_lock.release()
# return cnt
#
# def close(self):
# self.conn.close()
. Output only the next line. | grey = Greylist(self.fname) |
Here is a snippet: <|code_start|>from __future__ import print_function
class Config(object):
def __init__(self):
self.access_file='test/access.db'
self.access_file_nulls=True
class PolicyTestCase(unittest.TestCase):
def setUp(self):
self.config = Config()
if os.access('test/access',os.R_OK):
if not os.path.exists('test/access.db') or \
os.path.getmtime('test/access') > os.path.getmtime('test/access.db'):
cmd = 'tr : ! <test/access | makemap hash test/access.db'
if os.system(cmd):
print('failed!')
else:
print("Missing test/access")
def testPolicy(self):
<|code_end|>
. Write the next line using the current file imports:
import unittest
import sys
import os
from Milter.policy import MTAPolicy
and context from other files:
# Path: Milter/policy.py
# class MTAPolicy(object):
# "Get SPF policy by result from sendmail style access file."
# def __init__(self,sender,conf,access_file=None):
# if not access_file:
# access_file = conf.access_file
# self.use_nulls = conf.access_file_nulls
# self.sender = sender
# self.domain = sender.split('@')[-1].lower()
# self.acf = None
# self.access_file = access_file
#
# def close(self):
# if self.acf:
# self.acf.close()
#
# def __enter__(self):
# self.acf = None
# if self.access_file:
# try:
# self.acf = dbmopen(self.access_file,'r')
# except:
# print('%s: Cannot open for reading'%self.access_file)
# raise
# return self
# def __exit__(self,t,v,b): self.close()
#
# def getPolicy(self,pfx):
# acf = self.acf
# if not acf: return None
# if self.use_nulls: sfx = b'\x00'
# else: sfx = b''
# pfx = pfx.encode() + b'!'
# try:
# return acf[pfx + self.sender.encode() + sfx].rstrip(b'\x00').decode()
# except KeyError:
# try:
# return acf[pfx + self.domain.encode() + sfx].rstrip(b'\x00').decode()
# except KeyError:
# try:
# return acf[pfx + sfx].rstrip(b'\x00').decode()
# except KeyError:
# try:
# return acf[pfx[:-1] + sfx].rstrip(b'\x00').decode()
# except KeyError:
# return None
, which may include functions, classes, or code. Output only the next line. | with MTAPolicy('good@example.com',conf=self.config) as p: |
Continue the code snippet: <|code_start|> self._activity = time.time()
def _abort(self):
"What Milter sets for abort_callback"
self._priv.abort()
self._close()
def _close(self):
Milter.close_callback(self)
def _negotiate(self):
self._body = None
self._bodyreplaced = False
self._priv = None
self._opts = TestCtx.default_opts
self._stage = -1
rc = Milter.negotiate_callback(self,self._opts)
if rc == Milter.ALL_OPTS:
self._opts = TestCtx.default_opts
elif rc != Milter.CONTINUE:
self._abort()
self._close()
self._protocol = self._opts[1]
return rc
def _connect(self,host='localhost',helo='spamrelay',ip='1.2.3.4'):
rc = self._negotiate()
# FIXME: what if not CONTINUE or ALL_OPTS?
if self._protocol & Milter.P_NOCONNECT:
return Milter.CONTINUE
<|code_end|>
. Use current file imports:
from socket import AF_INET,AF_INET6
from sys import version as VERSION
from io import BytesIO
from StringIO import StringIO as BytesIO
from Milter import utils
import time
import mime
import Milter
and context (classes, functions, or code) from other files:
# Path: Milter/utils.py
# PAT_IP4 = r'\.'.join([r'(?:\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])']*4)
# MASK = 0xFFFFFFFF
# MASK6 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
# def addr2bin(s):
# def bin2long6(s):
# def inet_ntop(s):
# def inet_pton(s):
# def cidr(i,n,mask=MASK):
# def iniplist(ipaddr,iplist):
# def parseaddr(t):
# def decode(s, convert_eols=None):
# def parse_addr(t):
# def parse_header(val):
. Output only the next line. | if utils.ip4re.match(ip): |
Predict the next line for this snippet: <|code_start|>
def test_find_all_payables():
all_payables = payable.find_all()
assert all_payables is not None
def test_find_by():
<|code_end|>
with the help of current file imports:
from pagarme import payable
from tests.resources.dictionaries import payable_dictionary
and context from other files:
# Path: pagarme/payable.py
# def find_all():
# def find_by(search_params):
#
# Path: tests/resources/dictionaries/payable_dictionary.py
# TRANSACTION = transaction.create(transaction_dictionary.VALID_CREDIT_CARD_TRANSACTION)
# PAYABLES = transaction.payables(TRANSACTION['id'])
, which may contain function names, class names, or code. Output only the next line. | search_params = {'id': str(payable_dictionary.PAYABLES[0]['id'])} |
Next line prediction: <|code_start|>
BOLETO_TRANSACTION = {
'amount': '1000000',
'payment_method': 'boleto',
'postback_url': pagarme_test.create_postback_url(),
'customer': customer_dictionary.CUSTOMER,
}
CALCULATE_INTALLMENTS_AMOUNT = {
'amount': '10000',
'free_installments': "1",
'interest_rate': '13',
'max_installments': '12'
}
<|code_end|>
. Use current file imports:
(from pagarme import recipient
from tests.resources import pagarme_test
from tests.resources.dictionaries import card_dictionary
from tests.resources.dictionaries import customer_dictionary
from tests.resources.dictionaries import recipient_dictionary)
and context including class names, function names, or small code snippets from other files:
# Path: pagarme/recipient.py
# def create(dictionary):
# def default_recipient():
# def find_all():
# def find_by(search_params):
# def recipient_balance(recipient_id):
# def recipient_balance_operation(recipient_id):
# def recipient_balance_operation_id(recipient_id, operation_id):
# def update_recipient(recipient_id, dictionary):
#
# Path: tests/resources/pagarme_test.py
# AUTH_TEST = handler_request.authentication_key(None, True)
# POSTBACK_URL = 'http://teste.url.com'
# BUSINESS_CALENDAR_URL = 'https://pagarme.github.io/business-calendar/data/brazil/{0}.json'
# def create_postback_url():
# def generate_timestamp():
# def is_holiday(date):
# def is_weekend(date):
# def get_business_calendar(year):
#
# Path: tests/resources/dictionaries/card_dictionary.py
# INVALID_CARD = {
# 'card_number': '4242424242424242',
# 'card_cvv': '611',
# 'card_holder_name': 'THEON GREYJOY',
# 'card_expiration_date': '1220'
# }
# VALID_CARD = {
# 'card_number': '4242424242424242',
# 'card_cvv': '111',
# 'card_holder_name': 'DAENERYS TARGARYEN',
# 'card_expiration_date': '1220'
# }
#
# Path: tests/resources/dictionaries/customer_dictionary.py
# ADDRESS = {
# 'address': {
# 'zipcode': '04571020',
# 'neighborhood': 'Dragon Village',
# 'street': 'Rua Drogon',
# 'street_number': '240'
# }
# }
# PHONE = {
# 'phone': {
# 'number': '987654321',
# 'ddd': '11'
# }
# }
# CUSTOMER = {
# 'email': 'daenerys.targaryen@gmail.com',
# 'name': 'Daenerys Targaryen',
# 'document_number': '18152564000105',
# 'address': ADDRESS['address'],
# 'phone': PHONE['phone']
# }
#
# Path: tests/resources/dictionaries/recipient_dictionary.py
# BANK_ACCOUNT = bank_account.create(bank_account_dictionary.BANK_ACCOUNT)
# RECIPIENT = {
# 'anticipatable_volume_percentage': '80',
# 'automatic_anticipation_enabled': 'true',
# 'transfer_day': '5',
# 'transfer_enabled': 'true',
# 'transfer_interval': 'weekly',
# 'bank_account_id': BANK_ACCOUNT['id']
# }
# UPDATE_RECIPIENT = {
# 'transfer_enabled': 'false',
# 'anticipatable_volume_percentage': '85'
# }
. Output only the next line. | DEFAULT_RECIPIENT = recipient.default_recipient()['test'] |
Using the snippet: <|code_start|>
BOLETO_TRANSACTION = {
'amount': '1000000',
'payment_method': 'boleto',
<|code_end|>
, determine the next line of code. You have imports:
from pagarme import recipient
from tests.resources import pagarme_test
from tests.resources.dictionaries import card_dictionary
from tests.resources.dictionaries import customer_dictionary
from tests.resources.dictionaries import recipient_dictionary
and context (class names, function names, or code) available:
# Path: pagarme/recipient.py
# def create(dictionary):
# def default_recipient():
# def find_all():
# def find_by(search_params):
# def recipient_balance(recipient_id):
# def recipient_balance_operation(recipient_id):
# def recipient_balance_operation_id(recipient_id, operation_id):
# def update_recipient(recipient_id, dictionary):
#
# Path: tests/resources/pagarme_test.py
# AUTH_TEST = handler_request.authentication_key(None, True)
# POSTBACK_URL = 'http://teste.url.com'
# BUSINESS_CALENDAR_URL = 'https://pagarme.github.io/business-calendar/data/brazil/{0}.json'
# def create_postback_url():
# def generate_timestamp():
# def is_holiday(date):
# def is_weekend(date):
# def get_business_calendar(year):
#
# Path: tests/resources/dictionaries/card_dictionary.py
# INVALID_CARD = {
# 'card_number': '4242424242424242',
# 'card_cvv': '611',
# 'card_holder_name': 'THEON GREYJOY',
# 'card_expiration_date': '1220'
# }
# VALID_CARD = {
# 'card_number': '4242424242424242',
# 'card_cvv': '111',
# 'card_holder_name': 'DAENERYS TARGARYEN',
# 'card_expiration_date': '1220'
# }
#
# Path: tests/resources/dictionaries/customer_dictionary.py
# ADDRESS = {
# 'address': {
# 'zipcode': '04571020',
# 'neighborhood': 'Dragon Village',
# 'street': 'Rua Drogon',
# 'street_number': '240'
# }
# }
# PHONE = {
# 'phone': {
# 'number': '987654321',
# 'ddd': '11'
# }
# }
# CUSTOMER = {
# 'email': 'daenerys.targaryen@gmail.com',
# 'name': 'Daenerys Targaryen',
# 'document_number': '18152564000105',
# 'address': ADDRESS['address'],
# 'phone': PHONE['phone']
# }
#
# Path: tests/resources/dictionaries/recipient_dictionary.py
# BANK_ACCOUNT = bank_account.create(bank_account_dictionary.BANK_ACCOUNT)
# RECIPIENT = {
# 'anticipatable_volume_percentage': '80',
# 'automatic_anticipation_enabled': 'true',
# 'transfer_day': '5',
# 'transfer_enabled': 'true',
# 'transfer_interval': 'weekly',
# 'bank_account_id': BANK_ACCOUNT['id']
# }
# UPDATE_RECIPIENT = {
# 'transfer_enabled': 'false',
# 'anticipatable_volume_percentage': '85'
# }
. Output only the next line. | 'postback_url': pagarme_test.create_postback_url(), |
Given snippet: <|code_start|> 'amount': 500000,
'liable': 'true',
'charge_processing_fee': 'true'
}
]
SPLIT_RULE_PERCENTAGE = [
{
'recipient_id': DEFAULT_RECIPIENT,
'percentage': 50,
'liable': 'true',
'charge_processing_fee': 'true'
},
{
'recipient_id': RECIPIENT['id'],
'percentage': 50,
'liable': 'true',
'charge_processing_fee': 'true'
}
]
BOLETO_TRANSACTION_SPLIT_RULE_PERCENTAGE = {
'amount': BOLETO_TRANSACTION['amount'],
'payment_method': BOLETO_TRANSACTION['payment_method'],
'split_rules': SPLIT_RULE_PERCENTAGE,
'customer': customer_dictionary.CUSTOMER,
}
INVALID_CREDIT_CARD_TRANSACTION = {
'amount': '1000000',
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pagarme import recipient
from tests.resources import pagarme_test
from tests.resources.dictionaries import card_dictionary
from tests.resources.dictionaries import customer_dictionary
from tests.resources.dictionaries import recipient_dictionary
and context:
# Path: pagarme/recipient.py
# def create(dictionary):
# def default_recipient():
# def find_all():
# def find_by(search_params):
# def recipient_balance(recipient_id):
# def recipient_balance_operation(recipient_id):
# def recipient_balance_operation_id(recipient_id, operation_id):
# def update_recipient(recipient_id, dictionary):
#
# Path: tests/resources/pagarme_test.py
# AUTH_TEST = handler_request.authentication_key(None, True)
# POSTBACK_URL = 'http://teste.url.com'
# BUSINESS_CALENDAR_URL = 'https://pagarme.github.io/business-calendar/data/brazil/{0}.json'
# def create_postback_url():
# def generate_timestamp():
# def is_holiday(date):
# def is_weekend(date):
# def get_business_calendar(year):
#
# Path: tests/resources/dictionaries/card_dictionary.py
# INVALID_CARD = {
# 'card_number': '4242424242424242',
# 'card_cvv': '611',
# 'card_holder_name': 'THEON GREYJOY',
# 'card_expiration_date': '1220'
# }
# VALID_CARD = {
# 'card_number': '4242424242424242',
# 'card_cvv': '111',
# 'card_holder_name': 'DAENERYS TARGARYEN',
# 'card_expiration_date': '1220'
# }
#
# Path: tests/resources/dictionaries/customer_dictionary.py
# ADDRESS = {
# 'address': {
# 'zipcode': '04571020',
# 'neighborhood': 'Dragon Village',
# 'street': 'Rua Drogon',
# 'street_number': '240'
# }
# }
# PHONE = {
# 'phone': {
# 'number': '987654321',
# 'ddd': '11'
# }
# }
# CUSTOMER = {
# 'email': 'daenerys.targaryen@gmail.com',
# 'name': 'Daenerys Targaryen',
# 'document_number': '18152564000105',
# 'address': ADDRESS['address'],
# 'phone': PHONE['phone']
# }
#
# Path: tests/resources/dictionaries/recipient_dictionary.py
# BANK_ACCOUNT = bank_account.create(bank_account_dictionary.BANK_ACCOUNT)
# RECIPIENT = {
# 'anticipatable_volume_percentage': '80',
# 'automatic_anticipation_enabled': 'true',
# 'transfer_day': '5',
# 'transfer_enabled': 'true',
# 'transfer_interval': 'weekly',
# 'bank_account_id': BANK_ACCOUNT['id']
# }
# UPDATE_RECIPIENT = {
# 'transfer_enabled': 'false',
# 'anticipatable_volume_percentage': '85'
# }
which might include code, classes, or functions. Output only the next line. | 'card_number': card_dictionary.INVALID_CARD['card_number'], |
Here is a snippet: <|code_start|>
BOLETO_TRANSACTION = {
'amount': '1000000',
'payment_method': 'boleto',
'postback_url': pagarme_test.create_postback_url(),
<|code_end|>
. Write the next line using the current file imports:
from pagarme import recipient
from tests.resources import pagarme_test
from tests.resources.dictionaries import card_dictionary
from tests.resources.dictionaries import customer_dictionary
from tests.resources.dictionaries import recipient_dictionary
and context from other files:
# Path: pagarme/recipient.py
# def create(dictionary):
# def default_recipient():
# def find_all():
# def find_by(search_params):
# def recipient_balance(recipient_id):
# def recipient_balance_operation(recipient_id):
# def recipient_balance_operation_id(recipient_id, operation_id):
# def update_recipient(recipient_id, dictionary):
#
# Path: tests/resources/pagarme_test.py
# AUTH_TEST = handler_request.authentication_key(None, True)
# POSTBACK_URL = 'http://teste.url.com'
# BUSINESS_CALENDAR_URL = 'https://pagarme.github.io/business-calendar/data/brazil/{0}.json'
# def create_postback_url():
# def generate_timestamp():
# def is_holiday(date):
# def is_weekend(date):
# def get_business_calendar(year):
#
# Path: tests/resources/dictionaries/card_dictionary.py
# INVALID_CARD = {
# 'card_number': '4242424242424242',
# 'card_cvv': '611',
# 'card_holder_name': 'THEON GREYJOY',
# 'card_expiration_date': '1220'
# }
# VALID_CARD = {
# 'card_number': '4242424242424242',
# 'card_cvv': '111',
# 'card_holder_name': 'DAENERYS TARGARYEN',
# 'card_expiration_date': '1220'
# }
#
# Path: tests/resources/dictionaries/customer_dictionary.py
# ADDRESS = {
# 'address': {
# 'zipcode': '04571020',
# 'neighborhood': 'Dragon Village',
# 'street': 'Rua Drogon',
# 'street_number': '240'
# }
# }
# PHONE = {
# 'phone': {
# 'number': '987654321',
# 'ddd': '11'
# }
# }
# CUSTOMER = {
# 'email': 'daenerys.targaryen@gmail.com',
# 'name': 'Daenerys Targaryen',
# 'document_number': '18152564000105',
# 'address': ADDRESS['address'],
# 'phone': PHONE['phone']
# }
#
# Path: tests/resources/dictionaries/recipient_dictionary.py
# BANK_ACCOUNT = bank_account.create(bank_account_dictionary.BANK_ACCOUNT)
# RECIPIENT = {
# 'anticipatable_volume_percentage': '80',
# 'automatic_anticipation_enabled': 'true',
# 'transfer_day': '5',
# 'transfer_enabled': 'true',
# 'transfer_interval': 'weekly',
# 'bank_account_id': BANK_ACCOUNT['id']
# }
# UPDATE_RECIPIENT = {
# 'transfer_enabled': 'false',
# 'anticipatable_volume_percentage': '85'
# }
, which may include functions, classes, or code. Output only the next line. | 'customer': customer_dictionary.CUSTOMER, |
Given the code snippet: <|code_start|>
BOLETO_TRANSACTION = {
'amount': '1000000',
'payment_method': 'boleto',
'postback_url': pagarme_test.create_postback_url(),
'customer': customer_dictionary.CUSTOMER,
}
CALCULATE_INTALLMENTS_AMOUNT = {
'amount': '10000',
'free_installments': "1",
'interest_rate': '13',
'max_installments': '12'
}
DEFAULT_RECIPIENT = recipient.default_recipient()['test']
<|code_end|>
, generate the next line using the imports in this file:
from pagarme import recipient
from tests.resources import pagarme_test
from tests.resources.dictionaries import card_dictionary
from tests.resources.dictionaries import customer_dictionary
from tests.resources.dictionaries import recipient_dictionary
and context (functions, classes, or occasionally code) from other files:
# Path: pagarme/recipient.py
# def create(dictionary):
# def default_recipient():
# def find_all():
# def find_by(search_params):
# def recipient_balance(recipient_id):
# def recipient_balance_operation(recipient_id):
# def recipient_balance_operation_id(recipient_id, operation_id):
# def update_recipient(recipient_id, dictionary):
#
# Path: tests/resources/pagarme_test.py
# AUTH_TEST = handler_request.authentication_key(None, True)
# POSTBACK_URL = 'http://teste.url.com'
# BUSINESS_CALENDAR_URL = 'https://pagarme.github.io/business-calendar/data/brazil/{0}.json'
# def create_postback_url():
# def generate_timestamp():
# def is_holiday(date):
# def is_weekend(date):
# def get_business_calendar(year):
#
# Path: tests/resources/dictionaries/card_dictionary.py
# INVALID_CARD = {
# 'card_number': '4242424242424242',
# 'card_cvv': '611',
# 'card_holder_name': 'THEON GREYJOY',
# 'card_expiration_date': '1220'
# }
# VALID_CARD = {
# 'card_number': '4242424242424242',
# 'card_cvv': '111',
# 'card_holder_name': 'DAENERYS TARGARYEN',
# 'card_expiration_date': '1220'
# }
#
# Path: tests/resources/dictionaries/customer_dictionary.py
# ADDRESS = {
# 'address': {
# 'zipcode': '04571020',
# 'neighborhood': 'Dragon Village',
# 'street': 'Rua Drogon',
# 'street_number': '240'
# }
# }
# PHONE = {
# 'phone': {
# 'number': '987654321',
# 'ddd': '11'
# }
# }
# CUSTOMER = {
# 'email': 'daenerys.targaryen@gmail.com',
# 'name': 'Daenerys Targaryen',
# 'document_number': '18152564000105',
# 'address': ADDRESS['address'],
# 'phone': PHONE['phone']
# }
#
# Path: tests/resources/dictionaries/recipient_dictionary.py
# BANK_ACCOUNT = bank_account.create(bank_account_dictionary.BANK_ACCOUNT)
# RECIPIENT = {
# 'anticipatable_volume_percentage': '80',
# 'automatic_anticipation_enabled': 'true',
# 'transfer_day': '5',
# 'transfer_enabled': 'true',
# 'transfer_interval': 'weekly',
# 'bank_account_id': BANK_ACCOUNT['id']
# }
# UPDATE_RECIPIENT = {
# 'transfer_enabled': 'false',
# 'anticipatable_volume_percentage': '85'
# }
. Output only the next line. | RECIPIENT = recipient.create(recipient_dictionary.RECIPIENT) |
Next line prediction: <|code_start|>
TEMPORARY_COMPANY = 'https://api.pagar.me/1/companies/temporary'
KEYS = {}
def validate_response(pagarme_response):
if pagarme_response.ok:
return pagarme_response.json()
else:
return error(pagarme_response.json())
def create_temporary_company():
<|code_end|>
. Use current file imports:
(from .requests_retry import requests_retry_session)
and context including class names, function names, or small code snippets from other files:
# Path: pagarme/resources/requests_retry.py
# def requests_retry_session(
# retries=3,
# backoff_factor=0.3,
# status_forcelist=(500, 502, 504),
# session=None,
# ):
# session = session or requests.Session()
# session.headers.update(headers())
#
# retry = Retry(
# total=retries,
# read=retries,
# connect=retries,
# backoff_factor=backoff_factor,
# status_forcelist=status_forcelist,
# )
# adapter = HTTPAdapter(max_retries=retry)
# session.mount('https://', adapter)
# return session
. Output only the next line. | company = requests_retry_session().post(TEMPORARY_COMPANY) |
Next line prediction: <|code_start|> filename = pushbutton['filename']
audio_segments = utils.get_segments(filename)
print 'Single response to {} duration {} seconds with {} segments'.format(filename, audio_segments[-1], len(audio_segments)-1)
new_sentence = utils.csv_to_array(filename + 'cochlear')
norm_segments = np.rint(new_sentence.shape[0]*audio_segments/audio_segments[-1]).astype('int')
segment_id = utils.get_most_significant_word(filename)
NAP = utils.trim_right(new_sentence[norm_segments[segment_id]:norm_segments[segment_id+1]])
if debug:
plt.imshow(NAP.T, aspect='auto')
plt.draw()
best_match,_,_,_,_ = audio_memory.find(NAP)
soundfile = best_match.wav_file
segstart, segend = best_match.segment_idxs
voiceChannel = 1
speed = 1
amp = -3 # voice amplitude in dB
_,dur,maxamp,_ = utils.getSoundInfo(soundfile)
start = 0
voice1 = 'playfile {} {} {} {} {} {} {} {} {}'.format(1, voiceType1, start, soundfile, speed, segstart, segend, amp, maxamp)
voice2 = ''
print 'Recognized as sound {}'.format(best_match.audio_id)
# sound_to_face, video_producer
<|code_end|>
. Use current file imports:
(import multiprocessing as mp
import sys
import glob
import cPickle as pickle
import time
import os
import itertools
import random
import numpy as np
import zmq
import utils
import IO
import association
import my_sai_test as mysai
import myCsoundAudioOptions
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from uuid import uuid4
from collections import deque
from subprocess import call
from collections import namedtuple
from scipy.stats import itemfreq
from scipy.cluster.vq import kmeans, vq
from brain import _project, _extract_NAP, _three_amigos)
and context including class names, function names, or small code snippets from other files:
# Path: brain.py
# def _project(audio_id, sound_to_face, NAP, video_producer):
# stride = IO.VIDEO_SAMPLE_TIME / (IO.NAP_RATE/IO.NAP_STRIDE)
# length = np.floor(NAP.shape[0]*.8).astype('int')
# NAP = NAP[:length:stride]
# try:
# face_id = np.random.choice(sound_to_face[audio_id])
# tarantino = utils.load_esn(video_producer[(audio_id, face_id)])
# return tarantino(NAP)
# except:
# matches = filter(lambda key: key[0] == audio_id, video_producer.keys())
# if len(matches):
# tarantino = utils.load_esn(video_producer[random.choice(matches)])
# else:
# tarantino = utils.load_esn(video_producer[random.choice(video_producer.keys())])
# return tarantino(NAP)
#
# def _extract_NAP(segstart, segend, soundfile, suffix='cochlear'):
# new_sentence = utils.csv_to_array(soundfile + suffix)
# audio_segments = utils.get_segments(soundfile)
# segstart_norm = int(np.rint(new_sentence.shape[0]*segstart/audio_segments[-1]))
# segend_norm = int(np.rint(new_sentence.shape[0]*segend/audio_segments[-1]))
# return utils.trim_right(new_sentence[segstart_norm:segend_norm])
#
# def _three_amigos(context, host):
# stateQ = context.socket(zmq.SUB)
# stateQ.connect('tcp://{}:{}'.format(host, IO.STATE))
# stateQ.setsockopt(zmq.SUBSCRIBE, b'')
#
# eventQ = context.socket(zmq.SUB)
# eventQ.connect('tcp://{}:{}'.format(host, IO.EVENT))
# eventQ.setsockopt(zmq.SUBSCRIBE, b'')
#
# brainQ = context.socket(zmq.PUSH)
# brainQ.connect('tcp://{}:{}'.format(host, IO.BRAIN))
#
# return stateQ, eventQ, brainQ
. Output only the next line. | projection = _project(best_match.audio_id, sound_to_face, NAP, video_producer) |
Here is a snippet: <|code_start|>
start = 0
voice1 = 'playfile {} {} {} {} {} {} {} {} {}'.format(1, voiceType1, start, soundfile, speed, segstart, segend, amp, maxamp)
voice2 = ''
print 'Recognized as sound {}'.format(best_match.audio_id)
# sound_to_face, video_producer
projection = _project(best_match.audio_id, sound_to_face, NAP, video_producer)
scheduler.send_pyobj([[ dur, voice1, voice2, projection, FRAME_SIZE ]])
print 'Respond time from creation of wav file was {} seconds'.format(time.time() - utils.filetime(filename))
except:
utils.print_exception('Single response aborted.')
if 'play_sentence' in pushbutton:
try:
sentence = pushbutton['sentence']
sentence = eval(sentence)
print '*** (play) Play sentence', sentence
start = 0
nextTime1 = 0
play_events = []
for i in range(len(sentence)):
word_id = sentence[i]
soundfile = np.random.choice(wavs[word_id])
speed = 1
segstart, segend = wav_audio_ids[(soundfile, word_id)]
<|code_end|>
. Write the next line using the current file imports:
import multiprocessing as mp
import sys
import glob
import cPickle as pickle
import time
import os
import itertools
import random
import numpy as np
import zmq
import utils
import IO
import association
import my_sai_test as mysai
import myCsoundAudioOptions
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from uuid import uuid4
from collections import deque
from subprocess import call
from collections import namedtuple
from scipy.stats import itemfreq
from scipy.cluster.vq import kmeans, vq
from brain import _project, _extract_NAP, _three_amigos
and context from other files:
# Path: brain.py
# def _project(audio_id, sound_to_face, NAP, video_producer):
# stride = IO.VIDEO_SAMPLE_TIME / (IO.NAP_RATE/IO.NAP_STRIDE)
# length = np.floor(NAP.shape[0]*.8).astype('int')
# NAP = NAP[:length:stride]
# try:
# face_id = np.random.choice(sound_to_face[audio_id])
# tarantino = utils.load_esn(video_producer[(audio_id, face_id)])
# return tarantino(NAP)
# except:
# matches = filter(lambda key: key[0] == audio_id, video_producer.keys())
# if len(matches):
# tarantino = utils.load_esn(video_producer[random.choice(matches)])
# else:
# tarantino = utils.load_esn(video_producer[random.choice(video_producer.keys())])
# return tarantino(NAP)
#
# def _extract_NAP(segstart, segend, soundfile, suffix='cochlear'):
# new_sentence = utils.csv_to_array(soundfile + suffix)
# audio_segments = utils.get_segments(soundfile)
# segstart_norm = int(np.rint(new_sentence.shape[0]*segstart/audio_segments[-1]))
# segend_norm = int(np.rint(new_sentence.shape[0]*segend/audio_segments[-1]))
# return utils.trim_right(new_sentence[segstart_norm:segend_norm])
#
# def _three_amigos(context, host):
# stateQ = context.socket(zmq.SUB)
# stateQ.connect('tcp://{}:{}'.format(host, IO.STATE))
# stateQ.setsockopt(zmq.SUBSCRIBE, b'')
#
# eventQ = context.socket(zmq.SUB)
# eventQ.connect('tcp://{}:{}'.format(host, IO.EVENT))
# eventQ.setsockopt(zmq.SUBSCRIBE, b'')
#
# brainQ = context.socket(zmq.PUSH)
# brainQ.connect('tcp://{}:{}'.format(host, IO.BRAIN))
#
# return stateQ, eventQ, brainQ
, which may include functions, classes, or code. Output only the next line. | NAP = _extract_NAP(segstart, segend, soundfile) |
Based on the snippet: <|code_start|> NAP = _extract_NAP(segstart, segend, audio_segment.wav_file)
speed = 1
amp = -3
maxamp = 1
start = 0
voice1 = 'playfile {} {} {} {} {} {} {} {} {}'.format(1, 6, np.random.rand()/3, audio_segment.wav_file, speed, segstart, segend, amp, maxamp)
projection = _project(audio_segment.audio_id, sound_to_face, NAP, video_producer)
voice2 = 'playfile {} {} {} {} {} {} {} {} {}'.format(2, 6, np.random.randint(3,6), audio_segment.wav_file, speed, segstart, segend, amp, maxamp)
play_events.append([ dur, voice1, voice2, projection, FRAME_SIZE ])
print 'Dream mode playing back {} memories'.format(len(play_events))
scheduler.send_pyobj(play_events)
if 'save' in pushbutton:
utils.save('{}.{}'.format(pushbutton['save'], mp.current_process().name), [ sound_to_face, wordFace, face_to_sound, faceWord, video_producer, wavs, wav_audio_ids, audio_classifier, maxlen, NAP_hashes, face_id, face_recognizer, audio_memory ])
if 'load' in pushbutton:
sound_to_face, wordFace, face_to_sound, faceWord, video_producer, wavs, wav_audio_ids, audio_classifier, maxlen, NAP_hashes, face_id, face_recognizer, audio_memory = utils.load('{}.{}'.format(pushbutton['load'], mp.current_process().name))
def new_learn_audio(host, debug=False):
context = zmq.Context()
mic = context.socket(zmq.SUB)
mic.connect('tcp://{}:{}'.format(host, IO.MIC))
mic.setsockopt(zmq.SUBSCRIBE, b'')
dreamQ = context.socket(zmq.PUSH)
dreamQ.connect('tcp://{}:{}'.format(host, IO.DREAM))
<|code_end|>
, predict the immediate next line with the help of imports:
import multiprocessing as mp
import sys
import glob
import cPickle as pickle
import time
import os
import itertools
import random
import numpy as np
import zmq
import utils
import IO
import association
import my_sai_test as mysai
import myCsoundAudioOptions
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from uuid import uuid4
from collections import deque
from subprocess import call
from collections import namedtuple
from scipy.stats import itemfreq
from scipy.cluster.vq import kmeans, vq
from brain import _project, _extract_NAP, _three_amigos
and context (classes, functions, sometimes code) from other files:
# Path: brain.py
# def _project(audio_id, sound_to_face, NAP, video_producer):
# stride = IO.VIDEO_SAMPLE_TIME / (IO.NAP_RATE/IO.NAP_STRIDE)
# length = np.floor(NAP.shape[0]*.8).astype('int')
# NAP = NAP[:length:stride]
# try:
# face_id = np.random.choice(sound_to_face[audio_id])
# tarantino = utils.load_esn(video_producer[(audio_id, face_id)])
# return tarantino(NAP)
# except:
# matches = filter(lambda key: key[0] == audio_id, video_producer.keys())
# if len(matches):
# tarantino = utils.load_esn(video_producer[random.choice(matches)])
# else:
# tarantino = utils.load_esn(video_producer[random.choice(video_producer.keys())])
# return tarantino(NAP)
#
# def _extract_NAP(segstart, segend, soundfile, suffix='cochlear'):
# new_sentence = utils.csv_to_array(soundfile + suffix)
# audio_segments = utils.get_segments(soundfile)
# segstart_norm = int(np.rint(new_sentence.shape[0]*segstart/audio_segments[-1]))
# segend_norm = int(np.rint(new_sentence.shape[0]*segend/audio_segments[-1]))
# return utils.trim_right(new_sentence[segstart_norm:segend_norm])
#
# def _three_amigos(context, host):
# stateQ = context.socket(zmq.SUB)
# stateQ.connect('tcp://{}:{}'.format(host, IO.STATE))
# stateQ.setsockopt(zmq.SUBSCRIBE, b'')
#
# eventQ = context.socket(zmq.SUB)
# eventQ.connect('tcp://{}:{}'.format(host, IO.EVENT))
# eventQ.setsockopt(zmq.SUBSCRIBE, b'')
#
# brainQ = context.socket(zmq.PUSH)
# brainQ.connect('tcp://{}:{}'.format(host, IO.BRAIN))
#
# return stateQ, eventQ, brainQ
. Output only the next line. | stateQ, eventQ, brainQ = _three_amigos(context, host) |
Predict the next line for this snippet: <|code_start|>class NeverUseMeAgainParser:
def __init__(self, learn_state, respond_state):
self.learn_state = learn_state
self.respond_state = respond_state
def parse(self, message):
print '[self.] received:', message
if message == 'learn':
self.learn_state.value = 1
if message == 'respond':
self.respond_state.value = 1
if __name__ == '__main__':
ear_q = mp.Queue()
memorize_q = mp.Queue()
learned_q = mp.Queue()
response_q = mp.Queue()
manager = mp.Manager()
brain = manager.list()
output = manager.list()
learn_state = mp.Value('i', 0)
respond_state = mp.Value('i', 0)
parser = NeverUseMeAgainParser(learn_state, respond_state)
mp.Process(target=learn, args=(memorize_q, brain, learned_q)).start()
mp.Process(target=respond, args=(ear_q, brain, output, response_q)).start()
mp.Process(target=plot, args=(learned_q, response_q)).start()
mp.Process(target=csound, args=(memorize_q, ear_q, output, learn_state, respond_state)).start()
<|code_end|>
with the help of current file imports:
import multiprocessing as mp
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import Oger
import mdp
import csnd6
from collections import deque
from sklearn import preprocessing as pp
from communication import receive
from utils import net_rmse
and context from other files:
# Path: communication.py
# def send(message, context=None, host='localhost', port=5566):
#
# Path: utils.py
# DREAM_HOUR = 23
# EVOLVE_HOUR = 4
# SAVE_HOUR = 5
# REBOOT_HOUR = 6
# A = np.frombuffer(buf, dtype=md['dtype'])
# def save(filename, data):
# def load(filename):
# def filetime(filename):
# def plot_NAP_and_energy(NAP, plt):
# def bytes2human(n, format="%(value)i%(symbol)s"):
# def csv_to_array(filename, delimiter=' '):
# def array_to_csv(filename, data, delimiter=' '):
# def wait_for_wav(filename):
# def filesize(filename):
# def chunks(A, chunk_len):
# def wav_duration(filename):
# def trim(A, threshold=100):
# def trim_right(A, threshold=.2):
# def trim_wav(sound, threshold=100):
# def split_signal(data, threshold=100, length=5000, elbow_grease=100, plot=False, markers=[]):
# def split_wav(filename, threshold=100, length=5000, elbow_grease=100, plot=False):
# def send_zipped_pickle(socket, obj, flags=0, protocol=-1):
# def recv_zipped_pickle(socket, flags=0):
# def send_array(socket, A, flags=0, copy=True, track=False):
# def recv_array(socket, flags=0, copy=True, track=False):
# def diff_to_hex_bad(diff):
# def average_hash(image):
# def a_hash(image, hash_size=8):
# def p_hash(image, hash_size=64):
# def diff_to_hex(difference):
# def d_hash(image, hash_size = 8):
# def hamming_distance(s1, s2):
# def zero_pad(signal, length):
# def exact(signal, length):
# def scale(image):
# def getSoundInfo(filename):
# def get_segments(filename):
# def get_amps(filename):
# def get_most_significant_word(filename):
# def getLatestMemoryWavs(howmany):
# def updateAmbientMemoryWavs(currentFiles):
# def print_exception(msg=''):
# def scheduler(host):
# def true_wait(seconds):
# def reboot():
# def counter(host):
# def delete_loner(counterQ, data, query, protect, deleted_ids):
# def sentinel(host):
# def __init__(self, me, host='localhost'):
# def run(self):
# def __init__(self, host='localhost'):
# def write(self, txt):
# def flush(self):
# def __init__(self, host='localhost'):
# def write(self, txt):
# def flush(self):
# def log_sink():
# def run(self):
# def run(self):
# def brain_name():
# def find_last_valid_brain():
# def daily_routine(host):
# def load_esn(filename):
# def dump_esn(net, filename):
# class AliveNotifier(threading.Thread):
# class SimpleLogger:
# class Logger:
# class LoggerProcess(mp.Process):
# class MyProcess(mp.Process):
, which may contain function names, class names, or code. Output only the next line. | mp.Process(target=receive, args=(parser.parse,)).start() |
Next line prediction: <|code_start|> plt.draw()
plt.tight_layout()
def learn(memorize_q, brain, learned_q):
while True:
input_data = memorize_q.get()
scaler = pp.MinMaxScaler()
scaled_data = scaler.fit_transform(input_data)
reservoir = Oger.nodes.LeakyReservoirNode(output_dim=100,
leak_rate=0.8,
bias_scaling=.2,
reset_states=False)
readout = mdp.nodes.LinearRegressionNode(use_pinv=True)
net = mdp.hinet.FlowNode(reservoir + readout)
x = scaled_data[:-1]
y = scaled_data[1:]
net.train(x,y)
net.stop_training()
brain.append((net, scaler))
learned_q.put(scaled_data)
def respond(ear_q, brain, output, response_q):
while True:
signals = ear_q.get()
<|code_end|>
. Use current file imports:
(import multiprocessing as mp
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import Oger
import mdp
import csnd6
from collections import deque
from sklearn import preprocessing as pp
from communication import receive
from utils import net_rmse)
and context including class names, function names, or small code snippets from other files:
# Path: communication.py
# def send(message, context=None, host='localhost', port=5566):
#
# Path: utils.py
# DREAM_HOUR = 23
# EVOLVE_HOUR = 4
# SAVE_HOUR = 5
# REBOOT_HOUR = 6
# A = np.frombuffer(buf, dtype=md['dtype'])
# def save(filename, data):
# def load(filename):
# def filetime(filename):
# def plot_NAP_and_energy(NAP, plt):
# def bytes2human(n, format="%(value)i%(symbol)s"):
# def csv_to_array(filename, delimiter=' '):
# def array_to_csv(filename, data, delimiter=' '):
# def wait_for_wav(filename):
# def filesize(filename):
# def chunks(A, chunk_len):
# def wav_duration(filename):
# def trim(A, threshold=100):
# def trim_right(A, threshold=.2):
# def trim_wav(sound, threshold=100):
# def split_signal(data, threshold=100, length=5000, elbow_grease=100, plot=False, markers=[]):
# def split_wav(filename, threshold=100, length=5000, elbow_grease=100, plot=False):
# def send_zipped_pickle(socket, obj, flags=0, protocol=-1):
# def recv_zipped_pickle(socket, flags=0):
# def send_array(socket, A, flags=0, copy=True, track=False):
# def recv_array(socket, flags=0, copy=True, track=False):
# def diff_to_hex_bad(diff):
# def average_hash(image):
# def a_hash(image, hash_size=8):
# def p_hash(image, hash_size=64):
# def diff_to_hex(difference):
# def d_hash(image, hash_size = 8):
# def hamming_distance(s1, s2):
# def zero_pad(signal, length):
# def exact(signal, length):
# def scale(image):
# def getSoundInfo(filename):
# def get_segments(filename):
# def get_amps(filename):
# def get_most_significant_word(filename):
# def getLatestMemoryWavs(howmany):
# def updateAmbientMemoryWavs(currentFiles):
# def print_exception(msg=''):
# def scheduler(host):
# def true_wait(seconds):
# def reboot():
# def counter(host):
# def delete_loner(counterQ, data, query, protect, deleted_ids):
# def sentinel(host):
# def __init__(self, me, host='localhost'):
# def run(self):
# def __init__(self, host='localhost'):
# def write(self, txt):
# def flush(self):
# def __init__(self, host='localhost'):
# def write(self, txt):
# def flush(self):
# def log_sink():
# def run(self):
# def run(self):
# def brain_name():
# def find_last_valid_brain():
# def daily_routine(host):
# def load_esn(filename):
# def dump_esn(net, filename):
# class AliveNotifier(threading.Thread):
# class SimpleLogger:
# class Logger:
# class LoggerProcess(mp.Process):
# class MyProcess(mp.Process):
. Output only the next line. | rmse = net_rmse(brain, signals) |
Given the code snippet: <|code_start|>def sentinel(host):
context = zmq.Context()
life_signal_Q = context.socket(zmq.PULL)
life_signal_Q.bind('tcp://*:{}'.format(IO.SENTINEL))
sender = context.socket(zmq.PUSH)
sender.connect('tcp://{}:{}'.format(host, IO.EXTERNAL))
poller = zmq.Poller()
poller.register(life_signal_Q, zmq.POLLIN)
book = {}
save_name = False
save_time = 0
while True:
events = dict(poller.poll(timeout=IO.PROCESS_TIME_OUT*2))
if life_signal_Q in events:
process = life_signal_Q.recv_pyobj()
book[process] = time.time()
for process in book.keys():
if not save_name and time.time() - book[process] > IO.PROCESS_TIME_OUT*2:
print '{} HAS DIED, SAVING'.format(process)
save_name = brain_name()
save_time = time.time()
sender.send_json('save {}'.format(save_name))
<|code_end|>
, generate the next line using the imports in this file:
import os
import wave
import csv
import time
import re
import linecache
import sys
import cPickle as pickle
import zlib
import random
import multiprocessing as mp
import threading
import glob
import fcntl
import json
import sched
import datetime
import numpy as np
import zmq
import scipy.fftpack
import cv2
import IO
import matplotlib.pyplot as plt
import Oger
import mdp
from subprocess import call
from scipy.io import wavfile
from sklearn.covariance import EmpiricalCovariance, MinCovDet
from scipy.stats import itemfreq
from brain import cochlear
from brain import NUMBER_OF_BRAINS
from scipy.io import wavfile
and context (functions, classes, or occasionally code) from other files:
# Path: brain.py
# def cochlear(filename, stride, rate, db=-40, ears=1, a_1=-0.995, apply_filter=1, suffix='cochlear'):
# original_rate, data = wavfile.read(filename)
# assert data.dtype == np.int16
# data = data / float(2**15)
# if original_rate != rate:
# data = resample(data, float(rate)/original_rate, 'sinc_best')
# data = data*10**(db/20)
# utils.array_to_csv('{}-audio.txt'.format(filename), data)
# call(['./carfac-cmd', filename, str(len(data)), str(ears), str(rate), str(stride), str(a_1), str(apply_filter), suffix])
# naps = utils.csv_to_array(filename+suffix)
# return np.sqrt(np.maximum(0, naps)/np.max(naps))
#
# Path: brain.py
# NUMBER_OF_BRAINS = 5
. Output only the next line. | if save_name and (len(glob.glob('{}*'.format(save_name))) == NUMBER_OF_BRAINS or time.time() - save_time > IO.SYSTEM_TIME_OUT): |
Next line prediction: <|code_start|>''' [self.]
@author: Axel Tidemann, Øyvind Brandtsegg
@contact: axel.tidemann@gmail.com, obrandts@gmail.com
@license: GPL
'''
''' Finds the best parameters for the neural networks that performs audio recognition, using evolution.'''
audio_memories = pickle.load(open('counts.pickle'))
test = audio_memories[1::2]
train = audio_memories[:-1:2]
idxs = [0,6,7,8,9,12]
new_test = [chop(t[:,idxs]) for t in test ]
new_train = [chop(t[:,idxs]) for t in train ]
targets = []
for i, memory in enumerate(new_train):
target = np.zeros((memory.shape[0], len(train))) - 1
target[:,i] = 1
targets.append(target)
def fitness(chromosome):
<|code_end|>
. Use current file imports:
(import cPickle as pickle
import numpy as np
from pyevolve import G1DList, GSimpleGA, Mutators
from AI import _train_network
from brain import chop)
and context including class names, function names, or small code snippets from other files:
# Path: AI.py
# class MultiClassifier:
# def __init__(bins=10):
# def fit(data):
# def predict(test):
# def recognize(host):
# def learn(audio_in, audio_out, video_in, video_out, host):
# def live(audio_recognizer, audio_producer, audio2video, scaler, host):
#
# Path: brain.py
# FACE_HAAR_CASCADE_PATH = opencv_prefix + '/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml'
# EYE_HAAR_CASCADE_PATH = opencv_prefix + '/share/OpenCV/haarcascades/haarcascade_eye_tree_eyeglasses.xml'
# AUDIO_HAMMERTIME = 9
# RHYME_HAMMERTIME = 11
# FACE_HAMMERTIME = 15
# FRAME_SIZE = (160,120) # Neural network image size, 1/4 of full frame size.
# FACE_MEMORY_SIZE = 100
# AUDIO_MEMORY_SIZE = 500
# MAX_CATEGORY_SIZE = 10
# PROTECT_PERCENTAGE = .2
# NUMBER_OF_BRAINS = 5
# NAP = _extract_NAP(segstart, segend, soundfile)
# NAP = utils.trim_right(new_sentence[norm_segments[segment_id]:norm_segments[segment_id+1]])
# NAP = _extract_NAP(segstart, segend, soundfile)
# NAP = _extract_NAP(segstart, segend, audio_segment.wav_file)
# NAP = NAP[:length:stride]
# class AudioMemory:
# class OneTrickPony:
# def __init__(self):
# def _digitize(self, NAP):
# def _insert(self, D, key, value):
# def find(self, NAP):
# def learn(self, NAP, wav_file, segment_idxs):
# def all_segments(self):
# def forget(self, audio_segment):
# def _cleanse_keys(self):
# def new_respond(control_host, learn_host, debug=False):
# def new_learn_audio(host, debug=False):
# def new_dream(audio_memory):
# def cognition(host):
# def face_extraction(host, extended_search=False, show=False):
# def train_network(x, y, output_dim=100, leak_rate=.9, bias_scaling=.2, reset_states=True, use_pinv=True):
# def cochlear(filename, stride, rate, db=-40, ears=1, a_1=-0.995, apply_filter=1, suffix='cochlear'):
# def _predict_id(classifier, M, counterQ = False, modality = None):
# def _hamming_distance_predictor(audio_classifier, NAP, maxlen, NAP_hashes):
# def _recognize_audio_id(audio_recognizer, NAP):
# def _project(audio_id, sound_to_face, NAP, video_producer):
# def _extract_NAP(segstart, segend, soundfile, suffix='cochlear'):
# def _train_audio_recognizer(signal):
# def _train_mixture_audio_recognizer(NAPs):
# def _train_global_audio_recognizer(NAPs):
# def _recognize_audio_id(audio_recognizer, NAP):
# def _recognize_mixture_audio_id(audio_recognizer, NAP):
# def _recognize_global_audio_id(audio_recognizer, NAP, plt):
# def predict(self, x):
# def train_rPCA_SVM(x, y):
# def learn_video(host, debug=False):
# def learn_faces(host, debug=False):
# def _three_amigos(context, host):
. Output only the next line. | recognizer = _train_network(new_train, targets, output_dim=chromosome[0]*10, leak_rate=float(chromosome[1])/100, bias_scaling=float(chromosome[2])/100) |
Here is a snippet: <|code_start|># it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# [self.] 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 [self.]. If not, see <http://www.gnu.org/licenses/>.
''' [self.]
@author: Axel Tidemann, Øyvind Brandtsegg
@contact: axel.tidemann@gmail.com, obrandts@gmail.com
@license: GPL
'''
''' Finds the best parameters for the neural networks that performs audio recognition, using evolution.'''
audio_memories = pickle.load(open('counts.pickle'))
test = audio_memories[1::2]
train = audio_memories[:-1:2]
idxs = [0,6,7,8,9,12]
<|code_end|>
. Write the next line using the current file imports:
import cPickle as pickle
import numpy as np
from pyevolve import G1DList, GSimpleGA, Mutators
from AI import _train_network
from brain import chop
and context from other files:
# Path: AI.py
# class MultiClassifier:
# def __init__(bins=10):
# def fit(data):
# def predict(test):
# def recognize(host):
# def learn(audio_in, audio_out, video_in, video_out, host):
# def live(audio_recognizer, audio_producer, audio2video, scaler, host):
#
# Path: brain.py
# FACE_HAAR_CASCADE_PATH = opencv_prefix + '/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml'
# EYE_HAAR_CASCADE_PATH = opencv_prefix + '/share/OpenCV/haarcascades/haarcascade_eye_tree_eyeglasses.xml'
# AUDIO_HAMMERTIME = 9
# RHYME_HAMMERTIME = 11
# FACE_HAMMERTIME = 15
# FRAME_SIZE = (160,120) # Neural network image size, 1/4 of full frame size.
# FACE_MEMORY_SIZE = 100
# AUDIO_MEMORY_SIZE = 500
# MAX_CATEGORY_SIZE = 10
# PROTECT_PERCENTAGE = .2
# NUMBER_OF_BRAINS = 5
# NAP = _extract_NAP(segstart, segend, soundfile)
# NAP = utils.trim_right(new_sentence[norm_segments[segment_id]:norm_segments[segment_id+1]])
# NAP = _extract_NAP(segstart, segend, soundfile)
# NAP = _extract_NAP(segstart, segend, audio_segment.wav_file)
# NAP = NAP[:length:stride]
# class AudioMemory:
# class OneTrickPony:
# def __init__(self):
# def _digitize(self, NAP):
# def _insert(self, D, key, value):
# def find(self, NAP):
# def learn(self, NAP, wav_file, segment_idxs):
# def all_segments(self):
# def forget(self, audio_segment):
# def _cleanse_keys(self):
# def new_respond(control_host, learn_host, debug=False):
# def new_learn_audio(host, debug=False):
# def new_dream(audio_memory):
# def cognition(host):
# def face_extraction(host, extended_search=False, show=False):
# def train_network(x, y, output_dim=100, leak_rate=.9, bias_scaling=.2, reset_states=True, use_pinv=True):
# def cochlear(filename, stride, rate, db=-40, ears=1, a_1=-0.995, apply_filter=1, suffix='cochlear'):
# def _predict_id(classifier, M, counterQ = False, modality = None):
# def _hamming_distance_predictor(audio_classifier, NAP, maxlen, NAP_hashes):
# def _recognize_audio_id(audio_recognizer, NAP):
# def _project(audio_id, sound_to_face, NAP, video_producer):
# def _extract_NAP(segstart, segend, soundfile, suffix='cochlear'):
# def _train_audio_recognizer(signal):
# def _train_mixture_audio_recognizer(NAPs):
# def _train_global_audio_recognizer(NAPs):
# def _recognize_audio_id(audio_recognizer, NAP):
# def _recognize_mixture_audio_id(audio_recognizer, NAP):
# def _recognize_global_audio_id(audio_recognizer, NAP, plt):
# def predict(self, x):
# def train_rPCA_SVM(x, y):
# def learn_video(host, debug=False):
# def learn_faces(host, debug=False):
# def _three_amigos(context, host):
, which may include functions, classes, or code. Output only the next line. | new_test = [chop(t[:,idxs]) for t in test ] |
Given snippet: <|code_start|># -*- coding: latin-1 -*-
# Copyright 2014 Oeyvind Brandtsegg and Axel Tidemann
#
# This file is part of [self.]
#
# [self.] is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# [self.] 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 [self.]. If not, see <http://www.gnu.org/licenses/>.
''' Test suite for self.
@author: Axel Tidemann, Øyvind Brandtsegg
@contact: axel.tidemann@gmail.com, obrandts@gmail.com
@license: GPL
'''
def play_sounds(wait_secs):
for f in glob.glob('testsounds/44100/*.wav')[:5]:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from time import sleep
from IO import send
from utils import wav_duration
import glob
and context:
# Path: IO.py
# VIDEO_SAMPLE_TIME = 100 # Milliseconds
# NAP_STRIDE = 441
# NAP_RATE = 22050
# FRAME_SIZE = (640,480)
# PROCESS_TIME_OUT = 5*60
# SYSTEM_TIME_OUT = 30*60
# CAMERA = 5561
# PROJECTOR = 5562
# MIC = 5563
# SPEAKER = 5564
# STATE = 5565
# EXTERNAL = 5566 # If you change this, you're out of luck.
# SNAPSHOT= 5567
# EVENT = 5568
# SCHEDULER = 5569
# ROBO = 5570
# COGNITION = 5571
# FACE = 5572
# BRAIN = 5573
# ASSOCIATION = 5574
# SENTINEL = 5575
# LOGGER = 5576
# DREAM = 5577
# COUNTER = 5578
# def video():
# def audio():
#
# Path: utils.py
# def wav_duration(filename):
# sound = wave.open(filename, 'r')
# return sound.getnframes()/float(sound.getframerate())
which might include code, classes, or functions. Output only the next line. | send('playfile_input {}'.format(f)) |
Predict the next line after this snippet: <|code_start|>
# Copyright 2014 Oeyvind Brandtsegg and Axel Tidemann
#
# This file is part of [self.]
#
# [self.] is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# [self.] 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 [self.]. If not, see <http://www.gnu.org/licenses/>.
''' Test suite for self.
@author: Axel Tidemann, Øyvind Brandtsegg
@contact: axel.tidemann@gmail.com, obrandts@gmail.com
@license: GPL
'''
def play_sounds(wait_secs):
for f in glob.glob('testsounds/44100/*.wav')[:5]:
send('playfile_input {}'.format(f))
<|code_end|>
using the current file's imports:
from time import sleep
from IO import send
from utils import wav_duration
import glob
and any relevant context from other files:
# Path: IO.py
# VIDEO_SAMPLE_TIME = 100 # Milliseconds
# NAP_STRIDE = 441
# NAP_RATE = 22050
# FRAME_SIZE = (640,480)
# PROCESS_TIME_OUT = 5*60
# SYSTEM_TIME_OUT = 30*60
# CAMERA = 5561
# PROJECTOR = 5562
# MIC = 5563
# SPEAKER = 5564
# STATE = 5565
# EXTERNAL = 5566 # If you change this, you're out of luck.
# SNAPSHOT= 5567
# EVENT = 5568
# SCHEDULER = 5569
# ROBO = 5570
# COGNITION = 5571
# FACE = 5572
# BRAIN = 5573
# ASSOCIATION = 5574
# SENTINEL = 5575
# LOGGER = 5576
# DREAM = 5577
# COUNTER = 5578
# def video():
# def audio():
#
# Path: utils.py
# def wav_duration(filename):
# sound = wave.open(filename, 'r')
# return sound.getnframes()/float(sound.getframerate())
. Output only the next line. | sleep(wav_duration(f) + wait_secs) |
Given snippet: <|code_start|># [self.] 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 [self.]. If not, see <http://www.gnu.org/licenses/>.
''' [self.]
@author: Axel Tidemann, Øyvind Brandtsegg
@contact: axel.tidemann@gmail.com, obrandts@gmail.com
@license: GPL
'''
def transfer(NAPs, wavs, wav_audio_ids):
audio_memory = AudioMemory()
for audio_id, nappers in enumerate(NAPs):
for i in range(len(nappers)):
NAP = nappers[i]
if len(NAP):
clean_key, overlap_key = audio_memory._digitize(NAP)
crude_hash = utils.d_hash(NAP, hash_size=8)
fine_hash = utils.d_hash(NAP, hash_size=16)
wav_file = wavs[audio_id][i]
try:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from altbrain import AudioSegment, AudioMemory
import utils
and context:
# Path: altbrain.py
# AUDIO_HAMMERTIME = 9
# FRAME_SIZE = (160,120) # Neural network image size, 1/4 of full frame size.
# NAP = utils.trim_right(new_sentence[norm_segments[segment_id]:norm_segments[segment_id+1]])
# NAP = _extract_NAP(segstart, segend, soundfile)
# NAP = utils.trim_right(new_sentence[norm_segments[segment_id]:norm_segments[segment_id+1]])
# NAP = _extract_NAP(segstart, segend, soundfile)
# NAP = _extract_NAP(segstart, segend, audio_segment.wav_file)
# class AudioMemory:
# def __init__(self):
# def _digitize(self, NAP):
# def _insert(self, D, key, value):
# def find(self, NAP):
# def learn(self, NAP, wav_file, segment_idxs):
# def all_segments(self):
# def forget(self, audio_segment):
# def _cleanse_keys(self):
# def new_respond(control_host, learn_host, debug=False):
# def new_learn_audio(host, debug=False):
# def new_dream(audio_memory):
which might include code, classes, or functions. Output only the next line. | audio_segment = AudioSegment(audio_id, crude_hash, fine_hash, wav_file, wav_audio_ids[(wav_file, audio_id)]) |
Based on the snippet: <|code_start|>#!/usr/bin/python
# -*- coding: latin-1 -*-
# Copyright 2014 Oeyvind Brandtsegg and Axel Tidemann
#
# This file is part of [self.]
#
# [self.] is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# [self.] 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 [self.]. If not, see <http://www.gnu.org/licenses/>.
''' [self.]
@author: Axel Tidemann, Øyvind Brandtsegg
@contact: axel.tidemann@gmail.com, obrandts@gmail.com
@license: GPL
'''
def transfer(NAPs, wavs, wav_audio_ids):
<|code_end|>
, predict the immediate next line with the help of imports:
from altbrain import AudioSegment, AudioMemory
import utils
and context (classes, functions, sometimes code) from other files:
# Path: altbrain.py
# AUDIO_HAMMERTIME = 9
# FRAME_SIZE = (160,120) # Neural network image size, 1/4 of full frame size.
# NAP = utils.trim_right(new_sentence[norm_segments[segment_id]:norm_segments[segment_id+1]])
# NAP = _extract_NAP(segstart, segend, soundfile)
# NAP = utils.trim_right(new_sentence[norm_segments[segment_id]:norm_segments[segment_id+1]])
# NAP = _extract_NAP(segstart, segend, soundfile)
# NAP = _extract_NAP(segstart, segend, audio_segment.wav_file)
# class AudioMemory:
# def __init__(self):
# def _digitize(self, NAP):
# def _insert(self, D, key, value):
# def find(self, NAP):
# def learn(self, NAP, wav_file, segment_idxs):
# def all_segments(self):
# def forget(self, audio_segment):
# def _cleanse_keys(self):
# def new_respond(control_host, learn_host, debug=False):
# def new_learn_audio(host, debug=False):
# def new_dream(audio_memory):
. Output only the next line. | audio_memory = AudioMemory() |
Predict the next line for this snippet: <|code_start|># Copyright 2014 Oeyvind Brandtsegg and Axel Tidemann
#
# This file is part of [self.]
#
# [self.] is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3
# as published by the Free Software Foundation.
#
# [self.] 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 [self.]. If not, see <http://www.gnu.org/licenses/>.
''' [self.]
@author: Axel Tidemann, Øyvind Brandtsegg
@contact: axel.tidemann@gmail.com, obrandts@gmail.com
@license: GPL
'''
secs = int(sys.argv[1]) if len(sys.argv) >= 2 else 5
mode = (sys.argv[2]) if len(sys.argv) >= 3 else 'both'
autowait = 5
if mode == 'filelearn':
<|code_end|>
with the help of current file imports:
import time
import sys
from IO import send
and context from other files:
# Path: IO.py
# VIDEO_SAMPLE_TIME = 100 # Milliseconds
# NAP_STRIDE = 441
# NAP_RATE = 22050
# FRAME_SIZE = (640,480)
# PROCESS_TIME_OUT = 5*60
# SYSTEM_TIME_OUT = 30*60
# CAMERA = 5561
# PROJECTOR = 5562
# MIC = 5563
# SPEAKER = 5564
# STATE = 5565
# EXTERNAL = 5566 # If you change this, you're out of luck.
# SNAPSHOT= 5567
# EVENT = 5568
# SCHEDULER = 5569
# ROBO = 5570
# COGNITION = 5571
# FACE = 5572
# BRAIN = 5573
# ASSOCIATION = 5574
# SENTINEL = 5575
# LOGGER = 5576
# DREAM = 5577
# COUNTER = 5578
# def video():
# def audio():
, which may contain function names, class names, or code. Output only the next line. | send('playfile {}'.format(sys.argv[3])) |
Using the snippet: <|code_start|>
print '{} chosen to respond. Audio data: {} Video data: {}'.format(me.name, audio_data.shape, video_data.shape)
if audio_data.size == 0 and video_data.size == 0:
print '*** Audio data and video data arrays are empty. Aborting the response. ***'
continue
row_diff = audio_data.shape[0] - audio_producer.length
if row_diff < 0:
audio_data = np.vstack([ audio_data, np.zeros((-row_diff, audio_data.shape[1])) ])
else:
audio_data = audio_data[:audio_producer.length]
sound = audio_producer(audio_data)
stride = audio_producer.length/audio2video.length
projection = audio2video(audio_data[audio_data.shape[0] - stride*audio2video.length::stride])
# DREAM MODE: You can train a network with zero audio input -> video output, and use this
# to recreate the original training sequence with scary accuracy...
for row in projection:
send_array(projector, row)
for row in scaler.inverse_transform(sound):
send_array(speaker, row)
if 'save' in pushbutton:
filename = '{}.{}'.format(pushbutton['save'], me.name)
pickle.dump((audio_recognizer, audio_producer, audio2video, scaler, host), file(filename, 'w'))
<|code_end|>
, determine the next line of code. You have imports:
import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL
and context (class names, function names, or code) available:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
. Output only the next line. | print '{} saved as file {} ({})'.format(me.name, filename, filesize(filename)) |
Here is a snippet: <|code_start|>
if 'rmse' in pushbutton:
rmse = np.sqrt((np.array(list(error)).flatten() ** 2).mean())
sender.send_json('{} RMSE {}'.format(me.name, rmse))
if 'respond' in pushbutton and pushbutton['respond'] == me.name:
audio_data = np.array(list(audio))
video_data = np.array(list(video))
print '{} chosen to respond. Audio data: {} Video data: {}'.format(me.name, audio_data.shape, video_data.shape)
if audio_data.size == 0 and video_data.size == 0:
print '*** Audio data and video data arrays are empty. Aborting the response. ***'
continue
row_diff = audio_data.shape[0] - audio_producer.length
if row_diff < 0:
audio_data = np.vstack([ audio_data, np.zeros((-row_diff, audio_data.shape[1])) ])
else:
audio_data = audio_data[:audio_producer.length]
sound = audio_producer(audio_data)
stride = audio_producer.length/audio2video.length
projection = audio2video(audio_data[audio_data.shape[0] - stride*audio2video.length::stride])
# DREAM MODE: You can train a network with zero audio input -> video output, and use this
# to recreate the original training sequence with scary accuracy...
for row in projection:
<|code_end|>
. Write the next line using the current file imports:
import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL
and context from other files:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
, which may include functions, classes, or code. Output only the next line. | send_array(projector, row) |
Given the following code snippet before the placeholder: <|code_start|>
def recognize(host):
me = mp.current_process()
print me.name, 'PID', me.pid
context = zmq.Context()
rec_in = context.socket(zmq.SUB)
rec_in.connect('tcp://{}:{}'.format(host, RECOGNIZE_IN))
rec_in.setsockopt(zmq.SUBSCRIBE, b'')
rec_learn = context.socket(zmq.SUB)
rec_learn.connect('tcp://{}:{}'.format(host, RECOGNIZE_LEARN))
rec_learn.setsockopt(zmq.SUBSCRIBE, b'')
sender = context.socket(zmq.PUSH)
sender.connect('tcp://{}:{}'.format(host, EXTERNAL))
poller = zmq.Poller()
poller.register(rec_in, zmq.POLLIN)
poller.register(rec_learn, zmq.POLLIN)
memories = []
recognizer = []
while True:
events = dict(poller.poll())
if rec_in in events:
<|code_end|>
, predict the next line using imports from the current file:
import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL
and context including class names, function names, and sometimes code from other files:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
. Output only the next line. | audio_segment = recv_array(rec_in) |
Using the snippet: <|code_start|> if row_diff < 0:
scaled_audio_in = np.vstack([ scaled_audio_in, np.zeros((-row_diff, scaled_audio_in.shape[1])) ]) # Zeros because of level
elif row_diff > 0:
scaled_audio_in = scaled_audio_in[:len(scaled_audio_out)]
x = scaled_audio_in[:-1]
y = scaled_audio_out[1:]
audio_producer = _train_network(x, y)
audio_producer.length = audio_out.shape[0]
# Video is sampled at a much lower frequency than audio.
stride = audio_out.shape[0]/video_out.shape[0]
x = scaled_audio_in[scaled_audio_in.shape[0] - stride*video_out.shape[0]::stride]
y = video_out
audio2video = _train_network(x, y)
audio2video.length = video_out.shape[0]
print '[self.] learns in {} seconds'.format(time.time() - start_time)
live(audio_recognizer, audio_producer, audio2video, scaler, host)
def live(audio_recognizer, audio_producer, audio2video, scaler, host):
me = mp.current_process()
print me.name, 'PID', me.pid
context = zmq.Context()
mic = context.socket(zmq.SUB)
<|code_end|>
, determine the next line of code. You have imports:
import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL
and context (class names, function names, or code) available:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
. Output only the next line. | mic.connect('tcp://{}:{}'.format(host, MIC)) |
Using the snippet: <|code_start|>
x = scaled_audio_in[:-1]
y = scaled_audio_out[1:]
audio_producer = _train_network(x, y)
audio_producer.length = audio_out.shape[0]
# Video is sampled at a much lower frequency than audio.
stride = audio_out.shape[0]/video_out.shape[0]
x = scaled_audio_in[scaled_audio_in.shape[0] - stride*video_out.shape[0]::stride]
y = video_out
audio2video = _train_network(x, y)
audio2video.length = video_out.shape[0]
print '[self.] learns in {} seconds'.format(time.time() - start_time)
live(audio_recognizer, audio_producer, audio2video, scaler, host)
def live(audio_recognizer, audio_producer, audio2video, scaler, host):
me = mp.current_process()
print me.name, 'PID', me.pid
context = zmq.Context()
mic = context.socket(zmq.SUB)
mic.connect('tcp://{}:{}'.format(host, MIC))
mic.setsockopt(zmq.SUBSCRIBE, b'')
speaker = context.socket(zmq.PUSH)
<|code_end|>
, determine the next line of code. You have imports:
import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL
and context (class names, function names, or code) available:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
. Output only the next line. | speaker.connect('tcp://{}:{}'.format(host, SPEAKER)) |
Using the snippet: <|code_start|> audio_producer = _train_network(x, y)
audio_producer.length = audio_out.shape[0]
# Video is sampled at a much lower frequency than audio.
stride = audio_out.shape[0]/video_out.shape[0]
x = scaled_audio_in[scaled_audio_in.shape[0] - stride*video_out.shape[0]::stride]
y = video_out
audio2video = _train_network(x, y)
audio2video.length = video_out.shape[0]
print '[self.] learns in {} seconds'.format(time.time() - start_time)
live(audio_recognizer, audio_producer, audio2video, scaler, host)
def live(audio_recognizer, audio_producer, audio2video, scaler, host):
me = mp.current_process()
print me.name, 'PID', me.pid
context = zmq.Context()
mic = context.socket(zmq.SUB)
mic.connect('tcp://{}:{}'.format(host, MIC))
mic.setsockopt(zmq.SUBSCRIBE, b'')
speaker = context.socket(zmq.PUSH)
speaker.connect('tcp://{}:{}'.format(host, SPEAKER))
camera = context.socket(zmq.SUB)
<|code_end|>
, determine the next line of code. You have imports:
import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL
and context (class names, function names, or code) available:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
. Output only the next line. | camera.connect('tcp://{}:{}'.format(host, CAMERA)) |
Using the snippet: <|code_start|> stride = audio_out.shape[0]/video_out.shape[0]
x = scaled_audio_in[scaled_audio_in.shape[0] - stride*video_out.shape[0]::stride]
y = video_out
audio2video = _train_network(x, y)
audio2video.length = video_out.shape[0]
print '[self.] learns in {} seconds'.format(time.time() - start_time)
live(audio_recognizer, audio_producer, audio2video, scaler, host)
def live(audio_recognizer, audio_producer, audio2video, scaler, host):
me = mp.current_process()
print me.name, 'PID', me.pid
context = zmq.Context()
mic = context.socket(zmq.SUB)
mic.connect('tcp://{}:{}'.format(host, MIC))
mic.setsockopt(zmq.SUBSCRIBE, b'')
speaker = context.socket(zmq.PUSH)
speaker.connect('tcp://{}:{}'.format(host, SPEAKER))
camera = context.socket(zmq.SUB)
camera.connect('tcp://{}:{}'.format(host, CAMERA))
camera.setsockopt(zmq.SUBSCRIBE, b'')
projector = context.socket(zmq.PUSH)
<|code_end|>
, determine the next line of code. You have imports:
import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL
and context (class names, function names, or code) available:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
. Output only the next line. | projector.connect('tcp://{}:{}'.format(host, PROJECTOR)) |
Here is a snippet: <|code_start|> y = video_out
audio2video = _train_network(x, y)
audio2video.length = video_out.shape[0]
print '[self.] learns in {} seconds'.format(time.time() - start_time)
live(audio_recognizer, audio_producer, audio2video, scaler, host)
def live(audio_recognizer, audio_producer, audio2video, scaler, host):
me = mp.current_process()
print me.name, 'PID', me.pid
context = zmq.Context()
mic = context.socket(zmq.SUB)
mic.connect('tcp://{}:{}'.format(host, MIC))
mic.setsockopt(zmq.SUBSCRIBE, b'')
speaker = context.socket(zmq.PUSH)
speaker.connect('tcp://{}:{}'.format(host, SPEAKER))
camera = context.socket(zmq.SUB)
camera.connect('tcp://{}:{}'.format(host, CAMERA))
camera.setsockopt(zmq.SUBSCRIBE, b'')
projector = context.socket(zmq.PUSH)
projector.connect('tcp://{}:{}'.format(host, PROJECTOR))
stateQ = context.socket(zmq.SUB)
<|code_end|>
. Write the next line using the current file imports:
import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL
and context from other files:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
, which may include functions, classes, or code. Output only the next line. | stateQ.connect('tcp://{}:{}'.format(host, STATE)) |
Based on the snippet: <|code_start|>
def live(audio_recognizer, audio_producer, audio2video, scaler, host):
me = mp.current_process()
print me.name, 'PID', me.pid
context = zmq.Context()
mic = context.socket(zmq.SUB)
mic.connect('tcp://{}:{}'.format(host, MIC))
mic.setsockopt(zmq.SUBSCRIBE, b'')
speaker = context.socket(zmq.PUSH)
speaker.connect('tcp://{}:{}'.format(host, SPEAKER))
camera = context.socket(zmq.SUB)
camera.connect('tcp://{}:{}'.format(host, CAMERA))
camera.setsockopt(zmq.SUBSCRIBE, b'')
projector = context.socket(zmq.PUSH)
projector.connect('tcp://{}:{}'.format(host, PROJECTOR))
stateQ = context.socket(zmq.SUB)
stateQ.connect('tcp://{}:{}'.format(host, STATE))
stateQ.setsockopt(zmq.SUBSCRIBE, b'')
eventQ = context.socket(zmq.SUB)
eventQ.connect('tcp://{}:{}'.format(host, EVENT))
eventQ.setsockopt(zmq.SUBSCRIBE, b'')
snapshot = context.socket(zmq.REQ)
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL
and context (classes, functions, sometimes code) from other files:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
. Output only the next line. | snapshot.connect('tcp://{}:{}'.format(host, SNAPSHOT)) |
Next line prediction: <|code_start|>
print '[self.] learns in {} seconds'.format(time.time() - start_time)
live(audio_recognizer, audio_producer, audio2video, scaler, host)
def live(audio_recognizer, audio_producer, audio2video, scaler, host):
me = mp.current_process()
print me.name, 'PID', me.pid
context = zmq.Context()
mic = context.socket(zmq.SUB)
mic.connect('tcp://{}:{}'.format(host, MIC))
mic.setsockopt(zmq.SUBSCRIBE, b'')
speaker = context.socket(zmq.PUSH)
speaker.connect('tcp://{}:{}'.format(host, SPEAKER))
camera = context.socket(zmq.SUB)
camera.connect('tcp://{}:{}'.format(host, CAMERA))
camera.setsockopt(zmq.SUBSCRIBE, b'')
projector = context.socket(zmq.PUSH)
projector.connect('tcp://{}:{}'.format(host, PROJECTOR))
stateQ = context.socket(zmq.SUB)
stateQ.connect('tcp://{}:{}'.format(host, STATE))
stateQ.setsockopt(zmq.SUBSCRIBE, b'')
eventQ = context.socket(zmq.SUB)
<|code_end|>
. Use current file imports:
(import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL)
and context including class names, function names, or small code snippets from other files:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
. Output only the next line. | eventQ.connect('tcp://{}:{}'.format(host, EVENT)) |
Based on the snippet: <|code_start|> self.bins = bins
def fit(data):
minlength = min([ d.shape[0] for d in data ])
maxlength = max([ d.shape[0] for d in data ])
zones = np.linspace(minlength, maxlength, self.bins)
zones.astype('int')
def predict(test):
pass
def recognize(host):
me = mp.current_process()
print me.name, 'PID', me.pid
context = zmq.Context()
rec_in = context.socket(zmq.SUB)
rec_in.connect('tcp://{}:{}'.format(host, RECOGNIZE_IN))
rec_in.setsockopt(zmq.SUBSCRIBE, b'')
rec_learn = context.socket(zmq.SUB)
rec_learn.connect('tcp://{}:{}'.format(host, RECOGNIZE_LEARN))
rec_learn.setsockopt(zmq.SUBSCRIBE, b'')
sender = context.socket(zmq.PUSH)
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import multiprocessing as mp
import cPickle as pickle
import zmq
import numpy as np
import Oger
from uuid import uuid1
from collections import deque
from sklearn import preprocessing as pp
from utils import filesize, send_array, recv_array
from IO import MIC, SPEAKER, CAMERA, PROJECTOR, STATE, SNAPSHOT, EVENT, EXTERNAL
and context (classes, functions, sometimes code) from other files:
# Path: utils.py
# def filesize(filename):
# return bytes2human(os.path.getsize(filename))
#
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
#
# Path: IO.py
# MIC = 5563
#
# SPEAKER = 5564
#
# CAMERA = 5561
#
# PROJECTOR = 5562
#
# STATE = 5565
#
# SNAPSHOT= 5567
#
# EVENT = 5568
#
# EXTERNAL = 5566 # If you change this, you're out of luck.
. Output only the next line. | sender.connect('tcp://{}:{}'.format(host, EXTERNAL)) |
Predict the next line for this snippet: <|code_start|> publisher.bind('tcp://*:{}'.format(CAMERA))
projector = context.socket(zmq.PULL)
projector.bind('tcp://*:{}'.format(PROJECTOR))
eventQ = context.socket(zmq.SUB)
eventQ.connect('tcp://localhost:{}'.format(EVENT))
eventQ.setsockopt(zmq.SUBSCRIBE, b'')
poller = zmq.Poller()
poller.register(eventQ, zmq.POLLIN)
poller.register(projector, zmq.POLLIN)
while True:
events = dict(poller.poll(timeout=0))
if eventQ in events:
pushbutton = eventQ.recv_json()
if 'display2' in pushbutton:
cv2.moveWindow('Output', 2000, 100)
if 'fullscreen' in pushbutton:
cv2.setWindowProperty('Output', cv2.WND_PROP_FULLSCREEN, cv2.cv.CV_WINDOW_FULLSCREEN)
if projector in events:
cv2.imshow('Output', cv2.resize(recv_array(projector), FRAME_SIZE))
else:
cv2.imshow('Output', np.zeros(FRAME_SIZE[::-1]))
_, frame = camera.read()
frame = cv2.resize(frame, FRAME_SIZE)
<|code_end|>
with the help of current file imports:
import multiprocessing as mp
import os
import random
import utils
import time
import numpy as np
import zmq
import myCsoundAudioOptions
import cv2
import csnd6
from scipy.io import wavfile
from utils import send_array, recv_array
and context from other files:
# Path: utils.py
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
, which may contain function names, class names, or code. Output only the next line. | send_array(publisher, frame) |
Using the snippet: <|code_start|>
cv2.namedWindow('Output', cv2.WND_PROP_FULLSCREEN)
camera = cv2.VideoCapture(0)
context = zmq.Context()
publisher = context.socket(zmq.PUB)
publisher.bind('tcp://*:{}'.format(CAMERA))
projector = context.socket(zmq.PULL)
projector.bind('tcp://*:{}'.format(PROJECTOR))
eventQ = context.socket(zmq.SUB)
eventQ.connect('tcp://localhost:{}'.format(EVENT))
eventQ.setsockopt(zmq.SUBSCRIBE, b'')
poller = zmq.Poller()
poller.register(eventQ, zmq.POLLIN)
poller.register(projector, zmq.POLLIN)
while True:
events = dict(poller.poll(timeout=0))
if eventQ in events:
pushbutton = eventQ.recv_json()
if 'display2' in pushbutton:
cv2.moveWindow('Output', 2000, 100)
if 'fullscreen' in pushbutton:
cv2.setWindowProperty('Output', cv2.WND_PROP_FULLSCREEN, cv2.cv.CV_WINDOW_FULLSCREEN)
if projector in events:
<|code_end|>
, determine the next line of code. You have imports:
import multiprocessing as mp
import os
import random
import utils
import time
import numpy as np
import zmq
import myCsoundAudioOptions
import cv2
import csnd6
from scipy.io import wavfile
from utils import send_array, recv_array
and context (class names, function names, or code) available:
# Path: utils.py
# def send_array(socket, A, flags=0, copy=True, track=False):
# """send a numpy array with metadata"""
# md = dict(
# dtype = str(A.dtype),
# shape = A.shape,
# )
# socket.send_json(md, flags|zmq.SNDMORE)
# return socket.send(A, flags, copy=copy, track=track)
#
# def recv_array(socket, flags=0, copy=True, track=False):
# """recv a numpy array"""
# md = socket.recv_json(flags=flags)
# msg = socket.recv(flags=flags, copy=copy, track=track)
# buf = buffer(msg)
# A = np.frombuffer(buf, dtype=md['dtype'])
# return A.reshape(md['shape'])
. Output only the next line. | cv2.imshow('Output', cv2.resize(recv_array(projector), FRAME_SIZE)) |
Given the code snippet: <|code_start|>
##########################################################################
## Validators
##########################################################################
class InRange(object):
"""
Validator that specifies a value must be in a particular range
"""
def __init__(self, low, high):
self.low = low
self.high = high
def __call__(self, value):
if value > self.high or value < self.low:
raise serializers.ValidationError(
"value must be between %d and %d (inclusive)" % (self.low, self.high)
)
##########################################################################
## Serializers
##########################################################################
class TopicSerializer(serializers.HyperlinkedModelSerializer):
"""
Serializers topics and their weights.
"""
class Meta:
<|code_end|>
, generate the next line using the imports in this file:
from topics.models import Topic, Vote
from rest_framework import serializers
and context (functions, classes, or occasionally code) from other files:
# Path: topics/models.py
# class Topic(TimeStampedModel):
# """
# Stores a topic, basically a string like a tag and manages it.
# """
#
# # Topic fields
# title = models.CharField(max_length=128)
# slug = AutoSlugField(populate_from='title', unique=True)
# link = models.URLField(null=True, blank=True, default=None)
# refers_to = models.ForeignKey('self', related_name='references', null=True, blank=True, default=None)
# is_canonical = models.BooleanField(default=True)
#
# # Custom topic manager
# objects = TopicManager()
#
# # Topic meta class
# class Meta:
# db_table = 'topics'
# ordering = ('title', )
#
# def __unicode__(self):
# return self.title
#
# def vote_total(self):
# """
# Accumulates the votes via aggregation
# """
# votes = self.votes.aggregate(
# total=models.Sum('vote')
# )['total']
#
# if self.is_canonical:
# for ref in self.references.all():
# votes += ref.vote_total()
#
# return votes
#
# class Vote(TimeStampedModel):
# """
# Simple voting model that stores an up or down vote for a particular topic
# associated with a particular IP address (and time of day).
# """
#
# DATEFMT = "%a %b %d, %Y at %H:%M"
# BALLOT = Choices((-1, 'downvote', 'downvote'), (1, 'upvote', 'upvote'), (0, 'novote', 'novote'))
#
# # Vote fields
# vote = models.SmallIntegerField(choices=BALLOT, default=BALLOT.upvote)
# topic = models.ForeignKey(Topic, related_name='votes')
# ipaddr = models.GenericIPAddressField()
#
# # Custom voting manager
# objects = VotingManager()
#
# # Vote meta class
# class Meta:
# db_table = 'voting'
# ordering = ('-created',)
#
# def __unicode__(self):
# action = {
# -1: "-1",
# 0: "--",
# 1: "+1",
# }[self.vote]
#
# return "{} for \"{}\" ({} on {})".format(
# action, self.topic, self.ipaddr, self.modified.strftime(self.DATEFMT)
# )
. Output only the next line. | model = Topic |
Continue the code snippet: <|code_start|>#
# Copyright (C) 2015 District Data Labs
# For license information, see LICENSE.txt
#
# ID: views.py [] benjamin@bengfort.com $
"""
Views for the Topics application
"""
##########################################################################
## Imports
##########################################################################
##########################################################################
## HTML/Django Views
##########################################################################
class ResultView(TemplateView):
template_name = "site/results.html"
def get_context_data(self, **kwargs):
context = super(ResultView, self).get_context_data(**kwargs)
# Compute statistics for view
<|code_end|>
. Use current file imports:
import csv
import random
from topics.serializers import *
from topics.models import Topic, Vote
from topics.forms import MultiTopicForm
from django.http import HttpResponse
from django.views.generic import View, TemplateView
from django.views.generic.edit import FormView
from django.core.urlresolvers import reverse
from braces.views import LoginRequiredMixin
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.exceptions import APIException
and context (classes, functions, or code) from other files:
# Path: topics/models.py
# class Topic(TimeStampedModel):
# """
# Stores a topic, basically a string like a tag and manages it.
# """
#
# # Topic fields
# title = models.CharField(max_length=128)
# slug = AutoSlugField(populate_from='title', unique=True)
# link = models.URLField(null=True, blank=True, default=None)
# refers_to = models.ForeignKey('self', related_name='references', null=True, blank=True, default=None)
# is_canonical = models.BooleanField(default=True)
#
# # Custom topic manager
# objects = TopicManager()
#
# # Topic meta class
# class Meta:
# db_table = 'topics'
# ordering = ('title', )
#
# def __unicode__(self):
# return self.title
#
# def vote_total(self):
# """
# Accumulates the votes via aggregation
# """
# votes = self.votes.aggregate(
# total=models.Sum('vote')
# )['total']
#
# if self.is_canonical:
# for ref in self.references.all():
# votes += ref.vote_total()
#
# return votes
#
# class Vote(TimeStampedModel):
# """
# Simple voting model that stores an up or down vote for a particular topic
# associated with a particular IP address (and time of day).
# """
#
# DATEFMT = "%a %b %d, %Y at %H:%M"
# BALLOT = Choices((-1, 'downvote', 'downvote'), (1, 'upvote', 'upvote'), (0, 'novote', 'novote'))
#
# # Vote fields
# vote = models.SmallIntegerField(choices=BALLOT, default=BALLOT.upvote)
# topic = models.ForeignKey(Topic, related_name='votes')
# ipaddr = models.GenericIPAddressField()
#
# # Custom voting manager
# objects = VotingManager()
#
# # Vote meta class
# class Meta:
# db_table = 'voting'
# ordering = ('-created',)
#
# def __unicode__(self):
# action = {
# -1: "-1",
# 0: "--",
# 1: "+1",
# }[self.vote]
#
# return "{} for \"{}\" ({} on {})".format(
# action, self.topic, self.ipaddr, self.modified.strftime(self.DATEFMT)
# )
#
# Path: topics/forms.py
# class MultiTopicForm(forms.Form):
# """
# Post multiple topics separated by newlines.
# """
#
# topics = forms.CharField(
# widget=forms.Textarea, required=True,
# help_text="Enter multiple topics each on their own line."
# )
#
# def __init__(self, *args, **kwargs):
# self.request = kwargs.pop('request', None)
# super(MultiTopicForm, self).__init__(*args, **kwargs)
#
# @property
# def ipaddr(self):
# """
# Get the IP Address of the form submitter via the request.
# """
# if not hasattr(self, '_ipaddr'):
# self._ipaddr = get_real_ip(self.request) or get_ip(self.request)
# return self._ipaddr
#
# def clean_topics(self):
# """
# Run validation for topics form.
# """
#
# data = self.cleaned_data['topics']
# topics = filter(lambda x: x, [slugify(t) for t in data.splitlines()])
#
# # Check if there are commas or semicolons in the field.
# if "," in data or ";" in data or "|" in data:
# raise forms.ValidationError(
# _("This form is not comma, semicolon, or pipe delimited!"),
# code="bad_delimiter"
# )
#
# # Ensure at least two topics are submitted.
# if len(topics) < 2:
# raise forms.ValidationError(
# _("Please provide at least 2 topics, techniques, or technologies!"),
# code="single_topic_error"
# )
#
# # 50 topics is too many.
# if len(topics) > 50:
# raise forms.ValidationError(
# _("Thanks for thinking of so many topics! To prevent spam, however, "
# "we have to limit you to 50 topics per form submission."),
# code="topic_spam_error"
# )
#
# # Ensure topic uniqueness in submission.
# if len(frozenset(topics)) < len(topics):
# raise forms.ValidationError(
# _("Duplicate topics detected! Please check your list and try again."),
# code="duplicate_topics"
# )
#
# return data
#
# def save_topics(self):
# """
# Write the topics and their votes to disk.
# """
# for topic in Topic.objects.from_string(self.cleaned_data['topics']):
# Vote.objects.create(topic=topic, ipaddr=self.ipaddr)
. Output only the next line. | context['num_topics'] = Topic.objects.count() |
Using the snippet: <|code_start|># For license information, see LICENSE.txt
#
# ID: views.py [] benjamin@bengfort.com $
"""
Views for the Topics application
"""
##########################################################################
## Imports
##########################################################################
##########################################################################
## HTML/Django Views
##########################################################################
class ResultView(TemplateView):
template_name = "site/results.html"
def get_context_data(self, **kwargs):
context = super(ResultView, self).get_context_data(**kwargs)
# Compute statistics for view
context['num_topics'] = Topic.objects.count()
context['avg_topic_weight'] = Topic.objects.mean_weight()
<|code_end|>
, determine the next line of code. You have imports:
import csv
import random
from topics.serializers import *
from topics.models import Topic, Vote
from topics.forms import MultiTopicForm
from django.http import HttpResponse
from django.views.generic import View, TemplateView
from django.views.generic.edit import FormView
from django.core.urlresolvers import reverse
from braces.views import LoginRequiredMixin
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.exceptions import APIException
and context (class names, function names, or code) available:
# Path: topics/models.py
# class Topic(TimeStampedModel):
# """
# Stores a topic, basically a string like a tag and manages it.
# """
#
# # Topic fields
# title = models.CharField(max_length=128)
# slug = AutoSlugField(populate_from='title', unique=True)
# link = models.URLField(null=True, blank=True, default=None)
# refers_to = models.ForeignKey('self', related_name='references', null=True, blank=True, default=None)
# is_canonical = models.BooleanField(default=True)
#
# # Custom topic manager
# objects = TopicManager()
#
# # Topic meta class
# class Meta:
# db_table = 'topics'
# ordering = ('title', )
#
# def __unicode__(self):
# return self.title
#
# def vote_total(self):
# """
# Accumulates the votes via aggregation
# """
# votes = self.votes.aggregate(
# total=models.Sum('vote')
# )['total']
#
# if self.is_canonical:
# for ref in self.references.all():
# votes += ref.vote_total()
#
# return votes
#
# class Vote(TimeStampedModel):
# """
# Simple voting model that stores an up or down vote for a particular topic
# associated with a particular IP address (and time of day).
# """
#
# DATEFMT = "%a %b %d, %Y at %H:%M"
# BALLOT = Choices((-1, 'downvote', 'downvote'), (1, 'upvote', 'upvote'), (0, 'novote', 'novote'))
#
# # Vote fields
# vote = models.SmallIntegerField(choices=BALLOT, default=BALLOT.upvote)
# topic = models.ForeignKey(Topic, related_name='votes')
# ipaddr = models.GenericIPAddressField()
#
# # Custom voting manager
# objects = VotingManager()
#
# # Vote meta class
# class Meta:
# db_table = 'voting'
# ordering = ('-created',)
#
# def __unicode__(self):
# action = {
# -1: "-1",
# 0: "--",
# 1: "+1",
# }[self.vote]
#
# return "{} for \"{}\" ({} on {})".format(
# action, self.topic, self.ipaddr, self.modified.strftime(self.DATEFMT)
# )
#
# Path: topics/forms.py
# class MultiTopicForm(forms.Form):
# """
# Post multiple topics separated by newlines.
# """
#
# topics = forms.CharField(
# widget=forms.Textarea, required=True,
# help_text="Enter multiple topics each on their own line."
# )
#
# def __init__(self, *args, **kwargs):
# self.request = kwargs.pop('request', None)
# super(MultiTopicForm, self).__init__(*args, **kwargs)
#
# @property
# def ipaddr(self):
# """
# Get the IP Address of the form submitter via the request.
# """
# if not hasattr(self, '_ipaddr'):
# self._ipaddr = get_real_ip(self.request) or get_ip(self.request)
# return self._ipaddr
#
# def clean_topics(self):
# """
# Run validation for topics form.
# """
#
# data = self.cleaned_data['topics']
# topics = filter(lambda x: x, [slugify(t) for t in data.splitlines()])
#
# # Check if there are commas or semicolons in the field.
# if "," in data or ";" in data or "|" in data:
# raise forms.ValidationError(
# _("This form is not comma, semicolon, or pipe delimited!"),
# code="bad_delimiter"
# )
#
# # Ensure at least two topics are submitted.
# if len(topics) < 2:
# raise forms.ValidationError(
# _("Please provide at least 2 topics, techniques, or technologies!"),
# code="single_topic_error"
# )
#
# # 50 topics is too many.
# if len(topics) > 50:
# raise forms.ValidationError(
# _("Thanks for thinking of so many topics! To prevent spam, however, "
# "we have to limit you to 50 topics per form submission."),
# code="topic_spam_error"
# )
#
# # Ensure topic uniqueness in submission.
# if len(frozenset(topics)) < len(topics):
# raise forms.ValidationError(
# _("Duplicate topics detected! Please check your list and try again."),
# code="duplicate_topics"
# )
#
# return data
#
# def save_topics(self):
# """
# Write the topics and their votes to disk.
# """
# for topic in Topic.objects.from_string(self.cleaned_data['topics']):
# Vote.objects.create(topic=topic, ipaddr=self.ipaddr)
. Output only the next line. | context['num_responses'] = Vote.objects.num_responses() |
Continue the code snippet: <|code_start|>
##########################################################################
## HTML/Django Views
##########################################################################
class ResultView(TemplateView):
template_name = "site/results.html"
def get_context_data(self, **kwargs):
context = super(ResultView, self).get_context_data(**kwargs)
# Compute statistics for view
context['num_topics'] = Topic.objects.count()
context['avg_topic_weight'] = Topic.objects.mean_weight()
context['num_responses'] = Vote.objects.num_responses()
# Compute aggregate statistics via DB query.
stats = Vote.objects.response_stats()
context['avg_topics_per_response'] = stats['avg']
context['min_topics_per_response'] = stats['min']
context['max_topics_per_response'] = stats['max']
return context
class MultiTopicView(FormView):
template_name = "site/survey.html"
<|code_end|>
. Use current file imports:
import csv
import random
from topics.serializers import *
from topics.models import Topic, Vote
from topics.forms import MultiTopicForm
from django.http import HttpResponse
from django.views.generic import View, TemplateView
from django.views.generic.edit import FormView
from django.core.urlresolvers import reverse
from braces.views import LoginRequiredMixin
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.exceptions import APIException
and context (classes, functions, or code) from other files:
# Path: topics/models.py
# class Topic(TimeStampedModel):
# """
# Stores a topic, basically a string like a tag and manages it.
# """
#
# # Topic fields
# title = models.CharField(max_length=128)
# slug = AutoSlugField(populate_from='title', unique=True)
# link = models.URLField(null=True, blank=True, default=None)
# refers_to = models.ForeignKey('self', related_name='references', null=True, blank=True, default=None)
# is_canonical = models.BooleanField(default=True)
#
# # Custom topic manager
# objects = TopicManager()
#
# # Topic meta class
# class Meta:
# db_table = 'topics'
# ordering = ('title', )
#
# def __unicode__(self):
# return self.title
#
# def vote_total(self):
# """
# Accumulates the votes via aggregation
# """
# votes = self.votes.aggregate(
# total=models.Sum('vote')
# )['total']
#
# if self.is_canonical:
# for ref in self.references.all():
# votes += ref.vote_total()
#
# return votes
#
# class Vote(TimeStampedModel):
# """
# Simple voting model that stores an up or down vote for a particular topic
# associated with a particular IP address (and time of day).
# """
#
# DATEFMT = "%a %b %d, %Y at %H:%M"
# BALLOT = Choices((-1, 'downvote', 'downvote'), (1, 'upvote', 'upvote'), (0, 'novote', 'novote'))
#
# # Vote fields
# vote = models.SmallIntegerField(choices=BALLOT, default=BALLOT.upvote)
# topic = models.ForeignKey(Topic, related_name='votes')
# ipaddr = models.GenericIPAddressField()
#
# # Custom voting manager
# objects = VotingManager()
#
# # Vote meta class
# class Meta:
# db_table = 'voting'
# ordering = ('-created',)
#
# def __unicode__(self):
# action = {
# -1: "-1",
# 0: "--",
# 1: "+1",
# }[self.vote]
#
# return "{} for \"{}\" ({} on {})".format(
# action, self.topic, self.ipaddr, self.modified.strftime(self.DATEFMT)
# )
#
# Path: topics/forms.py
# class MultiTopicForm(forms.Form):
# """
# Post multiple topics separated by newlines.
# """
#
# topics = forms.CharField(
# widget=forms.Textarea, required=True,
# help_text="Enter multiple topics each on their own line."
# )
#
# def __init__(self, *args, **kwargs):
# self.request = kwargs.pop('request', None)
# super(MultiTopicForm, self).__init__(*args, **kwargs)
#
# @property
# def ipaddr(self):
# """
# Get the IP Address of the form submitter via the request.
# """
# if not hasattr(self, '_ipaddr'):
# self._ipaddr = get_real_ip(self.request) or get_ip(self.request)
# return self._ipaddr
#
# def clean_topics(self):
# """
# Run validation for topics form.
# """
#
# data = self.cleaned_data['topics']
# topics = filter(lambda x: x, [slugify(t) for t in data.splitlines()])
#
# # Check if there are commas or semicolons in the field.
# if "," in data or ";" in data or "|" in data:
# raise forms.ValidationError(
# _("This form is not comma, semicolon, or pipe delimited!"),
# code="bad_delimiter"
# )
#
# # Ensure at least two topics are submitted.
# if len(topics) < 2:
# raise forms.ValidationError(
# _("Please provide at least 2 topics, techniques, or technologies!"),
# code="single_topic_error"
# )
#
# # 50 topics is too many.
# if len(topics) > 50:
# raise forms.ValidationError(
# _("Thanks for thinking of so many topics! To prevent spam, however, "
# "we have to limit you to 50 topics per form submission."),
# code="topic_spam_error"
# )
#
# # Ensure topic uniqueness in submission.
# if len(frozenset(topics)) < len(topics):
# raise forms.ValidationError(
# _("Duplicate topics detected! Please check your list and try again."),
# code="duplicate_topics"
# )
#
# return data
#
# def save_topics(self):
# """
# Write the topics and their votes to disk.
# """
# for topic in Topic.objects.from_string(self.cleaned_data['topics']):
# Vote.objects.create(topic=topic, ipaddr=self.ipaddr)
. Output only the next line. | form_class = MultiTopicForm |
Given snippet: <|code_start|># For license information, see LICENSE.txt
#
# ID: models.py [] benjamin@bengfort.com $
"""
Topic modeling for data survey analysis
"""
##########################################################################
## Imports
##########################################################################
##########################################################################
## Topic Models
##########################################################################
class Topic(TimeStampedModel):
"""
Stores a topic, basically a string like a tag and manages it.
"""
# Topic fields
title = models.CharField(max_length=128)
slug = AutoSlugField(populate_from='title', unique=True)
link = models.URLField(null=True, blank=True, default=None)
refers_to = models.ForeignKey('self', related_name='references', null=True, blank=True, default=None)
is_canonical = models.BooleanField(default=True)
# Custom topic manager
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.db import models
from model_utils import Choices
from autoslug import AutoSlugField
from model_utils.models import TimeStampedModel
from topics.managers import TopicManager, VotingManager
and context:
# Path: topics/managers.py
# class TopicManager(models.Manager):
# """
# Helper functions for topic management
# """
#
# def from_title(self, title):
# """
# A get or create from a slug function.
# """
# # Titlecase the topic
# title = titlecase(title)
#
# # If the slug exists, return the object
# query = self.filter(slug=slugify(title))
# if query.exists():
# return query.first()
#
# # Otherwise create the topic with the title
# return self.create(title=title)
#
# def from_string(self, text):
# """
# Basically a get or create for a batch insert of topics separated by
# newlines as written into a text field or similar.
# """
# for line in frozenset(text.splitlines()):
# if line:
# yield self.from_title(line)
#
# def with_votes(self):
# """
# Annotates the topic model with a vote total.
# """
# return self.raw(VOTE_AGGREGATION_SQL)
#
# def mean_weight(self):
# """
# Returns the mean weight aggregation of all topics.
# """
# count = float(self.filter(is_canonical=True).count())
# total = sum(float(topic.vote_total) for topic in self.with_votes())
# return total / count
#
# class VotingManager(models.Manager):
# """
# Helper functions for vote management
# """
#
# def upvotes(self):
# """
# Returns the set of all up votes for a particular query.
# """
# return self.filter(vote=self.model.BALLOT.upvote)
#
# def downvotes(self):
# """
# Returns the set of all down votes for a particular query.
# """
# return self.filter(vote=self.model.BALLOT.downvote)
#
# def total(self):
# """
# Returns the sum of all up and down votes for a particular query.
# """
# return self.aggregate(
# total=models.Sum('vote')
# )
#
# def responses(self):
# """
# Returns an aggregation of IP address and the count per IP.
# """
# query = self.values("ipaddr")
# query = query.annotate(responses=models.Count('ipaddr'))
# query = query.order_by('ipaddr')
# return query
#
# def response_stats(self):
# """
# Returns a list of statistics from the responses histogram.
# """
# return self.responses().aggregate(
# num=models.Sum('responses'),
# avg=models.Avg('responses'),
# min=models.Min('responses'),
# max=models.Max('responses'),
# )
#
# def num_responses(self):
# """
# Returns the number of distinct IP addresses
# """
# return self.aggregate(r=models.Count('ipaddr', distinct=True))['r']
#
# def response_timeseries(self):
# """
# Returns a list of timeseries from the responses.
# """
# qss = QuerySetStats(self.all(), 'created')
# return qss.time_series(timezone.now() - timedelta(days=7), timezone.now())
which might include code, classes, or functions. Output only the next line. | objects = TopicManager() |
Based on the snippet: <|code_start|> """
votes = self.votes.aggregate(
total=models.Sum('vote')
)['total']
if self.is_canonical:
for ref in self.references.all():
votes += ref.vote_total()
return votes
##########################################################################
## Topic Voting
##########################################################################
class Vote(TimeStampedModel):
"""
Simple voting model that stores an up or down vote for a particular topic
associated with a particular IP address (and time of day).
"""
DATEFMT = "%a %b %d, %Y at %H:%M"
BALLOT = Choices((-1, 'downvote', 'downvote'), (1, 'upvote', 'upvote'), (0, 'novote', 'novote'))
# Vote fields
vote = models.SmallIntegerField(choices=BALLOT, default=BALLOT.upvote)
topic = models.ForeignKey(Topic, related_name='votes')
ipaddr = models.GenericIPAddressField()
# Custom voting manager
<|code_end|>
, predict the immediate next line with the help of imports:
from django.db import models
from model_utils import Choices
from autoslug import AutoSlugField
from model_utils.models import TimeStampedModel
from topics.managers import TopicManager, VotingManager
and context (classes, functions, sometimes code) from other files:
# Path: topics/managers.py
# class TopicManager(models.Manager):
# """
# Helper functions for topic management
# """
#
# def from_title(self, title):
# """
# A get or create from a slug function.
# """
# # Titlecase the topic
# title = titlecase(title)
#
# # If the slug exists, return the object
# query = self.filter(slug=slugify(title))
# if query.exists():
# return query.first()
#
# # Otherwise create the topic with the title
# return self.create(title=title)
#
# def from_string(self, text):
# """
# Basically a get or create for a batch insert of topics separated by
# newlines as written into a text field or similar.
# """
# for line in frozenset(text.splitlines()):
# if line:
# yield self.from_title(line)
#
# def with_votes(self):
# """
# Annotates the topic model with a vote total.
# """
# return self.raw(VOTE_AGGREGATION_SQL)
#
# def mean_weight(self):
# """
# Returns the mean weight aggregation of all topics.
# """
# count = float(self.filter(is_canonical=True).count())
# total = sum(float(topic.vote_total) for topic in self.with_votes())
# return total / count
#
# class VotingManager(models.Manager):
# """
# Helper functions for vote management
# """
#
# def upvotes(self):
# """
# Returns the set of all up votes for a particular query.
# """
# return self.filter(vote=self.model.BALLOT.upvote)
#
# def downvotes(self):
# """
# Returns the set of all down votes for a particular query.
# """
# return self.filter(vote=self.model.BALLOT.downvote)
#
# def total(self):
# """
# Returns the sum of all up and down votes for a particular query.
# """
# return self.aggregate(
# total=models.Sum('vote')
# )
#
# def responses(self):
# """
# Returns an aggregation of IP address and the count per IP.
# """
# query = self.values("ipaddr")
# query = query.annotate(responses=models.Count('ipaddr'))
# query = query.order_by('ipaddr')
# return query
#
# def response_stats(self):
# """
# Returns a list of statistics from the responses histogram.
# """
# return self.responses().aggregate(
# num=models.Sum('responses'),
# avg=models.Avg('responses'),
# min=models.Min('responses'),
# max=models.Max('responses'),
# )
#
# def num_responses(self):
# """
# Returns the number of distinct IP addresses
# """
# return self.aggregate(r=models.Count('ipaddr', distinct=True))['r']
#
# def response_timeseries(self):
# """
# Returns a list of timeseries from the responses.
# """
# qss = QuerySetStats(self.all(), 'created')
# return qss.time_series(timezone.now() - timedelta(days=7), timezone.now())
. Output only the next line. | objects = VotingManager() |
Predict the next line for this snippet: <|code_start|> )
# Ensure at least two topics are submitted.
if len(topics) < 2:
raise forms.ValidationError(
_("Please provide at least 2 topics, techniques, or technologies!"),
code="single_topic_error"
)
# 50 topics is too many.
if len(topics) > 50:
raise forms.ValidationError(
_("Thanks for thinking of so many topics! To prevent spam, however, "
"we have to limit you to 50 topics per form submission."),
code="topic_spam_error"
)
# Ensure topic uniqueness in submission.
if len(frozenset(topics)) < len(topics):
raise forms.ValidationError(
_("Duplicate topics detected! Please check your list and try again."),
code="duplicate_topics"
)
return data
def save_topics(self):
"""
Write the topics and their votes to disk.
"""
<|code_end|>
with the help of current file imports:
from django import forms
from collections import Counter
from topics.models import Topic, Vote
from ipware.ip import get_real_ip, get_ip
from django.utils.translation import ugettext as _
from django.template.defaultfilters import slugify
and context from other files:
# Path: topics/models.py
# class Topic(TimeStampedModel):
# """
# Stores a topic, basically a string like a tag and manages it.
# """
#
# # Topic fields
# title = models.CharField(max_length=128)
# slug = AutoSlugField(populate_from='title', unique=True)
# link = models.URLField(null=True, blank=True, default=None)
# refers_to = models.ForeignKey('self', related_name='references', null=True, blank=True, default=None)
# is_canonical = models.BooleanField(default=True)
#
# # Custom topic manager
# objects = TopicManager()
#
# # Topic meta class
# class Meta:
# db_table = 'topics'
# ordering = ('title', )
#
# def __unicode__(self):
# return self.title
#
# def vote_total(self):
# """
# Accumulates the votes via aggregation
# """
# votes = self.votes.aggregate(
# total=models.Sum('vote')
# )['total']
#
# if self.is_canonical:
# for ref in self.references.all():
# votes += ref.vote_total()
#
# return votes
#
# class Vote(TimeStampedModel):
# """
# Simple voting model that stores an up or down vote for a particular topic
# associated with a particular IP address (and time of day).
# """
#
# DATEFMT = "%a %b %d, %Y at %H:%M"
# BALLOT = Choices((-1, 'downvote', 'downvote'), (1, 'upvote', 'upvote'), (0, 'novote', 'novote'))
#
# # Vote fields
# vote = models.SmallIntegerField(choices=BALLOT, default=BALLOT.upvote)
# topic = models.ForeignKey(Topic, related_name='votes')
# ipaddr = models.GenericIPAddressField()
#
# # Custom voting manager
# objects = VotingManager()
#
# # Vote meta class
# class Meta:
# db_table = 'voting'
# ordering = ('-created',)
#
# def __unicode__(self):
# action = {
# -1: "-1",
# 0: "--",
# 1: "+1",
# }[self.vote]
#
# return "{} for \"{}\" ({} on {})".format(
# action, self.topic, self.ipaddr, self.modified.strftime(self.DATEFMT)
# )
, which may contain function names, class names, or code. Output only the next line. | for topic in Topic.objects.from_string(self.cleaned_data['topics']): |
Using the snippet: <|code_start|>
# Ensure at least two topics are submitted.
if len(topics) < 2:
raise forms.ValidationError(
_("Please provide at least 2 topics, techniques, or technologies!"),
code="single_topic_error"
)
# 50 topics is too many.
if len(topics) > 50:
raise forms.ValidationError(
_("Thanks for thinking of so many topics! To prevent spam, however, "
"we have to limit you to 50 topics per form submission."),
code="topic_spam_error"
)
# Ensure topic uniqueness in submission.
if len(frozenset(topics)) < len(topics):
raise forms.ValidationError(
_("Duplicate topics detected! Please check your list and try again."),
code="duplicate_topics"
)
return data
def save_topics(self):
"""
Write the topics and their votes to disk.
"""
for topic in Topic.objects.from_string(self.cleaned_data['topics']):
<|code_end|>
, determine the next line of code. You have imports:
from django import forms
from collections import Counter
from topics.models import Topic, Vote
from ipware.ip import get_real_ip, get_ip
from django.utils.translation import ugettext as _
from django.template.defaultfilters import slugify
and context (class names, function names, or code) available:
# Path: topics/models.py
# class Topic(TimeStampedModel):
# """
# Stores a topic, basically a string like a tag and manages it.
# """
#
# # Topic fields
# title = models.CharField(max_length=128)
# slug = AutoSlugField(populate_from='title', unique=True)
# link = models.URLField(null=True, blank=True, default=None)
# refers_to = models.ForeignKey('self', related_name='references', null=True, blank=True, default=None)
# is_canonical = models.BooleanField(default=True)
#
# # Custom topic manager
# objects = TopicManager()
#
# # Topic meta class
# class Meta:
# db_table = 'topics'
# ordering = ('title', )
#
# def __unicode__(self):
# return self.title
#
# def vote_total(self):
# """
# Accumulates the votes via aggregation
# """
# votes = self.votes.aggregate(
# total=models.Sum('vote')
# )['total']
#
# if self.is_canonical:
# for ref in self.references.all():
# votes += ref.vote_total()
#
# return votes
#
# class Vote(TimeStampedModel):
# """
# Simple voting model that stores an up or down vote for a particular topic
# associated with a particular IP address (and time of day).
# """
#
# DATEFMT = "%a %b %d, %Y at %H:%M"
# BALLOT = Choices((-1, 'downvote', 'downvote'), (1, 'upvote', 'upvote'), (0, 'novote', 'novote'))
#
# # Vote fields
# vote = models.SmallIntegerField(choices=BALLOT, default=BALLOT.upvote)
# topic = models.ForeignKey(Topic, related_name='votes')
# ipaddr = models.GenericIPAddressField()
#
# # Custom voting manager
# objects = VotingManager()
#
# # Vote meta class
# class Meta:
# db_table = 'voting'
# ordering = ('-created',)
#
# def __unicode__(self):
# action = {
# -1: "-1",
# 0: "--",
# 1: "+1",
# }[self.vote]
#
# return "{} for \"{}\" ({} on {})".format(
# action, self.topic, self.ipaddr, self.modified.strftime(self.DATEFMT)
# )
. Output only the next line. | Vote.objects.create(topic=topic, ipaddr=self.ipaddr) |
Next line prediction: <|code_start|>
##########################################################################
## Imports
##########################################################################
##########################################################################
## Admin Views
##########################################################################
class VoteInline(admin.TabularInline):
model = Vote
extra = 0
readonly_fields = ('created', )
class TopicAdmin(admin.ModelAdmin):
inlines = [
VoteInline,
]
readonly_fields = ('slug', 'created', 'vote_total')
list_display = ["title", "vote_total"]
##########################################################################
## Model Registration
##########################################################################
<|code_end|>
. Use current file imports:
(from django.contrib import admin
from topics.models import Topic, Vote
from django.db.models import Sum)
and context including class names, function names, or small code snippets from other files:
# Path: topics/models.py
# class Topic(TimeStampedModel):
# """
# Stores a topic, basically a string like a tag and manages it.
# """
#
# # Topic fields
# title = models.CharField(max_length=128)
# slug = AutoSlugField(populate_from='title', unique=True)
# link = models.URLField(null=True, blank=True, default=None)
# refers_to = models.ForeignKey('self', related_name='references', null=True, blank=True, default=None)
# is_canonical = models.BooleanField(default=True)
#
# # Custom topic manager
# objects = TopicManager()
#
# # Topic meta class
# class Meta:
# db_table = 'topics'
# ordering = ('title', )
#
# def __unicode__(self):
# return self.title
#
# def vote_total(self):
# """
# Accumulates the votes via aggregation
# """
# votes = self.votes.aggregate(
# total=models.Sum('vote')
# )['total']
#
# if self.is_canonical:
# for ref in self.references.all():
# votes += ref.vote_total()
#
# return votes
#
# class Vote(TimeStampedModel):
# """
# Simple voting model that stores an up or down vote for a particular topic
# associated with a particular IP address (and time of day).
# """
#
# DATEFMT = "%a %b %d, %Y at %H:%M"
# BALLOT = Choices((-1, 'downvote', 'downvote'), (1, 'upvote', 'upvote'), (0, 'novote', 'novote'))
#
# # Vote fields
# vote = models.SmallIntegerField(choices=BALLOT, default=BALLOT.upvote)
# topic = models.ForeignKey(Topic, related_name='votes')
# ipaddr = models.GenericIPAddressField()
#
# # Custom voting manager
# objects = VotingManager()
#
# # Vote meta class
# class Meta:
# db_table = 'voting'
# ordering = ('-created',)
#
# def __unicode__(self):
# action = {
# -1: "-1",
# 0: "--",
# 1: "+1",
# }[self.vote]
#
# return "{} for \"{}\" ({} on {})".format(
# action, self.topic, self.ipaddr, self.modified.strftime(self.DATEFMT)
# )
. Output only the next line. | admin.site.register(Topic, TopicAdmin) |
Predict the next line after this snippet: <|code_start|>
try:
except ImportError:
@pytest.fixture
def dut(moku):
<|code_end|>
using the current file's imports:
import pytest
from pymoku.instruments import WaveformGenerator
from unittest.mock import ANY
from mock import ANY
and any relevant context from other files:
# Path: pymoku/instruments.py
. Output only the next line. | i = WaveformGenerator() |
Given the following code snippet before the placeholder: <|code_start|>
try:
except ImportError:
@pytest.fixture
def dut(moku):
with patch('pymoku._frame_instrument.FrameBasedInstrument._set_running'):
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from pymoku.instruments import Oscilloscope
from pymoku import _oscilloscope
from unittest.mock import patch, ANY
from mock import patch, ANY
and context including class names, function names, and sometimes code from other files:
# Path: pymoku/instruments.py
#
# Path: pymoku/_oscilloscope.py
# REG_OSC_OUTSEL = 64
# REG_OSC_TRIGCTL = 67
# REG_OSC_ACTL = 66
# REG_OSC_DECIMATION = 65
# REG_OSC_AUTOTIMER = 74
# _OSC_SOURCE_CH1 = 0
# _OSC_SOURCE_CH2 = 1
# _OSC_SOURCE_DA1 = 2
# _OSC_SOURCE_DA2 = 3
# _OSC_SOURCE_EXT = 4
# _OSC_SOURCES = {
# 'in1': _OSC_SOURCE_CH1,
# 'in2': _OSC_SOURCE_CH2,
# 'out1': _OSC_SOURCE_DA1,
# 'out2': _OSC_SOURCE_DA2,
# 'ext': _OSC_SOURCE_EXT
# }
# _OSC_ROLL = ROLL
# _OSC_SWEEP = SWEEP
# _OSC_FULL_FRAME = FULL_FRAME
# _OSC_LB_ROUND = 0
# _OSC_LB_CLIP = 1
# _OSC_AIN_DDS = 0
# _OSC_AIN_DECI = 1
# _OSC_ADC_SMPS = ADC_SMP_RATE
# _OSC_BUFLEN = CHN_BUFLEN
# _OSC_TRIGLVL_MAX = 10.0 # V
# _OSC_TRIGLVL_MIN = -10.0 # V
# _OSC_SAMPLERATE_MIN = 10 # smp/s
# _OSC_SAMPLERATE_MAX = 500e6 # smp/s
# _OSC_PRETRIGGER_MAX = (2**12) - 1
# _OSC_POSTTRIGGER_MAX = -2**28
# _CLK_FREQ = 125e6
# _TIMER_ACCUM = 2.0**32
# class _CoreOscilloscope(_frame_instrument.FrameBasedInstrument):
# class Oscilloscope(
# _CoreOscilloscope, _waveform_generator.BasicWaveformGenerator):
# def __init__(self):
# def _calculate_decimation(self, t1, t2):
# def _calculate_render_downsample(self, t1, t2, decimation):
# def _cubic_int_to_scale(integer):
# def _calculate_buffer_offset(self, t1, decimation):
# def _calculate_render_offset(self, t1, decimation):
# def _calculate_frame_start_time(self, decimation,
# render_decimation, frame_offset):
# def _calculate_frame_timestep(self, decimation, render_decimation):
# def _calculate_buffer_timestep(self, decimation):
# def _calculate_buffer_start_time(self, decimation, buffer_offset):
# def _deci_gain(self):
# def set_timebase(self, t1, t2):
# def set_samplerate(self, samplerate, trigger_offset=0):
# def get_samplerate(self):
# def set_xmode(self, xmode):
# def set_precision_mode(self, state):
# def is_precision_mode(self):
# def _set_trigger(self, source, edge, level, minwidth, maxwidth,
# hysteresis, hf_reject, mode):
# def _set_source(self, ch, source):
# def set_defaults(self):
# def _calculate_scales(self):
# def _update_dependent_regs(self, scales):
# def _update_datalogger_params(self):
# def _get_hdrstr(self, ch1, ch2):
# def _get_fmtstr(self, ch1, ch2):
# def _on_reg_sync(self):
# def commit(self):
# def set_defaults(self):
# def set_trigger(self, source, edge, level, minwidth=None, maxwidth=None,
# hysteresis=10e-3, hf_reject=False, mode='auto'):
# def set_source(self, ch, source, lmode='round'):
# def _signal_source_volts_per_bit(self, source, scales, trigger=False):
. Output only the next line. | i = Oscilloscope() |
Based on the snippet: <|code_start|> dut.set_precision_mode(True)
dut.is_precision_mode()
moku._write_regs.assert_called_with(ANY)
def test_set_defaults(dut, moku):
'''
TODO Default test
'''
dut.set_defaults()
moku._write_regs.assert_called_with(ANY)
def test_set_trigger(dut, moku):
'''
TODO Default test
'''
dut.set_trigger('in1', 'rising', 0.0)
moku._write_regs.assert_called_with(ANY)
def test_set_source(dut, moku):
'''
TODO Default test
'''
dut.set_source(1, 'in1', 0.0)
moku._write_regs.assert_called_with(ANY)
@pytest.mark.parametrize('attr, value', [
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from pymoku.instruments import Oscilloscope
from pymoku import _oscilloscope
from unittest.mock import patch, ANY
from mock import patch, ANY
and context (classes, functions, sometimes code) from other files:
# Path: pymoku/instruments.py
#
# Path: pymoku/_oscilloscope.py
# REG_OSC_OUTSEL = 64
# REG_OSC_TRIGCTL = 67
# REG_OSC_ACTL = 66
# REG_OSC_DECIMATION = 65
# REG_OSC_AUTOTIMER = 74
# _OSC_SOURCE_CH1 = 0
# _OSC_SOURCE_CH2 = 1
# _OSC_SOURCE_DA1 = 2
# _OSC_SOURCE_DA2 = 3
# _OSC_SOURCE_EXT = 4
# _OSC_SOURCES = {
# 'in1': _OSC_SOURCE_CH1,
# 'in2': _OSC_SOURCE_CH2,
# 'out1': _OSC_SOURCE_DA1,
# 'out2': _OSC_SOURCE_DA2,
# 'ext': _OSC_SOURCE_EXT
# }
# _OSC_ROLL = ROLL
# _OSC_SWEEP = SWEEP
# _OSC_FULL_FRAME = FULL_FRAME
# _OSC_LB_ROUND = 0
# _OSC_LB_CLIP = 1
# _OSC_AIN_DDS = 0
# _OSC_AIN_DECI = 1
# _OSC_ADC_SMPS = ADC_SMP_RATE
# _OSC_BUFLEN = CHN_BUFLEN
# _OSC_TRIGLVL_MAX = 10.0 # V
# _OSC_TRIGLVL_MIN = -10.0 # V
# _OSC_SAMPLERATE_MIN = 10 # smp/s
# _OSC_SAMPLERATE_MAX = 500e6 # smp/s
# _OSC_PRETRIGGER_MAX = (2**12) - 1
# _OSC_POSTTRIGGER_MAX = -2**28
# _CLK_FREQ = 125e6
# _TIMER_ACCUM = 2.0**32
# class _CoreOscilloscope(_frame_instrument.FrameBasedInstrument):
# class Oscilloscope(
# _CoreOscilloscope, _waveform_generator.BasicWaveformGenerator):
# def __init__(self):
# def _calculate_decimation(self, t1, t2):
# def _calculate_render_downsample(self, t1, t2, decimation):
# def _cubic_int_to_scale(integer):
# def _calculate_buffer_offset(self, t1, decimation):
# def _calculate_render_offset(self, t1, decimation):
# def _calculate_frame_start_time(self, decimation,
# render_decimation, frame_offset):
# def _calculate_frame_timestep(self, decimation, render_decimation):
# def _calculate_buffer_timestep(self, decimation):
# def _calculate_buffer_start_time(self, decimation, buffer_offset):
# def _deci_gain(self):
# def set_timebase(self, t1, t2):
# def set_samplerate(self, samplerate, trigger_offset=0):
# def get_samplerate(self):
# def set_xmode(self, xmode):
# def set_precision_mode(self, state):
# def is_precision_mode(self):
# def _set_trigger(self, source, edge, level, minwidth, maxwidth,
# hysteresis, hf_reject, mode):
# def _set_source(self, ch, source):
# def set_defaults(self):
# def _calculate_scales(self):
# def _update_dependent_regs(self, scales):
# def _update_datalogger_params(self):
# def _get_hdrstr(self, ch1, ch2):
# def _get_fmtstr(self, ch1, ch2):
# def _on_reg_sync(self):
# def commit(self):
# def set_defaults(self):
# def set_trigger(self, source, edge, level, minwidth=None, maxwidth=None,
# hysteresis=10e-3, hf_reject=False, mode='auto'):
# def set_source(self, ch, source, lmode='round'):
# def _signal_source_volts_per_bit(self, source, scales, trigger=False):
. Output only the next line. | ('source_ch1', _oscilloscope._OSC_SOURCE_CH1), |
Next line prediction: <|code_start|>
try:
except ImportError:
@pytest.fixture
def dut(moku):
with patch('pymoku._stream_instrument.StreamBasedInstrument._set_running'):
<|code_end|>
. Use current file imports:
(import pytest
from pymoku.instruments import Datalogger
from pymoku import _datalogger
from unittest.mock import patch, ANY
from mock import patch, ANY)
and context including class names, function names, or small code snippets from other files:
# Path: pymoku/instruments.py
#
# Path: pymoku/_datalogger.py
# REG_DL_OUTSEL = 64
# REG_DL_ACTL = 66
# REG_DL_DECIMATION = 65
# _DL_SOURCE_ADC1 = 0
# _DL_SOURCE_ADC2 = 1
# _DL_SOURCE_DAC1 = 2
# _DL_SOURCE_DAC2 = 3
# _DL_SOURCE_EXT = 4
# _DL_LB_ROUND = 0
# _DL_LB_CLIP = 1
# _DL_AIN_DDS = 0
# _DL_AIN_DECI = 1
# _DL_ADC_SMPS = ADC_SMP_RATE
# _DL_BUFLEN = CHN_BUFLEN
# _DL_SCREEN_WIDTH = 1024
# _DL_ROLL = ROLL
# _DL_SAMPLERATE_MIN = 10 # Smp/s
# _DL_SAMPLERATE_MAX = _DL_ADC_SMPS # 500MSmp/s
# class Datalogger(_stream_instrument.StreamBasedInstrument,
# _waveform_generator.BasicWaveformGenerator):
# def __init__(self):
# def set_defaults(self):
# def set_samplerate(self, samplerate):
# def get_samplerate(self):
# def set_precision_mode(self, state):
# def is_precision_mode(self):
# def set_source(self, ch, source, lmode='round'):
# def _update_datalogger_params(self):
# def _on_reg_sync(self):
# def _get_hdrstr(self, ch1, ch2):
# def _get_fmtstr(self, ch1, ch2):
# def _deci_gain(self):
# def _calculate_scales(self):
# def _compute_total_scaling_factor(adc, dac, src, lmode):
. Output only the next line. | i = Datalogger() |
Given the code snippet: <|code_start|> dut.get_samplerate()
moku._write_regs.assert_called_with(ANY)
def test_set_precision_mode(dut, moku):
'''
TODO Default test
'''
dut.set_precision_mode(True)
dut.is_precision_mode()
moku._write_regs.assert_called_with(ANY)
def test_set_defaults(dut, moku):
'''
TODO Default test
'''
dut.set_defaults()
moku._write_regs.assert_called_with(ANY)
def test_set_source(dut, moku):
'''
TODO Default test
'''
dut.set_source(1, 'in1')
moku._write_regs.assert_called_with(ANY)
@pytest.mark.parametrize('attr, value', [
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from pymoku.instruments import Datalogger
from pymoku import _datalogger
from unittest.mock import patch, ANY
from mock import patch, ANY
and context (functions, classes, or occasionally code) from other files:
# Path: pymoku/instruments.py
#
# Path: pymoku/_datalogger.py
# REG_DL_OUTSEL = 64
# REG_DL_ACTL = 66
# REG_DL_DECIMATION = 65
# _DL_SOURCE_ADC1 = 0
# _DL_SOURCE_ADC2 = 1
# _DL_SOURCE_DAC1 = 2
# _DL_SOURCE_DAC2 = 3
# _DL_SOURCE_EXT = 4
# _DL_LB_ROUND = 0
# _DL_LB_CLIP = 1
# _DL_AIN_DDS = 0
# _DL_AIN_DECI = 1
# _DL_ADC_SMPS = ADC_SMP_RATE
# _DL_BUFLEN = CHN_BUFLEN
# _DL_SCREEN_WIDTH = 1024
# _DL_ROLL = ROLL
# _DL_SAMPLERATE_MIN = 10 # Smp/s
# _DL_SAMPLERATE_MAX = _DL_ADC_SMPS # 500MSmp/s
# class Datalogger(_stream_instrument.StreamBasedInstrument,
# _waveform_generator.BasicWaveformGenerator):
# def __init__(self):
# def set_defaults(self):
# def set_samplerate(self, samplerate):
# def get_samplerate(self):
# def set_precision_mode(self, state):
# def is_precision_mode(self):
# def set_source(self, ch, source, lmode='round'):
# def _update_datalogger_params(self):
# def _on_reg_sync(self):
# def _get_hdrstr(self, ch1, ch2):
# def _get_fmtstr(self, ch1, ch2):
# def _deci_gain(self):
# def _calculate_scales(self):
# def _compute_total_scaling_factor(adc, dac, src, lmode):
. Output only the next line. | ('source_ch1', _datalogger._DL_SOURCE_ADC1), |
Given the code snippet: <|code_start|>
try:
except ImportError:
@pytest.fixture
def dut(moku):
<|code_end|>
, generate the next line using the imports in this file:
import pytest
from pymoku.instruments import LockInAmp
from pymoku import _lockinamp
from unittest.mock import ANY
from mock import ANY
and context (functions, classes, or occasionally code) from other files:
# Path: pymoku/instruments.py
#
# Path: pymoku/_lockinamp.py
# REG_LIA_PM_BW1 = 90
# REG_LIA_PM_AUTOA1 = 91
# REG_LIA_PM_REACQ = 92
# REG_LIA_PM_RESET = 93
# REG_LIA_PM_OUTDEC = 94
# REG_LIA_PM_OUTSHIFT = 94
# REG_LIA_SIG_SELECT = 95
# REG_LIA_ENABLES = 96
# REG_LIA_PIDGAIN1 = 97
# REG_LIA_PIDGAIN2 = 98
# REG_LIA_INT_IGAIN1 = 99
# REG_LIA_INT_IGAIN2 = 100
# REG_LIA_INT_IFBGAIN1 = 101
# REG_LIA_INT_IFBGAIN2 = 102
# REG_LIA_INT_PGAIN1 = 103
# REG_LIA_INT_PGAIN2 = 104
# REG_LIA_GAIN_STAGE = 105
# REG_LIA_DIFF_DGAIN2 = 106
# REG_LIA_DIFF_PGAIN1 = 107
# REG_LIA_DIFF_PGAIN2 = 108
# REG_LIA_DIFF_IGAIN1 = 109
# REG_LIA_DIFF_IGAIN2 = 110
# REG_LIA_DIFF_IFBGAIN1 = 111
# REG_LIA_DIFF_IFBGAIN2 = 112
# REG_LIA_IN_OFFSET1 = 113
# REG_LIA_OUT_OFFSET1 = 114
# REG_LIA_INPUT_GAIN = 117
# REG_LIA_FREQDEMOD_L = 118
# REG_LIA_FREQDEMOD_H = 119
# REG_LIA_PHASEDEMOD_L = 120
# REG_LIA_PHASEDEMOD_H = 121
# REG_LIA_LO_FREQ_L = 122
# REG_LIA_LO_FREQ_H = 123
# REG_LIA_LO_PHASE_L = 124
# REG_LIA_LO_PHASE_H = 125
# REG_LIA_SINEOUTAMP = 126
# REG_LIA_SINEOUTOFF = 126
# REG_LIA_MONSELECT = 127
# _LIA_INPUT_SMPS = ADC_SMP_RATE
# _LIA_CHN_BUFLEN = CHN_BUFLEN
# _LIA_MON_NONE = 0
# _LIA_MON_IN1 = 1
# _LIA_MON_I = 2
# _LIA_MON_Q = 3
# _LIA_MON_OUT = 4
# _LIA_MON_AUX = 5
# _LIA_MON_IN2 = 6
# _LIA_MON_DEMOD = 7
# _LIA_SOURCE_A = 0
# _LIA_SOURCE_B = 1
# _LIA_SOURCE_IN1 = 2
# _LIA_SOURCE_IN2 = 3
# _LIA_SOURCE_EXT = 4
# _LIA_OSC_SOURCES = {
# 'a': _LIA_SOURCE_A,
# 'b': _LIA_SOURCE_B,
# 'in1': _LIA_SOURCE_IN1,
# 'in2': _LIA_SOURCE_IN2,
# 'ext': _LIA_SOURCE_EXT
# }
# _LIA_CONTROL_FS = 25.0e6
# _LIA_FREQSCALE = 1.0e9 / 2**48
# _LIA_PHASESCALE = 1.0 / 2**48
# _LIA_P_GAINSCALE = 2.0**16
# _LIA_ID_GAINSCALE = 2.0**24 - 1
# _LIA_SIGNALS = ['x', 'y', 'r', 'theta']
# _NON_PLL_ALLOWED_SIGS = ['x', 'sine', 'offset', 'none']
# class LockInAmp(PIDController, _CoreOscilloscope):
# def __init__(self):
# def set_defaults(self):
# def set_input_gain(self, gain=0):
# def set_outputs(self, main, aux, main_offset=0.0, aux_offset=0.0):
# def _update_pid_gain_selects(self):
# def _signal_select(sig):
# def set_pid_by_frequency(self, lia_ch, kp=1, i_xover=None, d_xover=None,
# si=None, sd=None, in_offset=0, out_offset=0):
# def set_pid_by_gain(self, lia_ch, g, kp=1.0, ki=0, kd=0, si=None,
# sd=None, in_offset=0, out_offset=0):
# def set_gain(self, lia_ch, g):
# def set_demodulation(self, mode, frequency=1e6, phase=0,
# output_amplitude=0.5):
# def set_filter(self, f_corner, order):
# def set_lo_output(self, amplitude, frequency, phase):
# def set_monitor(self, monitor_ch, source):
# def set_trigger(self, source, edge, level, minwidth=None,
# maxwidth=None, hysteresis=10e-3, hf_reject=False,
# mode='auto'):
# def _signal_source_volts_per_bit(self, source, scales, trigger=False):
# def _monitor_source_volts_per_bit(self, source, scales):
# def _demod_mode_to_gain(mode):
# def _update_dependent_regs(self, scales):
# def set_control_matrix(self):
. Output only the next line. | i = LockInAmp() |
Given snippet: <|code_start|> elif 8 <= factor <= 64:
d_wdfmuxsel = 1
d_outmuxsel = 2
d_cic1_dec = factor / 4
d_cic1_bitshift = 12 - math.log(d_cic1_dec ** 3, 2)
i_muxsel = 3
i_ratechange_cic1 = factor / 4
i_interprate_cic1 = 0
i_bitshift_cic1 = math.log(i_ratechange_cic1 ** 2, 2)
i_highrate_wdf1 = factor / 2 - 1
i_highrate_wdf2 = factor / 4 - 1
else: # 128 <= factor <= 1024
d_wdfmuxsel = 2
d_outmuxsel = 2
d_cic1_dec = 16
d_cic1_bitshift = 0
d_cic2_dec = factor / 64
d_cic2_bitshift = math.log(d_cic2_dec ** 3, 2)
i_muxsel = 4
i_ratechange_cic2 = factor / 64
i_interprate_cic2 = 0
i_bitshift_cic2 = math.log(i_ratechange_cic2 ** 2, 2)
i_ratechange_cic1 = 16
i_bitshift_cic1 = 8
i_interprate_cic1 = i_ratechange_cic2 - 1
i_highrate_wdf1 = factor / 2 - 1
i_highrate_wdf2 = factor / 4 - 1
self._instr._accessor_set(
self.regbase + self.REG_DECIMATION,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from ._instrument import to_reg_unsigned
import math
and context:
# Path: pymoku/_instrument.py
# def to_reg_unsigned(_offset, _len, allow_set=None, allow_range=None,
# xform=lambda obj, x: x):
# """ Returns a callable that will pack a new unsigned data value or
# bitfield in to a register. Designed as shorthand for common use in
# instrument register accessor lists. Supports single and compound
# registers (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param allow_set: Set containing all valid values of the data field.
# :param allow_range: a two-tuple specifying the bounds of the data value.
# :param xform: a callable that translates the user value written to the
# attribute to the register value
# """
#
# def __us(obj, val, old):
# val = xform(obj, val)
# mask = ((1 << _len) - 1) << _offset
#
# if allow_set and allow_range:
# raise MokuException("Can't check against both ranges and sets")
#
# if allow_set and val not in allow_set:
# return None
# elif allow_range and (val < allow_range[0] or val > allow_range[1]):
# return None
#
# v = _usgn(val, _len) << _offset
#
# try:
# return (old & ~mask) | v
# except TypeError:
# r = []
# for o in reversed(old):
# r.insert(0, (o & ~mask) | v & 0xFFFFFFFF)
#
# v = v >> 32
# mask = mask >> 32
#
# return tuple(r)
#
# return __us
which might include code, classes, or functions. Output only the next line. | to_reg_unsigned(0, 2), d_wdfmuxsel |
Continue the code snippet: <|code_start|>
try:
except ImportError:
@pytest.fixture
def dut(moku):
<|code_end|>
. Use current file imports:
import pytest
from pymoku.instruments import Phasemeter
from unittest.mock import ANY
from mock import ANY
and context (classes, functions, or code) from other files:
# Path: pymoku/instruments.py
. Output only the next line. | i = Phasemeter() |
Here is a snippet: <|code_start|>
try:
except ImportError:
filt_coeff = [[1.0],
[1.0, 0.64, -1.02, 0.646, -1.637, 0.898],
[1.0, 0.51, -0.75, 0.518, -1.403, 0.679],
[1.0, 0.31, -0.31, 0.314, -1.082, 0.410],
[1.0, 0.13, 0.122, 0.130, -0.795, 0.178]]
@pytest.fixture
def dut(moku):
with patch(
'pymoku._frame_instrument.'
'FrameBasedInstrument._set_running'):
<|code_end|>
. Write the next line using the current file imports:
import pytest
from pymoku.instruments import IIRFilterBox
from pymoku import _iirfilterbox
from unittest.mock import patch, ANY
from mock import patch, ANY
and context from other files:
# Path: pymoku/instruments.py
#
# Path: pymoku/_iirfilterbox.py
# REG_ENABLE = 96
# REG_MONSELECT = 111
# REG_INPUTOFFSET_CH0 = 112
# REG_INPUTOFFSET_CH1 = 113
# REG_OUTPUTOFFSET_CH0 = 114
# REG_OUTPUTOFFSET_CH1 = 115
# REG_CH0_CH0GAIN = 116
# REG_CH0_CH1GAIN = 117
# REG_CH1_CH0GAIN = 118
# REG_CH1_CH1GAIN = 119
# REG_INPUTSCALE_CH0 = 120
# REG_INPUTSCALE_CH1 = 121
# REG_OUTPUTSCALE_CH0 = 122
# REG_OUTPUTSCALE_CH1 = 123
# REG_SAMPLINGFREQ = 124
# REG_FILT_RESET = 62
# _IIR_MON_NONE = 0
# _IIR_MON_ADC1 = 1
# _IIR_MON_IN1 = 2
# _IIR_MON_OUT1 = 3
# _IIR_MON_ADC2 = 4
# _IIR_MON_IN2 = 5
# _IIR_MON_OUT2 = 6
# _IIR_MON_NONE = 0
# _IIR_MON_ADC1 = 1
# _IIR_MON_IN1 = 2
# _IIR_MON_OUT1 = 3
# _IIR_MON_ADC2 = 4
# _IIR_MON_IN2 = 5
# _IIR_MON_OUT2 = 6
# _IIR_SOURCE_A = 0
# _IIR_SOURCE_B = 1
# _IIR_SOURCE_IN1 = 2
# _IIR_SOURCE_IN2 = 3
# _IIR_SOURCE_EXT = 4
# _IIR_OSC_SOURCES = {
# 'a': _IIR_SOURCE_A,
# 'b': _IIR_SOURCE_B,
# 'in1': _IIR_SOURCE_IN1,
# 'in2': _IIR_SOURCE_IN2,
# 'ext': _IIR_SOURCE_EXT
# }
# _IIR_COEFFWIDTH = 48
# _IIR_INPUT_SMPS = ADC_SMP_RATE / 4
# _IIR_CHN_BUFLEN = 2**13
# _ADC_DEFAULT_CALIBRATION = 3750.0 # Bits/V (No attenuation)
# class IIRFilterBox(_CoreOscilloscope):
# def __init__(self):
# def set_defaults(self):
# def set_control_matrix(self, ch, scale_in1, scale_in2):
# def _update_control_matrix_regs(self):
# def _sync_control_matrix_regs(self):
# def set_filter(self, ch, sample_rate, filter_coefficients):
# def disable_output(self, ch):
# def set_gains_offsets(self, ch, input_gain=1.0, output_gain=1.0,
# input_offset=0, output_offset=0):
# def _update_gains_offsets_regs(self):
# def _sync_gains_offsets_regs(self):
# def set_monitor(self, monitor_ch, source):
# def set_trigger(self, source, edge, level, minwidth=None, maxwidth=None,
# hysteresis=10e-3, hf_reject=False, mode='auto'):
# def _signal_source_volts_per_bit(self, source, scales, trigger=False):
# def _monitor_source_volts_per_bit(self, source, scales):
# def _update_dependent_regs(self, scales):
# def _on_reg_sync(self):
, which may include functions, classes, or code. Output only the next line. | i = IIRFilterBox() |
Given snippet: <|code_start|> '''
TODO Default test
'''
dut.set_gains_offsets(1, 1.0, 1.0, 0, 0)
moku._write_regs.assert_called_with(ANY)
def test_set_monitor(dut, moku):
'''
TODO Default test
'''
dut.set_monitor('a', 'adc1')
moku._write_regs.assert_called_with(ANY)
def test_set_trigger(dut, moku):
'''
TODO Default test
'''
dut.set_trigger('in1', 'rising', 1.0, None, None, 10e-3, False, 'auto')
moku._write_regs.assert_called_with(ANY)
@pytest.mark.parametrize('attr, value', [
('mon1_source', 1),
('mon2_source', 1),
('input_en1', True),
('input_en2', True),
('output_en1', True),
('output_en2', True),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from pymoku.instruments import IIRFilterBox
from pymoku import _iirfilterbox
from unittest.mock import patch, ANY
from mock import patch, ANY
and context:
# Path: pymoku/instruments.py
#
# Path: pymoku/_iirfilterbox.py
# REG_ENABLE = 96
# REG_MONSELECT = 111
# REG_INPUTOFFSET_CH0 = 112
# REG_INPUTOFFSET_CH1 = 113
# REG_OUTPUTOFFSET_CH0 = 114
# REG_OUTPUTOFFSET_CH1 = 115
# REG_CH0_CH0GAIN = 116
# REG_CH0_CH1GAIN = 117
# REG_CH1_CH0GAIN = 118
# REG_CH1_CH1GAIN = 119
# REG_INPUTSCALE_CH0 = 120
# REG_INPUTSCALE_CH1 = 121
# REG_OUTPUTSCALE_CH0 = 122
# REG_OUTPUTSCALE_CH1 = 123
# REG_SAMPLINGFREQ = 124
# REG_FILT_RESET = 62
# _IIR_MON_NONE = 0
# _IIR_MON_ADC1 = 1
# _IIR_MON_IN1 = 2
# _IIR_MON_OUT1 = 3
# _IIR_MON_ADC2 = 4
# _IIR_MON_IN2 = 5
# _IIR_MON_OUT2 = 6
# _IIR_MON_NONE = 0
# _IIR_MON_ADC1 = 1
# _IIR_MON_IN1 = 2
# _IIR_MON_OUT1 = 3
# _IIR_MON_ADC2 = 4
# _IIR_MON_IN2 = 5
# _IIR_MON_OUT2 = 6
# _IIR_SOURCE_A = 0
# _IIR_SOURCE_B = 1
# _IIR_SOURCE_IN1 = 2
# _IIR_SOURCE_IN2 = 3
# _IIR_SOURCE_EXT = 4
# _IIR_OSC_SOURCES = {
# 'a': _IIR_SOURCE_A,
# 'b': _IIR_SOURCE_B,
# 'in1': _IIR_SOURCE_IN1,
# 'in2': _IIR_SOURCE_IN2,
# 'ext': _IIR_SOURCE_EXT
# }
# _IIR_COEFFWIDTH = 48
# _IIR_INPUT_SMPS = ADC_SMP_RATE / 4
# _IIR_CHN_BUFLEN = 2**13
# _ADC_DEFAULT_CALIBRATION = 3750.0 # Bits/V (No attenuation)
# class IIRFilterBox(_CoreOscilloscope):
# def __init__(self):
# def set_defaults(self):
# def set_control_matrix(self, ch, scale_in1, scale_in2):
# def _update_control_matrix_regs(self):
# def _sync_control_matrix_regs(self):
# def set_filter(self, ch, sample_rate, filter_coefficients):
# def disable_output(self, ch):
# def set_gains_offsets(self, ch, input_gain=1.0, output_gain=1.0,
# input_offset=0, output_offset=0):
# def _update_gains_offsets_regs(self):
# def _sync_gains_offsets_regs(self):
# def set_monitor(self, monitor_ch, source):
# def set_trigger(self, source, edge, level, minwidth=None, maxwidth=None,
# hysteresis=10e-3, hf_reject=False, mode='auto'):
# def _signal_source_volts_per_bit(self, source, scales, trigger=False):
# def _monitor_source_volts_per_bit(self, source, scales):
# def _update_dependent_regs(self, scales):
# def _on_reg_sync(self):
which might include code, classes, or functions. Output only the next line. | ('matrixscale_ch1_ch1', 1 / _iirfilterbox._ADC_DEFAULT_CALIBRATION), |
Predict the next line for this snippet: <|code_start|>
try:
except ImportError:
@pytest.fixture
def dut(moku):
with patch('pymoku._frame_instrument.FrameBasedInstrument._set_running'):
<|code_end|>
with the help of current file imports:
import pytest
from pymoku.instruments import PIDController
from unittest.mock import patch, ANY
from mock import patch, ANY
and context from other files:
# Path: pymoku/instruments.py
, which may contain function names, class names, or code. Output only the next line. | i = PIDController() |
Next line prediction: <|code_start|>
try:
except ImportError:
@pytest.fixture
def dut(moku):
with patch('pymoku._frame_instrument.FrameBasedInstrument._set_running'):
<|code_end|>
. Use current file imports:
(import pytest
from pymoku.instruments import FrequencyResponseAnalyzer
from unittest.mock import patch, ANY
from mock import patch, ANY)
and context including class names, function names, or small code snippets from other files:
# Path: pymoku/instruments.py
. Output only the next line. | i = FrequencyResponseAnalyzer() |
Predict the next line for this snippet: <|code_start|>
def build_is_compatible(moku):
# Check firmware versions
moku_fw = moku.get_firmware_build()
pymoku_fw = compat_fw[0]
if moku_fw == 65535:
return None # Development build, unable to determine
return moku_fw == pymoku_fw
def patch_is_compatible(moku):
<|code_end|>
with the help of current file imports:
from pymoku.version import compat_fw
from pymoku.version import compat_packs
and context from other files:
# Path: pymoku/version.py
#
# Path: pymoku/version.py
, which may contain function names, class names, or code. Output only the next line. | return set(moku._list_running_packs()) == set(compat_packs) |
Based on the snippet: <|code_start|> # Calculates magnitude of a sample given I,Q and gain correction
# factors
def calculate_magnitude(I, Q, G, frontend_scale):
if I is None or Q is None:
return None
else:
return 2.0 * math.sqrt(
(I or 0)**2 + (Q or 0)**2) * front_end_scale / (G or 1)
self.magnitude = [calculate_magnitude(I, Q, G, front_end_scale)
for I, Q, G in zip(self.i_sig,
self.q_sig, gain_correction)]
# Sometimes there's a transient condition at startup where we don't
# have a valid output_amp. Return Nones in that case in preference to
# exploding.
self.magnitude_dB = [None if not x else
20.0 * math.log10(x / output_amp)
if output_amp else None for x in self.magnitude]
self.phase = [None if (I is None or Q is None)
else (math.atan2(Q or 0, I or 0)) / (2.0 * math.pi)
for I, Q in zip(self.i_sig, self.q_sig)]
def __json__(self):
return {'magnitude': self.magnitude,
'magnitude_dB': self.magnitude_dB,
'phase': self.phase}
<|code_end|>
, predict the immediate next line with the help of imports:
import math
import struct
from pymoku import _frame_instrument
and context (classes, functions, sometimes code) from other files:
# Path: pymoku/_frame_instrument.py
# class FrameQueue(Queue):
# class FrameBasedInstrument(_input_instrument.InputInstrument,
# _instrument.MokuInstrument):
# def put(self, item, block=True, timeout=None):
# def get(self, block=True, timeout=None):
# def _init(self, maxsize):
# def __init__(self):
# def _set_frame_class(self, frame_class, **frame_kwargs):
# def _flush(self):
# def _set_buffer_length(self, buflen):
# def _get_buffer_length(self):
# def set_defaults(self):
# def get_data(self, timeout=None, wait=True):
# def set_framerate(self, fr):
# def get_realtime_data(self, timeout=None, wait=True):
# def _set_running(self, state):
# def _make_frame_socket(self):
# def _frame_worker(self):
. Output only the next line. | class FRAData(_frame_instrument.InstrumentData): |
Given the code snippet: <|code_start|>
class SweepGenerator(object):
_REG_CONFIG = 0
_REG_START_LSB = 1
_REG_START_MSB = 2
_REG_STOP_LSB = 3
_REG_STOP_MSB = 4
_REG_STEP_LSB = 5
_REG_STEP_MSB = 6
_REG_DURATION_LSB = 7
_REG_DURATION_MSB = 8
WAVE_TYPE_SINGLE = 0
WAVE_TYPE_UPDOWN = 1
WAVE_TYPE_SAWTOOTH = 2
WAVE_TYPE_TRIANGLE = 3
def __init__(self, instr, reg_base):
self._instr = instr
self.reg_base = reg_base
@property
def waveform(self):
r = self.reg_base + SweepGenerator._REG_CONFIG
return self._instr._accessor_get(r, from_reg_unsigned(0, 2))
@waveform.setter
def waveform(self, value):
r = self.reg_base + SweepGenerator._REG_CONFIG
self._instr._accessor_set(
<|code_end|>
, generate the next line using the imports in this file:
from pymoku._instrument import to_reg_unsigned
from pymoku._instrument import from_reg_unsigned
from pymoku._instrument import to_reg_bool
from pymoku._instrument import from_reg_bool
and context (functions, classes, or occasionally code) from other files:
# Path: pymoku/_instrument.py
# def to_reg_unsigned(_offset, _len, allow_set=None, allow_range=None,
# xform=lambda obj, x: x):
# """ Returns a callable that will pack a new unsigned data value or
# bitfield in to a register. Designed as shorthand for common use in
# instrument register accessor lists. Supports single and compound
# registers (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param allow_set: Set containing all valid values of the data field.
# :param allow_range: a two-tuple specifying the bounds of the data value.
# :param xform: a callable that translates the user value written to the
# attribute to the register value
# """
#
# def __us(obj, val, old):
# val = xform(obj, val)
# mask = ((1 << _len) - 1) << _offset
#
# if allow_set and allow_range:
# raise MokuException("Can't check against both ranges and sets")
#
# if allow_set and val not in allow_set:
# return None
# elif allow_range and (val < allow_range[0] or val > allow_range[1]):
# return None
#
# v = _usgn(val, _len) << _offset
#
# try:
# return (old & ~mask) | v
# except TypeError:
# r = []
# for o in reversed(old):
# r.insert(0, (o & ~mask) | v & 0xFFFFFFFF)
#
# v = v >> 32
# mask = mask >> 32
#
# return tuple(r)
#
# return __us
#
# Path: pymoku/_instrument.py
# def from_reg_unsigned(_offset, _len, xform=lambda obj, x: x):
# """ Returns a callable that will unpack an unsigned data value from a
# register bitfield. Designed as shorthand for common use in instrument
# register accessor lists. Supports single and compound registers
# (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param xform: a callable that translates the register value to the
# user attribute's natural units
# """
# mask = ((1 << _len) - 1) << _offset
#
# def __ug(obj, reg):
# try:
# return xform(obj, (reg & mask) >> _offset)
# except TypeError:
# v = 0
# for r in reg:
# v <<= 32
# v |= r
#
# return xform(obj, (v & mask) >> _offset)
#
# return __ug
#
# Path: pymoku/_instrument.py
# def to_reg_bool(_offset):
# """ Returns a callable that will pack a new boolean data value in to a
# single bit of a register. Designed as shorthand for common use in
# instrument register accessor lists. Equivalent to :any:
# `to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=int)`
#
# :param _offset: Offset of bit in the register (set)
# """
# return to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=lambda obj,
# x: int(x))
#
# Path: pymoku/_instrument.py
# def from_reg_bool(_offset):
# """ Returns a callable that will unpack a boolean value from a
# register bit. Designed as shorthand for common use in instrument
# register accessor lists. Equivalent to
# :any:`from_reg_unsigned(_offset, 1, xform=bool)`.
#
# :param _offset: Offset of data field in the register (set)
# """
# return from_reg_unsigned(_offset, 1, xform=lambda obj, x: bool(x))
. Output only the next line. | r, to_reg_unsigned(0, 2, |
Predict the next line after this snippet: <|code_start|>
class SweepGenerator(object):
_REG_CONFIG = 0
_REG_START_LSB = 1
_REG_START_MSB = 2
_REG_STOP_LSB = 3
_REG_STOP_MSB = 4
_REG_STEP_LSB = 5
_REG_STEP_MSB = 6
_REG_DURATION_LSB = 7
_REG_DURATION_MSB = 8
WAVE_TYPE_SINGLE = 0
WAVE_TYPE_UPDOWN = 1
WAVE_TYPE_SAWTOOTH = 2
WAVE_TYPE_TRIANGLE = 3
def __init__(self, instr, reg_base):
self._instr = instr
self.reg_base = reg_base
@property
def waveform(self):
r = self.reg_base + SweepGenerator._REG_CONFIG
<|code_end|>
using the current file's imports:
from pymoku._instrument import to_reg_unsigned
from pymoku._instrument import from_reg_unsigned
from pymoku._instrument import to_reg_bool
from pymoku._instrument import from_reg_bool
and any relevant context from other files:
# Path: pymoku/_instrument.py
# def to_reg_unsigned(_offset, _len, allow_set=None, allow_range=None,
# xform=lambda obj, x: x):
# """ Returns a callable that will pack a new unsigned data value or
# bitfield in to a register. Designed as shorthand for common use in
# instrument register accessor lists. Supports single and compound
# registers (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param allow_set: Set containing all valid values of the data field.
# :param allow_range: a two-tuple specifying the bounds of the data value.
# :param xform: a callable that translates the user value written to the
# attribute to the register value
# """
#
# def __us(obj, val, old):
# val = xform(obj, val)
# mask = ((1 << _len) - 1) << _offset
#
# if allow_set and allow_range:
# raise MokuException("Can't check against both ranges and sets")
#
# if allow_set and val not in allow_set:
# return None
# elif allow_range and (val < allow_range[0] or val > allow_range[1]):
# return None
#
# v = _usgn(val, _len) << _offset
#
# try:
# return (old & ~mask) | v
# except TypeError:
# r = []
# for o in reversed(old):
# r.insert(0, (o & ~mask) | v & 0xFFFFFFFF)
#
# v = v >> 32
# mask = mask >> 32
#
# return tuple(r)
#
# return __us
#
# Path: pymoku/_instrument.py
# def from_reg_unsigned(_offset, _len, xform=lambda obj, x: x):
# """ Returns a callable that will unpack an unsigned data value from a
# register bitfield. Designed as shorthand for common use in instrument
# register accessor lists. Supports single and compound registers
# (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param xform: a callable that translates the register value to the
# user attribute's natural units
# """
# mask = ((1 << _len) - 1) << _offset
#
# def __ug(obj, reg):
# try:
# return xform(obj, (reg & mask) >> _offset)
# except TypeError:
# v = 0
# for r in reg:
# v <<= 32
# v |= r
#
# return xform(obj, (v & mask) >> _offset)
#
# return __ug
#
# Path: pymoku/_instrument.py
# def to_reg_bool(_offset):
# """ Returns a callable that will pack a new boolean data value in to a
# single bit of a register. Designed as shorthand for common use in
# instrument register accessor lists. Equivalent to :any:
# `to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=int)`
#
# :param _offset: Offset of bit in the register (set)
# """
# return to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=lambda obj,
# x: int(x))
#
# Path: pymoku/_instrument.py
# def from_reg_bool(_offset):
# """ Returns a callable that will unpack a boolean value from a
# register bit. Designed as shorthand for common use in instrument
# register accessor lists. Equivalent to
# :any:`from_reg_unsigned(_offset, 1, xform=bool)`.
#
# :param _offset: Offset of data field in the register (set)
# """
# return from_reg_unsigned(_offset, 1, xform=lambda obj, x: bool(x))
. Output only the next line. | return self._instr._accessor_get(r, from_reg_unsigned(0, 2)) |
Continue the code snippet: <|code_start|> r1 = self.reg_base + SweepGenerator._REG_STEP_LSB
r2 = self.reg_base + SweepGenerator._REG_STEP_MSB
return self._instr._accessor_get((r2, r1), from_reg_unsigned(0, 64))
@step.setter
def step(self, value):
r1 = self.reg_base + SweepGenerator._REG_STEP_LSB
r2 = self.reg_base + SweepGenerator._REG_STEP_MSB
self._instr._accessor_set((r2, r1), to_reg_unsigned(0, 64), value)
@property
def duration(self):
r1 = self.reg_base + SweepGenerator._REG_DURATION_LSB
r2 = self.reg_base + SweepGenerator._REG_DURATION_MSB
return self._instr._accessor_get((r2, r1), from_reg_unsigned(0, 64))
@duration.setter
def duration(self, value):
r1 = self.reg_base + SweepGenerator._REG_DURATION_LSB
r2 = self.reg_base + SweepGenerator._REG_DURATION_MSB
self._instr._accessor_set((r2, r1), to_reg_unsigned(0, 64), value)
@property
def wait_for_trig(self):
r = self.reg_base + SweepGenerator._REG_CONFIG
return self._instr._accessor_get(r, from_reg_bool(2))
@wait_for_trig.setter
def wait_for_trig(self, value):
r = self.reg_base + SweepGenerator._REG_CONFIG
<|code_end|>
. Use current file imports:
from pymoku._instrument import to_reg_unsigned
from pymoku._instrument import from_reg_unsigned
from pymoku._instrument import to_reg_bool
from pymoku._instrument import from_reg_bool
and context (classes, functions, or code) from other files:
# Path: pymoku/_instrument.py
# def to_reg_unsigned(_offset, _len, allow_set=None, allow_range=None,
# xform=lambda obj, x: x):
# """ Returns a callable that will pack a new unsigned data value or
# bitfield in to a register. Designed as shorthand for common use in
# instrument register accessor lists. Supports single and compound
# registers (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param allow_set: Set containing all valid values of the data field.
# :param allow_range: a two-tuple specifying the bounds of the data value.
# :param xform: a callable that translates the user value written to the
# attribute to the register value
# """
#
# def __us(obj, val, old):
# val = xform(obj, val)
# mask = ((1 << _len) - 1) << _offset
#
# if allow_set and allow_range:
# raise MokuException("Can't check against both ranges and sets")
#
# if allow_set and val not in allow_set:
# return None
# elif allow_range and (val < allow_range[0] or val > allow_range[1]):
# return None
#
# v = _usgn(val, _len) << _offset
#
# try:
# return (old & ~mask) | v
# except TypeError:
# r = []
# for o in reversed(old):
# r.insert(0, (o & ~mask) | v & 0xFFFFFFFF)
#
# v = v >> 32
# mask = mask >> 32
#
# return tuple(r)
#
# return __us
#
# Path: pymoku/_instrument.py
# def from_reg_unsigned(_offset, _len, xform=lambda obj, x: x):
# """ Returns a callable that will unpack an unsigned data value from a
# register bitfield. Designed as shorthand for common use in instrument
# register accessor lists. Supports single and compound registers
# (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param xform: a callable that translates the register value to the
# user attribute's natural units
# """
# mask = ((1 << _len) - 1) << _offset
#
# def __ug(obj, reg):
# try:
# return xform(obj, (reg & mask) >> _offset)
# except TypeError:
# v = 0
# for r in reg:
# v <<= 32
# v |= r
#
# return xform(obj, (v & mask) >> _offset)
#
# return __ug
#
# Path: pymoku/_instrument.py
# def to_reg_bool(_offset):
# """ Returns a callable that will pack a new boolean data value in to a
# single bit of a register. Designed as shorthand for common use in
# instrument register accessor lists. Equivalent to :any:
# `to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=int)`
#
# :param _offset: Offset of bit in the register (set)
# """
# return to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=lambda obj,
# x: int(x))
#
# Path: pymoku/_instrument.py
# def from_reg_bool(_offset):
# """ Returns a callable that will unpack a boolean value from a
# register bit. Designed as shorthand for common use in instrument
# register accessor lists. Equivalent to
# :any:`from_reg_unsigned(_offset, 1, xform=bool)`.
#
# :param _offset: Offset of data field in the register (set)
# """
# return from_reg_unsigned(_offset, 1, xform=lambda obj, x: bool(x))
. Output only the next line. | self._instr._accessor_set(r, to_reg_bool(2), value) |
Predict the next line after this snippet: <|code_start|> r2 = self.reg_base + SweepGenerator._REG_STOP_MSB
self._instr._accessor_set((r2, r1), to_reg_unsigned(0, 64), value)
@property
def step(self):
r1 = self.reg_base + SweepGenerator._REG_STEP_LSB
r2 = self.reg_base + SweepGenerator._REG_STEP_MSB
return self._instr._accessor_get((r2, r1), from_reg_unsigned(0, 64))
@step.setter
def step(self, value):
r1 = self.reg_base + SweepGenerator._REG_STEP_LSB
r2 = self.reg_base + SweepGenerator._REG_STEP_MSB
self._instr._accessor_set((r2, r1), to_reg_unsigned(0, 64), value)
@property
def duration(self):
r1 = self.reg_base + SweepGenerator._REG_DURATION_LSB
r2 = self.reg_base + SweepGenerator._REG_DURATION_MSB
return self._instr._accessor_get((r2, r1), from_reg_unsigned(0, 64))
@duration.setter
def duration(self, value):
r1 = self.reg_base + SweepGenerator._REG_DURATION_LSB
r2 = self.reg_base + SweepGenerator._REG_DURATION_MSB
self._instr._accessor_set((r2, r1), to_reg_unsigned(0, 64), value)
@property
def wait_for_trig(self):
r = self.reg_base + SweepGenerator._REG_CONFIG
<|code_end|>
using the current file's imports:
from pymoku._instrument import to_reg_unsigned
from pymoku._instrument import from_reg_unsigned
from pymoku._instrument import to_reg_bool
from pymoku._instrument import from_reg_bool
and any relevant context from other files:
# Path: pymoku/_instrument.py
# def to_reg_unsigned(_offset, _len, allow_set=None, allow_range=None,
# xform=lambda obj, x: x):
# """ Returns a callable that will pack a new unsigned data value or
# bitfield in to a register. Designed as shorthand for common use in
# instrument register accessor lists. Supports single and compound
# registers (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param allow_set: Set containing all valid values of the data field.
# :param allow_range: a two-tuple specifying the bounds of the data value.
# :param xform: a callable that translates the user value written to the
# attribute to the register value
# """
#
# def __us(obj, val, old):
# val = xform(obj, val)
# mask = ((1 << _len) - 1) << _offset
#
# if allow_set and allow_range:
# raise MokuException("Can't check against both ranges and sets")
#
# if allow_set and val not in allow_set:
# return None
# elif allow_range and (val < allow_range[0] or val > allow_range[1]):
# return None
#
# v = _usgn(val, _len) << _offset
#
# try:
# return (old & ~mask) | v
# except TypeError:
# r = []
# for o in reversed(old):
# r.insert(0, (o & ~mask) | v & 0xFFFFFFFF)
#
# v = v >> 32
# mask = mask >> 32
#
# return tuple(r)
#
# return __us
#
# Path: pymoku/_instrument.py
# def from_reg_unsigned(_offset, _len, xform=lambda obj, x: x):
# """ Returns a callable that will unpack an unsigned data value from a
# register bitfield. Designed as shorthand for common use in instrument
# register accessor lists. Supports single and compound registers
# (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param xform: a callable that translates the register value to the
# user attribute's natural units
# """
# mask = ((1 << _len) - 1) << _offset
#
# def __ug(obj, reg):
# try:
# return xform(obj, (reg & mask) >> _offset)
# except TypeError:
# v = 0
# for r in reg:
# v <<= 32
# v |= r
#
# return xform(obj, (v & mask) >> _offset)
#
# return __ug
#
# Path: pymoku/_instrument.py
# def to_reg_bool(_offset):
# """ Returns a callable that will pack a new boolean data value in to a
# single bit of a register. Designed as shorthand for common use in
# instrument register accessor lists. Equivalent to :any:
# `to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=int)`
#
# :param _offset: Offset of bit in the register (set)
# """
# return to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=lambda obj,
# x: int(x))
#
# Path: pymoku/_instrument.py
# def from_reg_bool(_offset):
# """ Returns a callable that will unpack a boolean value from a
# register bit. Designed as shorthand for common use in instrument
# register accessor lists. Equivalent to
# :any:`from_reg_unsigned(_offset, 1, xform=bool)`.
#
# :param _offset: Offset of data field in the register (set)
# """
# return from_reg_unsigned(_offset, 1, xform=lambda obj, x: bool(x))
. Output only the next line. | return self._instr._accessor_get(r, from_reg_bool(2)) |
Given snippet: <|code_start|>
try:
except ImportError:
filt_coeff = [[1.0, 1.0, 0.0, 0.0, 0.0, 0.0],
[1.0, 1.0, 0.0, 0.0, 0.0, 0.0]]
@pytest.fixture
def dut(moku):
with patch(
'pymoku._frame_instrument.'
'FrameBasedInstrument._set_running'):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import pytest
from pymoku.instruments import LaserLockBox
from unittest.mock import patch, ANY
from mock import patch, ANY
and context:
# Path: pymoku/instruments.py
which might include code, classes, or functions. Output only the next line. | i = LaserLockBox() |
Based on the snippet: <|code_start|>
try:
except ImportError:
@pytest.fixture
def dut(moku):
<|code_end|>
, predict the immediate next line with the help of imports:
import pytest
from pymoku.instruments import ArbitraryWaveGen
from pymoku import _arbwavegen
from unittest.mock import ANY
from mock import ANY
and context (classes, functions, sometimes code) from other files:
# Path: pymoku/instruments.py
#
# Path: pymoku/_arbwavegen.py
# REG_ARB_SETTINGS1 = 88
# REG_ARB_LUT_LENGTH1 = 105
# REG_ARB_AMPLITUDE1 = 106
# REG_ARB_OFFSET1 = 107
# REG_ARB_SETTINGS2 = 108
# REG_ARB_LUT_LENGTH2 = 125
# REG_ARB_AMPLITUDE2 = 126
# REG_ARB_OFFSET2 = 127
# _ARB_MODE_1000 = 0x0
# _ARB_MODE_500 = 0x1
# _ARB_MODE_250 = 0x2
# _ARB_MODE_125 = 0x3
# _ARB_LUT_LENGTH = 8192
# _ARB_LUT_LSB = 2.0**32
# _ARB_LUT_INTERPLOATION_LENGTH = 2**32
# _ARB_TRIG_SRC_CH1 = 0
# _ARB_TRIG_SRC_CH2 = 1
# _ARB_TRIG_SRC_EXT = 4
# _ARB_TRIG_LVL_MIN = -5.0
# _ARB_TRIG_LVL_MAX = 5.0
# _ARB_TRIG_TYPE_SINGLE = 0
# _ARB_TRIG_TYPE_CONT = 2
# _ARB_SMPL_RATE = 1.0e9
# _ARB_INPUT_SMPS = ADC_SMP_RATE
# _ARB_CHN_BUFLEN = 2**13
# class ArbitraryWaveGen(_CoreOscilloscope):
# def __init__(self):
# def set_defaults(self):
# def _set_mode(self, ch, mode, length):
# def write_lut(self, ch, data, mode=None):
# def gen_waveform(self, ch, period, amplitude, phase=0, offset=0,
# interpolation=True, dead_time=0, dead_voltage=0, en=True):
# def set_waveform_trigger(self, ch, source, edge, level, minwidth=None,
# maxwidth=None, hysteresis=False):
# def set_waveform_trigger_output(self, ch, trig_en=True, single=False,
# duration=0, hold_last=False):
# def _update_dependent_regs(self, scales):
# def sync_phase(self):
# def reset_phase(self, ch):
# def get_frequency(self, ch):
# def gen_off(self, ch=None):
# def enable_output(self, ch=None, en=True):
# def _signal_source_volts_per_bit(self, source, scales, trigger=False):
. Output only the next line. | i = ArbitraryWaveGen() |
Given the following code snippet before the placeholder: <|code_start|> moku._write_regs.assert_called_with(ANY)
def test_reset_phase(dut, moku):
'''
TODO Default test
'''
dut.reset_phase(1)
moku._write_regs.assert_called_with(ANY)
def test_gen_off(dut, moku):
'''
TODO Default test
'''
dut.gen_off()
moku._write_regs.assert_called_with(ANY)
def test_enable_output(dut, moku):
'''
TODO Default test
'''
dut.enable_output()
moku._write_regs.assert_called_with(ANY)
@pytest.mark.parametrize('attr, value', [
('enable1', True),
('phase_rst1', True),
<|code_end|>
, predict the next line using imports from the current file:
import pytest
from pymoku.instruments import ArbitraryWaveGen
from pymoku import _arbwavegen
from unittest.mock import ANY
from mock import ANY
and context including class names, function names, and sometimes code from other files:
# Path: pymoku/instruments.py
#
# Path: pymoku/_arbwavegen.py
# REG_ARB_SETTINGS1 = 88
# REG_ARB_LUT_LENGTH1 = 105
# REG_ARB_AMPLITUDE1 = 106
# REG_ARB_OFFSET1 = 107
# REG_ARB_SETTINGS2 = 108
# REG_ARB_LUT_LENGTH2 = 125
# REG_ARB_AMPLITUDE2 = 126
# REG_ARB_OFFSET2 = 127
# _ARB_MODE_1000 = 0x0
# _ARB_MODE_500 = 0x1
# _ARB_MODE_250 = 0x2
# _ARB_MODE_125 = 0x3
# _ARB_LUT_LENGTH = 8192
# _ARB_LUT_LSB = 2.0**32
# _ARB_LUT_INTERPLOATION_LENGTH = 2**32
# _ARB_TRIG_SRC_CH1 = 0
# _ARB_TRIG_SRC_CH2 = 1
# _ARB_TRIG_SRC_EXT = 4
# _ARB_TRIG_LVL_MIN = -5.0
# _ARB_TRIG_LVL_MAX = 5.0
# _ARB_TRIG_TYPE_SINGLE = 0
# _ARB_TRIG_TYPE_CONT = 2
# _ARB_SMPL_RATE = 1.0e9
# _ARB_INPUT_SMPS = ADC_SMP_RATE
# _ARB_CHN_BUFLEN = 2**13
# class ArbitraryWaveGen(_CoreOscilloscope):
# def __init__(self):
# def set_defaults(self):
# def _set_mode(self, ch, mode, length):
# def write_lut(self, ch, data, mode=None):
# def gen_waveform(self, ch, period, amplitude, phase=0, offset=0,
# interpolation=True, dead_time=0, dead_voltage=0, en=True):
# def set_waveform_trigger(self, ch, source, edge, level, minwidth=None,
# maxwidth=None, hysteresis=False):
# def set_waveform_trigger_output(self, ch, trig_en=True, single=False,
# duration=0, hold_last=False):
# def _update_dependent_regs(self, scales):
# def sync_phase(self):
# def reset_phase(self, ch):
# def get_frequency(self, ch):
# def gen_off(self, ch=None):
# def enable_output(self, ch=None, en=True):
# def _signal_source_volts_per_bit(self, source, scales, trigger=False):
. Output only the next line. | ('mode1', _arbwavegen._ARB_MODE_125), |
Based on the snippet: <|code_start|>
class EmbeddedPLL(object):
_REG_BANDWIDTH = 0
_REG_AUTOACQ = 1
_REG_REACQ = 2
_REG_RESET = 3
def __init__(self, instr, reg_base):
self._instr = instr
self.reg_base = reg_base
@property
def bandwidth(self):
r = self.reg_base + EmbeddedPLL._REG_BANDWIDTH
<|code_end|>
, predict the immediate next line with the help of imports:
from ._instrument import from_reg_signed, from_reg_bool
from ._instrument import to_reg_signed, to_reg_bool
and context (classes, functions, sometimes code) from other files:
# Path: pymoku/_instrument.py
# def from_reg_signed(_offset, _len, xform=lambda obj, x: x):
# """ Returns a callable that will unpack a signed data value from a r
# egister bitfield. Designed as shorthand for common use in instrument
# register accessor lists. Supports single and compound registers
# (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param xform: a callable that translates the register value to the
# user attribute's natural units
# """
# # TODO: As above, this and the unsigned version share all but one
# # line of code, should consolidate.
# mask = ((1 << _len) - 1) << _offset
#
# def __sg(obj, reg):
# try:
# return xform(obj, _upsgn((reg & mask) >> _offset, _len))
# except TypeError:
# v = 0
# for r in reg:
# v <<= 32
# v |= r
#
# return xform(obj, _upsgn((v & mask) >> _offset, _len))
#
# return __sg
#
# def from_reg_bool(_offset):
# """ Returns a callable that will unpack a boolean value from a
# register bit. Designed as shorthand for common use in instrument
# register accessor lists. Equivalent to
# :any:`from_reg_unsigned(_offset, 1, xform=bool)`.
#
# :param _offset: Offset of data field in the register (set)
# """
# return from_reg_unsigned(_offset, 1, xform=lambda obj, x: bool(x))
#
# Path: pymoku/_instrument.py
# def to_reg_signed(_offset, _len, allow_set=None, allow_range=None,
# xform=lambda obj, x: x):
# """ Returns a callable that will pack a new signed data value in to a
# register. Designed as shorthand for common use in instrument register
# accessor lists. Supports single and compound registers (i.e. data values
# that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param allow_set: Set containing all valid values of the data field.
# :param allow_range: a two-tuple specifying the bounds of the data value.
# :param xform: a callable that translates the user value written to the
# attribute to the register value
# """
# # TODO: This signed and the below unsigned share all but one line of
# # code, should consolidate
# def __ss(obj, val, old):
# val = xform(obj, val)
# mask = ((1 << _len) - 1) << _offset
#
# if allow_set and allow_range:
# raise MokuException("Can't check against both ranges and sets")
#
# if allow_set and val not in allow_set:
# return None
# elif allow_range and (val < allow_range[0] or val > allow_range[1]):
# return None
#
# v = _sgn(val, _len) << _offset
#
# try:
# return (old & ~mask) | v
# except TypeError:
# r = []
# for o in reversed(old):
# r.insert(0, (o & ~mask) | v & 0xFFFFFFFF)
#
# v = v >> 32
# mask = mask >> 32
#
# return tuple(r)
#
# return __ss
#
# def to_reg_bool(_offset):
# """ Returns a callable that will pack a new boolean data value in to a
# single bit of a register. Designed as shorthand for common use in
# instrument register accessor lists. Equivalent to :any:
# `to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=int)`
#
# :param _offset: Offset of bit in the register (set)
# """
# return to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=lambda obj,
# x: int(x))
. Output only the next line. | return self._instr._accessor_get(r, from_reg_signed(0, 5)) |
Predict the next line for this snippet: <|code_start|>
class EmbeddedPLL(object):
_REG_BANDWIDTH = 0
_REG_AUTOACQ = 1
_REG_REACQ = 2
_REG_RESET = 3
def __init__(self, instr, reg_base):
self._instr = instr
self.reg_base = reg_base
@property
def bandwidth(self):
r = self.reg_base + EmbeddedPLL._REG_BANDWIDTH
return self._instr._accessor_get(r, from_reg_signed(0, 5))
@bandwidth.setter
def bandwidth(self, value):
r = self.reg_base + EmbeddedPLL._REG_BANDWIDTH
self._instr._accessor_set(r, to_reg_signed(0, 5), value) # allow_set?
@property
def autoacquire(self):
r = self.reg_base + EmbeddedPLL._REG_AUTOACQ
<|code_end|>
with the help of current file imports:
from ._instrument import from_reg_signed, from_reg_bool
from ._instrument import to_reg_signed, to_reg_bool
and context from other files:
# Path: pymoku/_instrument.py
# def from_reg_signed(_offset, _len, xform=lambda obj, x: x):
# """ Returns a callable that will unpack a signed data value from a r
# egister bitfield. Designed as shorthand for common use in instrument
# register accessor lists. Supports single and compound registers
# (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param xform: a callable that translates the register value to the
# user attribute's natural units
# """
# # TODO: As above, this and the unsigned version share all but one
# # line of code, should consolidate.
# mask = ((1 << _len) - 1) << _offset
#
# def __sg(obj, reg):
# try:
# return xform(obj, _upsgn((reg & mask) >> _offset, _len))
# except TypeError:
# v = 0
# for r in reg:
# v <<= 32
# v |= r
#
# return xform(obj, _upsgn((v & mask) >> _offset, _len))
#
# return __sg
#
# def from_reg_bool(_offset):
# """ Returns a callable that will unpack a boolean value from a
# register bit. Designed as shorthand for common use in instrument
# register accessor lists. Equivalent to
# :any:`from_reg_unsigned(_offset, 1, xform=bool)`.
#
# :param _offset: Offset of data field in the register (set)
# """
# return from_reg_unsigned(_offset, 1, xform=lambda obj, x: bool(x))
#
# Path: pymoku/_instrument.py
# def to_reg_signed(_offset, _len, allow_set=None, allow_range=None,
# xform=lambda obj, x: x):
# """ Returns a callable that will pack a new signed data value in to a
# register. Designed as shorthand for common use in instrument register
# accessor lists. Supports single and compound registers (i.e. data values
# that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param allow_set: Set containing all valid values of the data field.
# :param allow_range: a two-tuple specifying the bounds of the data value.
# :param xform: a callable that translates the user value written to the
# attribute to the register value
# """
# # TODO: This signed and the below unsigned share all but one line of
# # code, should consolidate
# def __ss(obj, val, old):
# val = xform(obj, val)
# mask = ((1 << _len) - 1) << _offset
#
# if allow_set and allow_range:
# raise MokuException("Can't check against both ranges and sets")
#
# if allow_set and val not in allow_set:
# return None
# elif allow_range and (val < allow_range[0] or val > allow_range[1]):
# return None
#
# v = _sgn(val, _len) << _offset
#
# try:
# return (old & ~mask) | v
# except TypeError:
# r = []
# for o in reversed(old):
# r.insert(0, (o & ~mask) | v & 0xFFFFFFFF)
#
# v = v >> 32
# mask = mask >> 32
#
# return tuple(r)
#
# return __ss
#
# def to_reg_bool(_offset):
# """ Returns a callable that will pack a new boolean data value in to a
# single bit of a register. Designed as shorthand for common use in
# instrument register accessor lists. Equivalent to :any:
# `to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=int)`
#
# :param _offset: Offset of bit in the register (set)
# """
# return to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=lambda obj,
# x: int(x))
, which may contain function names, class names, or code. Output only the next line. | return self._instr._accessor_get(r, from_reg_bool(0)) |
Predict the next line for this snippet: <|code_start|>
class EmbeddedPLL(object):
_REG_BANDWIDTH = 0
_REG_AUTOACQ = 1
_REG_REACQ = 2
_REG_RESET = 3
def __init__(self, instr, reg_base):
self._instr = instr
self.reg_base = reg_base
@property
def bandwidth(self):
r = self.reg_base + EmbeddedPLL._REG_BANDWIDTH
return self._instr._accessor_get(r, from_reg_signed(0, 5))
@bandwidth.setter
def bandwidth(self, value):
r = self.reg_base + EmbeddedPLL._REG_BANDWIDTH
<|code_end|>
with the help of current file imports:
from ._instrument import from_reg_signed, from_reg_bool
from ._instrument import to_reg_signed, to_reg_bool
and context from other files:
# Path: pymoku/_instrument.py
# def from_reg_signed(_offset, _len, xform=lambda obj, x: x):
# """ Returns a callable that will unpack a signed data value from a r
# egister bitfield. Designed as shorthand for common use in instrument
# register accessor lists. Supports single and compound registers
# (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param xform: a callable that translates the register value to the
# user attribute's natural units
# """
# # TODO: As above, this and the unsigned version share all but one
# # line of code, should consolidate.
# mask = ((1 << _len) - 1) << _offset
#
# def __sg(obj, reg):
# try:
# return xform(obj, _upsgn((reg & mask) >> _offset, _len))
# except TypeError:
# v = 0
# for r in reg:
# v <<= 32
# v |= r
#
# return xform(obj, _upsgn((v & mask) >> _offset, _len))
#
# return __sg
#
# def from_reg_bool(_offset):
# """ Returns a callable that will unpack a boolean value from a
# register bit. Designed as shorthand for common use in instrument
# register accessor lists. Equivalent to
# :any:`from_reg_unsigned(_offset, 1, xform=bool)`.
#
# :param _offset: Offset of data field in the register (set)
# """
# return from_reg_unsigned(_offset, 1, xform=lambda obj, x: bool(x))
#
# Path: pymoku/_instrument.py
# def to_reg_signed(_offset, _len, allow_set=None, allow_range=None,
# xform=lambda obj, x: x):
# """ Returns a callable that will pack a new signed data value in to a
# register. Designed as shorthand for common use in instrument register
# accessor lists. Supports single and compound registers (i.e. data values
# that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param allow_set: Set containing all valid values of the data field.
# :param allow_range: a two-tuple specifying the bounds of the data value.
# :param xform: a callable that translates the user value written to the
# attribute to the register value
# """
# # TODO: This signed and the below unsigned share all but one line of
# # code, should consolidate
# def __ss(obj, val, old):
# val = xform(obj, val)
# mask = ((1 << _len) - 1) << _offset
#
# if allow_set and allow_range:
# raise MokuException("Can't check against both ranges and sets")
#
# if allow_set and val not in allow_set:
# return None
# elif allow_range and (val < allow_range[0] or val > allow_range[1]):
# return None
#
# v = _sgn(val, _len) << _offset
#
# try:
# return (old & ~mask) | v
# except TypeError:
# r = []
# for o in reversed(old):
# r.insert(0, (o & ~mask) | v & 0xFFFFFFFF)
#
# v = v >> 32
# mask = mask >> 32
#
# return tuple(r)
#
# return __ss
#
# def to_reg_bool(_offset):
# """ Returns a callable that will pack a new boolean data value in to a
# single bit of a register. Designed as shorthand for common use in
# instrument register accessor lists. Equivalent to :any:
# `to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=int)`
#
# :param _offset: Offset of bit in the register (set)
# """
# return to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=lambda obj,
# x: int(x))
, which may contain function names, class names, or code. Output only the next line. | self._instr._accessor_set(r, to_reg_signed(0, 5), value) # allow_set? |
Here is a snippet: <|code_start|>
class EmbeddedPLL(object):
_REG_BANDWIDTH = 0
_REG_AUTOACQ = 1
_REG_REACQ = 2
_REG_RESET = 3
def __init__(self, instr, reg_base):
self._instr = instr
self.reg_base = reg_base
@property
def bandwidth(self):
r = self.reg_base + EmbeddedPLL._REG_BANDWIDTH
return self._instr._accessor_get(r, from_reg_signed(0, 5))
@bandwidth.setter
def bandwidth(self, value):
r = self.reg_base + EmbeddedPLL._REG_BANDWIDTH
self._instr._accessor_set(r, to_reg_signed(0, 5), value) # allow_set?
@property
def autoacquire(self):
r = self.reg_base + EmbeddedPLL._REG_AUTOACQ
return self._instr._accessor_get(r, from_reg_bool(0))
@autoacquire.setter
def autoacquire(self, value):
r = self.reg_base + EmbeddedPLL._REG_AUTOACQ
<|code_end|>
. Write the next line using the current file imports:
from ._instrument import from_reg_signed, from_reg_bool
from ._instrument import to_reg_signed, to_reg_bool
and context from other files:
# Path: pymoku/_instrument.py
# def from_reg_signed(_offset, _len, xform=lambda obj, x: x):
# """ Returns a callable that will unpack a signed data value from a r
# egister bitfield. Designed as shorthand for common use in instrument
# register accessor lists. Supports single and compound registers
# (i.e. data values that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param xform: a callable that translates the register value to the
# user attribute's natural units
# """
# # TODO: As above, this and the unsigned version share all but one
# # line of code, should consolidate.
# mask = ((1 << _len) - 1) << _offset
#
# def __sg(obj, reg):
# try:
# return xform(obj, _upsgn((reg & mask) >> _offset, _len))
# except TypeError:
# v = 0
# for r in reg:
# v <<= 32
# v |= r
#
# return xform(obj, _upsgn((v & mask) >> _offset, _len))
#
# return __sg
#
# def from_reg_bool(_offset):
# """ Returns a callable that will unpack a boolean value from a
# register bit. Designed as shorthand for common use in instrument
# register accessor lists. Equivalent to
# :any:`from_reg_unsigned(_offset, 1, xform=bool)`.
#
# :param _offset: Offset of data field in the register (set)
# """
# return from_reg_unsigned(_offset, 1, xform=lambda obj, x: bool(x))
#
# Path: pymoku/_instrument.py
# def to_reg_signed(_offset, _len, allow_set=None, allow_range=None,
# xform=lambda obj, x: x):
# """ Returns a callable that will pack a new signed data value in to a
# register. Designed as shorthand for common use in instrument register
# accessor lists. Supports single and compound registers (i.e. data values
# that span more than one register).
#
# :param _offset: Offset of data field in the register (set)
# :param _len: Length of data field in the register (set)
# :param allow_set: Set containing all valid values of the data field.
# :param allow_range: a two-tuple specifying the bounds of the data value.
# :param xform: a callable that translates the user value written to the
# attribute to the register value
# """
# # TODO: This signed and the below unsigned share all but one line of
# # code, should consolidate
# def __ss(obj, val, old):
# val = xform(obj, val)
# mask = ((1 << _len) - 1) << _offset
#
# if allow_set and allow_range:
# raise MokuException("Can't check against both ranges and sets")
#
# if allow_set and val not in allow_set:
# return None
# elif allow_range and (val < allow_range[0] or val > allow_range[1]):
# return None
#
# v = _sgn(val, _len) << _offset
#
# try:
# return (old & ~mask) | v
# except TypeError:
# r = []
# for o in reversed(old):
# r.insert(0, (o & ~mask) | v & 0xFFFFFFFF)
#
# v = v >> 32
# mask = mask >> 32
#
# return tuple(r)
#
# return __ss
#
# def to_reg_bool(_offset):
# """ Returns a callable that will pack a new boolean data value in to a
# single bit of a register. Designed as shorthand for common use in
# instrument register accessor lists. Equivalent to :any:
# `to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=int)`
#
# :param _offset: Offset of bit in the register (set)
# """
# return to_reg_unsigned(_offset, 1, allow_set=[0, 1], xform=lambda obj,
# x: int(x))
, which may include functions, classes, or code. Output only the next line. | self._instr._accessor_set(r, to_reg_bool(0), value) # allow_set? |
Based on the snippet: <|code_start|> initial=0.1,
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=600.0,
),
default_timeout=600.0,
client_info=client_info,
),
self.create_submission: gapic_v1.method.wrap_method(
self.create_submission, default_timeout=60.0, client_info=client_info,
),
}
def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def compute_threat_list_diff(
self,
) -> Callable[
<|code_end|>
, predict the immediate next line with the help of imports:
import abc
import pkg_resources
import google.auth # type: ignore
import google.api_core
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.webrisk_v1.types import webrisk
and context (classes, functions, sometimes code) from other files:
# Path: google/cloud/webrisk_v1/types/webrisk.py
# class ThreatType(proto.Enum):
# class CompressionType(proto.Enum):
# class ComputeThreatListDiffRequest(proto.Message):
# class Constraints(proto.Message):
# class ComputeThreatListDiffResponse(proto.Message):
# class ResponseType(proto.Enum):
# class Checksum(proto.Message):
# class SearchUrisRequest(proto.Message):
# class SearchUrisResponse(proto.Message):
# class ThreatUri(proto.Message):
# class SearchHashesRequest(proto.Message):
# class SearchHashesResponse(proto.Message):
# class ThreatHash(proto.Message):
# class ThreatEntryAdditions(proto.Message):
# class ThreatEntryRemovals(proto.Message):
# class RawIndices(proto.Message):
# class RawHashes(proto.Message):
# class RiceDeltaEncoding(proto.Message):
# class Submission(proto.Message):
# class CreateSubmissionRequest(proto.Message):
# THREAT_TYPE_UNSPECIFIED = 0
# MALWARE = 1
# SOCIAL_ENGINEERING = 2
# UNWANTED_SOFTWARE = 3
# COMPRESSION_TYPE_UNSPECIFIED = 0
# RAW = 1
# RICE = 2
# RESPONSE_TYPE_UNSPECIFIED = 0
# DIFF = 1
# RESET = 2
. Output only the next line. | [webrisk.ComputeThreatListDiffRequest], |
Based on the snippet: <|code_start|> self.search_hashes: gapic_v1.method.wrap_method(
self.search_hashes,
default_retry=retries.Retry(
initial=0.1,
maximum=60.0,
multiplier=1.3,
predicate=retries.if_exception_type(
core_exceptions.DeadlineExceeded,
core_exceptions.ServiceUnavailable,
),
deadline=600.0,
),
default_timeout=600.0,
client_info=client_info,
),
}
def close(self):
"""Closes resources associated with the transport.
.. warning::
Only call this method if the transport is NOT shared
with other clients - this may cause errors in other clients!
"""
raise NotImplementedError()
@property
def compute_threat_list_diff(
self,
) -> Callable[
<|code_end|>
, predict the immediate next line with the help of imports:
import abc
import pkg_resources
import google.auth # type: ignore
import google.api_core
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.webrisk_v1beta1.types import webrisk
and context (classes, functions, sometimes code) from other files:
# Path: google/cloud/webrisk_v1beta1/types/webrisk.py
# class ThreatType(proto.Enum):
# class CompressionType(proto.Enum):
# class ComputeThreatListDiffRequest(proto.Message):
# class Constraints(proto.Message):
# class ComputeThreatListDiffResponse(proto.Message):
# class ResponseType(proto.Enum):
# class Checksum(proto.Message):
# class SearchUrisRequest(proto.Message):
# class SearchUrisResponse(proto.Message):
# class ThreatUri(proto.Message):
# class SearchHashesRequest(proto.Message):
# class SearchHashesResponse(proto.Message):
# class ThreatHash(proto.Message):
# class ThreatEntryAdditions(proto.Message):
# class ThreatEntryRemovals(proto.Message):
# class RawIndices(proto.Message):
# class RawHashes(proto.Message):
# class RiceDeltaEncoding(proto.Message):
# THREAT_TYPE_UNSPECIFIED = 0
# MALWARE = 1
# SOCIAL_ENGINEERING = 2
# UNWANTED_SOFTWARE = 3
# COMPRESSION_TYPE_UNSPECIFIED = 0
# RAW = 1
# RICE = 2
# RESPONSE_TYPE_UNSPECIFIED = 0
# DIFF = 1
# RESET = 2
. Output only the next line. | [webrisk.ComputeThreatListDiffRequest], |
Predict the next line after this snippet: <|code_start|>
INSTRUCTIONS = """
To get MIDI realtime output in CAMP to work, you must select an appropriate MIDI bus.
This will be the bus that will drive instruments in your DAW, VST host, or externally.
Currently, only one bus can be used at a time with CAMP.
In the list below, the LAST bus will be selected unless the environment variable
CAMP_MIDI_BUS is set to a different number. For instance, at a bash prompt:
# export CAMP_MIDI_BUS=1
OR:
# CAMP_MIDI_BUS=1 PYTHONPATH=. python3 examples/01_minimal.py
In the future the bus choice may also be selectable using the Conductor() object.
If you happen to be using OS X, you probably want to create, and then select, an IAC bus.
Consult README.md in the source distribution for tips.
Available MIDI buses are:
"""
def play():
print(INSTRUCTIONS)
<|code_end|>
using the current file's imports:
from camp.playback.realtime import get_ports, get_bus
and any relevant context from other files:
# Path: camp/playback/realtime.py
# def get_ports():
# midi_out = rtmidi.MidiOut(b'out')
# available_ports = midi_out.ports
# return available_ports
#
# def get_bus():
# ports = get_ports()
# port_num = os.environ.get("CAMP_MIDI_BUS", len(ports) -1)
# return int(port_num)
. Output only the next line. | ports = get_ports() |
Predict the next line after this snippet: <|code_start|>This will be the bus that will drive instruments in your DAW, VST host, or externally.
Currently, only one bus can be used at a time with CAMP.
In the list below, the LAST bus will be selected unless the environment variable
CAMP_MIDI_BUS is set to a different number. For instance, at a bash prompt:
# export CAMP_MIDI_BUS=1
OR:
# CAMP_MIDI_BUS=1 PYTHONPATH=. python3 examples/01_minimal.py
In the future the bus choice may also be selectable using the Conductor() object.
If you happen to be using OS X, you probably want to create, and then select, an IAC bus.
Consult README.md in the source distribution for tips.
Available MIDI buses are:
"""
def play():
print(INSTRUCTIONS)
ports = get_ports()
for (i,x) in enumerate(ports):
print(" - %s: %s" % (i,x))
print("")
<|code_end|>
using the current file's imports:
from camp.playback.realtime import get_ports, get_bus
and any relevant context from other files:
# Path: camp/playback/realtime.py
# def get_ports():
# midi_out = rtmidi.MidiOut(b'out')
# available_ports = midi_out.ports
# return available_ports
#
# def get_bus():
# ports = get_ports()
# port_num = os.environ.get("CAMP_MIDI_BUS", len(ports) -1)
# return int(port_num)
. Output only the next line. | print("The currently selected bus is #%s" % get_bus()) |
Given 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 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 language governing permissions and
limitations under the License.
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from camp.band.members.member import Member
and context:
# Path: camp/band/members/member.py
# class Member(object):
#
# """
# camp.band.member Member is the base class for all band member plugins.
# Each implements on_signal below.
# """
#
# def __init__(self, channel=None, when=True):
# """
# Not every band member must specify a MIDI channel, but along each
# line in the chain it should be specified somewhere.
# """
# self.sends = []
# self.channel = channel
# self._when = when
#
# # FIXME: BUGLET? Depends how you use it.
# # currently reset does NOT reset the draw_from on the when.
# # to do this, we'll need to make sure every reset() calls super()
# # as it should. That's minor though.
# self.when = self.draw_from(self._when)
#
# def reset(self):
# """
# Restarts all iterators over from the beginning.
# """
# raise NotImplementedError()
#
# def draw_from(self, item):
# """
# In various places a band member needs to draw from a list.
# The default form of drawing from an array is to pop off the first
# element and consume it. However, when Selectors are employed, we might
# loop endlessly over the selection. This method exists to hide
# the need to understand choosers from those either building a band member
# or using the API at the simplest level.
# """
# if item is None:
# # this allows optional generators to be turned off.
# while True:
# yield None
# elif type(item) == list:
# for x in item:
# yield x
# elif isinstance(item, Selector):
# while True:
# try:
# yield item.draw()
# except StopIteration:
# return
# else:
# while True:
# yield item
#
# def send_to(self, obj):
# """
# Indicates what band members this band member informs.
# This can be thought as the opposite of listens_to.
# """
# if type(obj) == list:
# for x in obj:
# self.sends.append(x)
# else:
# self.sends.append(obj)
# return obj
#
# def listens_to(self, obj):
# """
# An alternate way of recording a communication arrangement
# that is a bit more natural.
# """
# if type(obj) == list:
# for x in obj:
# x.sends.append(self)
# else:
# obj.sends.append(self)
# return self
#
# def chain(self, chain_list):
# """
# A quick way of setting up a lot of nodes to output into one another.
# Returns the head and tail of the chain.
# See tests/band.py.
# """
#
#
# assert type(chain_list) == list
# assert len(chain_list) > 0
#
# item = chain_list.pop(0)
# assert item is not self
#
# self.send_to(item)
# head = item
#
# while len(chain_list):
# item = chain_list.pop(0)
# head.send_to(item)
# head = item
#
# return (self, item)
#
# def copy(self):
# raise NotImplementedError()
#
# def signal(self, event, start_time, end_time):
# """
# Fires the beat or note events down through the chain.
# Do not reimplement signal in subclasses - only on_signal
# """
#
# evt = event.copy()
# if self.channel is not None:
# evt.channel = self.channel
#
# should_run = next(self.when)
#
# if should_run:
# return self.on_signal(evt, start_time, end_time)
# else:
# # bypass THIS plugin and fire the sends directly
# # on_signal does not have a chance to run.
# results = []
# evt.keep_alive = True
# for send in self.sends:
# results.append(send.signal(evt, start_time, end_time))
# if len(results) > 0:
# return results
# else:
# return [ event ]
#
# def on_signal(self, event, start_time, end_time):
# """
# Override this pattern in each plugin, with variations, and return
# the list of events produced
# """
#
# # see scale_follower for a good example
# raise NotImplementedError
#
# def datafy(self, x):
# """
# Helper function used in serialization.
# """
# if type(x) == list:
# return [ self.datafy(y) for y in x ]
# elif type(x) == dict:
# result = {}
# for (k,v) in x.items():
# result[k] = self.datafy(v)
# return result
# elif x is None or type(x) in [ bool, int, float, str ]:
# return x
# else:
# return x.to_data()
which might include code, classes, or functions. Output only the next line. | class ScaleFollower(Member): |
Predict the next line after this snippet: <|code_start|>ma"""
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 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 language governing permissions and
limitations under the License.
"""
<|code_end|>
using the current file's imports:
from camp.band.members.member import Member
and any relevant context from other files:
# Path: camp/band/members/member.py
# class Member(object):
#
# """
# camp.band.member Member is the base class for all band member plugins.
# Each implements on_signal below.
# """
#
# def __init__(self, channel=None, when=True):
# """
# Not every band member must specify a MIDI channel, but along each
# line in the chain it should be specified somewhere.
# """
# self.sends = []
# self.channel = channel
# self._when = when
#
# # FIXME: BUGLET? Depends how you use it.
# # currently reset does NOT reset the draw_from on the when.
# # to do this, we'll need to make sure every reset() calls super()
# # as it should. That's minor though.
# self.when = self.draw_from(self._when)
#
# def reset(self):
# """
# Restarts all iterators over from the beginning.
# """
# raise NotImplementedError()
#
# def draw_from(self, item):
# """
# In various places a band member needs to draw from a list.
# The default form of drawing from an array is to pop off the first
# element and consume it. However, when Selectors are employed, we might
# loop endlessly over the selection. This method exists to hide
# the need to understand choosers from those either building a band member
# or using the API at the simplest level.
# """
# if item is None:
# # this allows optional generators to be turned off.
# while True:
# yield None
# elif type(item) == list:
# for x in item:
# yield x
# elif isinstance(item, Selector):
# while True:
# try:
# yield item.draw()
# except StopIteration:
# return
# else:
# while True:
# yield item
#
# def send_to(self, obj):
# """
# Indicates what band members this band member informs.
# This can be thought as the opposite of listens_to.
# """
# if type(obj) == list:
# for x in obj:
# self.sends.append(x)
# else:
# self.sends.append(obj)
# return obj
#
# def listens_to(self, obj):
# """
# An alternate way of recording a communication arrangement
# that is a bit more natural.
# """
# if type(obj) == list:
# for x in obj:
# x.sends.append(self)
# else:
# obj.sends.append(self)
# return self
#
# def chain(self, chain_list):
# """
# A quick way of setting up a lot of nodes to output into one another.
# Returns the head and tail of the chain.
# See tests/band.py.
# """
#
#
# assert type(chain_list) == list
# assert len(chain_list) > 0
#
# item = chain_list.pop(0)
# assert item is not self
#
# self.send_to(item)
# head = item
#
# while len(chain_list):
# item = chain_list.pop(0)
# head.send_to(item)
# head = item
#
# return (self, item)
#
# def copy(self):
# raise NotImplementedError()
#
# def signal(self, event, start_time, end_time):
# """
# Fires the beat or note events down through the chain.
# Do not reimplement signal in subclasses - only on_signal
# """
#
# evt = event.copy()
# if self.channel is not None:
# evt.channel = self.channel
#
# should_run = next(self.when)
#
# if should_run:
# return self.on_signal(evt, start_time, end_time)
# else:
# # bypass THIS plugin and fire the sends directly
# # on_signal does not have a chance to run.
# results = []
# evt.keep_alive = True
# for send in self.sends:
# results.append(send.signal(evt, start_time, end_time))
# if len(results) > 0:
# return results
# else:
# return [ event ]
#
# def on_signal(self, event, start_time, end_time):
# """
# Override this pattern in each plugin, with variations, and return
# the list of events produced
# """
#
# # see scale_follower for a good example
# raise NotImplementedError
#
# def datafy(self, x):
# """
# Helper function used in serialization.
# """
# if type(x) == list:
# return [ self.datafy(y) for y in x ]
# elif type(x) == dict:
# result = {}
# for (k,v) in x.items():
# result[k] = self.datafy(v)
# return result
# elif x is None or type(x) in [ bool, int, float, str ]:
# return x
# else:
# return x.to_data()
. Output only the next line. | class Duration(Member): |
Given snippet: <|code_start|> # inversions, as such, I' means first inversion of I, and I'' means
# second inversion, we'll optionally invert a bit further down
inversion = 0
if sym.endswith("''''"):
inversion = 3
sym = sym.replace("'''","")
elif sym.endswith("''"):
inversion = 2
sym = sym.replace("''","")
elif sym.endswith("'"):
inversion = 1
sym = sym.replace("'","")
# here's where we figure out what roman numbers are which, and if the
# roman number implies a chord type (it does - but it might be overridden
# above).
chord_data = CHORD_SYMBOLS.get(sym, None)
if chord_data is None:
raise Exception("do not know how to parse chord symbol: %s" % sym)
if chord_data == 'REST':
return None
# here's where we override the chord type if need be
(scale_num, typ) = chord_data
if override_typ is not None:
typ = override_typ
# now return the built chord, of the right type, inverting if required
base_note = self.note(scale_num)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from camp.core.chord import Chord
from camp.core.scale import scale
and context:
# Path: camp/core/chord.py
# class Chord(object):
#
# def __init__(self, notes=None, root=None, typ=None):
#
# """
# Constructs a chord, in different ways:
#
# notes = [ note('C4'), note('E4'), note('G4') ]
# chord = Chord(notes=notes)
#
# OR:
#
# chord = Chord(root=note('C4'), type='major')
#
# OR:
#
# chord = Chord(root='C4', type='major')
# """
#
# self.notes = []
#
# if notes and root:
# raise Exception("notes= and root= are mutually exclusive")
# if notes is None and root is None:
# raise Exception("specify either notes= or root=")
# if root and typ is None:
# raise Exception("typ= is required when using root=")
# if typ and typ not in CHORD_TYPES:
# raise Exception("unknown chord type: %s, expecting one of: %s" % (typ, CHORD_TYPES))
# if isinstance(root, str):
# root = note(root)
#
# if notes is not None:
# for x in notes:
# assert type(x) == Note
# self.notes = notes
#
# else:
# self.typ = typ
# self.root = root
# self.notes = self._chordify()
#
# def copy(self):
# notes = [ n.copy() for n in self.notes ]
# return Chord(notes=notes)
#
# def _chordify(self):
# """
# Internal method.
# Once self.root is set to a note, and self.typ is a chord type, like 'major', return the notes in the chord.
# """
# offsets = CHORD_TYPES[self.typ]
# notes = []
# notes.append(self.root)
# for offset in offsets:
# notes.append(self.root.transpose(semitones=offset))
# return notes
#
# def __repr__(self):
# """
# A chord prints like:
# Chord<C4,E4,G4>
# """
# note_list = ",".join([ n.short_name() for n in sorted(self.notes) ])
# return "Chord<%s>" % note_list
#
# def __eq__(self, other):
# """
# Chords are equal if they contain the same notes.
# """
# return sorted(self.notes) == sorted(other.notes)
#
# def transpose(self, steps=None, semitones=None, octaves=None):
# """
# Transposing a chord is returns a new chord with all of the notes transposed.
# """
# notes = [ note.transpose(steps=steps, octaves=octaves, semitones=None) for note in self.notes ]
# return Chord(notes=notes)
#
# def invert(self, amount=1, octaves=1):
# """
# Inverts a chord.
# ex: chord("c4 major").invert() -> chord(["E4","G4","C5"])
# """
# new_chord = self.copy()
# if amount >= 1:
# new_chord.notes[0] = new_chord.notes[0].transpose(octaves=octaves)
# if amount >= 2:
# new_chord.notes[1] = new_chord.notes[1].transpose(octaves=octaves)
# if amount >= 3:
# new_chord.notes[2] = new_chord.notes[2].transpose(octaves=octaves)
# return new_chord
#
# Path: camp/core/scale.py
# def scale(input):
# """
# Shortcut: scale(['C major') -> Scale object
# """
# (root, typ) = input.split()
# return Scale(root=note(root), typ=typ)
which might include code, classes, or functions. Output only the next line. | chord = Chord(root=base_note, typ=typ) |
Here is a 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 language governing permissions and
limitations under the License.
"""
CHORD_SYMBOLS = dict(
I = [ 1, 'major' ],
II = [ 2, 'major' ],
III = [ 3, 'major' ],
IV = [ 4, 'major' ],
V = [ 5, 'major' ],
VI = [ 6, 'major' ],
VII = [ 7, 'major' ],
i = [ 1, 'minor' ],
ii = [ 2, 'minor' ],
iii = [ 3, 'minor' ],
iv = [ 4, 'minor' ],
v = [ 5, 'minor' ],
vi = [ 6, 'minor' ],
vii = [ 7, 'minor' ],
)
CHORD_SYMBOLS['-'] = 'REST'
class Roman(object):
<|code_end|>
. Write the next line using the current file imports:
from camp.core.chord import Chord
from camp.core.scale import scale
and context from other files:
# Path: camp/core/chord.py
# class Chord(object):
#
# def __init__(self, notes=None, root=None, typ=None):
#
# """
# Constructs a chord, in different ways:
#
# notes = [ note('C4'), note('E4'), note('G4') ]
# chord = Chord(notes=notes)
#
# OR:
#
# chord = Chord(root=note('C4'), type='major')
#
# OR:
#
# chord = Chord(root='C4', type='major')
# """
#
# self.notes = []
#
# if notes and root:
# raise Exception("notes= and root= are mutually exclusive")
# if notes is None and root is None:
# raise Exception("specify either notes= or root=")
# if root and typ is None:
# raise Exception("typ= is required when using root=")
# if typ and typ not in CHORD_TYPES:
# raise Exception("unknown chord type: %s, expecting one of: %s" % (typ, CHORD_TYPES))
# if isinstance(root, str):
# root = note(root)
#
# if notes is not None:
# for x in notes:
# assert type(x) == Note
# self.notes = notes
#
# else:
# self.typ = typ
# self.root = root
# self.notes = self._chordify()
#
# def copy(self):
# notes = [ n.copy() for n in self.notes ]
# return Chord(notes=notes)
#
# def _chordify(self):
# """
# Internal method.
# Once self.root is set to a note, and self.typ is a chord type, like 'major', return the notes in the chord.
# """
# offsets = CHORD_TYPES[self.typ]
# notes = []
# notes.append(self.root)
# for offset in offsets:
# notes.append(self.root.transpose(semitones=offset))
# return notes
#
# def __repr__(self):
# """
# A chord prints like:
# Chord<C4,E4,G4>
# """
# note_list = ",".join([ n.short_name() for n in sorted(self.notes) ])
# return "Chord<%s>" % note_list
#
# def __eq__(self, other):
# """
# Chords are equal if they contain the same notes.
# """
# return sorted(self.notes) == sorted(other.notes)
#
# def transpose(self, steps=None, semitones=None, octaves=None):
# """
# Transposing a chord is returns a new chord with all of the notes transposed.
# """
# notes = [ note.transpose(steps=steps, octaves=octaves, semitones=None) for note in self.notes ]
# return Chord(notes=notes)
#
# def invert(self, amount=1, octaves=1):
# """
# Inverts a chord.
# ex: chord("c4 major").invert() -> chord(["E4","G4","C5"])
# """
# new_chord = self.copy()
# if amount >= 1:
# new_chord.notes[0] = new_chord.notes[0].transpose(octaves=octaves)
# if amount >= 2:
# new_chord.notes[1] = new_chord.notes[1].transpose(octaves=octaves)
# if amount >= 3:
# new_chord.notes[2] = new_chord.notes[2].transpose(octaves=octaves)
# return new_chord
#
# Path: camp/core/scale.py
# def scale(input):
# """
# Shortcut: scale(['C major') -> Scale object
# """
# (root, typ) = input.split()
# return Scale(root=note(root), typ=typ)
, which may include functions, classes, or code. Output only the next line. | def __init__(self, scale=None): |
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 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 language governing permissions and
limitations under the License.
"""
<|code_end|>
, determine the next line of code. You have imports:
from camp.band.members.member import Member
and context (class names, function names, or code) available:
# Path: camp/band/members/member.py
# class Member(object):
#
# """
# camp.band.member Member is the base class for all band member plugins.
# Each implements on_signal below.
# """
#
# def __init__(self, channel=None, when=True):
# """
# Not every band member must specify a MIDI channel, but along each
# line in the chain it should be specified somewhere.
# """
# self.sends = []
# self.channel = channel
# self._when = when
#
# # FIXME: BUGLET? Depends how you use it.
# # currently reset does NOT reset the draw_from on the when.
# # to do this, we'll need to make sure every reset() calls super()
# # as it should. That's minor though.
# self.when = self.draw_from(self._when)
#
# def reset(self):
# """
# Restarts all iterators over from the beginning.
# """
# raise NotImplementedError()
#
# def draw_from(self, item):
# """
# In various places a band member needs to draw from a list.
# The default form of drawing from an array is to pop off the first
# element and consume it. However, when Selectors are employed, we might
# loop endlessly over the selection. This method exists to hide
# the need to understand choosers from those either building a band member
# or using the API at the simplest level.
# """
# if item is None:
# # this allows optional generators to be turned off.
# while True:
# yield None
# elif type(item) == list:
# for x in item:
# yield x
# elif isinstance(item, Selector):
# while True:
# try:
# yield item.draw()
# except StopIteration:
# return
# else:
# while True:
# yield item
#
# def send_to(self, obj):
# """
# Indicates what band members this band member informs.
# This can be thought as the opposite of listens_to.
# """
# if type(obj) == list:
# for x in obj:
# self.sends.append(x)
# else:
# self.sends.append(obj)
# return obj
#
# def listens_to(self, obj):
# """
# An alternate way of recording a communication arrangement
# that is a bit more natural.
# """
# if type(obj) == list:
# for x in obj:
# x.sends.append(self)
# else:
# obj.sends.append(self)
# return self
#
# def chain(self, chain_list):
# """
# A quick way of setting up a lot of nodes to output into one another.
# Returns the head and tail of the chain.
# See tests/band.py.
# """
#
#
# assert type(chain_list) == list
# assert len(chain_list) > 0
#
# item = chain_list.pop(0)
# assert item is not self
#
# self.send_to(item)
# head = item
#
# while len(chain_list):
# item = chain_list.pop(0)
# head.send_to(item)
# head = item
#
# return (self, item)
#
# def copy(self):
# raise NotImplementedError()
#
# def signal(self, event, start_time, end_time):
# """
# Fires the beat or note events down through the chain.
# Do not reimplement signal in subclasses - only on_signal
# """
#
# evt = event.copy()
# if self.channel is not None:
# evt.channel = self.channel
#
# should_run = next(self.when)
#
# if should_run:
# return self.on_signal(evt, start_time, end_time)
# else:
# # bypass THIS plugin and fire the sends directly
# # on_signal does not have a chance to run.
# results = []
# evt.keep_alive = True
# for send in self.sends:
# results.append(send.signal(evt, start_time, end_time))
# if len(results) > 0:
# return results
# else:
# return [ event ]
#
# def on_signal(self, event, start_time, end_time):
# """
# Override this pattern in each plugin, with variations, and return
# the list of events produced
# """
#
# # see scale_follower for a good example
# raise NotImplementedError
#
# def datafy(self, x):
# """
# Helper function used in serialization.
# """
# if type(x) == list:
# return [ self.datafy(y) for y in x ]
# elif type(x) == dict:
# result = {}
# for (k,v) in x.items():
# result[k] = self.datafy(v)
# return result
# elif x is None or type(x) in [ bool, int, float, str ]:
# return x
# else:
# return x.to_data()
. Output only the next line. | class Ordered(Member): |
Given the code snippet: <|code_start|> self._when = when
# FIXME: BUGLET? Depends how you use it.
# currently reset does NOT reset the draw_from on the when.
# to do this, we'll need to make sure every reset() calls super()
# as it should. That's minor though.
self.when = self.draw_from(self._when)
def reset(self):
"""
Restarts all iterators over from the beginning.
"""
raise NotImplementedError()
def draw_from(self, item):
"""
In various places a band member needs to draw from a list.
The default form of drawing from an array is to pop off the first
element and consume it. However, when Selectors are employed, we might
loop endlessly over the selection. This method exists to hide
the need to understand choosers from those either building a band member
or using the API at the simplest level.
"""
if item is None:
# this allows optional generators to be turned off.
while True:
yield None
elif type(item) == list:
for x in item:
yield x
<|code_end|>
, generate the next line using the imports in this file:
from camp.band.selectors.selector import Selector
and context (functions, classes, or occasionally code) from other files:
# Path: camp/band/selectors/selector.py
# class Selector(object):
#
# def __init__(self, alist, mode=None):
# raise NotImplementedError()
#
# def draw(self):
# raise NotImplementedError()
#
# def to_data(self):
# raise NotImplementedError()
. Output only the next line. | elif isinstance(item, Selector): |
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 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 language governing permissions and
limitations under the License.
"""
class TestNote(object):
def test_comparisons(self):
for nm in NOTES:
<|code_end|>
, determine the next line of code. You have imports:
from camp.core.note import Note, NOTES, note
and context (class names, function names, or code) available:
# Path: camp/core/note.py
# class Note(object):
#
# def __init__(self, name=None, octave=None, velocity=127, duration=0.0625):
#
# """
# Constructs a note.
# note = Note(name='C', octave='4')
# """
#
# assert name is not None
# name = name.title()
# assert name in NOTES or name in EQUIVALENCE
# if octave is None:
# octave = 4
# assert octave is not None and type(octave) == int
#
# self.name = self._equivalence(name)
# self.octave = octave
#
# def copy(self):
# return Note(name=self.name, octave=self.octave)
#
# def _equivalence(self, name):
# """
# Normalize note names on input, C# -> Db, etc
# Internally everything uses flats.
# """
#
# if name in EQUIVALENCE:
# return NOTES[EQUIVALENCE.index(name)]
# return name
#
# def _scale_degrees_to_steps(self, input):
# """
# A 3rd "3" is 3 steps, but a "b3" (minor third) is 2.5 and a "#3" (augmented third) is 3.5
# This is used in scale.py to make defining scales easier.
# See https://en.wikipedia.org/wiki/List_of_musical_scales_and_modes
# """
# return SCALE_DEGREES_TO_STEPS[str(input)]
#
# def transpose(self, steps=0, semitones=0, degrees=None, octaves=0):
# """
# Returns a note a given number of steps or octaves or (other things) higher.
#
# steps -- half step as 0.5, whole step as 1, or any combination. The most basic way to do things.
# semitones - 1 semitone is simply a half step. Provided to keep some implementations more music-literate.
# octaves - 6 whole steps, or 12 half steps. Easy enough.
# degrees - scale degrees, to keep scale definition somewhat music literate. "3" is a third, "b3" is a flat third, "3#" is an augmented third, etc.
#
# You can combine all of them at the same time if you really want (why?), in which case they are additive.
# """
#
#
# if degrees is not None:
# degree_steps = self._scale_degrees_to_steps(degrees)
# else:
# degree_steps = 0
# if steps is None:
# steps = 0
# if octaves is None:
# octaves = 0
# if semitones is None:
# semitones = 0
#
# steps = steps + (octaves * 6) + (semitones * 0.5) + degree_steps
#
# note = self
# if steps > 0:
# while steps > 0:
# note = note.up_half_step()
# steps = steps - 0.5
# else:
# while steps < 0:
# note = note.down_half_step()
# steps = steps + 0.5
# return note
#
# def _numeric_name(self):
# """
# Give a number for the note - used by internals only
# """
# return NOTES.index(self.name)
#
# def note_number(self):
# """
# What order is this note on the keyboard?
# """
# nn = NOTES.index(self.name) + (12 * self.octave)
# return nn
#
# def up_half_step(self):
# """
# What note is a half step up from this one?
# """
# number = self._numeric_name()
# name = UP_HALF_STEP[number]
# if self.name == 'B':
# return Note(name=name, octave=self.octave+1)
# return Note(name=name, octave=self.octave)
#
# def down_half_step(self):
# """
# What note is a half step down from this one?
# """
# number = self._numeric_name()
# name = DOWN_HALF_STEP[number]
# if self.name == 'C':
# return Note(name=name, octave=self.octave-1)
# return Note(name=name, octave=self.octave)
#
# def __eq__(self, other):
# """
# Are two notes the same?
# """
# return self.note_number() == other.note_number()
#
# def __lt__(self, other):
# """
# Are two notes the same?
# """
# return self.note_number() < other.note_number()
#
# def short_name(self):
# """
# Returns a string like Eb4
# """
# return "%s%s" % (self.name, self.octave)
#
# def __repr__(self):
# return "Note<%s%s>" % (self.name, self.octave)
#
# NOTES = [ 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B' ]
#
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
. Output only the next line. | assert Note(name=nm, octave=4) > Note(name=nm, octave=3) |
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/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 language governing permissions and
limitations under the License.
"""
class TestNote(object):
def test_comparisons(self):
<|code_end|>
using the current file's imports:
from camp.core.note import Note, NOTES, note
and any relevant context from other files:
# Path: camp/core/note.py
# class Note(object):
#
# def __init__(self, name=None, octave=None, velocity=127, duration=0.0625):
#
# """
# Constructs a note.
# note = Note(name='C', octave='4')
# """
#
# assert name is not None
# name = name.title()
# assert name in NOTES or name in EQUIVALENCE
# if octave is None:
# octave = 4
# assert octave is not None and type(octave) == int
#
# self.name = self._equivalence(name)
# self.octave = octave
#
# def copy(self):
# return Note(name=self.name, octave=self.octave)
#
# def _equivalence(self, name):
# """
# Normalize note names on input, C# -> Db, etc
# Internally everything uses flats.
# """
#
# if name in EQUIVALENCE:
# return NOTES[EQUIVALENCE.index(name)]
# return name
#
# def _scale_degrees_to_steps(self, input):
# """
# A 3rd "3" is 3 steps, but a "b3" (minor third) is 2.5 and a "#3" (augmented third) is 3.5
# This is used in scale.py to make defining scales easier.
# See https://en.wikipedia.org/wiki/List_of_musical_scales_and_modes
# """
# return SCALE_DEGREES_TO_STEPS[str(input)]
#
# def transpose(self, steps=0, semitones=0, degrees=None, octaves=0):
# """
# Returns a note a given number of steps or octaves or (other things) higher.
#
# steps -- half step as 0.5, whole step as 1, or any combination. The most basic way to do things.
# semitones - 1 semitone is simply a half step. Provided to keep some implementations more music-literate.
# octaves - 6 whole steps, or 12 half steps. Easy enough.
# degrees - scale degrees, to keep scale definition somewhat music literate. "3" is a third, "b3" is a flat third, "3#" is an augmented third, etc.
#
# You can combine all of them at the same time if you really want (why?), in which case they are additive.
# """
#
#
# if degrees is not None:
# degree_steps = self._scale_degrees_to_steps(degrees)
# else:
# degree_steps = 0
# if steps is None:
# steps = 0
# if octaves is None:
# octaves = 0
# if semitones is None:
# semitones = 0
#
# steps = steps + (octaves * 6) + (semitones * 0.5) + degree_steps
#
# note = self
# if steps > 0:
# while steps > 0:
# note = note.up_half_step()
# steps = steps - 0.5
# else:
# while steps < 0:
# note = note.down_half_step()
# steps = steps + 0.5
# return note
#
# def _numeric_name(self):
# """
# Give a number for the note - used by internals only
# """
# return NOTES.index(self.name)
#
# def note_number(self):
# """
# What order is this note on the keyboard?
# """
# nn = NOTES.index(self.name) + (12 * self.octave)
# return nn
#
# def up_half_step(self):
# """
# What note is a half step up from this one?
# """
# number = self._numeric_name()
# name = UP_HALF_STEP[number]
# if self.name == 'B':
# return Note(name=name, octave=self.octave+1)
# return Note(name=name, octave=self.octave)
#
# def down_half_step(self):
# """
# What note is a half step down from this one?
# """
# number = self._numeric_name()
# name = DOWN_HALF_STEP[number]
# if self.name == 'C':
# return Note(name=name, octave=self.octave-1)
# return Note(name=name, octave=self.octave)
#
# def __eq__(self, other):
# """
# Are two notes the same?
# """
# return self.note_number() == other.note_number()
#
# def __lt__(self, other):
# """
# Are two notes the same?
# """
# return self.note_number() < other.note_number()
#
# def short_name(self):
# """
# Returns a string like Eb4
# """
# return "%s%s" % (self.name, self.octave)
#
# def __repr__(self):
# return "Note<%s%s>" % (self.name, self.octave)
#
# NOTES = [ 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B' ]
#
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
. Output only the next line. | for nm in NOTES: |
Given 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 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 language governing permissions and
limitations under the License.
"""
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from camp.band.members.member import Member
and context:
# Path: camp/band/members/member.py
# class Member(object):
#
# """
# camp.band.member Member is the base class for all band member plugins.
# Each implements on_signal below.
# """
#
# def __init__(self, channel=None, when=True):
# """
# Not every band member must specify a MIDI channel, but along each
# line in the chain it should be specified somewhere.
# """
# self.sends = []
# self.channel = channel
# self._when = when
#
# # FIXME: BUGLET? Depends how you use it.
# # currently reset does NOT reset the draw_from on the when.
# # to do this, we'll need to make sure every reset() calls super()
# # as it should. That's minor though.
# self.when = self.draw_from(self._when)
#
# def reset(self):
# """
# Restarts all iterators over from the beginning.
# """
# raise NotImplementedError()
#
# def draw_from(self, item):
# """
# In various places a band member needs to draw from a list.
# The default form of drawing from an array is to pop off the first
# element and consume it. However, when Selectors are employed, we might
# loop endlessly over the selection. This method exists to hide
# the need to understand choosers from those either building a band member
# or using the API at the simplest level.
# """
# if item is None:
# # this allows optional generators to be turned off.
# while True:
# yield None
# elif type(item) == list:
# for x in item:
# yield x
# elif isinstance(item, Selector):
# while True:
# try:
# yield item.draw()
# except StopIteration:
# return
# else:
# while True:
# yield item
#
# def send_to(self, obj):
# """
# Indicates what band members this band member informs.
# This can be thought as the opposite of listens_to.
# """
# if type(obj) == list:
# for x in obj:
# self.sends.append(x)
# else:
# self.sends.append(obj)
# return obj
#
# def listens_to(self, obj):
# """
# An alternate way of recording a communication arrangement
# that is a bit more natural.
# """
# if type(obj) == list:
# for x in obj:
# x.sends.append(self)
# else:
# obj.sends.append(self)
# return self
#
# def chain(self, chain_list):
# """
# A quick way of setting up a lot of nodes to output into one another.
# Returns the head and tail of the chain.
# See tests/band.py.
# """
#
#
# assert type(chain_list) == list
# assert len(chain_list) > 0
#
# item = chain_list.pop(0)
# assert item is not self
#
# self.send_to(item)
# head = item
#
# while len(chain_list):
# item = chain_list.pop(0)
# head.send_to(item)
# head = item
#
# return (self, item)
#
# def copy(self):
# raise NotImplementedError()
#
# def signal(self, event, start_time, end_time):
# """
# Fires the beat or note events down through the chain.
# Do not reimplement signal in subclasses - only on_signal
# """
#
# evt = event.copy()
# if self.channel is not None:
# evt.channel = self.channel
#
# should_run = next(self.when)
#
# if should_run:
# return self.on_signal(evt, start_time, end_time)
# else:
# # bypass THIS plugin and fire the sends directly
# # on_signal does not have a chance to run.
# results = []
# evt.keep_alive = True
# for send in self.sends:
# results.append(send.signal(evt, start_time, end_time))
# if len(results) > 0:
# return results
# else:
# return [ event ]
#
# def on_signal(self, event, start_time, end_time):
# """
# Override this pattern in each plugin, with variations, and return
# the list of events produced
# """
#
# # see scale_follower for a good example
# raise NotImplementedError
#
# def datafy(self, x):
# """
# Helper function used in serialization.
# """
# if type(x) == list:
# return [ self.datafy(y) for y in x ]
# elif type(x) == dict:
# result = {}
# for (k,v) in x.items():
# result[k] = self.datafy(v)
# return result
# elif x is None or type(x) in [ bool, int, float, str ]:
# return x
# else:
# return x.to_data()
which might include code, classes, or functions. Output only the next line. | class Velocity(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
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 language governing permissions and
limitations under the License.
"""
def endlessly_generate(alist):
while True:
for item in alist:
yield item
<|code_end|>
. Use current file imports:
from camp.band.selectors.selector import Selector
and context (classes, functions, or code) from other files:
# Path: camp/band/selectors/selector.py
# class Selector(object):
#
# def __init__(self, alist, mode=None):
# raise NotImplementedError()
#
# def draw(self):
# raise NotImplementedError()
#
# def to_data(self):
# raise NotImplementedError()
. Output only the next line. | class Endlessly(Selector): |
Based on the snippet: <|code_start|>class Chord(object):
def __init__(self, notes=None, root=None, typ=None):
"""
Constructs a chord, in different ways:
notes = [ note('C4'), note('E4'), note('G4') ]
chord = Chord(notes=notes)
OR:
chord = Chord(root=note('C4'), type='major')
OR:
chord = Chord(root='C4', type='major')
"""
self.notes = []
if notes and root:
raise Exception("notes= and root= are mutually exclusive")
if notes is None and root is None:
raise Exception("specify either notes= or root=")
if root and typ is None:
raise Exception("typ= is required when using root=")
if typ and typ not in CHORD_TYPES:
raise Exception("unknown chord type: %s, expecting one of: %s" % (typ, CHORD_TYPES))
if isinstance(root, str):
<|code_end|>
, predict the immediate next line with the help of imports:
from camp.core.note import note, Note
and context (classes, functions, sometimes code) from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# class Note(object):
#
# def __init__(self, name=None, octave=None, velocity=127, duration=0.0625):
#
# """
# Constructs a note.
# note = Note(name='C', octave='4')
# """
#
# assert name is not None
# name = name.title()
# assert name in NOTES or name in EQUIVALENCE
# if octave is None:
# octave = 4
# assert octave is not None and type(octave) == int
#
# self.name = self._equivalence(name)
# self.octave = octave
#
# def copy(self):
# return Note(name=self.name, octave=self.octave)
#
# def _equivalence(self, name):
# """
# Normalize note names on input, C# -> Db, etc
# Internally everything uses flats.
# """
#
# if name in EQUIVALENCE:
# return NOTES[EQUIVALENCE.index(name)]
# return name
#
# def _scale_degrees_to_steps(self, input):
# """
# A 3rd "3" is 3 steps, but a "b3" (minor third) is 2.5 and a "#3" (augmented third) is 3.5
# This is used in scale.py to make defining scales easier.
# See https://en.wikipedia.org/wiki/List_of_musical_scales_and_modes
# """
# return SCALE_DEGREES_TO_STEPS[str(input)]
#
# def transpose(self, steps=0, semitones=0, degrees=None, octaves=0):
# """
# Returns a note a given number of steps or octaves or (other things) higher.
#
# steps -- half step as 0.5, whole step as 1, or any combination. The most basic way to do things.
# semitones - 1 semitone is simply a half step. Provided to keep some implementations more music-literate.
# octaves - 6 whole steps, or 12 half steps. Easy enough.
# degrees - scale degrees, to keep scale definition somewhat music literate. "3" is a third, "b3" is a flat third, "3#" is an augmented third, etc.
#
# You can combine all of them at the same time if you really want (why?), in which case they are additive.
# """
#
#
# if degrees is not None:
# degree_steps = self._scale_degrees_to_steps(degrees)
# else:
# degree_steps = 0
# if steps is None:
# steps = 0
# if octaves is None:
# octaves = 0
# if semitones is None:
# semitones = 0
#
# steps = steps + (octaves * 6) + (semitones * 0.5) + degree_steps
#
# note = self
# if steps > 0:
# while steps > 0:
# note = note.up_half_step()
# steps = steps - 0.5
# else:
# while steps < 0:
# note = note.down_half_step()
# steps = steps + 0.5
# return note
#
# def _numeric_name(self):
# """
# Give a number for the note - used by internals only
# """
# return NOTES.index(self.name)
#
# def note_number(self):
# """
# What order is this note on the keyboard?
# """
# nn = NOTES.index(self.name) + (12 * self.octave)
# return nn
#
# def up_half_step(self):
# """
# What note is a half step up from this one?
# """
# number = self._numeric_name()
# name = UP_HALF_STEP[number]
# if self.name == 'B':
# return Note(name=name, octave=self.octave+1)
# return Note(name=name, octave=self.octave)
#
# def down_half_step(self):
# """
# What note is a half step down from this one?
# """
# number = self._numeric_name()
# name = DOWN_HALF_STEP[number]
# if self.name == 'C':
# return Note(name=name, octave=self.octave-1)
# return Note(name=name, octave=self.octave)
#
# def __eq__(self, other):
# """
# Are two notes the same?
# """
# return self.note_number() == other.note_number()
#
# def __lt__(self, other):
# """
# Are two notes the same?
# """
# return self.note_number() < other.note_number()
#
# def short_name(self):
# """
# Returns a string like Eb4
# """
# return "%s%s" % (self.name, self.octave)
#
# def __repr__(self):
# return "Note<%s%s>" % (self.name, self.octave)
. Output only the next line. | root = note(root) |
Predict the next line after this snippet: <|code_start|> """
Constructs a chord, in different ways:
notes = [ note('C4'), note('E4'), note('G4') ]
chord = Chord(notes=notes)
OR:
chord = Chord(root=note('C4'), type='major')
OR:
chord = Chord(root='C4', type='major')
"""
self.notes = []
if notes and root:
raise Exception("notes= and root= are mutually exclusive")
if notes is None and root is None:
raise Exception("specify either notes= or root=")
if root and typ is None:
raise Exception("typ= is required when using root=")
if typ and typ not in CHORD_TYPES:
raise Exception("unknown chord type: %s, expecting one of: %s" % (typ, CHORD_TYPES))
if isinstance(root, str):
root = note(root)
if notes is not None:
for x in notes:
<|code_end|>
using the current file's imports:
from camp.core.note import note, Note
and any relevant context from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# class Note(object):
#
# def __init__(self, name=None, octave=None, velocity=127, duration=0.0625):
#
# """
# Constructs a note.
# note = Note(name='C', octave='4')
# """
#
# assert name is not None
# name = name.title()
# assert name in NOTES or name in EQUIVALENCE
# if octave is None:
# octave = 4
# assert octave is not None and type(octave) == int
#
# self.name = self._equivalence(name)
# self.octave = octave
#
# def copy(self):
# return Note(name=self.name, octave=self.octave)
#
# def _equivalence(self, name):
# """
# Normalize note names on input, C# -> Db, etc
# Internally everything uses flats.
# """
#
# if name in EQUIVALENCE:
# return NOTES[EQUIVALENCE.index(name)]
# return name
#
# def _scale_degrees_to_steps(self, input):
# """
# A 3rd "3" is 3 steps, but a "b3" (minor third) is 2.5 and a "#3" (augmented third) is 3.5
# This is used in scale.py to make defining scales easier.
# See https://en.wikipedia.org/wiki/List_of_musical_scales_and_modes
# """
# return SCALE_DEGREES_TO_STEPS[str(input)]
#
# def transpose(self, steps=0, semitones=0, degrees=None, octaves=0):
# """
# Returns a note a given number of steps or octaves or (other things) higher.
#
# steps -- half step as 0.5, whole step as 1, or any combination. The most basic way to do things.
# semitones - 1 semitone is simply a half step. Provided to keep some implementations more music-literate.
# octaves - 6 whole steps, or 12 half steps. Easy enough.
# degrees - scale degrees, to keep scale definition somewhat music literate. "3" is a third, "b3" is a flat third, "3#" is an augmented third, etc.
#
# You can combine all of them at the same time if you really want (why?), in which case they are additive.
# """
#
#
# if degrees is not None:
# degree_steps = self._scale_degrees_to_steps(degrees)
# else:
# degree_steps = 0
# if steps is None:
# steps = 0
# if octaves is None:
# octaves = 0
# if semitones is None:
# semitones = 0
#
# steps = steps + (octaves * 6) + (semitones * 0.5) + degree_steps
#
# note = self
# if steps > 0:
# while steps > 0:
# note = note.up_half_step()
# steps = steps - 0.5
# else:
# while steps < 0:
# note = note.down_half_step()
# steps = steps + 0.5
# return note
#
# def _numeric_name(self):
# """
# Give a number for the note - used by internals only
# """
# return NOTES.index(self.name)
#
# def note_number(self):
# """
# What order is this note on the keyboard?
# """
# nn = NOTES.index(self.name) + (12 * self.octave)
# return nn
#
# def up_half_step(self):
# """
# What note is a half step up from this one?
# """
# number = self._numeric_name()
# name = UP_HALF_STEP[number]
# if self.name == 'B':
# return Note(name=name, octave=self.octave+1)
# return Note(name=name, octave=self.octave)
#
# def down_half_step(self):
# """
# What note is a half step down from this one?
# """
# number = self._numeric_name()
# name = DOWN_HALF_STEP[number]
# if self.name == 'C':
# return Note(name=name, octave=self.octave-1)
# return Note(name=name, octave=self.octave)
#
# def __eq__(self, other):
# """
# Are two notes the same?
# """
# return self.note_number() == other.note_number()
#
# def __lt__(self, other):
# """
# Are two notes the same?
# """
# return self.note_number() < other.note_number()
#
# def short_name(self):
# """
# Returns a string like Eb4
# """
# return "%s%s" % (self.name, self.octave)
#
# def __repr__(self):
# return "Note<%s%s>" % (self.name, self.octave)
. Output only the next line. | assert type(x) == Note |
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
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 language governing permissions and
limitations under the License.
"""
<|code_end|>
, generate the next line using the imports in this file:
from camp.band.members.member import Member
and context (functions, classes, or occasionally code) from other files:
# Path: camp/band/members/member.py
# class Member(object):
#
# """
# camp.band.member Member is the base class for all band member plugins.
# Each implements on_signal below.
# """
#
# def __init__(self, channel=None, when=True):
# """
# Not every band member must specify a MIDI channel, but along each
# line in the chain it should be specified somewhere.
# """
# self.sends = []
# self.channel = channel
# self._when = when
#
# # FIXME: BUGLET? Depends how you use it.
# # currently reset does NOT reset the draw_from on the when.
# # to do this, we'll need to make sure every reset() calls super()
# # as it should. That's minor though.
# self.when = self.draw_from(self._when)
#
# def reset(self):
# """
# Restarts all iterators over from the beginning.
# """
# raise NotImplementedError()
#
# def draw_from(self, item):
# """
# In various places a band member needs to draw from a list.
# The default form of drawing from an array is to pop off the first
# element and consume it. However, when Selectors are employed, we might
# loop endlessly over the selection. This method exists to hide
# the need to understand choosers from those either building a band member
# or using the API at the simplest level.
# """
# if item is None:
# # this allows optional generators to be turned off.
# while True:
# yield None
# elif type(item) == list:
# for x in item:
# yield x
# elif isinstance(item, Selector):
# while True:
# try:
# yield item.draw()
# except StopIteration:
# return
# else:
# while True:
# yield item
#
# def send_to(self, obj):
# """
# Indicates what band members this band member informs.
# This can be thought as the opposite of listens_to.
# """
# if type(obj) == list:
# for x in obj:
# self.sends.append(x)
# else:
# self.sends.append(obj)
# return obj
#
# def listens_to(self, obj):
# """
# An alternate way of recording a communication arrangement
# that is a bit more natural.
# """
# if type(obj) == list:
# for x in obj:
# x.sends.append(self)
# else:
# obj.sends.append(self)
# return self
#
# def chain(self, chain_list):
# """
# A quick way of setting up a lot of nodes to output into one another.
# Returns the head and tail of the chain.
# See tests/band.py.
# """
#
#
# assert type(chain_list) == list
# assert len(chain_list) > 0
#
# item = chain_list.pop(0)
# assert item is not self
#
# self.send_to(item)
# head = item
#
# while len(chain_list):
# item = chain_list.pop(0)
# head.send_to(item)
# head = item
#
# return (self, item)
#
# def copy(self):
# raise NotImplementedError()
#
# def signal(self, event, start_time, end_time):
# """
# Fires the beat or note events down through the chain.
# Do not reimplement signal in subclasses - only on_signal
# """
#
# evt = event.copy()
# if self.channel is not None:
# evt.channel = self.channel
#
# should_run = next(self.when)
#
# if should_run:
# return self.on_signal(evt, start_time, end_time)
# else:
# # bypass THIS plugin and fire the sends directly
# # on_signal does not have a chance to run.
# results = []
# evt.keep_alive = True
# for send in self.sends:
# results.append(send.signal(evt, start_time, end_time))
# if len(results) > 0:
# return results
# else:
# return [ event ]
#
# def on_signal(self, event, start_time, end_time):
# """
# Override this pattern in each plugin, with variations, and return
# the list of events produced
# """
#
# # see scale_follower for a good example
# raise NotImplementedError
#
# def datafy(self, x):
# """
# Helper function used in serialization.
# """
# if type(x) == list:
# return [ self.datafy(y) for y in x ]
# elif type(x) == dict:
# result = {}
# for (k,v) in x.items():
# result[k] = self.datafy(v)
# return result
# elif x is None or type(x) in [ bool, int, float, str ]:
# return x
# else:
# return x.to_data()
. Output only the next line. | class Channel(Member): |
Predict the next line for this snippet: <|code_start|> 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()
roman.do("C4,E4,G4") == chord("C4 major")
roman.do("C4 major") == chord("C4,E4,G4")
roman.do("C4") == note("C4")
"""
pass
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
# between them
if sym is None or sym == '-':
# REST:
return chord([])
if '-' in sym:
return chord(sym.replace("-"," "))
elif "," in sym:
return chord(sym.split(","))
else:
<|code_end|>
with the help of current file imports:
from camp.core.note import note
from camp.core.chord import chord, Chord
and context from other files:
# Path: camp/core/note.py
# def note(st):
# """
# note('Db3') -> Note(name='Db', octave=3)
# """
# if type(st) == Note:
# return st
# match = NOTE_SHORTCUT_REGEX.match(st)
# if not match:
# raise Exception("cannot form note from: %s" % st)
# name = match.group(1)
# octave = match.group(2)
# if octave == '' or octave is None:
# octave = 4
# octave = int(octave)
# return Note(name=name, octave=octave)
#
# Path: camp/core/chord.py
# def chord(input):
# """
# Shortcut: chord(['C5', 'E5', 'G5') -> Chord object
# Shortcut: chord('C5 dim') -> Chord object
# """
# if type(input) == list:
# notes = [ note(n) for n in input ]
# return Chord(notes)
# else:
# tokens = input.split()
# assert len(tokens) == 2, "invalid chord expression: %s" % input
# return Chord(root=note(tokens[0]), typ=tokens[1])
#
# class Chord(object):
#
# def __init__(self, notes=None, root=None, typ=None):
#
# """
# Constructs a chord, in different ways:
#
# notes = [ note('C4'), note('E4'), note('G4') ]
# chord = Chord(notes=notes)
#
# OR:
#
# chord = Chord(root=note('C4'), type='major')
#
# OR:
#
# chord = Chord(root='C4', type='major')
# """
#
# self.notes = []
#
# if notes and root:
# raise Exception("notes= and root= are mutually exclusive")
# if notes is None and root is None:
# raise Exception("specify either notes= or root=")
# if root and typ is None:
# raise Exception("typ= is required when using root=")
# if typ and typ not in CHORD_TYPES:
# raise Exception("unknown chord type: %s, expecting one of: %s" % (typ, CHORD_TYPES))
# if isinstance(root, str):
# root = note(root)
#
# if notes is not None:
# for x in notes:
# assert type(x) == Note
# self.notes = notes
#
# else:
# self.typ = typ
# self.root = root
# self.notes = self._chordify()
#
# def copy(self):
# notes = [ n.copy() for n in self.notes ]
# return Chord(notes=notes)
#
# def _chordify(self):
# """
# Internal method.
# Once self.root is set to a note, and self.typ is a chord type, like 'major', return the notes in the chord.
# """
# offsets = CHORD_TYPES[self.typ]
# notes = []
# notes.append(self.root)
# for offset in offsets:
# notes.append(self.root.transpose(semitones=offset))
# return notes
#
# def __repr__(self):
# """
# A chord prints like:
# Chord<C4,E4,G4>
# """
# note_list = ",".join([ n.short_name() for n in sorted(self.notes) ])
# return "Chord<%s>" % note_list
#
# def __eq__(self, other):
# """
# Chords are equal if they contain the same notes.
# """
# return sorted(self.notes) == sorted(other.notes)
#
# def transpose(self, steps=None, semitones=None, octaves=None):
# """
# Transposing a chord is returns a new chord with all of the notes transposed.
# """
# notes = [ note.transpose(steps=steps, octaves=octaves, semitones=None) for note in self.notes ]
# return Chord(notes=notes)
#
# def invert(self, amount=1, octaves=1):
# """
# Inverts a chord.
# ex: chord("c4 major").invert() -> chord(["E4","G4","C5"])
# """
# new_chord = self.copy()
# if amount >= 1:
# new_chord.notes[0] = new_chord.notes[0].transpose(octaves=octaves)
# if amount >= 2:
# new_chord.notes[1] = new_chord.notes[1].transpose(octaves=octaves)
# if amount >= 3:
# new_chord.notes[2] = new_chord.notes[2].transpose(octaves=octaves)
# return new_chord
, which may contain function names, class names, or code. Output only the next line. | return note(sym) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.