def run_method_2(): # Replicates the method outlined in the Google Doc source = data_source.DataSource() T = 100 K = 10 zero_vec = np.zeros(10) ws = [zero_vec, zero_vec] gs = [zero_vec] for t in range(T): w_cur = ws[-1] w_prev = ws[-2] g_prev = gs[-1] # Generate K random machines to perform the modified DSVRG updates inner_results = [ machine.Machine(source, data_count=100).execute_modified_DSVRG( w_cur, w_prev, g_prev) for _ in range(K) ] w_next = np.mean([w for (w, _) in inner_results]) g_cur = np.mean([g for (_, g) in inner_results]) ws.append(w_next) gs.append(g_cur) pass
def setUp(self): self.tmpdir = tempfile.mkdtemp() # automatically cleaned up for a test, but you have to create it yourself self.vm_tmpdir = "/var/lib/kite_test" # create a machine self.machine = machinelib.Machine(user=opts.user, address=opts.address, ssh_port=opts.port, identity_file=opts.identity_file, verbose=opts.verbosity) # check machine reachable and ssh workable # abort/fail the test if one of them does not work self.machine.wait_boot() self.journal_start = self.machine.journal_cursor() # helps with mapping journal output to particular tests name = "%s.%s" % (self.__class__.__name__, self._testMethodName) self.machine.execute("logger -p user.info 'KITETEST: start %s'" % name) self.addCleanup(self.machine.execute, "logger -p user.info 'KITETEST: end %s'" % name) # core dumps get copied per-test, don't clobber subsequent tests with them self.addCleanup(self.machine.execute, "sudo rm -rf /var/lib/systemd/coredump") # temporary directory in the VM self.addCleanup( self.machine.execute, "if [ -d {0} ]; then findmnt --list --noheadings --output " "TARGET | grep ^{0} | xargs -r umount && rm -r {0}; fi".format( self.vm_tmpdir))
def test_init(self): gpio = fake_gpio.FakeGPIO() assert gpio.mode is None assert gpio.warnings is None m = machine.Machine(gpio=gpio) assert gpio.mode == gpio.BCM assert not gpio.warnings assert len(m.triggers) == 0
def start_machine(args, jsonmachine): """Executes the Turing machine and prints every step.""" try: for step in machine.Machine(jsonmachine, args.Tape): print(step.print) except ValueError as e: print(f'Input error: {e}') sys.exit(1)
def _build_machine_list(self): parsed_virsh_list = self._parse_virsh_list() machine_list = [] for i in range(0, self.count_machines()): if parsed_virsh_list[i][2] == "shut" and len( parsed_virsh_list[i]) == 4: machine_list.append( machine.Machine( parsed_virsh_list[i][0], parsed_virsh_list[i][1], parsed_virsh_list[i][2] + " " + parsed_virsh_list[i][3])) else: machine_list.append( machine.Machine(parsed_virsh_list[i][0], parsed_virsh_list[i][1], parsed_virsh_list[i][2])) return machine_list
def __init__(self, master=None): super().__init__(master) self.pack() self.create_widgets() self.init_frame() self.machine = machine.Machine() self.init_data() pub.subscribe(self.listener, "other_frame_destroyed")
def test_machine(self): """Function: test_machine Description: Test with no arguments. Arguments: """ self.assertTrue(machine.Machine())
def run(ctx): """Used to run axonbot_slack.""" load_settings(ctx) bot = machine.Machine() try: bot.run() except KeyboardInterrupt: machine.utils.text.announce("Goodbye!")
def __init__(self): """ relies on OVH_ENDPOINT OVH_APPLICATION_KEY OVH_APPLICATION_SECRET OVH_CONSUMER_KEY """ self.ovh = _ovh.Client() self.machine = _machine.Machine(path="/usr/local/bin/docker-machine")
def set_machines(self, config, num_machines): machines = dict() for id in range(num_machines): for type, mr in config["machines"].iteritems(): machines[id] = machine.Machine(mr, type, id) print len(machines) return machines
def main(): os.system('clear') slotMachine = machine.Machine(50, 1) cli.gameIntro() cli.printHelp() slotMachine.printBalance() while True: if slotMachine.balance > 0: cli.CLI(slotMachine) else: slotMachine.isBroke()
def main(): os.system('clear') slot_machine = machine.Machine(50, 1) cli.game_intro() cli.print_help() slot_machine.print_balance() while True: if slot_machine.balance > 0: cli.CLI(slot_machine) else: slot_machine.is_broke()
def getMachinesFromFile(self, machineXMLFilePath): machineList = [] # value to return try: tree = ET.parse(machineXMLFilePath) root = tree.getroot() except: print(f"Failed where: parsing the file {machineXMLFilePath}") return None filelements = [] # all the <machine name="?"> for elem in root: filelements.append(elem) for child in filelements: tags = ['interfaces/Interface[@name=\"eth0\"]/ipv4Address', 'userName', 'password', 'roles/role'] data = [] data.append(child.attrib['name']) for cc in tags: data.append(child.find(cc).text) machineList.append(machine.Machine(data[0], data[1], data[2], data[3], data[4])) return machineList
def __init__( self, filename: str, every_n_video_frames: int = 1, audio_bitrate: int = 14700, audio_normalization: float = None, max_bytes_out: int = None, video_mode: VideoMode = VideoMode.HGR, palette: Palette = Palette.NTSC, ): self.filename = filename # type: str self.every_n_video_frames = every_n_video_frames # type: int self.max_bytes_out = max_bytes_out # type: int self.video_mode = video_mode # type: VideoMode self.palette = palette # type: Palette self.audio = audio.Audio( filename, bitrate=audio_bitrate, normalization=audio_normalization) # type: audio.Audio self.frame_grabber = frame_grabber.FileFrameGrabber( filename, mode=video_mode, palette=self.palette) self.video = video.Video( self.frame_grabber, ticks_per_second=self.audio.sample_rate, mode=video_mode, palette=self.palette ) # type: video.Video # Byte offset within TCP stream self.stream_pos = 0 # type: int # Current audio tick opcode count within movie stream. self.ticks = 0 # type: int # Tracks internal state of player virtual machine self.state = machine.Machine() # Currently operating on AUX memory bank? self.aux_memory_bank = False
def main(): try: patch = os.path.realpath(__file__) patch = os.path.dirname(patch) + "\strings2.xml" print('path:', patch) #myInit = InitConfigure.InitConfigure(patch) myInit = InitConfigure.InitConfigure("E:\Automatic\strings2.xml") except Exception as e: print("初始化检验失败:", e) input('press enter key to exit') #判断配置文件是否加载成功 try: if myInit._isInitOk: ''' 第三解压目标文件下的压缩文件 ''' FileUtilty.GetReady(myInit) print("解压获取文件完成......") print("开始解析modem log.....") else: print("加载配置文件失败...") pass except Exception as e: print("加载配置文件错误:", e) input('press enter key to exit') mainMachine = machine.Machine(myInit) result = mainMachine.getResult() try: if result: pygalShow = PygalShow.PygalShow(result, myInit.targetDirectory) pygalShow.show() #ShowView.showMianInfo(result) except Exception as e: print("展示结果失败:", e) input('press enter key to exit')
def paint(start_color: Optional[int] = None) -> Dict[Point, Color]: m = machine.Machine(get_intcodes("day11input")) pos: Point = Point(0, 0) r = Robot(Point(0, 0), turn, 1.0) c = Canvas() if start_color: print(Color(start_color)) c.paint(pos, Color(start_color)) m.io = deque([c.color(pos)]) # while not m.halted: try: m.process() # compute color color = Color(m.io.popleft()) # what is the color to paint c.paint(pos, color) m.process() # compute turn tur = m.io.popleft() pos = r.step(tur) m.io.append(c.color(pos)) except IndexError: print("index error") break print(c.painted_grids) return c.canvas
def __init__(self, config): '''Initialize the Cortex.''' logging.basicConfig(format='%(asctime)s %(message)s') self.config = config self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.INFO) self.mode = OperationMode.ATTRACT self.game = game.Game() self.start_event = pygame.event.Event(self.START_EVENT) self.machine = machine.Machine(self.start_event) self.display = display.Display(config, False) self.last_target = 0 self.last_points = 0 # Configure the targets and their event handlers self.targets = [] for target in self.game.targets: value = self.game.targets[target] self.log(logging.INFO, 'target: {} - {}'.format(target, value)) event = self.TARGET_EVENT sub_event = (target, value) self.targets.append( self.machine.create_trigger('target {}'.format(target), target, event, sub_event)) # XXX: Create a mapping of pygame.events to target objects # This will allow the event handler to lookup the target based on event self.log(logging.INFO, 'Cortex target list:') self.log(logging.INFO, self.targets) self.end_event = pygame.event.Event(self.END_EVENT) self.log(logging.INFO, 'end_event: {}'.format(self.end_event)) pygame.time.set_timer(self.POLL_EVENT, self.POLL_SPEED) pygame.init()
ch = channel.ChannelHistory() c.c_id, ch.c_id = channel_no, channel_no channel_no += 2 c.availability = random.randint(0, 1) channels.append(c) channels_history.append(ch) while len(machines) < 500: include = False machineX = random.randint(0, 600) machineY = random.randint(0, 600) ax = (baseX - machineX)**2 ay = (baseY - machineY)**2 distance = math.sqrt(ax + ay) if distance < 300: new_machine = machine.Machine() new_machine.x = machineX new_machine.y = machineY for m in machines: if machineX == m.x and machineY == m.y: include = True if include is False: new_machine.m_id = len(machines) + 1 new_machine.channel = 702 if new_machine.m_id % 9 is 0 else 704 if new_machine.m_id % 9 is 1 else 706 if new_machine.m_id % 9 is 2 else 708 \ if new_machine.m_id % 9 is 3 else 710 if new_machine.m_id % 9 is 4 else 712 if new_machine.m_id % 9 is 5 else 714 if new_machine.m_id % 9 is 6 else 716 \ if new_machine.m_id % 9 is 7 else 718 machines.append(new_machine) over = 0 for i in range(1, 101): over += 1 / (i**0.8)
def __init__(self, *args, **kwds): self._callbacks = {} self._machine = self.Table(machine.Machine())
"""Interface to docker-machine command line to provision machines""" from subprocess import Popen, PIPE import os import tempfile import time import click import machine from multiprocessing import Process, Pool m = machine.Machine(path="/usr/local/bin/docker-machine") existing = [x['Name'] for x in m.ls() if x['Name']] import libtmux server = libtmux.Server() s = server.list_sessions()[0] @click.command() @click.argument("cmd") def parallel_run(cmd): for i, e in enumerate(existing): w = s.new_window(window_name=e) p = w.attached_pane p.send_keys('eval $(docker-machine env %s)' % e) p.send_keys('docker create -it anair17/ss /bin/bash') time.sleep(5) # TODO: how to get the ID of the docker create better container_id = p.cmd('capture-pane', '-p').stdout[-2] print(container_id)
def testPrintMachine(self): mach = machine.Machine('ahmad.mtv', 'core2duo', 4, 'linux', 'asharif') self.assertTrue('ahmad.mtv' in str(mach))
def start(): print('Starting machine') time.sleep(1) print('Coffee Machine is ready') return machine.Machine(400, 540, 120, 9, 550)
import machine import InitConfigure myInit = InitConfigure.InitConfigure() print("初始化检验完成.....") #判断配置文件是否加载成功 if myInit._isInitOk: ''' 第三解压目标文件下的压缩文件 ''' FileUtilty.GetReady(myInit) print("解压获取文件完成......") print("开始解析modem log.....") else: print("加载配置文件错误...") pass mainMachine = machine.Machine(myInit) result = mainMachine.getResult() if result: ShowView.showMianInfo(result) ''' radioMachine = machine.Machine(keyword_radio,year,targetDirectory,resultDirectory,startTime,endTime) result = radioMachine.getRadioResult() print("=============",result) radioMachine = machine.Machine(keyword_kernel,year,targetDirectory,resultDirectory,startTime,endTime) result = radioMachine.getKernelResult() print("=============",result) '''
from memory import Memory from registers import IRegister from registers import FRegister import timingmodel import program import config import machine import sys if __name__ == '__main__': if len(sys.argv) > 2: if (int(sys.argv[2]) < 32): print("Cannot initialize simulator with fewer than 32 registers") quit() print("Initializing machine with " + sys.argv[2] + " registers") config.machine = machine.Machine( numIntRegisters=int(sys.argv[2]), numFloatRegisters=int(sys.argv[2]), timingModel=timingmodel.basicTimingModel) else: print("Using default machine configuration with 256 registers") p = program.Program() p.buildCodeFromFile(sys.argv[1]) config.machine.execProgram(p)
""" Upload 'custart.csv' to jensen machine. Blind Pew 2017 <*****@*****.**> GNU GPL v3 """ import sys import machine l = 'D' linka = [] for i in range(len(machine.Const.SERIAL[l])): linka.append(machine.Machine(machine.Const.NAME[i], machine.Const.IP[i], machine.Const.SERIAL[l][i])) def pouziti(): print("\nUsage:",sys.argv[0],"<filename>\n") if(len(sys.argv)>1): soubor = sys.argv[1] else: pouziti() sys.exit(0) for stroj in linka: try: stroj.connect()
parser = argparse.ArgumentParser("Simulate RISC-V execution") parser.add_argument("-m", dest="memuse", action="store_true", default=False, help="show memory usage") parser.add_argument("asm", help="assembly file to simulate") parser.add_argument("nregs", nargs="?", help="number of registers to simulate") args = parser.parse_args() if args.nregs: if int(args.nregs) < 32: print("Cannot initialize simulator with fewer than 32 registers") sys.exit(1) print("Initializing machine with " + args.nregs + " registers") config.machine = machine.Machine( numIntRegisters=int(args.nregs), numFloatRegisters=int(args.nregs), timingModel=timingmodel.basicTimingModel) else: print("Using default machine configuration with 256 registers") p = program.Program() p.buildCodeFromFile(args.asm) config.machine.execProgram(p, args.memuse)
'script to find common states. will also unlabel states if there is an unlabeler for the randomizer.' import sys, time import rng, randos, machine, unlabel pyrandom = rng.Python() if len(sys.argv) < 2: print('Usage: python3 findCommonStates.py RANDOMIZER') print() print('Randomizers:') for name in sorted(randos.byname): print(' ', name) exit(1) Rando = randos.byname[sys.argv[1]] m = machine.Machine(Rando) unlabelStates = Rando.__name__ in unlabel.unlabel state = None count = {} total = 0 t = time.time() while True: count[state] = count.get(state, 0) + 1 total += 1 trans = m.getedges(state) r = pyrandom.random() for (nextstate, piece), prob in trans.items():
for typedix, code in zip(module['func'], module['code']): functype = module['type'][typedix] # Signature func = machine.Function(nparams=len(functype.params), returns=bool(functype.returns), code=wadze.parse_code(code).instructions) defined_functions.append(func) functions = imported_functions + defined_functions # Declare "exported" functions exports = { exp.name: functions[exp.ref] for exp in module['export'] if isinstance(exp, wadze.ExportFunction) } m = machine.Machine(functions, 20 * 65536) # Hack on memory # Initialize memory for data in module['data']: m.execute(data.offset, None) offset = m.pop() m.memory[offset:offset + len(data.values)] = data.values from machine import float64, int32 # call something width = float64(800.0) height = float64(600.0) m.call(exports['resize'], width, height) # Game loop
def test_create_trigger(self): gpio = fake_gpio.FakeGPIO() m = machine.Machine(gpio=gpio) assert len(m.triggers) == 0 m.create_trigger('test', 1, 0, 0) assert len(m.triggers) == 1
def main(): sorter = machine.Machine() print("test") sorter.calibrate() time.sleep(3) sorter.sort_random()