Beispiel #1
0
 def Start(self):
   """Start the HTTP server."""
   if FLAGS.http_port:
     self.server = rocket.Rocket(interfaces=('0.0.0.0', FLAGS.http_port),
                                 method='wsgi',
                                 app_info={'wsgi_app': self.app})
     self.server.start(background=True)
Beispiel #2
0
    def Start(self):
        F9FT=R.Rocket()
        axA=self.AccelerationFigure.subplots()
        axA.grid()
        axA.set_title("Acceleration")
        axA.set_xlabel("seconds")
        axA.set_ylabel("m/s^2")
        
        axA.set_xlim(0,F9FT._Rocket__FirstStageTime+F9FT._Rocket__SecondStageTime+10)
        axA.set_ylim(-10,40)
        lineA=C.Functions.Acceleration(F9FT,self.AccelerationFigure,axA)
        
        self.canvasA.draw()
       

        axV=self.VelocityFigure.subplots()    
        axV.grid()
        axV.set_title("Velocity")
        axV.set_xlabel("seconds")
        axV.set_ylabel("km/h")
        axV.set_xlim(0,F9FT._Rocket__FirstStageTime+F9FT._Rocket__SecondStageTime+10)
        axV.set_ylim(0,20000)
        lineV=C.Functions.Velocity(F9FT,self.VelocityFigure,axV)
    
        
        self.canvasV.draw()

        C.Functions.FirstStagePlot(F9FT)
        C.Functions.SecondStagePlot(F9FT)
        C.Functions.VelocityPlot(F9FT)
    def __init__(self):
        self.running = True
        self.settings = settings.Settings()
        self.WIDTH = self.settings.WIDTH
        self.HEIGHT = self.settings.HEIGHT
        self.red = 58
        self.green = 177
        self.blue = 255
        self.bg_color = (self.red, self.green, self.blue)
        # self.bg_color = self.settings.bg_color

        # initialize screen
        self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
        pygame.display.set_caption("Demo2 Launch")
        self.screen_rect = self.screen.get_rect()
        self.stars = star.pygame.sprite.Group()
        self.create_stars()
        # create Clouds
        self.cloud_group = pygame.sprite.Group()
        self.create_clouds()
        # create Rocket
        self.rocket = rocket.Rocket(self)
        # create exhaust
        self.exhaust_group = pygame.sprite.Group()
        self.create_exhaust()
        # create tower
        self.tower = launch_pad.LaunchPad(self)
        # fps
        self.FPS = 60
        self.clock = pygame.time.Clock()
Beispiel #4
0
def start_the_game():
    clock = pygame.time.Clock()
    score = Score(display)
    rocketa = hero.Hero()
    # enemy = rocket.Rocket(rocketa, display, 1000, 700)
    # enemy2 = rocket.Rocket(rocketa, display, 100, 100)
    coin = bonus.Bonus(display, rocketa, 10)
    coin_list = []
    enemy_list = []
    coin_counter = 0
    time_start = pygame.time.get_ticks()
    run = True
    while run:

        if pygame.time.get_ticks() % 1500 == 0:
            enemy_list.append(
                rocket.Rocket(rocketa, display,
                              random.randint(-200, const.width_display + 50),
                              random.randint(-200, const.height_display + 50)))
        clock.tick(const.FPS)

        rocketa.change_xy()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        keys = pygame.key.get_pressed()

        display.blit(const.bg, (0, 0))

        if keys[pygame.K_LEFT]:
            rocketa.go_left()
            rocketa.rotate_left()
        elif keys[pygame.K_RIGHT]:
            rocketa.go_right()
            rocketa.rotate_right()
        else:
            rocketa.rect()

        if keys[pygame.K_ESCAPE]:
            menu.Pause()

        if coin.check():
            coin_counter += 1

        # enemy.is_collision()
        # enemy2.is_collision()
        for i in enemy_list:
            i.enemy_change_xy()
            i.is_collision()

        coin.update()

        score.score_update(coin_counter)

        # enemy.enemy_change_xy()
        # enemy2.enemy_change_xy()

        pygame.display.flip()
Beispiel #5
0
def run_game():
    pygame.init()
    screen = pygame.display.set_mode((1200, 800))
    pygame.display.set_caption("Rocket or idk")

    rocket_0 = rocket.Rocket(screen)

    while True:
        gf.check_events(rocket_0)
        rocket_0.update()
        gf.update_screen(screen, rocket_0)
    def selection(self):
        newRockets = []
        for i in range(0, len(self.rockets)):
            parentA = self.matingpool[np.random.randint(len(
                self.matingpool))].dna
            parentB = self.matingpool[np.random.randint(len(
                self.matingpool))].dna
            child = parentA.crossover(parentB)
            child.mutation()
            newRockets.append(R.Rocket(self.info, dna=child))

        self.rockets = newRockets
Beispiel #7
0
def gen():

    # starting values, real numbers for an N2501 motor
    isp = 179  # s
    thrust = 2510  # N
    impulse = 15280  # N*s
    CD = 0.6

    # Randomize
    isp = random.gauss(isp, isp * 0.03)  # 3% spread
    thrust = random.gauss(thrust, thrust * 0.10)  # 10% spread
    impulse = random.uniform(impulse - 200, impulse + 200)  # +/- 200 N*s
    cd_avg = random.gauss(0.6, 0.1)  # ~16% spread

    r = rocket.Rocket(isp, thrust, impulse, [cd_avg])
    return r.rocket
 def test_trajectory(self):
     """Checks if the rocket can follow the trajectory."""
     P = read_table("rocket_trajectory.txt")
     P0 = P[0]
     F = rocket.Rocket(Vect(P0[1], P0[2]), Vect(0, 0), Vect(0, 0))
     maxerr = 0.0
     for P1 in P[1:]:
         t, x, y = P1
         # ...
         dt = t - P0[0]
         pos = Vect(x, y)
         F.simule(pos, dt)
         lasterr = (F.X - pos).abs()
         if lasterr > maxerr:
             maxerr = lasterr
         P0 = P1
     self.assertLess(lasterr, ERRORLAST)
     self.assertLess(maxerr, ERRORMAX)
 def test_thrust(self):
     """Checks if the rocket can compute the correct thrust."""
     P = read_table("rocket_thrust.txt")
     P0 = P[0]
     F = rocket.Rocket(Vect(P0[1], P0[2]), Vect(0, 0), Vect(0, 0))
     maxerr = 0.0
     for P1 in P[1:]:
         t, x, y, px, py = P1
         # ...
         dt = t - P0[0]
         pos = Vect(x, y)
         F.simule(pos, dt)
         thrust = Vect(px, py)
         lasterr = (F.P - thrust).abs() / F.P.abs()
         if lasterr > maxerr:
             maxerr = lasterr
         P0 = P1
     self.assertLess(lasterr, ERRORLAST)
     self.assertLess(maxerr, ERRORMAX)
Beispiel #10
0
def main():
    modes = 2

    t_span = [0, 500]
    xy = [0, 0]
    V = 0.0
    mu = 0
    Theta = 90

    M_warhead, M_control = 500, 50
    M_useful = M_warhead + M_control
    M = [M_warhead, M_control, M_useful]

    icx = 1.5

    I_10, p00 = [2700, 2400], [7e6, 5e6]
    p_out = 7e4
    k = 1.2

    eta = [5, 3]
    beta = 1.3
    q_m = 70000
    ny = 30
    lamL = 18
    Dmax = 500
    mu_max = 0.65

    t_start = 30
    H_max = 80

    s_conds = Rocket.StartConds(xy, V, mu, Theta)
    params = Rocket.Params(icx, M, eta, beta, q_m, ny, lamL, Dmax, mu_max)
    engine = Rocket.Engine(I_10, p00, p_out, k)
    rocket = Rocket.Rocket(modes, s_conds, params, engine, t_start, H_max)
    world = World.ModelWorld(t_span, rocket)

    world.show_atmosphere()
    print(world)

    world.calc_trajectory()
    world.show_trajectory()
Beispiel #11
0
    def store_globals(self):
        """We store references to some things here that are needed all
        over the game."""

        # number of levels
        self.numlevels = len(leveldata.ALLDATA)

        # the main sprites
        self.moon = moon.Moon(self)
        self.rocket = rocket.Rocket(self)
        self.pbar = powerbar.Powerbar(self)
        self.gbar = gravitybar.Gravitybar(self)

        # text 'gravity' and 'power' for status bars are stored as
        # additional sprites
        self.pbartext = fontsprite.FontSprite(self.barfont, 'power',
                                              fontsprite.PBARLOC)
        self.gbartext = fontsprite.FontSprite(self.barfont, 'gravity',
                                              fontsprite.GBARLOC)

        # some states needed by many objects
        self.hitmoon = False
        self.rktdead = False  # dead if gone off-screen
        self.hitasteroid = False

        # number of rockets destroyed so far in game
        self.numdestroyed = 0
        self.destroyedtext = fontsprite.FontSprite(self.destfont,
                                                   '{0}{1}'.format\
                                                   (fontsprite.DTEXT,0),
                                                   fontsprite.DESTLOC)

        # collision functions
        # rocket with asteroids (scaled rect collision)
        self.collide_roid = pygame.sprite.collide_rect_ratio(Game.\
                                                               CRECTROID)
        # rocket with moon ('pixel perfect' collision)
        self.collide_moon = pygame.sprite.collide_mask

        # scroller handles moving screen and sprites etc
        self.scroller = scrolling.Scroller(self)
Beispiel #12
0
def main():
    initial_state = {
        "xpos": 0,
        "ypos": 0,
        "zpos": 0,
        "xvel": 0,
        "yvel": 0,
        "zvel": 0,
        "xacc": 0,
        "yacc": 0,
        "zacc": 0,
        "theta_roll": 0,
        "theta_pitch": 0,
        "theta_yaw": 0,
        "omega_roll": 0,
        "omega_pitch": 0,
        "omega_yaw": 0,
        "alpha_roll": 0,
        "alpha_pitch": 0,
        "alpha_yaw": 0,
        "time": 0,
    }
    vehicle_state = st.State(initial_state)

    # TODO add some sort of environment class

    # make the rocket object for position referencing
    vehicle = ro.Rocket(vehicle_state)
    # generate the structural components
    structure = co.Component(10, [.1, 0, 0], "structure")
    structure1 = co.Component(10, [.1, 0, 0], "structure1")
    structure2 = co.Component(10, [.1, 0, 0], "structure2")
    structure3 = co.Component(10, [.1, 0, 0], "structure3")
    vehicle.add_components(structure, structure1, structure2, structure3)
    sensor1 = co.Sensor('accel', [0, 10], structure2)
    vehicle.add_components(sensor1)
    print(vehicle.get_components())
    print(vehicle.get_state()['xpos'])
Beispiel #13
0
def main():
    args = parse_args()
    dataset_name = args.dataset_name

    test_df = np.genfromtxt(
        f"{args.datasets_root}/{dataset_name}/{dataset_name}_TEST",
        delimiter=',')
    train_df = np.genfromtxt(
        f"{args.datasets_root}/{dataset_name}/{dataset_name}_TRAIN",
        delimiter=',')

    X_train, y_train = train_df[:, 1:], train_df[:, 0]
    X_test, y_test = test_df[:, 1:], test_df[:, 0]

    ts_length = X_train.shape[-1]

    classifier = RidgeClassifier(normalize=True)
    r = rocket.Rocket(input_length=ts_length, classifier=classifier)

    r.fit(X_train, y_train)

    accuracy = r.score(X_test, y_test)

    print(f"Dataset {dataset_name}, Test accuracy: {accuracy}")
Beispiel #14
0
    def __init__(
        self,
        ip='127.0.0.1',
        port=8000,
        password='',
        pid_filename='httpserver.pid',
        log_filename='httpserver.log',
        profiler_filename=None,
        ssl_certificate=None,
        ssl_private_key=None,
        ssl_ca_certificate=None,
        min_threads=None,
        max_threads=None,
        server_name=None,
        request_queue_size=5,
        timeout=10,
        socket_timeout=1,
        shutdown_timeout=None,  # Rocket does not use a shutdown timeout
        path=None,
        interfaces=None  # Rocket is able to use several interfaces - must be list of socket-tuples as string
    ):
        """
        starts the web server.
        """

        if interfaces:
            # if interfaces is specified, it must be tested for rocket parameter correctness
            # not necessarily completely tested (e.g. content of tuples or ip-format)
            import types
            if isinstance(interfaces, types.ListType):
                for i in interfaces:
                    if not isinstance(i, types.TupleType):
                        raise "Wrong format for rocket interfaces parameter - see http://packages.python.org/rocket/"
            else:
                raise "Wrong format for rocket interfaces parameter - see http://packages.python.org/rocket/"

        if path:
            # if a path is specified change the global variables so that web2py
            # runs from there instead of cwd or os.environ['web2py_path']
            global web2py_path
            path = os.path.normpath(path)
            web2py_path = path
            global_settings.applications_parent = path
            os.chdir(path)
            [add_path_first(p) for p in (path, abspath('site-packages'), "")]
            if exists("logging.conf"):
                logging.config.fileConfig("logging.conf")

        save_password(password, port)
        self.pid_filename = pid_filename
        if not server_name:
            server_name = socket.gethostname()
        logger.info('starting web server...')
        rocket.SERVER_NAME = server_name
        rocket.SOCKET_TIMEOUT = socket_timeout
        sock_list = [ip, port]
        if not ssl_certificate or not ssl_private_key:
            logger.info('SSL is off')
        elif not rocket.ssl:
            logger.warning('Python "ssl" module unavailable. SSL is OFF')
        elif not exists(ssl_certificate):
            logger.warning('unable to open SSL certificate. SSL is OFF')
        elif not exists(ssl_private_key):
            logger.warning('unable to open SSL private key. SSL is OFF')
        else:
            sock_list.extend([ssl_private_key, ssl_certificate])
            if ssl_ca_certificate:
                sock_list.append(ssl_ca_certificate)

            logger.info('SSL is ON')
        app_info = {
            'wsgi_app': appfactory(wsgibase, log_filename, profiler_filename)
        }

        self.server = rocket.Rocket(
            interfaces or tuple(sock_list),
            method='wsgi',
            app_info=app_info,
            min_threads=min_threads,
            max_threads=max_threads,
            queue_size=int(request_queue_size),
            timeout=int(timeout),
            handle_signals=False,
        )
Beispiel #15
0
import sys
import unittest
import numpy as np
sys.path.append('D:\\6dof_rocket_sim\sim')
import rocket as ro
import components as co

#class TestRocket(unittest.TestCase):

land_shark = ro.Rocket({'xpos': 0})
#fin1 = co.Component(10, [0,1,0], 'fin1')
#fin2 = co.Component(10, [0,1,0], 'fin2')
#fin3 = co.Component(10, [0,1,0], 'fin3')
#fin4 = co.Component(10, [0,1,0], 'fin4')
airframe = co.Cylinder(10, [1, 1, 1], 'airframe', .1, 10)
#print(airframe.get_inertia_tensor()[0,0])
#print(airframe.mass*(airframe.get_pos()[1]**2 + airframe.get_pos()[2]**2))
land_shark.add_components(airframe)
#print(land_shark.get_components())
#print(land_shark.get_mass())
np.set_printoptions(precision=2)
print(type(land_shark.get_inertia_tensor()[0, 0]))
print(land_shark.get_inertia_tensor())
 def __init__(self, INFO):
     self.info = INFO
     self.popsize = 10
     self.rockets = [R.Rocket(self.info) for i in range(0, self.popsize)]
     self.matingpool = []
Beispiel #17
0
        
class labelledEntry(tk.Tk):
    def __init__(self,root,label:str):
        self.container = ttk.Frame(root)
        self.label = ttk.Label(self.container,text=label)
        self.entry = ttk.Entry(self.container)
        self.label.grid(row=0, column=0)
        self.entry.grid(row=0, column=1)
with open("../cfg/theme.json") as f: #themeing file for the gui
    cfg = json.load(f)
rock = rocket.Rocket('test/test.json',
                     [
                        rocket.fileParent('Rocket'),
                        rocket.tube('alex',24.3,62.3,57.3,0.2),
                        rocket.tube('jon',32,56,89,0.2),
                        rocket.tube('a',43,56,9,0.2),
                            rocket.tube('b',34,25,8.,0.2,'a'),
                            rocket.tube('c',23,10,7,0.2,'a'), #the part in {} is a set, the rest is tuple
                        rocket.motor('m',40,24,56,40,{}),
                        rocket.nosecone('nose',0,24,16,True,10)
                     ]
                     )
rock.SaveJson('test.json')
#rock = rocket.loadJsontoObject('test.json')
#print(rock.parts)
# creating main tkinter window/toplevel 
root = tk.Tk() #main window root
root.title('LibreRocket V0')
#root.iconbitmap('../img/icon.ico') #TODO make icon
eh.initsavefile(rock)
partdialogs.initdialogs(root)
partdialogs.inittree(rock.parts)
Beispiel #18
0
# Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0)
purple = (255, 0, 255)

# Asteroids
ast_list = [asteroid.Asteroid(200, window_width), asteroid.Asteroid(550, window_width),
            asteroid.Asteroid(900, window_width), asteroid.Asteroid(1250, window_width),
            asteroid.Asteroid(1600, window_width)]

# Rocket
rocket_ = rocket.Rocket(window_width * 0.44, window_height * 0.7, car_width, car_width)

music = media.music_load()
pygame.mixer.music.set_volume(.4)
pygame.mixer.music.play(-1)


# ----------------------------------------------------------

def rocket(exploded):
    screen.blit(rocket_.sprite, (rocket_.x, rocket_.y))
    if exploded:
        explosion()


def asteroid():
Beispiel #19
0
def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument('-p',
                        '--port',
                        type=int,
                        action='store',
                        dest='port',
                        default=9007,
                        required=False,
                        help='set port number')
    parser.add_argument('-i',
                        '--ip',
                        type=str,
                        action='store',
                        dest='ip',
                        default='127.0.0.1',
                        required=False,
                        help='set ip address')
    parser.add_argument('-t',
                        '--tokenfile',
                        type=str,
                        action='store',
                        dest='tokenfile',
                        default=expanduser('~') + '/.localslackirc',
                        required=False,
                        help='set the token file')
    parser.add_argument('-u',
                        '--nouserlist',
                        action='store_true',
                        dest='nouserlist',
                        required=False,
                        help='don\'t display userlist')
    parser.add_argument('-j',
                        '--autojoin',
                        action='store_true',
                        dest='autojoin',
                        required=False,
                        help="Automatically join all remote channels")
    parser.add_argument(
        '-o',
        '--override',
        action='store_true',
        dest='overridelocalip',
        required=False,
        help='allow non 127. addresses, this is potentially dangerous')
    parser.add_argument(
        '--rc-url',
        type=str,
        action='store',
        dest='rc_url',
        default=None,
        required=False,
        help=
        'The rocketchat URL. Setting this changes the mode from slack to rocketchat'
    )

    args = parser.parse_args()
    # Exit if their chosden ip isn't local. User can override with -o if they so dare
    if not args.ip.startswith('127') and not args.overridelocalip:
        exit('supplied ip isn\'t local\nlocalslackirc has no encryption or ' \
                'authentication, it\'s recommended to only allow local connections\n' \
                'you can override this with -o')

    if 'PORT' in environ:
        port = int(environ['PORT'])
    else:
        port = args.port

    if 'TOKEN' in environ:
        token = environ['TOKEN']
    else:
        try:
            with open(args.tokenfile) as f:
                token = f.readline().strip()
        except (FileNotFoundError, PermissionError):
            exit(f'Unable to open the token file {args.tokenfile}')

    if args.rc_url:
        sl_client = rocket.Rocket(
            args.rc_url, token)  # type: Union[slack.Slack, rocket.Rocket]
        provider = Provider.ROCKETCHAT
    else:
        sl_client = slack.Slack(token)
        provider = Provider.SLACK
    sl_events = sl_client.events_iter()
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversocket.bind((args.ip, port))
    serversocket.listen(1)

    poller = select.poll()

    while True:
        s, _ = serversocket.accept()
        ircclient = Client(s, sl_client, args.nouserlist, args.autojoin,
                           provider)

        poller.register(s.fileno(), select.POLLIN)
        if sl_client.fileno is not None:
            poller.register(sl_client.fileno, select.POLLIN)

        # Main loop
        timeout = 2
        while True:
            s_event = poller.poll(timeout)  # type: List[Tuple[int,int]]
            sl_event = next(sl_events)

            if s_event:
                text = s.recv(1024)
                if len(text) == 0:
                    break
                #FIXME handle the case when there is more to be read
                for i in text.split(b'\n')[:-1]:
                    i = i.strip()
                    if i:
                        ircclient.command(i)

            while sl_event:
                print(sl_event)
                ircclient.slack_event(sl_event)
                sl_event = next(sl_events)
Beispiel #20
0
# -*- coding: utf-8 -*-
"""
Created on Wed Apr  4 13:44:20 2018

@author: Rizqi Okta E
"""

import rocket as r

my_rocket = r.Rocket(1, 2)
print(my_rocket.y)
my_rocket.move_rocket(y_increment=2)
print(my_rocket.y)
def __init__rocket(rocket_params):
    '''Initializes Rocket object based on input parameters (see Rocket class for explication of parameters).'''
    Rocket=rocket.Rocket(*rocket_params)
    return Rocket
Beispiel #22
0
gray = (50, 50, 50)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
yellow = (255, 255, 0)

# sprite pixel format converting
for convert_sprites in sprites.all_sprites:
    convert_sprites.convert_alpha()

# framerate
clock = pygame.time.Clock()
FPS = 30

# player variables
player = rocket.Rocket(100, display_height / 2 - 40)
moving = True
godmode = False

# score variables
score = 0
highscore_file = open('highscore.dat', "r")
highscore_int = int(highscore_file.read())

# enemy rocket variables
enemy_ufo = enemy_ufo.EnemyUfo(-200, display_height / 2 - 40)
enemy_ufo_alive = False

# alien variables
alien = alien.Alien(-200, 400)
alien_alive = False
Beispiel #23
0
    def __init__(
        self,
        ip='127.0.0.1',
        port=8000,
        password='',
        pid_filename='httpserver.pid',
        log_filename='httpserver.log',
        profiler_filename=None,
        ssl_certificate=None,
        ssl_private_key=None,
        numthreads=10,
        server_name=None,
        request_queue_size=5,
        timeout=10,
        shutdown_timeout=None,  # Rocket does not use a shutdown timeout
        path=None,
        interfaces=None  # Rocket is able to use several interfaces - must be list of socket-tuples as string 
    ):
        """
        starts the web server.
        """

        if interfaces:
            # if interfaces is specified, it must be tested for rocket parameter correctness
            # not necessarily completely tested (e.g. content of tuples or ip-format)
            import types
            if isinstance(interfaces, types.ListType):
                for i in interfaces:
                    if not isinstance(i, types.TupleType):
                        raise "Wrong format for rocket interfaces parameter - see http://packages.python.org/rocket/"
            else:
                raise "Wrong format for rocket interfaces parameter - see http://packages.python.org/rocket/"

        if path:
            # if a path is specified change the global variables so that web2py
            # runs from there instead of cwd or os.environ['web2py_path']
            global web2py_path
            path = os.path.normpath(path)
            web2py_path = path
            os.chdir(web2py_path)

            try:
                sys.path.remove(path)
            except ValueError:
                pass
            sys.path.insert(0, path)
            try:
                sys.path.remove(os.path.join(path, 'site-packages'))
            except ValueError:
                pass
            sys.path.insert(0, os.path.join(path, 'site-packages'))
            try:
                sys.path.remove("")
            except ValueError:
                pass
            sys.path.insert(0, "")

        save_password(password, port)
        self.pid_filename = pid_filename
        if not server_name:
            server_name = socket.gethostname()
        logger.info('starting web server...')
        rocket.SERVER_NAME = server_name
        sock_list = [ip, port]
        if not ssl_certificate or not ssl_private_key:
            logger.info('SSL is off')
        elif not rocket.ssl:
            logger.warning('Python "ssl" module unavailable. SSL is OFF')
        if not ssl_certificate or not ssl_private_key:
            logger.info('SSL is off')
        elif not rocket.ssl:
            logger.warning('Python "ssl" module unavailable. SSL is OFF')
        elif not os.path.exists(ssl_certificate):
            logger.warning('unable to open SSL certificate. SSL is OFF')
        elif not os.path.exists(ssl_private_key):
            logger.warning('unable to open SSL private key. SSL is OFF')
        else:
            sock_list.extend([ssl_private_key, ssl_certificate])
            logger.info('SSL is ON')
        app_info = {
            'wsgi_app': appfactory(wsgibase, log_filename, profiler_filename)
        }

        if not interfaces:
            self.server = rocket.Rocket(
                tuple(sock_list),
                'wsgi',
                app_info,
                min_threads=int(numthreads),
                queue_size=int(request_queue_size),
                timeout=int(timeout),
                no_sigterm=True,
            )
        else:
            self.server = rocket.Rocket(
                interfaces,
                'wsgi',
                app_info,
                min_threads=int(numthreads),
                queue_size=int(request_queue_size),
                timeout=int(timeout),
                no_sigterm=True,
            )
Beispiel #24
0
 def shoot(self):
     shoot_sound.play()
     r = rocket.Rocket(self.rect.centerx, self.rect.centery, self.angle)
     rockets.add(r)
     all_sprites.add(r)
Beispiel #25
0
import matplotlib.pyplot as plt
import numpy as np
import math, rocket, planets

fire = rocket.Rocket(
    31,
    90,
    time_step=0.0625,
    altitude=22000,
    propellant_mass_fraction=0.80,
    mixture_ratio=7.4,
    tank_pressure=7e6,
    tank_safety_factor=1.2
)  # Initialize your rocket with design parameters and starting conditions
initial_mass = fire.vehicle.mass.total
fire.calc(150)  # Method's parameter is the length of simulation in seconds
final_mass = fire.vehicle.mass.total
exhaust_velocity = fire.engine.exhaust_velocity

Theorectical_Delta_V = exhaust_velocity * math.log(initial_mass / final_mass)
Model_Delta_V = fire.log[-1][2]

print('Theorectical Delta-V: ' + str(Theorectical_Delta_V) + ' m/s')
print('Model Delta-V: ' + str(Model_Delta_V) + ' m/s')
relative_error = (math.fabs(Theorectical_Delta_V - Model_Delta_V) /
                  Theorectical_Delta_V) * 100
print('Relative Error: ' + str(round(relative_error, 4)) + '%')
Beispiel #26
0
import rocket as space_module
from random import randint

rocket_names = [['01', 'john'], ['02', 'op'], ['03', 'black'], ['04', 'jack'],
                ['05', 'smith']]

rockets = [space_module.Rocket(el[0], el[1]) for el in rocket_names]
for x in range(len(rockets)):
    horiz = randint(-50, 50)
    vert = randint(1, 100)
    rockets[x].moving(horiz, vert)
    print(rockets[x].name)

shuttles = [
    space_module.Shuttle(el[0], el[1], 0, 0, randint(0, 10))
    for el in rocket_names
]
for sh in shuttles:
    x = randint(-50, 50)
    y = randint(0, 100)
    sh.moving(x, y)
    print(sh.flights)
    print(sh.x)
Beispiel #27
0
# -*- coding: utf-8 -*-
import code, datetime, time, rocket, utils, os
from random import shuffle

data = []
with open('/scan/.scan') as f:
    for r in f.read().split('\n'):
        try:
            u, *c = r.split(' ')
            if u:
                c = [float(v) for v in c]
                data.append((u, c))
        except:
            pass
while True:
    shuffle(data)
    for u, c in data:
        R = rocket.Rocket(u)
        i = j = 0
        for g in R.gyms(c)['gyms']:
            if g.get('raid_end', False):
                if utils.save_event(g):
                    i += 1
                else:
                    j += 1
        for p in R.pokemons(c)['pokemons']:
            if utils.save_event(p):
                i += 1
            else:
                j += 1
    time.sleep(10)
Beispiel #28
0
def main(argv):
    """Start the frontend."""
    try:
        argv = FLAGS(argv)  # parse flags
    except gflags.FlagsError, exception:
        print('%s\\nUsage: %s ARGS\\n%s' % (exception, sys.argv[0], FLAGS),
              file=sys.stderr)
        sys.exit(1)

    if not os.path.isdir(FLAGS.rundir):
        print('ERROR: OpenHTF Run directory does not exist',
              FLAGS.rundir,
              file=sys.stderr)
        sys.exit(1)

    manager = stations.StationManager()
    openhtf_app = app.InitializeApp(manager)

    logging.getLogger('Rocket').setLevel(
        logging.INFO)  # Make Rocket less chatty
    rocket_server = rocket.Rocket(interfaces=('0.0.0.0', FLAGS.port),
                                  method='wsgi',
                                  app_info={'wsgi_app': openhtf_app})
    print('Starting server at http://localhost:%d' % FLAGS.port)
    rocket_server.start()


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    main(sys.argv)
Beispiel #29
0
Vtref = np.load(model_path + "/Goddard_ReferenceTrajectory/Vt.npy")
mref = np.load(model_path + "/Goddard_ReferenceTrajectory/m.npy")
Ttref = np.load(model_path + "/Goddard_ReferenceTrajectory/Tt.npy")
Trref = np.load(model_path + "/Goddard_ReferenceTrajectory/Tr.npy")

Rfun = PchipInterpolator(tref, Rref)
Thetafun = PchipInterpolator(tref, Thetaref)
Vrfun = PchipInterpolator(tref, Vrref)
Vtfun = PchipInterpolator(tref, Vtref)
mfun = PchipInterpolator(tref, mref)
Ttfun = PchipInterpolator(tref, Ttref)
Trfun = PchipInterpolator(tref, Trref)

Nstates = 5
Ncontrols = 2
obj = vehicle.Rocket()

################################ M A I N ###############################################


def initPOP1():
    global old_hof
    # this function outputs the first n individuals of the hall of fame of the first GP run
    res = old_hof.shuffle()
    # for i in range(10):
    #   res.append(hof[0])
    return res


def main(size_pop, size_gen, Mu, cxpb, mutpb, init_cond, rho_newmodel):
Beispiel #30
0
]  # The individual's stage wet mass
stage_propellant_mass_fractions = [
    stage_propellant_masses[i] / total_masses_by_section[i]
    for i in range(0, 3)
]  # Propellant mass / initial mass

# Stage 1
# INCLUDE TAGENTIAL VELOCITY
print(tan_velocity)
stage = 1
stage1 = rocket.Rocket(
    total_masses_by_section[stage - 1],
    burn_time[stage - 1],
    start_time=start_time,
    altitude=altitude,
    velocity_tangential=tan_velocity,
    velocity_radial=0,
    propellant_mass_fraction=stage_propellant_mass_fractions[stage - 1],
    mixture_ratio=7.4,
    tank_pressure=7e6,
    tank_safety_factor=1.2,
    angle=angle[stage - 1])
stage1.calc(burn_time[stage - 1])
altitude = stage1.log[-1][1]  # Altitude, meters
rad_velocity = stage1.log[-1][2]  # Radial velocity, m/s
tan_velocity = stage1.log[-1][8] - (Earth.velocity_angular *
                                    (Earth.radius + altitude_start)
                                    )  # Tangential velocity, m/s
start_time += burn_time[stage - 1]

# Stage 2
print(tan_velocity)