Ejemplo n.º 1
0
def toggle(bus):
	with bus_lock:
		try:
			with db('ha.db') as c:
				_bus_write(c,bus,0)
			time.sleep(5)
		finally:
			with db('ha.db') as c:
				_bus_write(c,bus,1)
Ejemplo n.º 2
0
async def get(ctx):
    allowance = not_allowed(ctx, get.name, bot)
    if allowance[0]:
        await bot.say(f'acess denied,channel for ={get.name} is {allowance[1]}'
                      )
        return

    db = utils.db(ctx=ctx)
    query = db.query(user=True, server=True)
    if len(query) == 0:
        await bot.say('Need to bet once in order to use this command')
        return

    balance = float(query[0][4])
    mult = query[0][8]
    timp = query[0][5]

    if time == None:
        balance += 200
        await bot.say('You got a refill!!Your new balance is: ' + str(balance))
        db.updateTime(time.time())
        db.updateBalance(balance)
    else:
        rtime = time.time()
        diff = rtime - timp
        if diff < 0:
            await bot.say('You cannot get a refill yet!!')
        else:
            diff = round(diff / 3600)
            balance += (diff + 1) * mult
            await bot.say('You got a refill!!Now you got: ' + str(balance))
            db.updateBalance(balance)
            db.updateTime(rtime + 3600)
Ejemplo n.º 3
0
async def on_member_update(before, after):
    old = before.name + '#' + before.discriminator
    new = after.name + '#' + after.discriminator
    if old != new:
        db = utils.db(member=before)
        db.updateUser(new)
        print('updated user')
Ejemplo n.º 4
0
def register():
    name=request.args.get('name','')
    mydb=utils.db()
    color = "#%s" % "".join([hex(random.randrange(0, 255))[2:] for i in range(3)])
    print color;
    r = mydb.add_user(name,color)
    return json.dumps(r);
Ejemplo n.º 5
0
def authorize(url):
    db = utils.db()['db']

    code = url.split("?code=")[1].split("&")[0]
    payload = {'redirect_uri': utils.config('callback_uri'),
                   'code': code,
                   'grant_type': 'authorization_code',
                   'scope': utils.config('scope')}
    
    auth_header = base64.b64encode(six.text_type(utils.config('client_id') + ':' + utils.config('client_secret')).encode('ascii'))
    headers = {'Authorization': 'Basic %s' % auth_header.decode('ascii')}

    results = requests.post('https://accounts.spotify.com/api/token', data=payload, headers=headers)

    token_info = results.json()

    token_info['expires_at'] = int(time.time()) + token_info['expires_in']

    token_info['client_id'] = utils.config('client_id')

    token_info['client_secret'] = utils.config('client_secret')

    token_info['prefix'] = utils.config('prefix')

    token_info['scope'] = utils.config('scope')

    db.insert(token_info)

    utils.output('end', 'success', utils.translate('logged'))
Ejemplo n.º 6
0
def update():
    name=request.args.get('name','')
    x=int(request.args.get('x','-1'))
    y=int(request.args.get('y','-1'))
    mydb=utils.db()
    mydb.cleanup()
    mydb.update(name,x,y)
    return "True"
Ejemplo n.º 7
0
def update(id, bus_id, name, addr):
    with db("ha.db") as c:
        if bus_id is not None:
            c.execute("update device set bus_id=? where id=?", (bus_id, id))
        if name is not None:
            print "update:" + str(name) + " id " + str(id)
            c.execute("update device set name=? where id=?", (name, id))
        if addr is not None:
            c.execute("update device set address=? where id=?", (addr, id))
Ejemplo n.º 8
0
    def plot_time_series(self,
                         f_start=None,
                         f_stop=None,
                         if_id=0,
                         logged=True,
                         orientation='h',
                         MJD_time=False,
                         **kwargs):
        """ Plot the time series.

         Args:
            f_start (float): start frequency, in MHz
            f_stop (float): stop frequency, in MHz
            logged (bool): Plot in linear (False) or dB units (True),
            kwargs: keyword args to be passed to matplotlib imshow()
        """

        ax = plt.gca()
        plot_f, plot_data = self.grab_data(f_start, f_stop, if_id)

        if logged and self.header[b'nbits'] >= 8:
            plot_data = db(plot_data)

        #Since the data has been squeezed, the axis for time goes away if only one bin, causing a bug with axis=1
        if len(plot_data.shape) > 1:
            plot_data = plot_data.mean(axis=1)
        else:
            plot_data = plot_data.mean()

        #Make proper time axis for plotting (but only for plotting!). Note that this makes the values inclusive.
        extent = self._calc_extent(plot_f=plot_f,
                                   plot_t=self.timestamps,
                                   MJD_time=MJD_time)
        plot_t = np.linspace(extent[2], extent[3], len(self.timestamps))

        if MJD_time:
            tlabel = "Time [MJD]"
        else:
            tlabel = "Time [s]"

        if logged:
            plabel = "Power [dB]"
        else:
            plabel = "Power [counts]"

        # Reverse oder if vertical orientation.
        if 'v' in orientation:
            plt.plot(plot_data, plot_t, **kwargs)
            plt.xlabel(plabel)

        else:
            plt.plot(plot_t, plot_data, **kwargs)
            plt.xlabel(tlabel)
            plt.ylabel(plabel)

        ax.autoscale(axis='both', tight=True)
Ejemplo n.º 9
0
def NoSS_old(X, EigDiffCutoff=4):
    """Older way of finding the SignalEndIdx based on thresholding and
    eigenvalue difference cutoff

    Args:
        X: CSI, shape=[count, subcarriers, nrx]
        EigDiffCutoff: eigenvalue difference cutoff

    Refs:
        1. GetQnBackscatter.m: line 50-64
    """
    R = (X @ X.transpose(0, 2, 1).conj()).mean(axis=0)
    w, v = eigh(R)
    w = sorted(np.abs(w), reverse=True)[:5]

    Criterion1 = np.diff(db(w)) <= max(-EigDiffCutoff, min(db(w)))
    Criterion3 = w[:-1] / w[0] > 0.03
    index, = np.nonzero(Criterion1 * Criterion3)
    return index[-1] + 1
Ejemplo n.º 10
0
    def plot_waterfall(self, f_start=None, f_stop=None, if_id=0, logged=True, cb=True, MJD_time=False, **kwargs):
        """ Plot waterfall of data

        Args:
            f_start (float): start frequency, in MHz
            f_stop (float): stop frequency, in MHz
            logged (bool): Plot in linear (False) or dB units (True),
            cb (bool): for plotting the colorbar
            kwargs: keyword args to be passed to matplotlib imshow()
        """

        plot_f, plot_data = self.grab_data(f_start, f_stop, if_id)

        #Using accending frequency for all plots.
        if self.header[b'foff'] < 0:
            plot_data = plot_data[..., ::-1] # Reverse data
            plot_f = plot_f[::-1]

        if logged:
            plot_data = db(plot_data)

        # Make sure waterfall plot is under 4k*4k
        dec_fac_x, dec_fac_y = 1, 1
        if plot_data.shape[0] > MAX_IMSHOW_POINTS[0]:
            dec_fac_x = int(plot_data.shape[0] / MAX_IMSHOW_POINTS[0])

        if plot_data.shape[1] > MAX_IMSHOW_POINTS[1]:
            dec_fac_y =  int(plot_data.shape[1] /  MAX_IMSHOW_POINTS[1])

        plot_data = rebin(plot_data, dec_fac_x, dec_fac_y)

        try:
            plt.title(self.header[b'source_name'])
        except KeyError:
            plt.title(self.filename)

        extent = self._calc_extent(plot_f=plot_f,plot_t=self.timestamps,MJD_time=MJD_time)

        plt.imshow(plot_data,
            aspect='auto',
            origin='lower',
            rasterized=True,
            interpolation='nearest',
            extent=extent,
            cmap='viridis',
            **kwargs
        )
        if cb:
            plt.colorbar()
        plt.xlabel("Frequency [MHz]")
        if MJD_time:
            plt.ylabel("Time [MJD]")
        else:
            plt.ylabel("Time [s]")
Ejemplo n.º 11
0
def history(bus,interval,steps,after):
        with db('ha.db') as c:
		_bus_read(c,bus)
		t = int(time.time())
		newafter = c.cursor().execute('SELECT MAX(last_updated) FROM bus_history WHERE bus_id=?',(bus,)).fetchall()[0];
		if newafter == after:
			return []
		data = c.cursor().execute('SELECT last_updated,status FROM bus_history WHERE bus_id=? AND last_updated >= ? ORDER BY id DESC',(bus,t - interval)).fetchall()
		data.insert(0, [t,_bus_read(c,bus)])
		h = history2plot(t, interval, steps, data)
		return {'history':h,'after': t}
Ejemplo n.º 12
0
async def balance(ctx, member: discord.Member = None):
    allowance = not_allowed(ctx, balance.name, bot)
    if allowance[0]:
        await bot.say(
            f'acess denied,channel for ={balance.name} is {allowance[1]}')
        return

    if member != None:
        db = utils.db(member=member)
    else:
        db = utils.db(ctx=ctx)

    n = db.query(user=True, server=True)
    embed = discord.Embed(title='BALANCE',
                          description='',
                          colour=discord.Colour.gold())

    if len(n) > 0:
        embed.add_field(name=f'{db.userName} balance is:', value=f'{n[0][4]}')
    else:
        embed.add_field(name='Your balance is:', value='20000')
    await bot.say(embed=embed)
Ejemplo n.º 13
0
async def give(ctx, user: discord.Member, amount):
    allowance = not_allowed(ctx, give.name, bot)
    if allowance[0]:
        await bot.say(
            f'acess denied,channel for ={give.name} is {allowance[1]}')
        return

    if user == None:
        await bot.say('ENTER A USER, like this ->@User#1111')
        return
    elif user.id == ctx.message.author.id:
        await bot.say('You cant donate to yourself')
        return

    n = utils.Check(ctx)
    db = utils.db(ctx=ctx)
    user = utils.db(member=user)
    userQuery = user.query(user=True, server=True)
    donator = db.query(user=True, server=True)

    if len(userQuery) == 0 or len(donator) == 0:
        await bot.say(
            'The giving or receiving user needs to bet at least once!!')
        return

    balance = n.balance()
    amount = utils.Check.amount(amount, balance)

    if n.broke(amount, balance):
        await n.display(amount, balance, bot)
        return
    else:
        balance -= amount
        db.updateBalance(balance)
        don = userQuery[0][4]
        don = float(don) + amount
        user.updateBalance(don)
    await bot.say(f'{user.userName} got a donation of {amount}!!')
Ejemplo n.º 14
0
def discover(i2c_addr):
	with habus.bus_lock:
		try:
			with db('ha.db') as c:
				habus._bus_write(c,1,0)
			time.sleep(6)
		finally:
			with db('ha.db') as c:
				habus._bus_write(c,1,1)

		timeout = 5 # 5 seconds timeout for device discovery, you need to poweroff/poweron device during this timeframe
		while True:
			if timeout <= 0:
				raise IOError('device was not discovered in 5 seconds')
			try:
				bus.write_word_data(i2c_addr, 0x01, 0x200)
				if bus.read_word_data(i2c_addr, 0x01) == 0x200:
					return i2c_addr
			except IOError,err:
				time.sleep(1.0)
				timeout -= 1
				continue
			time.sleep(1.0)
			timeout -= 1
Ejemplo n.º 15
0
Archivo: app.py Proyecto: sduncan/Code
def story(title=""):
    mydb = utils.db()
    if request.method == 'GET':
        lines = mydb.returnStory(title)
        return render_template('storytemp.html', title=title, lines=lines)
    else:
        button=request.form.get('button', None)
        title=request.form.get('title', "")
        new_line=request.form.get('new_line', "")
        if button == 'Add':
            mydb.addLineToStory(title, new_line)
            return redirect("/story/%s" %(title))
        elif button == 'Delete':
            mydb.removeAStory(title)
            return redirect("/")
        else:
            return redirect("/")
Ejemplo n.º 16
0
Archivo: app.py Proyecto: sduncan/Code
def home():
    mydb = utils.db()
    if request.method=='POST':
        button=request.form.get('button', None)
        new_story=request.form.get('new_story', "")
        selected=request.form.get('title', "")
        if button=="Choose story":
            url=urllib2.quote("/story/%s" %(selected))
            return redirect(url)
        if button=="Create story" and len(new_story)>0:
            mydb.addStory(new_story)
            return redirect("/")
        elif button=="Drop stories":
            mydb.removeStories()
            return redirect("/")

    titles = mydb.returnTitles()
    return render_template('template.html',titles=titles)
Ejemplo n.º 17
0
def _bus_checks():
	while True:
		time.sleep(5)
		try:
			with bus_lock:
				with db('ha.db') as c:
					bus1 = _bus_read(c,1)
					if not bus1:
						_bus_write(c,1,1)
					bus2 = _bus_read(c,2)
					if not bus2:
						_bus_write(c,2,1)
					bus3 = _bus_read(c,3)
					if not bus3:
						_bus_write(c,3,1)
		except KeyboardInterrupt:
			break
		except Exception,ex:
			print "exception happened during periodic bus status check:"+str(ex)
Ejemplo n.º 18
0
async def slot(ctx, amount):
    allowance = not_allowed(ctx, slot.name, bot)
    if allowance[0]:
        await bot.say(
            f'acess denied,channel for ={slot.name} is {allowance[1]}')
        return

    db = utils.db(ctx)
    check = utils.Check(ctx)
    lev = level.Level(ctx)

    balance = check.balance()
    amount = utils.Check.amount(amount, balance)

    if utils.Check.broke(amount, balance):
        await check.display(amount, balance, bot)
        return
    else:
        Slot = game.slot(balance, amount, ctx)
        grid = Slot.generate()
        win = Slot.check_win(grid)
        if not win:
            balance = Slot.new_balance(win)
            check.embed.add_field(
                name=f'{db.userName} YOU LOST now you have {balance} left',
                value=Slot.display(grid))
        else:
            balance = Slot.new_balance(win)
            check.embed.add_field(
                name=f'{db.userName} YOU WON now you got {balance}',
                value=Slot.display(grid))
            lev.get_level()
            lev.evaluate(amount)
    db.updateBalance(balance)
    await bot.say(embed=check.embed)

    log = statistics.bet_log(ctx)
    log.update_count()
Ejemplo n.º 19
0
async def dice(ctx, range, amount):
    allowance = not_allowed(ctx, dice.name, bot)
    if allowance[0]:
        await bot.say(
            f'acess denied,channel for ={dice.name} is {allowance[1]}')
        return

    db = utils.db(ctx)
    check = utils.Check(ctx)
    lev = level.Level(ctx)
    balance = check.balance()
    amount = utils.Check.amount(amount, balance)

    if '-' not in range:
        await bot.say(f'add a - to your range like this -> 30-80')
        return

    if utils.Check.broke(amount, balance):
        await check.display(amount, balance, bot)
        return
    else:
        Dice = game.dice(range, amount, balance, ctx)
        Dice.update_balance()
        if Dice.win():
            check.embed.add_field(
                name=f'{ctx.message.author} you won it rolled {Dice.choice}!!!',
                value=f'New balance:{Dice.balance}')
        else:
            check.embed.add_field(
                name=
                f'{ctx.message.author} you LOST it rolled {Dice.choice}!!!',
                value=f'New balance:{Dice.balance}')

        log = statistics.bet_log(ctx)

        log.update_count()
        await bot.say(embed=check.embed)
Ejemplo n.º 20
0
async def lead(ctx, top: int = None):
    allowance = not_allowed(ctx, lead.name, bot)
    if allowance[0]:
        await bot.say(
            f'acess denied,channel for ={lead.name} is {allowance[1]}')
        return

    db = utils.db(ctx=ctx)
    n = db.query(server=True)
    f = [[n[i][4], n[i][3]] for i in range(0, len(n))]
    info = sorted(f)
    length = len(n)

    user = []
    balance = []
    finalBalance = []
    for i in range(0, length):
        user.insert(i, info[i][1])
        balance.insert(i, info[i][0])
        finalBalance.insert(i, info[i][0])

    embed = discord.Embed(tite='LEADERBOARD',
                          description='',
                          colour=discord.Colour.purple())
    ranks = [None] * length
    pos = 1

    while None in ranks:
        biggest = balance[-1]
        index = [i for i, x in enumerate(balance) if x == biggest]
        for i in index:
            ranks[i] = pos
        pos += 1
        del balance[index[0]:index[-1] + 1]

    embed = level.lead.Display(ranks, finalBalance, user, embed, top)
    await bot.say(embed=embed)
Ejemplo n.º 21
0
async def gamble(ctx, amount):
    allowance = not_allowed(ctx, gamble.name, bot)
    if allowance[0]:
        await bot.say(
            f'acess denied, channel for ={gamble.name} is {allowance[1]}')
        return

    n = utils.Check(ctx)
    db = utils.db(ctx)
    lev = level.Level(ctx)

    balance = n.balance()
    amount = utils.Check.amount(amount, balance)

    if utils.Check.broke(amount, balance):
        await n.display(amount, balance, bot)
        return
    else:
        rn = random.randint(0, 1)
        if rn == 0:
            balance += amount
            n.embed.add_field(name=f'{n.info.userName} YOU WON!!!',
                              value=f'New balance: {balance}')
        if rn == 1:
            balance -= amount
            n.embed.add_field(name=f"{n.info.userName} YOU LOST",
                              value=f'New balance: {balance}')

        lev.get_level()
        lev.evaluate(amount)

    await bot.say(embed=n.embed)
    db.updateBalance(balance)

    log = statistics.bet_log(ctx)
    log.update_count()
Ejemplo n.º 22
0
async def on_ready():
    print("i was born read eksdi lol xddd 420 69")
    print("I am running as " + bot.user.name)
    print("With the ID: " + bot.user.id)
    print(discord.__version__)
    search = utils.db()
    query = search.query()

    t1 = time.time()
    for i in range(0, len(query)):
        user = await bot.get_user_info(query[i][1])
        username = user.name + '#' + user.discriminator
        if query[i][3] != username:
            with sqlite3.connect('info.db') as conn:
                c = conn.cursor()
                c.execute('UPDATE value SET userName=(?) WHERE userName=(?)', (
                    username,
                    query[i][3],
                ))
                conn.commit()
    t2 = time.time()
    delta = str(t2 - t1)
    print('finished checking in: ' + delta + ' seconds')
    '''
Ejemplo n.º 23
0
def getBalls():
    name = str(request.args.get('name',''))
    mydb=utils.db()
    return json.dumps(mydb.get_balls(name))
Ejemplo n.º 24
0
def generate_report(app_id):
    reviews_table = db()['reviews']
    reviews = [r for r in reviews_table.find({'appId': app_id})]

    sia = SentimentIntensityAnalyzer()

    analysed_reviews = []

    def normalize(data):
        url_pattern = re.compile(r'https?://\S+|www\.\S+')
        data = url_pattern.sub(r'', data)
        data = re.sub('\S*@\S*\s?', '', data)
        data = re.sub('\s+', ' ', data)
        data = re.sub("\'", "", data)

        return data

    def analyse_review(review):
        score_c = score_t = {'neg': 0, 'neu': 1, 'pos': 0, 'compound': 0}

        if review.get('title'):
            score_t = sia.polarity_scores(normalize(review['title']))

        if review.get('content'):
            score_c = sia.polarity_scores(normalize(review['content']))

        title_coeff = 0.05
        content_coeff = 0.95

        merged_score = {}

        for key in score_c:
            merged_score[key] = title_coeff * float(
                score_t[key]) + content_coeff * float(score_c[key])

        merged_score['compound'] = (merged_score['compound'])

        return merged_score

    for r in reviews:
        score = analyse_review(r)
        analysed_reviews.append({str(r['_id']): score})

    sorted_analysed_reviews = sorted(
        analysed_reviews, key=lambda k: list(k.values())[0]['compound'])
    labels = []

    for sar in sorted_analysed_reviews:
        compound = list(sar.values())[0]['compound']
        if (compound <= -0.5):
            labels.append("Terrible")
        elif (-0.5 < compound < -0.05):
            labels.append("Bad")
        elif (-0.05 < compound < 0.05):
            labels.append("Satisfactory")
        elif (0.05 < compound < 0.5):
            labels.append("Good")
        elif (compound >= 0.5):
            labels.append("Excellent")

    return {
        'bad_reviews': json.dumps(sorted_analysed_reviews[0:10]),
        'good_reviews': json.dumps(sorted_analysed_reviews[-10:]),
        'verdict': Counter(labels).most_common(1)[0][0],
    }
Ejemplo n.º 25
0
def attack():
    nameTar=str(request.args.get('tarName',''))
    newHealth=int(request.args.get('dmg','-1'))
    mydb=utils.db()
    mydb.takeDmg(nameTar,newHealth)
    return "Attacked"
Ejemplo n.º 26
0
    def plot_spectrum_min_max(self,
                              t=0,
                              f_start=None,
                              f_stop=None,
                              logged=False,
                              if_id=0,
                              c=None,
                              **kwargs):
        """ Plot frequency spectrum of a given file

        Args:
            logged (bool): Plot in linear (False) or dB units (True)
            if_id (int): IF identification (if multiple IF signals in file)
            c: color for line
            kwargs: keyword args to be passed to matplotlib plot()
        """
        ax = plt.gca()

        plot_f, plot_data = self.grab_data(f_start, f_stop, if_id)

        #Using accending frequency for all plots.
        if self.header[b'foff'] < 0:
            plot_data = plot_data[..., ::-1]  # Reverse data
            plot_f = plot_f[::-1]

        fig_max = plot_data[0].max()
        fig_min = plot_data[0].min()

        print("averaging along time axis...")

        #Since the data has been squeezed, the axis for time goes away if only one bin, causing a bug with axis=1
        if len(plot_data.shape) > 1:
            plot_max = plot_data.max(axis=0)
            plot_min = plot_data.min(axis=0)
            plot_data = plot_data.mean(axis=0)
        else:
            plot_max = plot_data.max()
            plot_min = plot_data.min()
            plot_data = plot_data.mean()

        # Rebin to max number of points
        dec_fac_x = 1
        MAX_PLT_POINTS = 8 * 64  # Low resoluition to see the difference.
        if plot_data.shape[0] > MAX_PLT_POINTS:
            dec_fac_x = int(plot_data.shape[0] / MAX_PLT_POINTS)

        plot_data = rebin(plot_data, dec_fac_x, 1)
        plot_min = rebin(plot_min, dec_fac_x, 1)
        plot_max = rebin(plot_max, dec_fac_x, 1)
        plot_f = rebin(plot_f, dec_fac_x, 1)

        if logged:
            plt.plot(plot_f, db(plot_data), "#333333", label='mean', **kwargs)
            plt.plot(plot_f, db(plot_max), "#e74c3c", label='max', **kwargs)
            plt.plot(plot_f, db(plot_min), '#3b5b92', label='min', **kwargs)
            plt.ylabel("Power [dB]")
        else:
            plt.plot(plot_f, plot_data, "#333333", label='mean', **kwargs)
            plt.plot(plot_f, plot_max, "#e74c3c", label='max', **kwargs)
            plt.plot(plot_f, plot_min, '#3b5b92', label='min', **kwargs)
            plt.ylabel("Power [counts]")
        plt.xlabel("Frequency [MHz]")
        plt.legend()

        try:
            plt.title(self.header[b'source_name'])
        except KeyError:
            plt.title(self.filename)

        plt.xlim(plot_f[0], plot_f[-1])
        if logged:
            plt.ylim(db(fig_min), db(fig_max))
Ejemplo n.º 27
0
def _bus_write(c,bus,value):
	if value:
		value = 0
	else:
		value = 1
	print 'writing to port:'+str(value)
	GPIO.output(28,value)
	status = GPIO.input(29)
	if status:
		value = 0
	else:
		value = 1
	c.execute('UPDATE bus set status = ? WHERE id = ?',(status,bus))
# poweron on startup
try:
	with db('ha.db') as c:
		_bus_write(c,1,1)
except Exception,ex:
        print "failed to initially poweron bus, error:"+str(ex)

#pediodic timer to update periodically our main bus
def _bus_checks():
	while True:
		time.sleep(5)
		try:
			with bus_lock:
				with db('ha.db') as c:
					bus1 = _bus_read(c,1)
					if not bus1:
						_bus_write(c,1,1)
					bus2 = _bus_read(c,2)
Ejemplo n.º 28
0
import utils
import time
from tinydb import TinyDB, Query
import requests
import json
import base64
import socket
from urllib.parse import urlencode
import webbrowser
import six

db = utils.db()['db']
data = db.all()[0]

access_token = data['access_token']
expires_at = data['expires_at']
refresh_token = data['refresh_token']
client_id = data['client_id']
client_secret = data['client_secret']
prefix = data['prefix']


def getAccessToken():
    global access_token

    now = int(time.time())

    if expires_at - now < 60:
        access_token = refreshAccessToken(refresh_token, db)

    return access_token
Ejemplo n.º 29
0
    def plot_spectrum(self,
                      t=0,
                      f_start=None,
                      f_stop=None,
                      logged=False,
                      if_id=0,
                      c=None,
                      **kwargs):
        """ Plot frequency spectrum of a given file

        Args:
            t (int): integration number to plot (0 -> len(data))
            logged (bool): Plot in linear (False) or dB units (True)
            if_id (int): IF identification (if multiple IF signals in file)
            c: color for line
            kwargs: keyword args to be passed to matplotlib plot()
        """
        if self.header[b'nbits'] <= 2:
            logged = False
            t = 'all'
        ax = plt.gca()

        plot_f, plot_data = self.grab_data(f_start, f_stop, if_id)

        #Using accending frequency for all plots.
        if self.header[b'foff'] < 0:
            plot_data = plot_data[..., ::-1]  # Reverse data
            plot_f = plot_f[::-1]

        if isinstance(t, int):
            print("extracting integration %i..." % t)
            plot_data = plot_data[t]
        elif t == b'all':
            print("averaging along time axis...")
            #Since the data has been squeezed, the axis for time goes away if only one bin, causing a bug with axis=1
            if len(plot_data.shape) > 1:
                plot_data = plot_data.mean(axis=0)
            else:
                plot_data = plot_data.mean()
        else:
            raise RuntimeError("Unknown integration %s" % t)

        # Rebin to max number of points
        dec_fac_x = 1
        if plot_data.shape[0] > MAX_PLT_POINTS:
            dec_fac_x = int(plot_data.shape[0] / MAX_PLT_POINTS)

        plot_data = rebin(plot_data, dec_fac_x, 1)
        plot_f = rebin(plot_f, dec_fac_x, 1)

        if not c:
            kwargs['c'] = '#333333'

        if logged:
            plt.plot(plot_f, db(plot_data), label='Stokes I', **kwargs)
            plt.ylabel("Power [dB]")
        else:

            plt.plot(plot_f, plot_data, label='Stokes I', **kwargs)
            plt.ylabel("Power [counts]")
        plt.xlabel("Frequency [MHz]")
        plt.legend()

        try:
            plt.title(self.header[b'source_name'])
        except KeyError:
            plt.title(self.filename)

        plt.xlim(plot_f[0], plot_f[-1])
Ejemplo n.º 30
0
async def roll(ctx, amount, choice):
    allowance = not_allowed(ctx, roll.name, bot)
    if allowance[0]:
        await bot.say(
            f'acess denied,channel for ={roll.name} is {allowance[1]}')
        return

    p = ['r', 'b', 'g']
    if choice != 'r' and choice != 'b' and choice != 'g':
        await bot.say(
            f'INVALID CHOICE,type {p[0]} for red,{p[1]} for black and {p[2]} for green'
        )
        return

    n = utils.Check(ctx)
    db = utils.db(ctx)
    lev = level.Level(ctx)

    balance = n.balance()
    amount = utils.Check.amount(amount, balance)

    emoji = {'r': ':red_circle:', 'b': ':black_circle:', 'g': ':green_apple:'}

    rn = random.randint(0, 16)
    display = ''
    win = ''

    if rn == 16:
        win = 'g'
    elif rn % 2 == 0:
        win = 'r'
    elif rn % 2 != 0:
        win = 'b'

    for i in range(0, 9):
        if rn == 16:
            display += emoji['g']
            rn = 0
        elif rn % 2 == 0:
            display += emoji['r']
            rn += 1
        else:
            display += emoji['b']
            rn += 1
    cursor = ':point_up:'

    if utils.Check.broke(amount, balance):
        await n.display(amount, balance, bot)
        return
    else:
        if win == choice:
            if choice == 'g':
                balance += amount * 14
                n.embed.add_field(
                    name=display + '\n' + cursor + '\n' +
                    f'{db.userName} you won,ON GREEN!!! balance->' +
                    str(balance),
                    value='--------------------')
            else:
                balance += amount
                n.embed.add_field(name=display + '\n' + cursor + '\n' +
                                  f'{db.userName} you won,new balance is ->' +
                                  str(balance),
                                  value='------------------')
        else:
            balance -= amount
            n.embed.add_field(name=display + '\n' + cursor + '\n' +
                              f'{db.userName} you lost,new balance is ->' +
                              str(balance),
                              value='----------------------')
        lev.get_level()
        lev.evaluate(amount)

    db.updateBalance(balance)
    await bot.say(embed=n.embed)

    log = statistics.bet_log(ctx)
    log.update_count()
Ejemplo n.º 31
0
def update(bus, onoff):
	with db('ha.db') as c:
		_bus_write(c,bus, onoff)
Ejemplo n.º 32
0
def getBalls():
    mydb=utils.db()
    return json.dumps(mydb.get_balls())
Ejemplo n.º 33
0
def users():
    #name=request.args.get('name','')
    mydb=utils.db()
    return json.dumps(mydb.get_users())
Ejemplo n.º 34
0
def create(bus_id, name, addr):
    with db("ha.db") as c:
        c.execute("insert into device(bus_id,name,address) values (?,?,?)", (bus_id, name, addr))
Ejemplo n.º 35
0
def delete(id):
    with db("ha.db") as c:
        c.execute("delete from device where id=?", (id,))
Ejemplo n.º 36
0
def list():
    with db("ha.db") as c:
        return c.cursor().execute("SELECT * FROM device").fetchall()
Ejemplo n.º 37
0
def getPolygons():
    mydb=utils.db()
    return json.dumps(mydb.get_polygons())
Ejemplo n.º 38
0
def bus(id):
    with db("ha.db") as c:
        return c.cursor().execute("SELECT bus_id FROM device WHERE id=?", (id,)).fetchall()[0][0]
Ejemplo n.º 39
0
def register():
    name=request.args.get('name','')
    mydb=utils.db()
    r = mydb.add_user(name)
    return json.dumps(r);
Ejemplo n.º 40
0
    global start_from
    global year
    global dir_in
    global dir_pdfs
    global illinois_entities_xlsx_file
    global illinois_entities_sheet
    global script_name
    start_time = datetime.utcnow()
    script_name = "get_IL.py"
    result = 1
    error_message = ""
    config_file = ""

    config = configparser.ConfigParser()
    config.read('conf.ini')
    db = db(config)
    try:
        dbparameters = db.readProps('illinois')
        config_file = str(dbparameters)
        with open('IL_parms.txt', 'r') as fp:
            dparameters = json.load(fp)
        ftpurl = dbparameters["url"] or dparameters["ftpurl"]
        url = urllib.parse.urlparse(ftpurl)
        start_from = dbparameters["start_from"] or dparameters["start_from"]
        year = dbparameters["year"] or dparameters["year"]
        dir_in = dbparameters["dir_in"] or dparameters["dir_in"]
        dir_pdfs = dbparameters["dir_pdfs"] or dparameters["dir_pdfs"]
        illinois_entities_xlsx_file = dbparameters[
            "illinois_entities_xlsx_file"] or dparameters[
                "illinois_entities_xlsx_file"]
        illinois_entities_sheet = dbparameters[
Ejemplo n.º 41
0
def run(string, entities):
	"""Download new videos from a YouTube playlist"""

	db = utils.db()['db']
	query = utils.db()['query']
	operations = utils.db()['operations']
	apikey = utils.config('api_key')
	playlistid = utils.config('playlist_id')
	# https://developers.google.com/youtube/v3/docs/playlistItems/list
	url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=' + playlistid + '&key=' + apikey
	
	utils.output('inter', 'reaching_playlist', utils.translate('reaching_playlist'))
	# Get videos from the playlist
	try:
		r = utils.http('GET', url)

		# In case there is a problem like wrong settings
		if 'error' in r.json():
			error = r.json()['error']['errors'][0]
			return utils.output('settings_error', 'settings_error', utils.translate('settings_errors', {
				'reason': error['reason'],
				'message': error['message']
			}))


		items = r.json()['items']
		videoids = []
		videos = []

		for item in items:
			resource = item['snippet']['resourceId']

			if resource['kind'] == 'youtube#video':
				videoids.append(resource['videoId'])
				videos.append({
					'id': resource['videoId'],
					'title': item['snippet']['title']
				})
	except requests.exceptions.RequestException as e:
		return utils.output('request_error', 'request_error', utils.translate('request_errors'))

	Entry = query()

	# First initialization
	if db.count(Entry.platform == 'youtube') == 0:
		db.insert({
			'platform': 'youtube',
			'checked_at': int(time()),
			'downloaded_videos': []
		})
	else:
		db.update({ 'checked_at': int(time()) }, Entry.platform == 'youtube')

	# Get videos already downloaded
	downloadedvideos = db.get(Entry.platform == 'youtube')['downloaded_videos']

	todownload = []
	for video in videos:
		if video['id'] not in downloadedvideos:
			todownload.append(video)

	nbrtodownload = len(todownload)

	if nbrtodownload == 0:
		return utils.output('nothing_to_download', 'nothing_to_download', utils.translate('nothing_to_download'))

	utils.output('inter', 'nb_to_download', utils.translate('nb_to_download', {
		'nb': nbrtodownload
	}))

	# Create the module downloads directory
	moduledldir = utils.createdldir()

	for i, video in enumerate(todownload):
		utils.output('inter', 'downloading', utils.translate('downloading', {
			'video_title': video['title']
		}))

		# Download the video
		yt = YouTube('https://youtube.com/watch?v=' + video['id'])
		yt.streams.first().download(moduledldir)

		# Add the new downloaded video to the DB
		downloadedvideos.append(video['id'])
		db.update({ 'downloaded_videos': downloadedvideos }, Entry.platform == 'youtube')

	# Will synchronize the content (because "end" type) if synchronization enabled
	return utils.output('end', 'success', utils.translate('success'))
Ejemplo n.º 42
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import requests
import utils
from time import time

# Package database
db = utils.db()['db']

# Lists of the module table
db_lists = db.table('todo_lists')
# Todos of the module table
db_todos = db.table('todo_todos')

# Query
Query = utils.db()['query']()

# Time stamp
timestamp = int(time())

def create_list(string, entities):
	"""Create a to-do list"""

	# List name
	listname = ''

	# Find entities
	for item in entities:
		if item['entity'] == 'list':
			listname = item['sourceText'].lower()