Esempio n. 1
0
 async def testing(self,
                   ctx):  # idk why this function is called 'testing()'
     user = self.bot.get_user(self.bot.owner_id)  # just get my name
     x = open(
         'times.csv')  # get ping avarage that s the next 15 lines or so
     xx = csv.reader(x)
     xxx = list(xx)
     all_times = 0
     for x in xxx:
         c = []
         c.append(x[0])
         c[0] = int(c[0])
         all_times += c[0]
     time = all_times / len(xxx)
     time = str(time)
     time = list(time)
     for i in range(len(time) - 4):
         time.pop()
     _time = ''.join(time)
     embed = discord.Embed(title='',
                           color=0x000000)  # the info embed so yeah
     url = self.bot.user.avatar_url
     user = self.bot.get_user(665674407611727915)
     embed.set_author(name=user.name, icon_url=url)
     embed.set_thumbnail(url=url)
     users = 0
     for guild in self.bot.guilds:
         users += len(guild.members)
     commands = 0
     for command in self.bot.commands:
         commands += 1
     lat = self.bot.latency * 1000
     l = int(lat)
     l = truncate(l, 2)
     lat = str(l)  # lots of fields
     embed.add_field(
         name='__Stats__',
         value=
         '**Avg ping time:** {}ms\n**Websocket latency:** {}ms\n**Num of guilds:** {}\n**Users:** {}\n**Commands:** {}\n**Cooldown:** 5s'
         .format(_time, lat, len(self.bot.guilds), users, commands),
         inline=True)
     embed.add_field(
         name='__Code__',
         value=
         '**discord.py version:** {}\n**Lines:** >720\n**Files:** >15\n**Cogs:** {}\n**Functions:** >47'
         .format(discord.__version__, len(self.bot.cogs)),
         inline=True)
     embed.add_field(name='__Created by:__', value=user, inline=False)
     embed.add_field(
         name='Links:',
         value=
         '[**invite**](https://discordapp.com/api/oauth2/authorize?client_id=665674407611727915&permissions=8&scope=bot)  **|** [**source**](https://github.com/insert-ctrl/discord-utils-src)',
         inline=False)
     embed.set_footer(
         text='ID: {} | Made by {} | Made using repl.it | Playing uthelp'.
         format(self.bot.user.id, user))
     sended = await ctx.send(embed=embed)
     await sended.add_reaction(emoji='\U0001f44d')
     await sended.add_reaction(emoji='\U0001f44e')
     await sended.add_reaction(emoji='\U00002699')
def animate(i):

    global count

    if (arduinoSerialData.inWaiting() >
            0):  #Check if data is on the serial port
        new_data_as_string = arduinoSerialData.readline()
        new_data_string = new_data_as_string.strip()
        if (new_data_string != ''):
            new_data = float(new_data_string)

            count += 0.1
            distances.append(new_data)
            time.append(count)

    #time = range(0,len(count))
    #time = range(0,100)

    ax1.clear()
    ax1.plot(time, distances)
    ax1.set(
        xlabel='Time (seconds)',
        ylabel='Distance (mm)',
        title='Single distance measured by VL53L1X sensor(update rate: 50 Hz)')
    if (len(distances) > 100):
        distances.pop(0)
        time.pop(0)
Esempio n. 3
0
async def end(ctx, *, msg=None):
    logging_channel = bot.get_channel(626495610261864468)
    time = list(str(datetime.datetime.now()))
    for x in range(10):
        time.pop()
    time = "".join(time)
    length = tLen()
    if length[0] == False:
        await ctx.send(length[1])
    elif length[0] == True and length[1] < 1:
        await ctx.send(
            'Looks like there aren\'t any topics yet. ``.add [topic]``')
    elif length[0] == True and length[1] > 0:
        printlist = dFormat()
        if printlist[0] == False:
            await ctx.send(printlist[1])
        elif printlist[0] == True:
            if msg == None:
                await logging_channel.send('ended: ' + time + '\n\n' +
                                           str(printlist[1]))
            elif msg != None:
                await logging_channel.send('ended: ' + time + '\ncomment: ' +
                                           msg + '\n\n' + str(printlist[1]))

            f = open('topics.txt', 'w', encoding="utf-8")
            f.write('')
            f.close()
            f = open('notes.txt', 'w', encoding="utf-8")
            f.write('')
            f.close()
Esempio n. 4
0
def export():
    time.pop(0)
    data = [["initial_data"] + initial_data,
            ['wait between shown images'] + time,
            ['answer as expected?'] + correct]

    out_file = open('example2.csv', 'w', newline='')
    with out_file:
        writer = csv.writer(out_file, dialect='excel')
        writer.writerows(data)

    print("Writing complete")
Esempio n. 5
0
def eliminate_errerdata(Cutoff, time, data):
    data_median = median(data)
    arg = []
    #### search ####
    for j in range(len(data)):
        if abs(data[j] - data_median) >= Cutoff:
            arg.insert(0, j)
    #### eliminate ####
    for j in arg:
        time.pop(j)
        data.pop(j)
    return time, data
Esempio n. 6
0
    def stripSecond(self, time):
        strTime = None

        if len(time) == 3:
            time.pop(2)
            self.addZero(time)
            strTime = ':'.join(time)
            logger.debug("stripped second and time is %s"%(strTime))
        elif len(time) == 2:
            self.addZero(time)
            strTime = ':'.join(time)
            logger.debug("it just contain hour and mins, %s"%(strTime))
        else:
            logger.debug("the time format has error, %s"%(':'.join(time)))

        return strTime
Esempio n. 7
0
def updateData(interval):
    data = list_data[next(index)]
    time.append(dt.datetime.now().strftime('%H:%M:%S'))
    y_pressure.append(float(data))
    y_volume.append(float(data))
    if len(time) > 10:
        time.pop(0)
        y_pressure.pop(0)
        y_volume.pop(0)
        ax_pressure.clear()
        ax_volume.clear()
    if data > 8:
        Notify.Notification.new("Max pressure Alert").show()
    plt.subplots_adjust(bottom=0.2)
    plt.xticks(rotation=45, ha='right')
    ax_pressure.plot(time, y_pressure)
    ax_volume.plot(time, y_volume)
    ax_volume.title.set_text('Volume (mL)')
    ax_pressure.title.set_text('Pressure (mbars)')
Esempio n. 8
0
    def save_article(self, num, content):
        '''
        :param content: a list get from screen
        '''
        chinese_keyword = {
            'board': '看板',
        }

        author_line = content[0].encode('utf-8').split()
        if not chinese_keyword['board'] in author_line:
            return
        _i = author_line.index(chinese_keyword['board'])
        author = ' '.join(author_line[1:_i])

        title_line = content[1].encode('utf-8').split()[1:]
        title = ' '.join(title_line)

        time_line = content[2].encode('utf-8').split()[1:]
        time = ' '.join(time_line)
        if not time.find('(') == -1:
            time = time[time.find('(') + 1:time.find(')')]
        time = time.split()
        time.pop(1)
        time = ' '.join(time)
        print time


        article = '\n'.join(content[3:]).encode('utf-8')

        try:
            post = Teacher.get(bbs_id=num)
            post.content = article
            post.save()
            logger.info('Update: {id}'.format(id=num))
        except Teacher.DoesNotExist:
            post = Teacher.create(author=author,
                title=title,
                pub_time=time,
                content=article,
                bbs_id=num
            )
            logger.info('Insert: {id}'.format(id=num))
Esempio n. 9
0
def get_CPU():
    mem = {}
    cpu = {}
    result = subprocess_cmd('top -b -n1 | head -n 4').decode('utf-8')
    lines = result.split('\n')
    l0 = lines[0].split()
    l1 = lines[2].split()
    l2 = lines[3].split()
    time = []
    for i in l0[4:]:
        if i == 'user,': break
        time.append(i)
    time.pop()
    cpu['TIME OF EXECUTION'] = ' '.join(time)
    cpu['CPU USAGE %'] = l1[1] + l1[3]
    mem['RAM TOTAL'] = l2[3]
    mem['RAM USED'] = l2[7]
    result = subprocess_cmd(
        'netstat -an | grep :443 | grep ESTABLISHED | wc -l').decode('utf-8')
    return {'CPU': cpu, 'RAM': mem, 'Connections': result}
Esempio n. 10
0
def snap(path, time):
    snapped_path = []
    cnt = 100

    for i in range(int(len(path)/cnt)):
        #use gmaps service to snap to road, cannot accept nan
        snap_road_result = gmaps.snap_to_roads(path[i*cnt:(i+1)*cnt], interpolate = False)
        for k in snap_road_result:
            lat = k['location']['latitude']
            lon = k['location']['longitude']
            snapped_path.append([lat, lon])
    
    snap_road_result = gmaps.snap_to_roads(path[int(len(path)/cnt)*cnt:], interpolate = False)
    for k in snap_road_result:
        lat = k['location']['latitude']
        lon = k['location']['longitude']
        snapped_path.append([lat, lon])
    
    #randomly drop some time
    for i in range(len(time) - len(snapped_path)):
        ind = random.randint(0, len(time)-1)
        time.pop(ind)

    return snapped_path, time
Esempio n. 11
0
def get_time(sec):
    verbose = ["sec(s)", "min(s)", "hour(s)", "day(s)"]
    time = []
    time += [sec // (24 * 3600)]  # days
    sec %= (24 * 3600)
    time += [sec // 3600]  # hours
    sec %= 3600
    time += [sec // 60]  # minutes
    sec %= 60
    time += [sec]  # seconds
    time = time[::-1]
    time_output = ""
    for i in range(len(time)):
        val = time.pop()
        tag = verbose.pop()
        if val != 0:
            time_output += "{}{} :".format(int(val), tag)
    return time_output[:-2]
Esempio n. 12
0
#!/bin/python
# -*- coding: utf-8 -*-
import time
import pyvona
import pygame
import subprocess

#Creates Time variable
time = time.strftime("%I %M %p")
time = list(time)

if time[0][0] == "0":
	time.pop(0)
	time = ''.join(time)
else:
	time = ''.join(time)

time = "The Current Time is " + time
v = pyvona.create_voice('GDNAJW3FDVSMQKUCCFKQ','RoXbQ1VnTPU/dvmzhSwx43mjnXhBzlEeMc2qoNcu')
#Settings for ivona
v.voice_name = 'Brian'
v.speech_rate = 'slow'
#Get ogg file with speech
v.fetch_voice(time, '/mnt/ram/tempspeech.ogg')


pygame.mixer.init()
pygame.mixer.music.load("/mnt/ram/tempspeech.ogg")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
    continue
Esempio n. 13
0
response = subprocess.Popen(
    'systemctl -l status noia.service | grep downloaded',
    shell=True,
    stdout=subprocess.PIPE).stdout.read()

# Month
month = re.findall('^.{0,3} ', response, re.MULTILINE)
month = month.pop()[:-1]

# Day
day = re.findall('^.{0,3} \d+', response, re.MULTILINE)
day = day.pop()[4:]

# Time
time = re.findall('^.{0,3} \d+ \d+:\d+:\d+', response, re.MULTILINE)
time = time.pop()[7:]

# Downloaded in bytes
downloaded = re.findall('downloaded=\d+', response, re.MULTILINE)
downloaded = downloaded.pop().replace('downloaded=', '')

# Uploaded in bytes
uploaded = re.findall('uploaded=\d+', response, re.MULTILINE)
uploaded = uploaded.pop().replace('uploaded=', '')

# Uptime Hours
hours = re.findall('for \d+', response, re.MULTILINE)
hours = hours.pop().replace('for ', '')

# Uptime Minutes
minutes = re.findall('hours, \d+', response, re.MULTILINE)
            elif (str(text2num(bkdate)).isdigit()):
                for i in range(text2num(bkdate)):
                    bookdate = bookdate + " " + "and" + " " + str(
                        todayday + datetime.timedelta(days=i))
                    dateflag = 1
                    forflag = 1
        break
if (dateflag == 1) and (forflag == 1):
    bookdate = bookdate.lower().strip().split(' ', 1)[1]
time = ([i for i in time if i not in stop])
for x in range(len(time)):
    timestr = timestr + " " + ''.join(time[x]).lower().strip()
for x in range(0, len(time)):
    pos = (dictword[''.join(time[x]).lower().strip()])
    if (str1.split()[pos] == "pm"):
        time.pop(x)
        time.pop(x)
        time.extend(
            [str(text2num(str1.split()[pos - 1])) + str(str1.split()[pos])])
        break
for x in range(0, len(time)):
    if (("pm" in ''.join(time[x]).lower().strip())
            or ("am" in ''.join(time[x]).lower().strip())):
        pos = ''.join(time[x]).lower().strip().find("am")
        pos1 = ''.join(time[x]).lower().strip().find("pm")
        if ((''.join(time[x]).lower().strip()[pos - 1]).isdigit()) or (
            (''.join(time[x]).lower().strip()[pos1 - 1]).isdigit()):
            booktime = ''.join(time[x]).lower().strip()
            timeflag = 1
    else:
        posi = (dictword[''.join(time[x]).lower().strip()])
Esempio n. 15
0
def run_rocket_config(ri, rf, L0, ngrain, Ae_At_0, At_0, mass_ballast_0, T_bi):

    # givens/constants
    n = 0.35
    a0 = 0.030 * units["(in / s) * (lbf / in^2) ^ -0.35"]
    sigma_p = 0.001 * units["1/F"]
    c_star = 5210 * units["ft/s"]
    rho_p = 0.065 * units["lb/in^3"]
    T_b0 = 70.0 * units["F"]
    # T_bi = 70.0 * units["F"]
    w_step = (0.01 * units["in"])
    k_exhaust = 1.3
    grain_spacing = 0.125 * units["in"]
    mass_ballast = mass_ballast_0
    mass_structure = 40.0 * units["lb"]
    mass_per_length = 0.25 * units["lb/in"]

    # maxes
    MAX_PRESSURE = 1000.0 * units["psi"]
    MAX_ACCELERATION = 15.0 * units[""]
    MAX_CASE_LENGTH = 34.0 * units["in"]

    # L[i]sts / dynamic vars
    r = []                      # radius of propellant
    L = []                      # length of propellant
    At = []                     # throat area
    Ae_At = []                  # area ratio
    w = []                      # web distance
    time = []                   # time 
    delDt = []                  # change in diameter at the throat
    CF = []                     # coefficient of thrust
    thrust = []                 # thrust
    It = []                     # total impulse
    Is = []                     # specific impulse
    rate = []                   # burn rate
    throat_diameter = []        # diameter at throat
    mass_propellant = []        # mass of propellant
    burn_area = []                 # area of burn
    p1 = []                     # chamber pressure
    ambient_gas = []              # list of gas properties (Gas class)
    Is_compute = []                     # specific impulse

    # pr4 / phyics variables
    altitude = []
    velocity = []
    acceleration = []
    mach = []
    drag_coeff = []
    drag = []
    F_M = []                    # force over mass term for force balance
    D_M = []                    # drag over mass term for force balance
    
    # vehicle characteristics
    vehicle_mass = []
    vehicle_diameter = 6.19 * units("in")
    vehicle_cx_area = np.pi * vehicle_diameter ** 2 / 4.0

    # initial values
    r.append(ri)    
    L.append(L0)
    At.append(At_0)
    Ae_At.append(Ae_At_0)
    w.append(0.0 * units["in"])
    time.append(0.0 * units["s"])
    It.append(0.0 * units["lbf * sec"])
    Is.append(0.0 * units["sec"])
    Is_compute.append(0.0 * units["sec"])
    throat_diameter.append(np.sqrt(4.0 * At[0] / np.pi))
    altitude.append(0 * units("ft"))                      # altitude of H untsville, AL

    # initial physics
    velocity.append(0.0 * units("ft/s"))
    
    # misc initial calculations
    Ae = Ae_At[0] * At[0]
    w_max = calc_w_max(r[0],rf,L[0])
    mass_case = 4.0 * mass_per_length * (L[0] + grain_spacing)

    burned_out = False
    output=[]
    physics_output=[]
    i = 0
    burnout_it = -1
    last_it = -1
    It_total = It[0]

    # pre-run design constraints
    Aport_At0 = np.pi * r[0] ** 2 / At[0]
    case_length = (L0 + grain_spacing) * ngrain 
    if(Aport_At0 < 2.0):
        print("Invalid Configuration: A_p,0 / A_t,0 > 2.0 (%s)" % Aport_At0)
        return 0.0        
    if(case_length > MAX_CASE_LENGTH):
        print("Invalid Configuration: case length > 34.0 in (%s)" % case_length)
        return 0.0

    # loop while propellant isn't burned out
    while(True):

        #time dependent values that rely on previous value
        if(i > 0):
            velocity.append(velocity[i-1] + acceleration[i-1] * (time[i] - time[i-1]))
            altitude.append(altitude[i-1] + (velocity[i] + velocity[i-1]) / 2 * (time[i] - time[i-1]))
            
            if(altitude[i] < 0.0):
                time.pop()
                altitude.pop()
                velocity.pop()
                break
        elif(i > 1000):
            print("Trajectory timeout!")
            break
            
        # update gas state
        ambient_gas.append(Gas("air",altitude[i]))

        #with T[i] calculate Mach number and the CD
        mach.append(velocity[i] / ambient_gas[i].speed_of_sound)
        drag_coeff.append(drag_coefficient_from_mach(mach[i]) * units[""])
        drag.append(0.5 * ambient_gas[i].density * drag_coeff[i] * velocity[i] ** 2 * vehicle_cx_area)

        if(velocity[i-1] < 0):
            time.pop()
            altitude.pop()
            velocity.pop()
            last_it = i
            break
            drag[i] *= -1
        
        # calculate area of current burn surface
        burn_area.append(burn_surface_area(L[i], r[i], rf, ngrain))

        # if propellant is still burning
        if(not burned_out):

            p1.append(chamber_pressure(burn_area[i], At[i], rho_p, T_bi, T_b0, a0, sigma_p, c_star, n))
            rate.append(burning_rate(T_bi, T_b0, a0, sigma_p, p1[i], n))

            # calculate force stuff
            # print("%s / %s = %s" % (p1[i], ambient_gas[i].pressure, p1[i] / ambient_gas[i].pressure))
            CF.append(CF2(k_exhaust,Ae_At[i], p1[i] / ambient_gas[i].pressure))
            thrust.append(CF[i] * p1[i] * At[i])
            mass_propellant.append(mass_of_propellant(L[i], r[i], rf, rho_p, ngrain))
            
            # after one iteration, we can calculate impulse
            if(i > 0):
                It.append(0.5*(thrust[i] + thrust[i - 1])*(time[i] - time[i - 1]))
                Is.append(It[i] * lbfToLbm / ((mass_propellant[i - 1] - mass_propellant[i]) * g0_EN))

            # check this or next step will burnout, if so, do half step instead
            if(w[i] >= w_max):
                burned_out = True
            else:

                w.append(w[i] + w_step)         # current web distance
                L.append(L[0] - 2 * w[i + 1])   # current grain length (decreases w[i]th burn)
                r.append(r[0] + w[i + 1])       # current radius (increases w[i]th burn)

                # calculate new time step from burn rate
                time.append(time[i] + w_step / rate[i]) 

                # calculate change in diameter at throat
                delDt.append(0.000087 * units["in ^ 3 / s / lbf"] * p1[i] * (time[i + 1] - time[i]))

                if(w[i + 1] + w_step > w_max):
                    w_step = 0.005 * units["in"]
                    burnout_it = i


        # else if propellant is all burned up
        else:
            It.append(0.0 * It[0])
            Is.append(0.0 * Is[0])
            p1.append(0.0 * p1[0])
            rate.append(0.0 * rate[0])
            CF.append(0.0 * CF[0])
            thrust.append(0.0 * thrust[0])

        # same as else above, but we want it to happen the first time burn is turned off
        if(burned_out):  

            mass_propellant.append(0 * mass_propellant[0])

            w.append(w[i])
            L.append(L[0] - 2 * w[i + 1])   # current grain length (decreases w[i]th burn)
            r.append(r[0] + w[i + 1])       # current radius (increases w[i]th burn)

            # switch to 0.1 time step
            time.append(time[i] + 0.1 * units["s"])
            delDt.append(0.0 * delDt[0])

        vehicle_mass.append(mass_ballast + mass_propellant[i] + mass_structure + mass_case)

        F_M.append(thrust[i] / vehicle_mass[i] * lbfToLbm)
        D_M.append(drag[i] / vehicle_mass[i])
        acceleration.append(F_M[i] - D_M[i] - g0_EN)

        ## New Step ## 
        # The following calcs had initial value and utilize the above values #
        # i.e. a lot of [i + 1]'s #

        # get new area at throat
        throat_diameter.append(throat_diameter[i] + delDt[i])
        At.append(np.pi * (throat_diameter[i + 1] / 2) ** 2)
        Ae_At.append(Ae / At[i + 1])
        # print("%s\t%s\t%s\t%s\n" % (time[i],vehicle_mass[i], w[i], velocity[i]))

        It_total += It[i]

        # check if iteration violates any condition
        if(acceleration[i] / g0_EN >= MAX_ACCELERATION):
            print("Invalid Configuration: exceeded max acceleration")
            print("--> %s >= %s" % (acceleration[i] / g0_EN, MAX_ACCELERATION))
            return 0.0
        if(p1[i] > MAX_PRESSURE):
            print("Invalid Configuration: exceeded max pressure")
            return 0.0
        if(CF[i] < CFmin(Ae_At[i]) and not burned_out):
            print("Invalid Configuration: below min CF")
            # pressure_p = np.array([val.magnitude for val in p1]) 
            # print("%f, %f, %f" %(np.min(pressure_p), np.mean(pressure_p), np.max(pressure_p)))

            return 0.0

        # output
        p1[i].ito("psi")
        output.append([w[i],burn_area[i],mass_propellant[i] ,time[i],throat_diameter[i],At[i] 
            ,p1[i] ,CF[i],thrust[i],It[i],rate[i],delDt[i],Ae_At[i]])
        physics_output.append([time[i],vehicle_mass[i],velocity[i],altitude[i],
            ambient_gas[i].pressure,ambient_gas[i].temperature,ambient_gas[i].speed_of_sound,mach[i],
            drag_coeff[i],ambient_gas[i].density,F_M[i],D_M[i],acceleration[i]])

        #increment i
        i += 1

    # for i in range(0,len(It)):
    #     print("%s \t %s \t %s" % (It[i], mass_propellant[i], Is[i]))
    # pressure_p = np.array([val.magnitude for val in p1]) 
    # print(np.mean(pressure_p))
    # return max(altitude).magnitude

    headers = ["web burned", "area", "mass", "time", "Dt ", "At", "P1_e", "C_F", "F_e", "I", "r", "del d", "Ae/At"]
    physics_headers = ["time", "Mveh", "velocity", "altitude", "p3", "temperature", "a", "Mach", "C_d", "rho_3", "F/M", "D/M", "acceleration"]
    # print_output_table(headers,output)
    # print_output_table(physics_headers,physics_output)
    # write_output_table(headers,output,"param_data.txt")
    # write_output_table(physics_headers,physics_output,"physics_data.txt")

    if(burnout_it == -1):
        # print("Warning: no burnout!")
        burnout_it = last_it        

    # convert pint arrays to numpy for plotting/processing
    Is_sub = Is[0:burnout_it]
    Is_p = np.array([val.to_base_units().magnitude for val in Is_sub]) 
    It_p = np.array([val.to_base_units().magnitude for val in It]) 
    time_p = np.array([val.to_base_units().magnitude for val in time]) 
    mp_p = np.array([val.magnitude for val in mass_propellant])
    p1_p = np.array([val.magnitude for val in p1]) 
    F_p = np.array([val.magnitude for val in thrust]) 
    CF_p = np.array([val.magnitude for val in CF]) 
    Ae_At_p = np.array([val.magnitude for val in Ae_At]) 
    acceleration_p = np.array([val.magnitude for val in acceleration]) 
    velocity_p = np.array([val.magnitude for val in velocity]) 
    altitude_p = np.array([val.magnitude for val in altitude]) 

    # Misc post calculations
    Is_ave = (It_total / mass_propellant[0].magnitude)
    max_altitude = max(altitude).magnitude

    config_folder = "results/final/%d" % int(max_altitude)
    if(not os.path.isdir(config_folder)):
        os.mkdir(config_folder)
    matplotlib.rcParams.update({'font.size': 14})
    plt.plot(time_p[:burnout_it],mp_p[:burnout_it])
    plt.xlabel("time [s]")
    plt.ylabel("mass of propellant [kg]")
    plt.savefig("results/final/%d/mass_propellant.png" % int(max_altitude))
    plt.clf()

    plt.plot(time_p[:burnout_it],p1_p[:burnout_it])
    plt.xlabel("time [s]")
    plt.ylabel("chamber pressure [kg]")
    plt.savefig("results/final/%d/chamber_pressure.png" % int(max_altitude))
    plt.clf()

    plt.plot(time_p[:burnout_it],F_p[:burnout_it])
    plt.xlabel("time [s]")
    plt.ylabel("thrust [kg]")
    plt.savefig("results/final/%d/thrust.png" % int(max_altitude))
    plt.clf()

    plt.plot(time_p,acceleration_p)
    plt.xlabel("time [s]")
    plt.ylabel("acceleration [ft/s^2]")
    plt.savefig("results/final/%d/acceleration.png" % int(max_altitude))
    plt.clf()

    plt.plot(time_p,velocity_p)
    plt.xlabel("time [s]")
    plt.ylabel("velocity [ft/s]")
    plt.savefig("results/final/%d/velocity.png" % int(max_altitude))
    plt.clf()

    plt.plot(time_p,altitude_p)
    plt.xlabel("time [s]")
    plt.ylabel("altitude [ft]")
    plt.savefig("results/final/%d/altitude.png" % int(max_altitude))
    plt.clf()

    Plot3_7_PR09(Ae_At_p[:burnout_it],CF_p[:burnout_it]).savefig("results/final/%d/thrust_coefficient.png" % int(max_altitude))
    plt.clf()
    # print("")
    # print("It_total: %s" % np.sum(It_p))
    # print("Is_ave: %s" % Is_ave)
    # print("P1_max %s" % max(p1))
    # print("F_max %s" % max(thrust))
    # print("Aport / At_0: %s" % Aport_At0)

    # print("A_max %s" % max(altitude))
    burnout_it = burnout_it - 1
    print("%.3f | %.3f | %.3f | %.3f |%.3f | %.3f | %.3f" % (mp_p[0],burn_area[0].magnitude,time[burnout_it].magnitude,
            Is_ave.magnitude, max(p1).magnitude,max(thrust).magnitude, Aport_At0.magnitude))
    print("%.3f | %.3f | %.3f | %.3f |%.3f | %.3f |%.3f | %.3f | %.3f" % (mass_case.magnitude, 
        vehicle_mass[0].magnitude, altitude[burnout_it].magnitude, velocity[burnout_it].magnitude, acceleration[burnout_it].magnitude,
        max_altitude, max(velocity).magnitude, max(acceleration).magnitude, max(acceleration).magnitude / g0_EN.magnitude))
    # print(" = %f ft" % max_altitude)
    return (mp_p[0],burn_area[0].magnitude,time[burnout_it].magnitude,
            Is_ave.magnitude, max(p1).magnitude,max(thrust).magnitude, Aport_At0.magnitude, 
            max_altitude, max(velocity).magnitude, max(acceleration).magnitude)
Esempio n. 16
0
time = []
for i in range(1, 51):
    URL = BASE + str(i)
    r = session_requests.get(URL)
    soup = BeautifulSoup(r.content, 'html.parser')
    for node in soup.find_all("a", "storylink"):
        title.append(node.text)
    for node in soup.find_all("span", "age"):
        time.append(node.text)
    for node in soup.find_all("a", "hnuser"):
        hnuser.append(node.text)
    for node in soup.find_all("span", "score"):
        score.append(node.text)
    if len(title) > len(hnuser):
        title.pop()
        time.pop()


class post(Document):
    title = StringField(max_length=120, required=True)
    author = StringField(max_length=120, required=True)
    time = StringField(max_length=120, required=True)
    score = StringField(max_length=50, required=True)


#puts data in mongodb
connect(db='hackerycom',
        username='******',
        password='******',
        host='ds253918.mlab.com:53918')
Esempio n. 17
0
def VideoLogAPI(request):
    video_id = request.GET.get("video_id")
    logs = VideoLog.objects.filter(video_id=video_id).order_by('-created_at')
    is_moving_avg = request.GET.get("is_moving_avg")
    time_gap = request.GET.get("time_gap")
    count = 10
    car_inflow = []
    car_outflow = []
    bike_inflow = []
    bike_outflow = []
    truck_inflow = []
    truck_outflow = []
    ci = 0
    co = 0
    bi = 0
    bo = 0
    ti = 0
    to = 0
    time = []
    t_count = 0
    if is_moving_avg and int(is_moving_avg) == 1:
        logs = logs.filter(moving_avg__isnull=False)
    else:
        logs = logs.filter(moving_avg__isnull=True)
    if time_gap:
        time_gap = int(time_gap)
        count = count * time_gap
    if logs.exists():
        logs = logs[:count]
        asia = timezone("Asia/Kolkata")
        time.append(logs[0].created_at.astimezone(asia).strftime("%H:%M"))
    for log in logs:
        if time_gap:
            if t_count % time_gap == 0 and t_count > 1:
                car_inflow.append(ci)
                car_outflow.append(co)
                bike_inflow.append(bi)
                bike_outflow.append(bo)
                truck_inflow.append(ti)
                truck_outflow.append(to)
                ci = 0
                co = 0
                bi = 0
                bo = 0
                ti = 0
                to = 0
                t_count = 0
                asia = timezone("Asia/Kolkata")
                time.append(log.created_at.astimezone(asia).strftime("%H:%M"))
            else:
                t_count += 1
                temp = json.loads(log.moving_avg)
                ci += temp[0]
                co += temp[3]
                bi += temp[1]
                bo += temp[4]
                ti += temp[2]
                to += temp[5]
        elif is_moving_avg and int(is_moving_avg) == 1:
            temp = json.loads(log.moving_avg)
            car_inflow.append(temp[0])
            car_outflow.append(temp[3])
            bike_inflow.append(temp[1])
            bike_outflow.append(temp[4])
            truck_inflow.append(temp[2])
            truck_outflow.append(temp[5])
            asia = timezone("Asia/Kolkata")
            time.append(log.created_at.astimezone(asia).strftime("%H:%M"))
        else:
            temp = json.loads(log.data)
            car_inflow.append(temp[0])
            car_outflow.append(temp[4])
            bike_inflow.append(temp[1])
            bike_outflow.append(temp[5])
            truck_inflow.append(temp[2])
            truck_outflow.append(temp[6])
            asia = timezone("Asia/Kolkata")
            time.append(log.created_at.astimezone(asia).strftime("%H:%M"))
    car_inflow.reverse()
    car_outflow.reverse()
    bike_inflow.reverse()
    bike_outflow.reverse()
    truck_inflow.reverse()
    truck_outflow.reverse()
    time.reverse()
    if time_gap:
        time.pop()
    data = [
        car_inflow, car_outflow, bike_inflow, bike_outflow, truck_inflow,
        truck_outflow
    ]
    log = VideoLog.objects.filter(moving_avg__isnull=True,
                                  video_id=video_id).order_by('-created_at')
    vehicle_count = []
    if log.exists():
        vehicle_count = log[0].data
    return HttpResponse(
        json.dumps({
            "vehicle_count": vehicle_count,
            "data": {
                "y": data,
                "x": time
            }
        }))