Esempio n. 1
0
    def graph(self, *args):
        # load template
        with open("template.json", "r") as f:
            template = loadJSON(f)

        item = self.scoutingDataLB.get(self.scoutingDataLB.curselection())
        label = None
        # item should be a question (possibly with data (INT))
        # get JSONlabel
        for i in template:
            try:
                if i['question'] in item:
                    label = i['jsonLabel']
            except KeyError:
                pass

        if label is None:
            return

        data = []
        for key_, value_ in self.currentTeam.JSONdata.items():
            for key, value in value_.items():
                if key == label:
                    data.append(value)

        self.__graph__(data)
Esempio n. 2
0
def version_info():
    with open(path.join(path.dirname(argv[0]), 'printsrv', 'package.json'), 'rU') as package_file:
        try:
            local_package_json = loadJSON(package_file)
        except ValueError:
            print 'WARNING: local package.json is damaged.'
            local_package_json = {'version': 'N/A'}
    return local_package_json['version']
Esempio n. 3
0
    def refreshQuestions(self):

        with open('template.json', 'r') as template:
            for i in loadJSON(template):
                if i['type'] == 'header' or i['type'] == 'space':
                    continue

                self.questionsListBox.insert(END, i['question'])
Esempio n. 4
0
	def trainset(self,fname,tportion=0.25,epochs=50):
		if 'datasets/' not in fname:
			fname = 'datasets/' + fname
		if '.json' not in fname:
			fname = fname + '.json'
		f = open(fname)
		mlist = loadJSON(f)
		f.close()
		tportion = int(len(mlist)*max(0,min(1.0,tportion)))
		for k in range(epochs):
			print 'Training: epoch #' + str(k)
			for match in npchoice(mlist,tportion,replace=False):
				a,b = match['a'],match['b']
				self.update(a,b,match['val'])
Esempio n. 5
0
 def trainset(self, fname, tportion=0.25, epochs=50):
     if 'datasets/' not in fname:
         fname = 'datasets/' + fname
     if '.json' not in fname:
         fname = fname + '.json'
     f = open(fname)
     mlist = loadJSON(f)
     f.close()
     tportion = int(len(mlist) * max(0, min(1.0, tportion)))
     for k in range(epochs):
         print 'Training: epoch #' + str(k)
         for match in npchoice(mlist, tportion, replace=False):
             a, b = match['a'], match['b']
             self.update(a, b, match['val'])
Esempio n. 6
0
	def load(fname='NN-00',features=FTVEC):
		if 'datasets/' not in fname:
			fname = 'datasets/' + fname
		if '.json' not in fname:
			fname = fname + '.json'
		f = open(fname)
		data = loadJSON(f)
		f.close()
		NN = NeuralNet(features,hiddencount=data['hsize'])
		for i,hnode in enumerate(NN.hidden):
			hinfo = data['h'+str(i)]
			hnode.bias = hinfo['bias']
			hnode.weights = hinfo['weights']
		NN.output.bias = data['out']['bias']
		NN.output.weights = data['out']['weights']
		return NN
Esempio n. 7
0
 def load(fname='NN-00', features=FTVEC):
     if 'datasets/' not in fname:
         fname = 'datasets/' + fname
     if '.json' not in fname:
         fname = fname + '.json'
     f = open(fname)
     data = loadJSON(f)
     f.close()
     NN = NeuralNet(features, hiddencount=data['hsize'])
     for i, hnode in enumerate(NN.hidden):
         hinfo = data['h' + str(i)]
         hnode.bias = hinfo['bias']
         hnode.weights = hinfo['weights']
     NN.output.bias = data['out']['bias']
     NN.output.weights = data['out']['weights']
     return NN
Esempio n. 8
0
def update():
    try:
        with open('database.json', 'r') as f:
            if time() - loadJSON(f)['last_update'] < 1000:
                return getRet()
    except (FileNotFoundError, JSONDecodeError, KeyError):
        pass
    api.sync()

    od = dict()
    with open("database.json", 'w') as f:
        # Collaborators
        od['users'] = list()
        for collaborator in api.state['collaborators']:
            od['users'].append(f"{collaborator['full_name']} "
                               f"<{collaborator['email']}> "
                               f"(Todoist User #{collaborator['id']})")
        # Projects
        od['projects'] = dict()
        for project in api.state['projects']:
            od['projects'][project['id']] = project['name']
        # Tasks
        od['items'] = list()
        for item in api.state['items']:
            od['items'].append(todoistitem2dict(item))
        # Completed Tasks
        for project_id in [project['id'] for project in api.state['projects']]:
            for item in api.items.get_completed(project_id):
                od['items'].append(todoistitem2dict(item))
        od['items'] = list(
            filter(lambda filter_item: filter_item is not None, od['items']))
        od['meta'] = {
            'users-count': len(od['users']),
            'tasks-count': len(od['items'])
        }
        od['last_update'] = int(time())
        dumpJSON(od, f)
    return getRet()
Esempio n. 9
0
def main():
    with open('database.json', 'r') as f:
        db = loadJSON(f)
        start = request.args.get(
            'after',
            default=0,
            type=int
        )
        perpage = request.args.get(
            'perpage',
            default=8,
            type=int
        )
        end = min([
            start + perpage - 1,
            len(db['items'])
        ])
        litems = db['items'] if perpage < 1 else db['items'][start:end + 1]
        pid = request.args.get('project', type=int)
        if pid is not None:
            litems = filter(lambda item: item['parent-project'] == pid, litems)
        return render_template(
            "infoIndex.html",
            currTime=lambda: strftime("%c"),
            litems=litems,
            pagination=None if perpage < 1 else {
                'page': round(start / perpage) + 1,
                'totalPages': max(1, ceil(len(db['items']) / perpage)),
                'perpage': perpage,
                'first_page_url': '/?after=%i&perpage=%i' % (0, perpage),
                'last_page_url': '/?after=%i&perpage=%i' % (len(db['items']) - len(db['items']) % perpage, perpage),
                'prev_page_url': '/?after=%i&perpage=%i' % (max(0, start - perpage), perpage),
                'next_page_url': '/?after=%i&perpage=%i' % (end + 1 if end + 1 < len(db['items']) else start, perpage)
            },
            timedelta2readable=lambda seconds: str(timedelta(seconds=seconds))
        )
Esempio n. 10
0

class FixedDropout(Dropout):
    def _get_noise_shape(self, inputs):
        if self.noise_shape is None:
            return self.noise_shape
        return tuple([
            shape(inputs)[i] if sh is None else sh
            for i, sh in enumerate(self.noise_shape)
        ])


customObjects = {'swish': nn.swish, 'FixedDropout': FixedDropout}

with open(join(dirname(realpath(__file__)), 'Settings.json'), 'r') as f:
    data = loadJSON(f)
    currentPath = join(str(data['CurrentPath']))
    relativeData = join(str(data['RelativeData']))
    classNames = list(array(data['ClassNames']).astype(str))
    imageDimensions = list(array(data['ImageDimensions']).astype(int))
    mode = str(data['Mode'])

checkpointsDir = join(currentPath, 'Checkpoints')
logDir = join(currentPath, 'Log')

if mode == 'classification':

    def resize(imageDimensions):
        return Sequential([
            CenterPadToAspectRatio(float(imageDimensions[0]) /
                                   float(imageDimensions[1]),
Esempio n. 11
0
def getRet():
    with open('database.json', 'r') as f:
        return loadJSON(f)
Esempio n. 12
0
def dictFromJSONFile(fName):
    '''
    Take a JSON file, return a dict with the information.
    '''
    with open(fName) as f:
        return loadJSON(f)
Esempio n. 13
0
    def selectTeamFromList(self, teamNumber):
        if not tba.isOnline():
            return
        # TODO: use team module instead
        # do we? idk? this whole thing has gone to crap and i cant wait to nuke it

        team = Team(teamNumber)
        self.currentTeam = team

        teamname = team.name

        attendedEvents = "Attended events:\n"
        for event, record in team.attendedEvents.items():
            attendedEvents += "{}:{}".format(event, record)
            attendedEvents += '\n'

        for child in self.teamInfoFrame.winfo_children():
            child.destroy()

        header = Label(self.teamInfoFrame,
                       text="Team " + str(teamNumber) + " : " + teamname,
                       font=("Helvetica", 20, "bold"))
        header.grid(row=0, column=0, columnspan=9999)

        attendedEvents = Label(self.teamInfoFrame, text=attendedEvents)
        attendedEvents.grid(row=1, column=0)

        # setup team image
        img = Image.open(team.image)

        def onImageClick(event):
            if system() == 'Darwin':  # macOS
                subCall(('open', team.image))
            elif system() == 'Windows':  # Windows
                startfile(team.image)
            else:  # linux variants
                subCall(('xdg-open', team.image))

        # 231 x 231 is about the size of our defualt image, use that as our max size
        img.thumbnail((231, 231), Image.ANTIALIAS)

        self.photo = ImageTk.PhotoImage(img)
        imgLabel = Label(self.teamInfoFrame, image=self.photo)
        imgLabel.bind(
            "<Button-1>", onImageClick
        )  # call onImageClick when mouse1 is pressed on the image
        imgLabel.grid(row=1, column=1, padx=10, pady=10)

        # display scouting data
        scoutingDataFrame = Frame(self.teamInfoFrame)
        scoutingDataFrame.grid(row=2, column=0, columnspan=2, sticky=NSEW)

        # setup scroll bars and listbox to display the data
        scrollx = Scrollbar(scoutingDataFrame, orient=HORIZONTAL)
        scrolly = Scrollbar(scoutingDataFrame)
        self.scoutingDataLB = Listbox(scoutingDataFrame,
                                      xscrollcommand=scrollx.set,
                                      yscrollcommand=scrolly.set)
        self.scoutingDataLB.bind("<Double-Button-1>", self.graph)
        scrollx.config(command=self.scoutingDataLB.xview)
        scrolly.config(command=self.scoutingDataLB.yview)

        scrollx.grid(row=1, column=0, sticky=EW)
        scrolly.grid(row=0, column=1, sticky=NS)
        self.scoutingDataLB.grid(row=0, column=0, sticky=NSEW)
        scoutingDataFrame.columnconfigure(0, weight=1)

        # setup seperate box for comments because massimo wants it
        commentsScrollx = Scrollbar(scoutingDataFrame, orient=HORIZONTAL)
        commentsScrolly = Scrollbar(scoutingDataFrame)
        commentsLB = Listbox(scoutingDataFrame,
                             xscrollcommand=commentsScrollx.set,
                             yscrollcommand=commentsScrolly.set)
        commentsScrollx.config(command=commentsLB.xview)
        commentsScrolly.config(command=commentsLB.yview)

        commentsScrollx.grid(row=3, column=0)
        commentsScrolly.grid(row=2, column=1)
        commentsLB.grid(row=2, column=0, sticky=NSEW)
        commentsLB.insert(END, "Comments:")

        # load template
        with open("template.json", "r") as f:
            template = loadJSON(f)

        # loop though our scouting data, grab each question, and display it

        # categorize our data
        # vars for ints
        totals = {}
        increments = {}

        # non-ints
        nonInts = {
        }  # going to be like this {question0:[data from match 1, match 2, match 3], question1:[...
        for key_, value_ in team.JSONdata.items():
            for key, value in value_.items():

                if key == "robot" or key == "match":
                    continue

                if type(value) is int:
                    try:
                        totals[key] += value
                        increments[key] += 1
                    except KeyError:
                        totals[key] = value
                        increments[key] = 1

                else:
                    if type(value) == bool:
                        value = "Yes" if value else "No"

                    try:
                        nonInts[key].append(value)
                    except KeyError:
                        nonInts[key] = [value]

        for key, value in totals.items():
            # find the question
            question = ""
            for i in template:
                try:
                    if i['jsonLabel'] == key:
                        question = i['question']
                except KeyError:
                    pass

            # add this question to our data output
            self.scoutingDataLB.insert(
                END, question + " : " +
                str(round((float(value) / increments[key]), 2)))

        for key, value in nonInts.items():
            # find the question
            # this is pretty similar to the previous loop and could probably be combined but at this point idk
            if key != "comments":
                question = ""
                for i in template:
                    try:
                        if i['jsonLabel'] == key:
                            question = i['question']
                    except KeyError:
                        pass

                # add it to our box/output
                self.scoutingDataLB.insert(END, question + ":")

            for i in value:
                if i.strip() != '':
                    if key == "comments":
                        commentsLB.insert(END, "    " + i)
                    else:
                        self.scoutingDataLB.insert(END, "    " + i)
Esempio n. 14
0
        raise ValueError('"info" must be either "fiscal", "tickets" or "update" in {0}.'.format(PLP_FILENAME))
    if plp_json_data['info'] == 'fiscal':
        if not 'operation' in plp_json_data:
            raise IndexError('Missing "operation" field in plp file {0}.'.format(PLP_FILENAME))
        if plp_json_data['operation'] not in ('sale', 'refund', 'startshift', 'endshift'):
            raise ValueError('"operation" must be one of "sale", "refund", "startshift", "endshift" in {0}.'.format(PLP_FILENAME))
    if plp_json_data['info'] == 'update':
        if not 'version' in plp_json_data:
            print('Note: Missing "version" field in plp file {0}.'.format(PLP_FILENAME))


# Detect plp file type.
# If valid JSON, read file type from 'info' field, otherwise assume it's for tickets
try:
    with open(PLP_FILENAME, 'rU') as plp_data_file:
        PLP_JSON_DATA = loadJSON(plp_data_file)
        PLP_JSON_FILENAME = PLP_FILENAME
        chmod(PLP_JSON_FILENAME, S_IWRITE)
except ValueError:
    PLP_JSON_DATA = read_plp_file(PLP_FILENAME)
    # Backward compatible
    PLP_JSON_DATA['info'] = 'tickets'
    PLP_JSON_FILENAME = '{0}.json'.format(PLP_FILENAME)
else:
    pass

PLP_CONTENT_TYPE = PLP_JSON_DATA['info']
PLP_PRINTER_TYPE = (PLP_JSON_DATA['printerType'] if 'printerType' in PLP_JSON_DATA else PLP_CONTENT_TYPE)

if PLP_PRINTER_TYPE == 'fiscal':
    with ioOpen(PLP_JSON_FILENAME, 'w', encoding='utf-8') as outfile:
Esempio n. 15
0
from json import load as loadJSON
from os import path
from sys import argv

BASEDIR = path.realpath(path.dirname(argv[0]))
PACKAGE_FILE_NAME = path.join(BASEDIR, 'package.json')

with open(PACKAGE_FILE_NAME, 'r') as package_json_file:
    VERSION = loadJSON(package_json_file)['version']
Esempio n. 16
0
    def updateSort(self, question, listBox, reversed=False):
        listBox.delete(0, END)

        data = {}
        jsonLabel = ""
        isRdo = False
        with open('template.json') as t:
            template = loadJSON(t)

            for i in template:
                if i["type"] == "header" or i["type"] == "space":
                    continue

                if i['question'] == question:
                    isRdo = i['type'] == 'rdoBtn'
                    jsonLabel = i['jsonLabel']

        for file in listdir(GUI.filedir):
            if file.lower().endswith(".json"):
                with open(GUI.filedir + '\\' + file) as f:
                    fileJson = loadJSON(f)

                for i in fileJson:
                    try:
                        robot = i['robot']
                        toAdd = i[jsonLabel]

                        if isRdo:
                            if toAdd == '':
                                continue

                            toAdd = int(toAdd)

                        if robot in data:
                            data[robot].append(toAdd)
                        else:
                            data[robot] = [toAdd]
                    except KeyError:  # that question isn't in this data
                        continue

        # now we have to do some operations depending on what datatype we're working with
        # get our datatype

        datatype = type(data[list(data.keys())[0]][0])

        newData = {}
        if datatype == int:
            # turn everything into averages
            for team, value in data.items():
                total = 0.0
                for i in value:
                    total += i

                total /= len(value)

                newData[team] = total

        elif datatype == bool:
            # calculate our average (false = 0, true = 1, >=.5 is true)
            for team, value in data.items():
                total = 0.0
                for i in value:
                    total += 1 if i else 0

                total /= len(value)

                newData[team] = total * 100

        sortedData = sorted(newData.items(),
                            key=itemgetter(1),
                            reverse=reversed)

        for i in sortedData:
            listBox.insert(END, i)
Esempio n. 17
0
 async def getMeme(self, interaction: discord.Interaction):
     meme = loadJSON(request('https://meme-api.herokuapp.com/gimme').text)
     embed = discord.Embed(title=meme['title'])
     embed.set_image(url=meme['url'])
     await interaction.response.send_message(embed=embed)