예제 #1
0
    def __init__(self, sound_manager, x, y):
        Box.__init__(self, sound_manager, x, y)

        self.box_time = -1
        self.game_time = 0
        self.init_frames()
        self.refresh_image(self.display_frame)
예제 #2
0
파일: cli.py 프로젝트: pombredanne/box
def checkin(url, files, message=None):
    """Check in files to a repository"""
    from box import Box
    b = Box(url)

    if b.type != 'local':
        raise BoxError('Not a box: %s' % url)

    if not files:
        raise BoxError('No files')

    def _write(path):
        log.debug('writing: %s' % path)
        item = Item.from_path(repo=b, path=path)
        v.addItem(item=item)

    v = b.addVersion()
    count = 1
    total = len(files) 
    while count <= total:
        print '[%s/%s] %0.2f%%' %(count, total, (float(count) / total) * 100), '*'*count, '\r',
        _write(os.path.abspath(files[count-1]))
        count += 1
        sys.stdout.flush()
    v.save(message=message)
    print
예제 #3
0
파일: cli.py 프로젝트: pombredanne/box
def checkout(url, version=None):
    """Check out latest snapshot of blob or repository"""
    from box import Box
    b = Box(url)

    def _write(item):
        log.debug('writing: %s' % item.name)
        if item.type != 'blob':
            return
        if b.type in ['box', 'local']:
            path = os.path.join(b.name, item.path)
            pdir = os.path.dirname(path)
            if not os.path.isdir(pdir):
                os.makedirs(pdir)
        else:
            path = item.name

        f = open(path, 'w')
        f.write(item.data())
        f.close()

    if b.type == 'blob':
        _write(b)
    else:
        items = b.items()
        count = 1
        total = len(items)
        while count <= total:
            print '[%s/%s] %0.2f%%' %(count, total, (float(count) / total) * 100), '*'*count, '\r',
            _write(items[count-1])
            count += 1
            sys.stdout.flush()
        print
예제 #4
0
 def __init__(self, argon):
     self.hue = 0.0
     self.saturation = 0.0
     self.value = 1.0
     self.gradient = argon.image('hue-saturation-360x256.png')
     Box.__init__(self, 0, 0,  480+20, 256+20)
     self.which = -1
예제 #5
0
파일: intron.py 프로젝트: cheery/essence
 def __init__(self, generator, *args):
     Box.__init__(self, (0,0,0,0), None)
     self.node       = None
     self.controller = None
     self.generator  = generator
     self.args       = args
     self.rebuild()
	def __init__(self, brick, color, tileDir, thickness, density, unglueThreshold=None, shatterLimit=None, shatterThreshold=None, noSetup=False):
		if noSetup: return
		
		depth = thickness / 2
		world = brick.world
		parent = brick.parent
		size = entrywiseMult(vecInvert(tileDir), brick.size) + (vecBasic(tileDir) * depth)
		pos = brick.node.getPos() + entrywiseMult(tileDir, brick.size) + (vecFromList(tileDir) * depth)
		self.tileDir = tileDir
		if unglueThreshold == None: unglueThreshold = 5
		if shatterThreshold == None: shatterThreshold = 10
		dir = getNeutralDir()

		Box.__init__(self, world, parent, color, pos, dir, size, density, unglueThreshold, shatterLimit, shatterThreshold)

		self.thickness = thickness
		self.brick = brick
		self.brick.addTile(self)

		# Glue to brick.
		self.glue = OdeFixedJoint(self.world.world)
		self.glue.attachBodies(self.body, brick.body)
		self.glue.set()

		# Adjust collision bitmasks.
		self.geom.setCategoryBits(GameObject.bitmaskTileGlued)
		self.geom.setCollideBits(GameObject.bitmaskAll & ~GameObject.bitmaskBox & ~GameObject.bitmaskTileGlued & ~GameObject.bitmaskTile)
예제 #7
0
파일: theme.py 프로젝트: nunb/MaTiSSe
 def reset(cls):
   """Reset to default state."""
   Box.reset()
   Note.reset()
   Figure.reset()
   Table.reset()
   Video.reset()
예제 #8
0
 def __init__(self, offset=0, box=None):
     Box.__init__(self, offset, box)
     if isinstance(box, FullBox) and box != None:
         self.large_size = box.large_size
         self.user_type = box.user_type
     else:
         self.version = 0
         self.flags = ''
예제 #9
0
def settings():
    if request.method == "POST":
        app.logger.debug("Received post '{0}', '{1}'".format(request.form["client_id"], request.form["client_secret"]))
        box = Box(app.logger)
        box.set_value("client_id", request.form["client_id"])
        box.set_value("client_secret", request.form["client_secret"])
        return redirect("/", code=302)
    return render_template("settings.html")
예제 #10
0
 def __init__(self, world, parent, color, pos, dir, axis, size, density):
     Box.__init__(self, world, parent, color, pos, dir, size, density)
     self.body.setGravityMode(False)
     self.joint = OdeHingeJoint(world.world)
     self.joint.attach(self.body, None)
     self.joint.setAnchor(self.node.getPos())
     self.joint.setAxis(*axis)
     self.joint.setParamBounce(0.0)
예제 #11
0
파일: container.py 프로젝트: cheery/essence
 def __init__(self, nodes, style):
     self.nodes = nodes
     self.offset0 = [0] * (len(nodes) + 1)
     self.offset1 = [0] * (len(nodes) + 1)
     self.flow0 = [0] * len(nodes)
     self.flow1 = [0] * len(nodes)
     self.base0 = 0 
     self.base1 = 0
     Box.__init__(self, (0,0,0,0), style)
예제 #12
0
파일: richtext.py 프로젝트: cheery/essence
 def __init__(self, font, text, tags, head=0, tail=0):
     self.font = font
     self.text = text
     self.tags = tags
     self.head = head + 11
     self.tail = tail + 40
     Box.__init__(self)
     self.width  = 300
     self.line_height = font.height * 1.2
     self.dragging = False
예제 #13
0
def authorize():
    box = Box(app.logger)
    code = request.args.get("code")

    if code is None:
        callback = "https://" + request.headers.get("Host") + "/auth/authorize"
        auth_url = box.authorization_url(callback)
        return redirect(auth_url, code=302)

    box.authorize(code)
    return redirect("/", code=302)
예제 #14
0
파일: storyCard.py 프로젝트: seanh/PandaZUI
    def __init__(self):

        icon = loader.loadTexture('storymaps/data/actions/add.svg.png')
        icon.setMagfilter(Texture.FTLinearMipmapLinear)
        icon.setMinfilter(Texture.FTLinearMipmapLinear)
        rollover_icon = loader.loadTexture('storymaps/data/actions/add_rollover.svg.png')
        rollover_icon.setMagfilter(Texture.FTLinearMipmapLinear)
        rollover_icon.setMinfilter(Texture.FTLinearMipmapLinear)
        self.addButton = DirectButton(image= (icon, rollover_icon, rollover_icon, icon), command = self.add, suppressMouse=0)
        b = Box()
        b.fill(self.addButton)              
        self.buttons.append(b)
        self.addButton['state'] = DGG.NORMAL
예제 #15
0
    def __init__(self, sound_manager, x, y, num_coins=1):
        Box.__init__(self, sound_manager, x, y)

        self.num_coins = num_coins
        self.empty_frame = None
        self.coin_box_frames = []
        self.frame_idx = 0
        self.coin_box_time = 0
        self.game_time = 0
        self.transition_time = 0

        self.coin_score_group = pygame.sprite.Group()

        self.init_frames()
        self.refresh_image(self.coin_box_frames[0])
예제 #16
0
    def paint(self, image, color=colors.RED):

        points = []
        for line in self.lines:
            for word in line.words:
                for point in word.contour:
                    points.append(point)
        points = numpy.array(points)    # This needs to have the format [ [[a,b]], [[c,d]] ]
        box = Box(points)
        image = box.paint(image, color)

        for line in self.lines:
            image = line.paint(image, colors.BURNT_YELLOW, centerLine=True)

        return image
예제 #17
0
    def __init__(self, sound_manager, group, x, y, powerup=c.POWERUP_MUSHROOM):
        Box.__init__(self, sound_manager, x, y)

        self.group = group
        self.powerup = powerup
        self.empty_frame = None
        self.coin_box_frames = []
        self.frame_idx = 0
        self.coin_box_time = 0
        self.game_time = 0
        self.transition_time = 0
        self.empty = False

        self.init_frames()
        self.refresh_image(self.coin_box_frames[0])
예제 #18
0
 def mark(self, coords, color, sType=False):
     # Obarvení kostky v poli
     box = Box(size_hint=(None, None))
     box.coords = (coords[0], coords[1])
     box.colored = color
     box.size_hint = (1/12., 1/22.)
     box.pos_hint = {'x':coords[0]*(1/12.), 'y':(21-coords[1])*(1/22.)}
     box.opacity = 1
     self.add_widget(box)
     self.coords[coords[1]][coords[0]] = box
     box.active = True
     if sType != False:
         box.special(sType, True)
	def make2(self, tile, color, tileDir, pos, size, density, shatterLimit=None, shatterThreshold=None):
		self = Tile(0, 0, 0, 0, 0, noSetup = True)
		world = tile.world
		parent = tile.parent
		self.tileDir = tileDir
		if shatterThreshold == None: shatterThreshold = 10
		dir = getNeutralDir()

		Box.__init__(self, world, parent, color, pos, dir, size, density, shatterLimit, shatterThreshold)

		self.thickness = tile.thickness
		self.brick = tile.brick
		self.glue = None

		# Adjust collision bitmasks.
		self.geom.setCategoryBits(GameObject.bitmaskTile)
		self.geom.setCollideBits(GameObject.bitmaskAll & ~GameObject.bitmaskTileGlued & ~GameObject.bitmaskTile)

		return self
예제 #20
0
    def peek(self, file_strm):
        if file_strm is None:
            print "file_strm is None"
            return file_strm

        file_strm = Box.peek(self, file_strm)

        self.version = file_strm.peek_uint8()
        self.flags = file_strm.peek_byte(3)

        return file_strm
예제 #21
0
파일: storyCard.py 프로젝트: seanh/PandaZUI
    def __init__(self):

        f = 'storymaps/data/actions/copy.svg.png'
        icon = loader.loadTexture(f)
        icon.setMagfilter(Texture.FTLinearMipmapLinear)
        icon.setMinfilter(Texture.FTLinearMipmapLinear)
        f = 'storymaps/data/actions/copy_rollover.svg.png'
        rollover_icon = loader.loadTexture(f)
        rollover_icon.setMagfilter(Texture.FTLinearMipmapLinear)
        rollover_icon.setMinfilter(Texture.FTLinearMipmapLinear)
        copyButton = DirectButton(image=(icon, rollover_icon,
                                         rollover_icon, icon),
                                  command=self.copy,suppressMouse=0)
        b = Box()
        b.fill(copyButton)                            
        self.buttons.append(b)

        f = 'storymaps/data/actions/paste.svg.png'
        icon = loader.loadTexture(f)
        icon.setMagfilter(Texture.FTLinearMipmapLinear)
        icon.setMinfilter(Texture.FTLinearMipmapLinear)
        f = 'storymaps/data/actions/paste_rollover.svg.png'
        rollover_icon = loader.loadTexture(f)
        rollover_icon.setMagfilter(Texture.FTLinearMipmapLinear)
        rollover_icon.setMinfilter(Texture.FTLinearMipmapLinear)
        pasteButton = DirectButton(image=(icon, rollover_icon,
                                          rollover_icon, icon),
                                   command=self.paste,suppressMouse=0)
        b = Box()
        b.fill(pasteButton)                            
        self.buttons.append(b)

        f = 'storymaps/data/actions/remove.svg.png'
        icon = loader.loadTexture(f)
        icon.setMagfilter(Texture.FTLinearMipmapLinear)
        icon.setMinfilter(Texture.FTLinearMipmapLinear)
        f = 'storymaps/data/actions/remove_rollover.svg.png'
        rollover_icon = loader.loadTexture(f)
        rollover_icon.setMagfilter(Texture.FTLinearMipmapLinear)
        rollover_icon.setMinfilter(Texture.FTLinearMipmapLinear)
        removeButton = DirectButton(image=(icon, rollover_icon,
                                           rollover_icon, icon),
                                    command=self.remove, suppressMouse=0)
        b = Box()
        b.fill(removeButton)                            
        self.buttons.append(b)        
예제 #22
0
def copyCube(boxes):
    from box import Box
    ret=[]
    for i in range(len(boxes)):
        box=Box(boxes[i].boxType)
        box.xz=deepcopy(boxes[i].xz)
        box.yz=deepcopy(boxes[i].yz)
        box.xy=deepcopy(boxes[i].xy)
        box.pos=deepcopy(boxes[i].pos)
        
        box.xzBox=boxes[i].xzBox
        box.yzBox=boxes[i].yzBox
        box.xyBox=boxes[i].xyBox
        ret.append(box)
    return ret
예제 #23
0
파일: psmain.py 프로젝트: diopib/pp
    def __init__(self):
        self.camera = Camera([15.0, 0.0, 2.5],
                             [0.0, 0.0, 2.5],
                             [0.0, 0.0, 1.0])
        self.aspect = 1.0
        self.numP = 300
        self.t = 0
        # flag to rotate camera view
        self.rotate = True

        # save current working directory
        cwd = os.getcwd()

        # initialize glfw - this changes cwd
        glfw.glfwInit()
        
        # restore cwd
        os.chdir(cwd)

        # version hints
        glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, 3)
        glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, 3)
        glfw.glfwWindowHint(glfw.GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE)
        glfw.glfwWindowHint(glfw.GLFW_OPENGL_PROFILE, 
                            glfw.GLFW_OPENGL_CORE_PROFILE)

        # make a window
        self.width, self.height = 640, 480
        self.aspect = self.width/float(self.height)
        self.win = glfw.glfwCreateWindow(self.width, self.height, 
                                     b"Particle System")
        # make context current
        glfw.glfwMakeContextCurrent(self.win)
        
        # initialize GL
        glViewport(0, 0, self.width, self.height)
        glEnable(GL_DEPTH_TEST)
        glClearColor(0.2, 0.2, 0.2,1.0)

        # set window callbacks
        glfw.glfwSetMouseButtonCallback(self.win, self.onMouseButton)
        glfw.glfwSetKeyCallback(self.win, self.onKeyboard)
        glfw.glfwSetWindowSizeCallback(self.win, self.onSize)        

        # create 3D
        self.psys = ParticleSystem(self.numP)
        self.box = Box(1.0)

        # exit flag
        self.exitNow = False
예제 #24
0
    def decode(self, file_strm):
        if file_strm is None:
            print "file_strm is None"
            return file_strm

        file_strm = Box.decode(self, file_strm)

        self.version = file_strm.read_uint8()
        self.offset += UInt8ByteLen

        self.flags = file_strm.read_byte(3)
        self.offset += Int8ByteLen * 3

        return file_strm
예제 #25
0
def write_stop_list_table(out_file, stop_list_map):
    out_file.write("CREATE TABLE IF NOT EXISTS trip_stops (id INTEGER PRIMARY KEY, blob STRING);\n")
    for stop_list_id, lst in stop_list_map.items():
        box = Box()
        box.add_short(len(lst))

        for stop_id, sequence in lst:
            try:
                box.add_string(stop_id)
                box.add_short(sequence)
            except:
                print((stop_id, sequence))
                raise

        out_file.write("INSERT INTO trip_stops VALUES (%d, %s);\n" % (
            stop_list_id, box.get_blob_string()
        ))
예제 #26
0
 def __init__(self):
     self._create_sdk()
     self._filename = None
     self._camera = None
     self._box = Box()
     self._photo_queue = Queue()
     self._photo_thread = Thread(target=self._process_queue)
     self._photo_thread.daemon = True
     self._photo_thread.start()
     self._name = None
     self._message = None
     self._photos = []
     self._waiting_for_callback = False
     self._event_object = None
     self._no_shutdown_thread = None
     self._stop_no_shutdown_thread = False
예제 #27
0
class Colorpicker(Box):
    def __init__(self, argon):
        self.hue = 0.0
        self.saturation = 0.0
        self.value = 1.0
        self.gradient = argon.image('hue-saturation-360x256.png')
        Box.__init__(self, 0, 0,  480+20, 256+20)
        self.which = -1

    @property
    def rgba(self):
        return hsva(self.hue, self.saturation, self.value).rgba

    def update(self):
        self.major   = Box(self.left+10+0,   self.top+10, 360, 256)
        self.minor   = Box(self.left+10+360, self.top+10, 30,  256)
        self.preview = Box(self.left+10+390, self.top+10, 90,  256)

    def render(self, argon):
        self.update()
        v1 = hsva(self.hue, self.saturation, 1.0).rgba
        x0, y0 = self.major.interpolate((self.hue/360.0, self.saturation))
        x1, y1 = self.minor.interpolate((0, 1-self.value))
        argon.render([
            (self.rect, black, argon.plain),
            (self.major.rect, white.mix(black, self.value), self.gradient),
            (self.minor.rect, (v1, v1, black, black), argon.plain),
            (self.preview.rect, self.rgba, argon.plain),
            ((x0, y0, 1, 1), black, argon.plain),
            ((x1, y1, 30, 1), black, argon.plain),
        ])

    def setcolor(self, pos, which):
        if which == 0:
            i, j = self.major.point_interval(pos)
            self.hue        = i * 360.0
            self.saturation = j
        elif which == 1:
            i, j = self.minor.point_interval(pos)
            self.value = 1 - j

    def mousedown(self, button, pos):
        if button == 1:
            if self.major.point_inside(pos):
                self.setcolor(pos, 0)
                self.which = 0
            if self.minor.point_inside(pos):
                self.setcolor(pos, 1)
                self.which = 1

    def mouseup(self, button, pos):
        self.which = -1

    def mousemotion(self, pos, vel):
        self.setcolor(pos, self.which)
예제 #28
0
def write_arrivals_table(out_file, arrivals_map):
    out_file.write("CREATE TABLE IF NOT EXISTS arrivals (id INTEGER PRIMARY KEY, blob STRING);\n")
    for arrival_id, lst in arrivals_map.items():
        box = Box()
        box.add_short(len(lst))

        for arrival_seconds, departure_seconds in lst:
            if arrival_seconds % 60 != 0:
                raise Exception("arrival_seconds % 60 != 0")
            if (arrival_seconds / 60) > 0xffff or arrival_seconds < 0:
                raise Exception("arrival_seconds out of range")
            box.add_short(arrival_seconds/60)
            #box.add_int(departure_seconds)

        out_file.write("INSERT INTO arrivals VALUES (%d, %s);\n" % (
            arrival_id, box.get_blob_string()
        ))
예제 #29
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_through_queue(self):
     my_box = Box(a=4, c={"d": 3})
     queue = Queue()
     queue.put(my_box)
     assert queue.get()
예제 #30
0
    parser.add_argument('--output_dir', type=str, default="plots")
    args = parser.parse_args()
    start = time.time()

    data_dir = "data"
    logger.initialize(args.output_dir, debug=args.debug)
    logger.info(vars(args))
    save_dir = logger.get_savedir()
    logger.info("Written to {}".format(save_dir))

    # Load json
    prediction_path = os.path.join(args.fold_path, "prediction.json")
    with open(prediction_path) as f:
        data = json.load(f)
        predictions = data["predictions"]
        sargs = Box(data["arguments"])

    print("Loading data...")
    dataset = joblib.load(sargs.in_data)
    valid_split = sargs.eval_split + sargs.nb_splits * 2
    valid_dataset = SceneDatasetForAnalysis(
        dataset, sargs.input_len,
        sargs.offset_len if "offset" in sargs else 10, sargs.pred_len,
        sargs.width, sargs.height)

    print(len(valid_dataset))

    # Green, Purple, Yellow, Gray, Cyan
    colors = [(0, 255, 0), (255, 42, 107), (0, 255, 255), (163, 163, 163),
              (192, 192, 0)]
예제 #31
0
import os
from box import Box
from .PartDomesticator import GoldenGateDomesticator

this_dir = os.path.realpath(__file__)
standards_dir = os.path.join(os.path.dirname(this_dir), "assembly_standards")

BUILTIN_STANDARDS = Box({})
for fname in os.listdir(standards_dir):
    name, ext = os.path.splitext(fname)
    if ext != ".csv":
        continue
    path = os.path.join(standards_dir, fname)
    BUILTIN_STANDARDS[name] = GoldenGateDomesticator.standard_from_spreadsheet(
        path, name_prefix=name + "_"
    )
예제 #32
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_pop_items(self):
     bx = Box(a=4)
     assert bx.popitem() == ("a", 4)
     with pytest.raises(BoxKeyError):
         assert bx.popitem()
from box.converters import yaml

from dvc_sample_project.monitoring import report, shorten_path
from dvc_sample_project.utils.fs import find_parent_containing

def _join_path(loader, node):
    seq = loader.construct_sequence(node)
    return Path().joinpath(*seq)

def _get_from_env(loader, node):
    return os.environ.get(node.value, None)

yaml.SafeLoader.add_constructor('!join_path', _join_path)
yaml.SafeLoader.add_constructor('!env', _get_from_env)

params = Box(box_dots=True)
config = Box(box_dots=True)

def load_configs():
    for name in ["params", "config"]:
        filename = find_parent_containing(f"{name}.yaml", return_parent=False)
        try:
            loaded = Box.from_yaml(
                filename=filename,
                box_dots=True,
                Loader=yaml.SafeLoader,
            )
            report("config", f"Loaded {name} from [!path]{shorten_path(filename)}[/]")
            globals()[name].merge_update(loaded)
        except Exception as e:
            report("config", f"Exception [!alert]{type(e).__name__}({e})[/] occured while parsing [!path]{shorten_path(filename)}[/]")
예제 #34
0
def print_updates(args):
    data = yield getPage("http://developer.mbta.com/lib/gtrtfs/Passages.pb")
    update = gtfs_realtime_pb2.FeedMessage()
    update.ParseFromString(data)

    trip_id_to_delays = defaultdict(list)
    trip_ids = set()
    for entity in update.entity:
        trip_id = str(entity.trip_update.trip.trip_id)
        trip_ids.add(trip_id)
        for stop_time_update in entity.trip_update.stop_time_update:
            # TODO: error-check for lack of arrival.delay
            tup = stop_time_update.stop_sequence, stop_time_update.arrival.delay
            trip_id_to_delays[trip_id].append(tup)
        if trip_id in trip_id_to_delays:
            trip_id_to_delays[trip_id] = sorted(trip_id_to_delays[trip_id], key=itemgetter(0))



    con = sqlite3.connect(args.db)
    cur = con.cursor()
    # injection risk here! SQLite can't handle this many parameters, though
    trip_ids_str = ", ".join(("'%s'" % escaped(x)) for x in trip_ids)

    query = ('SELECT stop_times.offset, arrivals.blob, '
             'trip_ids.route_id, trip_ids.trip_id, trip_stops.blob '
             'FROM trip_ids '
             'JOIN stop_times ON stop_times.trip_id = trip_ids.id AND trip_ids.trip_id IN (%s) '
             'JOIN arrivals ON arrivals.id = stop_times.arrival_id '
             'JOIN trip_stops ON trip_stops.id = stop_times.stop_list_id ') % trip_ids_str
    results = cur.execute(query)

    stop_results = defaultdict(list)

    for offset, arrivals_blob_str, route_id, trip_id, stop_list_blob_str in results:
        trip_id = str(trip_id)

        arrivals_blob = Box(arrivals_blob_str)
        arrivals_len = arrivals_blob.read_short()

        stop_list_blob = Box(stop_list_blob_str)
        stop_list_len = stop_list_blob.read_short()

        for i in xrange(arrivals_len):
            current_delay = 0
            stop_id = stop_list_blob.read_string()
            sequence_id = stop_list_blob.read_short()
            arrival_minutes = arrivals_blob.read_short()

            if trip_id in trip_id_to_delays[trip_id]:
                for stop_sequence, delay in trip_id_to_delays[trip_id]:
                    if stop_sequence > sequence_id:
                        break
                    current_delay = delay

            arrival_seconds = arrival_minutes * 60
            tup = (offset + arrival_seconds, route_id, current_delay, trip_id, sequence_id)
            stop_results[stop_id].append(tup)


    now = datetime.now()
    midnight = now.replace(hour=0, minute=0, second=0, microsecond=0)
    now_seconds = (now - midnight).seconds

    if args.stop_id in stop_results:
        lst = stop_results[args.stop_id]
        new_lst = [(seconds, route_id, delay, trip_id, sequence_id)
                   for (seconds, route_id, delay, trip_id, sequence_id) in lst
                   if (seconds + delay) > now_seconds]

        new_lst = sorted(new_lst, key=lambda x: x[0] + x[2])

        if len(new_lst) == 0:
            print("No arrivals for %s" % args.stop_id)
        else:
            for seconds, route_id, delay, trip_id, sequence_id in new_lst:
                print("Next arrival for stop %s (sequence %d) on"
                      " route %s is at %s with delay %d (total %s) on trip %s" % (args.stop_id,
                                                                       sequence_id,
                                                                       route_id,
                                                                       time_to_string(seconds),
                                                                       delay,
                                                                       time_to_string(seconds + delay),
                                                                       trip_id))
    else:
        print("%s is not in any of the trips specified by the SQL query" % args.stop_id)
예제 #35
0
파일: test_box.py 프로젝트: philipsd6/Box
    def test_default_box(self):
        bx = Box(test_dict, default_box=True, default_box_attr={"hi": "there"})
        assert bx.key_88 == {"hi": "there"}
        assert bx["test"] == {"hi": "there"}

        bx2 = Box(test_dict, default_box=True, default_box_attr=Box)
        assert isinstance(bx2.key_77, Box)

        bx3 = Box(default_box=True, default_box_attr=3)
        assert bx3.hello == 3

        bx4 = Box(default_box=True, default_box_attr=None)
        assert bx4.who_is_there is None

        bx5 = Box(default_box=True, default_box_attr=[])
        assert isinstance(bx5.empty_list_please, list)
        assert len(bx5.empty_list_please) == 0
        bx5.empty_list_please.append(1)
        assert bx5.empty_list_please[0] == 1

        bx6 = Box(default_box=True, default_box_attr=[])
        my_list = bx6.get("new_list")
        my_list.append(5)
        assert bx6.get("new_list")[0] == 5

        bx7 = Box(default_box=True, default_box_attr=False)
        assert bx7.nothing is False

        bx8 = Box(default_box=True, default_box_attr=0)
        assert bx8.nothing == 0

        # Tests __get_default's `copy` clause
        s = {1, 2, 3}
        bx9 = Box(default_box=True, default_box_attr=s)
        assert isinstance(bx9.test, set)
        assert bx9.test == s
        assert id(bx9.test) != id(s)

        bx10 = Box({"from": "here"}, default_box=True)
        assert bx10.xfrom == "here"
        bx10.xfrom = 5
        assert bx10.xfrom == 5
        assert bx10 == {"from": 5}
예제 #36
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_items(self):
     b = Box()
     b.foo = {}
     assert isinstance(list(b.items())[0][1], Box)
     c = Box()
     c.foohoo = []
     assert isinstance(list(c.items())[0][1], BoxList)
     d = Box(movie_data)
     assert len(movie_data["movies"].items()) == len(d.movies.items())
     e = Box(movie_data, box_dots=True)
     assert sorted(e.items(dotted=True), key=lambda x: x[0]) == sorted(
         [
             ("movies.Robin Hood: Men in Tights.Director", "Mel Brooks"),
             ("movies.Robin Hood: Men in Tights.Stars[0].imdb", "nm0000144"),
             ("movies.Robin Hood: Men in Tights.Stars[0].name", "Cary Elwes"),
             ("movies.Robin Hood: Men in Tights.Stars[0].role", "Robin Hood"),
             ("movies.Robin Hood: Men in Tights.Stars[1].imdb", "nm0507659"),
             ("movies.Robin Hood: Men in Tights.Stars[1].name", "Richard Lewis"),
             ("movies.Robin Hood: Men in Tights.Stars[1].role", "Prince John"),
             ("movies.Robin Hood: Men in Tights.Stars[2].imdb", "nm0715953"),
             ("movies.Robin Hood: Men in Tights.Stars[2].name", "Roger Rees"),
             ("movies.Robin Hood: Men in Tights.Stars[2].role", "Sheriff of Rottingham"),
             ("movies.Robin Hood: Men in Tights.Stars[3].imdb", "nm0001865"),
             ("movies.Robin Hood: Men in Tights.Stars[3].name", "Amy Yasbeck"),
             ("movies.Robin Hood: Men in Tights.Stars[3].role", "Marian"),
             ("movies.Robin Hood: Men in Tights.imdb_stars", 6.7),
             ("movies.Robin Hood: Men in Tights.length", 104),
             ("movies.Robin Hood: Men in Tights.rating", "PG-13"),
             ("movies.Spaceballs.Director", "Mel Brooks"),
             ("movies.Spaceballs.Stars[0].imdb", "nm0000316"),
             ("movies.Spaceballs.Stars[0].name", "Mel Brooks"),
             ("movies.Spaceballs.Stars[0].role", "President Skroob"),
             ("movies.Spaceballs.Stars[1].imdb", "nm0001006"),
             ("movies.Spaceballs.Stars[1].name", "John Candy"),
             ("movies.Spaceballs.Stars[1].role", "Barf"),
             ("movies.Spaceballs.Stars[2].imdb", "nm0001548"),
             ("movies.Spaceballs.Stars[2].name", "Rick Moranis"),
             ("movies.Spaceballs.Stars[2].role", "Dark Helmet"),
             ("movies.Spaceballs.imdb_stars", 7.1),
             ("movies.Spaceballs.length", 96),
             ("movies.Spaceballs.rating", "PG"),
         ],
         key=lambda x: x[0],
     )
     with pytest.raises(BoxError):
         Box(box_dots=False).items(dotted=True)
예제 #37
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_pickle_default_box(self):
     if platform.python_implementation() == "PyPy":
         pytest.skip("Pickling does not work correctly on PyPy")
     bb = Box(default_box=True)
     loaded = pickle.loads(pickle.dumps(bb))
     assert bb == loaded
예제 #38
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_update_with_integer(self):
     bx = Box()
     bx[1] = 4
     assert bx[1] == 4
     bx.update({1: 2})
     assert bx[1] == 2
예제 #39
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_revered(self):
     bx = Box()
     bx.a = 1
     bx.c = 2
     assert list(reversed(bx)) == ["c", "a"]
예제 #40
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_bad_recursive(self):
     b = Box()
     bl = b.setdefault("l", [])
     bl.append(["foo"])
     assert bl == [["foo"]], bl
예제 #41
0
    def test_singularity_start(self):
        repo = self.mk_repo()
        conf = ConfigLoader.load(
            engine_name="singularity", workspace_dir=repo.working_dir
        )

        step = Box(
            {
                "uses": "docker://*****:*****@master", "args": ["ls"],}]}
            r.run(WorkflowParser.parse(wf_data=wf_data))

            wf_data = {
                "steps": [
                    {
                        "uses": "docker://alpine:3.9",
                        "args": ["sh", "-c", "echo $FOO > hello.txt ; pwd"],
                        "env": {"FOO": "bar"},
                    }
                ]
            }
            r.run(WorkflowParser.parse(wf_data=wf_data))
            with open(os.path.join(repo.working_dir, "hello.txt"), "r") as f:
                self.assertEqual(f.read(), "bar\n")

            wf_data = {
                "steps": [
                    {
                        "uses": "docker://alpine:3.9",
                        "args": ["nocommandisnamedlikethis"],
                    }
                ]
            }
            self.assertRaises(SystemExit, r.run, WorkflowParser.parse(wf_data=wf_data))

        repo.close()
예제 #42
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_get_box_config(self):
     bx = Box()
     bx_config = bx.__getattr__("_box_config")
     assert bx_config
     with pytest.raises(BoxKeyError):
         bx["_box_config"]
예제 #43
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_iter(self):
     bx = Box()
     bx.a = 1
     bx.c = 2
     assert list(bx.__iter__()) == ["a", "c"]
예제 #44
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_box_modify_tuples(self):
     bx = Box(extended_test_dict, modify_tuples_box=True)
     assert bx.tuples_galore[0].item == 3
     assert isinstance(bx.tuples_galore[0], Box)
     assert isinstance(bx.tuples_galore[1], tuple)
예제 #45
0
파일: Well.py 프로젝트: pk-organics/Plateo
class Well:
    """Generic class for a well.

    Parameters
    ----------

    plate
      The plate on which the well is located

    row
      The well's row (a number, starting from 0)

    column
      The well's column (a number, starting from 0)

    name
      The well's name, for instance "A1"

    data
      A dictionnary storing data on the well, used in algorithms and reports.


    """
    capacity = None

    def __init__(self, plate, row, column, name, data=None):
        self.plate = plate
        self.row = row
        self.column = column
        self.name = name
        self.data = Box({} if data is None else data)
        self.sources = []
        self.content = WellContent()

    @property
    def volume(self):
        return self.content.volume

    def iterate_sources_tree(self):
        for source in self.sources:
            if isinstance(source, Well):
                for parent in source.iterate_sources_tree():
                    yield parent
            else:
                yield source
        yield self

    def transfer_to_other_well(self, destination_well, transfer_volume):
        if self.is_empty:
            raise TransferError("Transfer %s => %s impossible: %s is empty" %
                                (self, destination_well, self))
        factor = float(transfer_volume) / self.volume

        #  pre-check in both source and destination wells that transfers
        #  are valid
        if factor > 1:
            raise TransferError(("Substraction of %.2e L from %s impossible."
                                 " Current volume: %.2e L") %
                                (transfer_volume, self, self.volume))
        final_destination_volume = destination_well.volume + transfer_volume
        if ((destination_well.capacity is not None)
                and (final_destination_volume > destination_well.capacity)):
            raise TransferError(
                "Transfer of %.2e L from %s to %s brings volume over capacity."
                % (transfer_volume, self, destination_well))

        #  If you arrive here, it means that the transfer is valid, do it.
        quantities_transfered = {
            component: quantity * factor
            for component, quantity in self.content.quantities.items()
        }
        destination_well.add_content(quantities_transfered,
                                     volume=transfer_volume)
        self.subtract_content(quantities_transfered, volume=transfer_volume)
        if self not in destination_well.sources:
            destination_well.sources.append(self)

    def add_content(self, components_quantities, volume=None):
        if volume > 0:
            final_volume = self.content.volume + volume
            if (self.capacity is not None) and (final_volume > self.capacity):
                raise TransferError(
                    "Transfer of %.2e L to %s brings volume over capacity." %
                    (volume, self))
            self.content.volume = final_volume
        for component, quantity in components_quantities.items():
            if component not in self.content.quantities:
                self.content.quantities[component] = 0
            self.content.quantities[component] += quantity

    def subtract_content(self, components_quantities, volume=0):
        if volume > 0:
            if volume > self.volume:
                raise TransferError(
                    ("Substraction of %.2e L from %s impossible."
                     " Current volume: %.2e L") % (volume, self, self.volume))
            self.content.volume -= volume
        for component, quantity in components_quantities.items():
            if self.content.quantities[component] == quantity:
                self.content.quantities.pop(component)
            else:
                self.content.quantities[component] -= quantity

    def empty_completely(self):
        self.content.quantities = {}
        self.content.volume = 0

    @property
    def coordinates(self):
        """Return (well.row, well.column)"""
        return (self.row, self.column)

    @property
    def is_empty(self):
        """Return true iff the well's volume is 0"""
        return (self.volume == 0)

    def __repr__(self):
        return "(%s-%s)" % (self.plate.name, self.name)

    def pretty_summary(self):
        data = "\n    ".join([""] + [("%s: %s" % (key, value))
                                     for key, value in self.data.items()])
        content = "\n    ".join(
            [""] + [("%s: %s" % (key, value))
                    for key, value in self.content.quantities.items()])
        return ("{self}\n"
                "  Volume: {self.volume}\n"
                "  Content: {content}\n"
                "  Metadata: {data}").format(self=self,
                                             content=content,
                                             data=data)

    def to_dict(self):
        return dict([
            ["name", self.name],
            ["content", self.content.to_dict()],
            ["row", self.row],
            ["column", self.column],
        ] + list(self.data.items()))

    def index_in_plate(self, direction='row'):
        """Return the index of the well in the plate."""
        return self.plate.wellname_to_index(self.name, direction=direction)

    def is_after(self, other, direction='row'):
        """Return whether this well is located strictly after the other well.
        
        Examples
        --------
        To iterate over all free wells after the last non-free well of a plate:

        >>> direction = 'row'
        >>> last_occupied_well = plate.last_nonempty_well(direction=direction)
        >>> free_wells = (w for w in plate.iter_wells(direction=direction)
        >>>               if w.is_after(last_occupied_well))
        >>> for well in free_wells: ...
        """
        well_index = self.index_in_plate(direction=direction)
        other_index = other.index_in_plate(direction=direction)
        return well_index > other_index

    def __lt__(self, other):
        return str(self) < str(other)
예제 #46
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_camel_killer_hashables(self):
     bx = Box(camel_killer_box=True)
     bx[(1, 2)] = 32
     assert bx == {(1, 2): 32}
예제 #47
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_get_default_box(self):
     bx = Box(default_box=True)
     assert bx.get("test", 4) == 4
     assert isinstance(bx.get("a"), Box)
     assert bx.get("test", None) is None
def validate_properties(props):
    return Box(properties_schema.validate(props), camel_killer_box=True)
예제 #49
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_conversion_dup_only(self):
     with pytest.raises(BoxError):
         Box(movie_data, conversion_box=False, box_duplicates="error")
예제 #50
0
 def request_vars(self):
     return Box(self._request_args)
예제 #51
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_safe_attrs(self):
     assert Box()._safe_attr("BAD!KEY!1") == "BAD_KEY_1"
     assert Box(camel_killer_box=True)._safe_attr("BAD!KEY!2") == "bad_key_2"
     assert Box()._safe_attr((5, 6, 7)) == "x5_6_7"
     assert Box()._safe_attr(356) == "x356"
예제 #52
0
class Map:
    def __init__(self, width, height):
        self.player = Player(2, 2)
        self.box = Box(3, 3)
        self.gate = Gate(4, 4)
        self.width = width
        self.height = height

    def print(self):
        for y in range(self.height):
            for x in range(self.width):
                if self.player.match(x, y):
                    print(self.player.text, end="")
                elif self.box.match(x, y):
                    print(self.box.text, end="")
                elif self.gate.match(x, y):
                    print(self.gate.text, end="")
                else:
                    print("- ", end="")
            print()

    def move_player(self, dx, dy):
        self.player.move(dx, dy)

    def move_box(self, dx, dy):
        self.box.move(dx, dy)

    def in_map(self, x, y):
        if x < 0 or y < 0 or x > self.width - 1 or y > self.height - 1:
            return True
        return False

    def process_input(self, move):
        direction = move.upper()
        dx, dy = 0, 0
        if direction == "W":
            dx, dy = 0, -1
        elif direction == "S":
            dx, dy = 0, 1
        elif direction == "A":
            dx, dy = -1, 0
        elif direction == "D":
            dx, dy = 1, 0

        next_px, next_py = self.player.calc_next(dx, dy)
        if self.in_map(next_px, next_py):
            print("Another direction please! ")
        else:
            next_bx, next_by = self.box.x + dx, self.box.y + dy
            if next_px == self.box.x and next_py == self.box.y:
                if self.in_map(next_bx, next_by):
                    print("Your box is facing wall, another direction please!")
                else:
                    self.player.move(dx, dy)
                    self.box.move(dx, dy)
            else:
                self.player.move(dx, dy)

    def loop(self):
        while True:
            self.print()
            move = input("Your move (A,S,D,W): ")
            self.process_input(move)
            if self.box.x == self.gate.x and self.box.y == self.gate.y:
                print("You win the game, congrats!")
                self.print()
                break
예제 #53
0
 def __init__(self, width, height):
     self.player = Player(2, 2)
     self.box = Box(3, 3)
     self.gate = Gate(4, 4)
     self.width = width
     self.height = height
예제 #54
0
async def test_cloud_hook(
    cloud_hook_id: str,
    flow_run_id: str = None,
    state: prefect.engine.state.State = None,
):
    """
    Sends a test payload to a hook

    Args:
        - cloud_hook_id (str): the hook id
        - flow_run_id (str, optional): a flow run ID to test with. If provided, the event will pull event details
            from the flow run
        - state (State, optional): a sample state
    """

    if state is None:
        state = prefect.engine.state.Success(message="Test success state")
    serialized_state = state.serialize()

    if cloud_hook_id is None:
        raise ValueError("Invalid ID")

    # verify that the hook actually exists
    hook = await models.CloudHook.where(id=cloud_hook_id).first(
        {"type", "config", "tenant_id"}
    )
    if not hook:
        raise ValueError("Invalid ID")

    # if a flow run has been provided, construct an event mirroring the actual event
    # we'd expect to see
    if flow_run_id:
        flow_run = await models.FlowRun.where(id=flow_run_id).first(
            {"id", "tenant_id", "flow_id", "name", "version"}
        )
        new_flow_run = Box(
            id=flow_run.id,
            is_test_event=True,
            tenant_id=flow_run.tenant_id,
            flow_id=flow_run.flow_id,
            name=flow_run.name,
            version=flow_run.version + 1,
            state=type(state).__name__,
            serialized_state=state.serialize(),
        )
        flow = await models.Flow.where(id=flow_run.flow_id).first(
            selection_set={
                "id": True,
                "tenant_id": True,
                "name": True,
                "environment": True,
                "version_group_id": True,
            }
        )

        tenant = await models.Tenant.where(id=flow_run.tenant_id).first({"id", "slug"})

        test_event = events.FlowRunStateChange(
            flow_run=new_flow_run.to_dict(),
            flow=flow.dict(),
            tenant=tenant.dict(),
            state=dict(
                version=1,
                state=serialized_state["type"],
                serialized_state=serialized_state,
            ),
        )
    # otherwise populate the event with dummy data
    else:
        test_event = events.FlowRunStateChange(
            is_test_event=True,
            flow_run=dict(id=str(uuid.uuid4()), name=names.generate_slug(2)),
            tenant=dict(id=hook.tenant_id, slug="test-slug"),
            flow=dict(id=str(uuid.uuid4()), name="Cloud Hook Test Flow"),
            state=dict(
                version=1,
                state=serialized_state["type"],
                serialized_state=serialized_state,
            ),
        )

    if hook.type == "WEBHOOK":
        await _call_webhook(url=hook.config["url"], event=test_event)
    elif hook.type == "SLACK_WEBHOOK":
        await _call_slack_webhook(url=hook.config["url"], event=test_event)
    elif hook.type == "PREFECT_MESSAGE":
        await _call_prefect_message(event=test_event)
    elif hook.type == "TWILIO":
        await _call_twilio(
            account_sid=hook.config["account_sid"],
            auth_token=hook.config["auth_token"],
            messaging_service_sid=hook.config["messaging_service_sid"],
            to=hook.config["to"],
            event=test_event,
        )
    elif hook.type == "PAGERDUTY":
        await _call_pagerduty(
            api_token=hook.config["api_token"],
            routing_key=hook.config["routing_key"],
            severity=hook.config["severity"],
            event=test_event,
        )
    else:
        raise ValueError("Invalid type")
예제 #55
0
파일: Well.py 프로젝트: pk-organics/Plateo
 def __init__(self, quantities=None, volume=0):
     if quantities is None:
         quantities = {}
     self.volume = volume
     self.quantities = Box(quantities)
예제 #56
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_pop(self):
     bx = Box(a=4, c={"d": 3}, sub_box=Box(test=1))
     assert bx.pop("a") == 4
     with pytest.raises(BoxKeyError):
         bx.pop("b")
     assert bx.pop("a", None) is None
     assert bx.pop("a", True) is True
     with pytest.raises(BoxError):
         bx.pop(1, 2, 3)
     bx.pop("sub_box").pop("test")
     assert bx == {"c": {"d": 3}}
     assert bx.pop("c", True) is not True
예제 #57
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_or_boxes(self):
     b = Box(c=1, d={"sub": 1}, e=1)
     c = dict(d={"val": 2}, e=4)
     assert b | c == Box(c=1, d={"val": 2}, e=4)
     with pytest.raises(BoxError):
         Box() | BoxList()
예제 #58
0
파일: Well.py 프로젝트: pk-organics/Plateo
 def make_empty(self):
     self.volume = 0
     self.quantities = Box({})
예제 #59
0
파일: test.py 프로젝트: pombredanne/box
#!/usr/bin/env python

from box import Box, Item

# create new box

# create new version
b = Box('/tmp/foo')
v = b.addVersion()

# add new item to version and save
i = Item.from_path(b, '/Users/rsgalloway/Desktop/snow.jpg')
v.addItems([i])
print v.items()
print v.tree
v.save('teesting add version, adding snow.jpg')
print v.tree
print b.items()
print v.versions(-1).tree

# inherit items from parents

예제 #60
0
파일: test_box.py 프로젝트: philipsd6/Box
 def test_type_recast(self):
     b = Box(id="6", box_recast={"id": int})
     assert isinstance(b.id, int)
     with pytest.raises(ValueError):
         b["sub_box"] = {"id": "bad_id"}