예제 #1
0
def kmeans(task):

    start = time.time()

    output = []

    buildings, antennas, reward = read(path + task)

    X = np.array([[int(building.x), (building.y)] for building in buildings])

    kmeans = KMeans(n_clusters=len(antennas), max_iter=1)
    kmeans.fit(X)

    centroids_x = [int(value[0]) for value in kmeans.cluster_centers_]
    centroids_y = [int(value[1]) for value in kmeans.cluster_centers_]

    antennas.sort(key=lambda antenna: antenna.speed, reverse=True)

    for i in range(len(centroids_x)):
        antennas[i].x = centroids_x[i]
        antennas[i].y = centroids_y[i]
        output.append(antennas[i])

    write('output/' + str(task.split('.')[0]) + '.txt', output)

    print(task, str(time.time() - start))
예제 #2
0
    def print_board(self, k):
        '''print board function'''
        if self.player.level == 1:
            print_background(self)
            print_player(self)
            draw_brick(self, self.bricks)
            print_enemy(self)
            print_bullet(self, self.bullets)
            print_bullet(self, self.ebul)

            if self.alivev == 1:
                print_villain(self, self.vil.posx, self.vil.posy)

            if self.alivev == 0:
                win(self)
                # time.sleep(3)

            temp = ""

            string = '\033[93m' + "Life=" + str(
                self.player.life) + " Score=" + str(
                    self.player.score) + " Coins=" + str(
                        self.player.coins) + "\n" + '\033[0m'
            if k >= 550 and self.alivev == 1:
                string += '\033[93m' + "Boss Life=" + \
                    str(self.vil.life) + "\n" + '\033[0m'

            temp += string

            for i in range(40):

                for j in range(k, k + 150, 1):
                    temp += self.level1[i][j]

            print(temp)
        else:
            print_background(self)
            print_player(self)
            draw_brick(self, self.bricks2)
            draw_coin(self, self.coins)

            if time.time() - self.time >= 0.3:
                write(self)
                self.time = time.time()

            temp = ""

            string = '\033[93m' + "Life=" + str(
                self.player.life) + " Score=" + str(
                    self.player.score) + " Coins=" + str(
                        self.player.coins) + "\n" + '\033[0m'

            temp += string

            for i in range(40):

                for j in range(k, k + 150, 1):
                    temp += self.level1[i][j]

            print(temp)
예제 #3
0
파일: Simulation.py 프로젝트: timjrd/mrsep
    def new(self, params):
        os.makedirs(params.out_dir, exist_ok=True)

        self.params = params
        w.write(params.out_dir + "/params.json",
                w.pretty_json(params.to_json()))

        self.sample = Sample().new(params)
        sample_file = params.out_dir + "/sample.fasta"
        w.write(sample_file, w.fasta(self.sample))

        art_prefix = params.out_dir + "/art"
        art = os.environ['ART_ILLUMINA']
        subprocess.run([
            art, "--in", sample_file, "--out", art_prefix, "--rndSeed",
            str(params.seed)
        ] + params.art_flags,
                       stdout=subprocess.DEVNULL)
        self.art_output = r.read(art_prefix + ".aln", r.aln(params.take_ref))

        self.instance = Instance().new(params, self.art_output)
        w.write(params.out_dir + "/instance.json",
                w.json(self.instance.to_json()))
        w.write(params.out_dir + "/instance.txt",
                w.text(self.instance.to_text()))
        w.write(params.out_dir + "/instance.stats.json",
                w.json(self.instance.stats()))

        return self
    def displayStats(self):
        if self.tests_failed:
            bg_colour = "#ff0000"
            fg_colour = "#ffffff"
        else:
            bg_colour = "#00ff00"
            fg_colour = "#000000"

        tests_passed = self.tests_completed - self.tests_failed
        if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
            output = "<table cellpadding=4 width=100%><tr><td bgcolor='" + bg_colour + "'><font face='arial' size=4 color='" + fg_colour + "'><b>"
        else:
            output = ""
        output += self.getNameFmt(
        ) + "Passed %d " % tests_passed + "/ %d" % self.tests_completed + " tests"

        if self.tests_failed:
            output += " (%d failed)" % self.tests_failed

        if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
            output += "</b></font></td></tr></table>"
        else:
            output += "\n"

        write(output)
예제 #5
0
def subopen(args, stdin=None, shell=False, cwd=None, env=None):
    temp = None
    pid = None
    close_fds = True
    rstrip = True
    try:
        if stdin is not None and isstring(stdin):
            temp = tempfile()
            write(temp, stdin)
            stdin = open(temp)
        args = tolist(args)
        for i, arg in enumerate(args):
            if not isinstance(arg, int):
                if PY3:
                    args[i] = str(arg)  # python3
                else:
                    args[i] = __builtin__.unicode(arg)  # python2
        if not env:
            env = os.environ.copy()
        process = subprocess.Popen(args,
                                   stdin=stdin,
                                   stderr=subprocess.PIPE,
                                   stdout=subprocess.PIPE,
                                   close_fds=close_fds,
                                   shell=shell,
                                   cwd=cwd,
                                   env=env,
                                   universal_newlines=False  # ,
                                   # startupinfo=startupinfo#,
                                   # creationflags=creationflags
                                   )
        pid = process.pid
        stdoutdata, stderrdata = process.communicate()
        if PY3:
            # python3. process.communicate returns bytes
            stdoutdata = str(stdoutdata, "utf-8")  # stdoutdata
            stderrdata = str(stderrdata, "utf-8")  # stderrdata
        # rstrip
        if rstrip and stdoutdata:
            stdoutdata = stdoutdata.rstrip()
        if rstrip and stderrdata:
            stderrdata = stderrdata.rstrip()
        returncode = process.returncode
        return (returncode, stdoutdata, stderrdata)
        # raise CalledProcessError(returncode,args,err)
        # if returncode!=0:
        # raise CalledProcessError(returncode,args,stderrdata)
        # return stdoutdata
    finally:
        try:
            if pid:
                os.killpg(pid, signal.SIGTERM)
        except Exception:
            pass
            # print(format_exc())
        rm(temp)
예제 #6
0
 def testConflictedMerge(self):
     config.journalPath = self.localDir
     write.time = datetime.datetime.strftime(datetime.datetime.strptime("11:00:00", "%H:%M:%S"), config.timeFormat)
     write.write(name="1800-01-01", tags=self.remoteContent[0], content=self.localContent[1], quiet=True)
     merge = sync.Sync(self.remoteDir, self.localDir)
     sync.raw_input = lambda _: "2" 
     merge.merge()
     self.assertEqual(filecmp.dircmp(self.remoteDir, self.localDir).left_only, [])
     self.assertEqual(filecmp.dircmp(self.remoteDir, self.localDir).right_only, [])
     self.assertEqual(filecmp.dircmp(self.remoteDir, self.localDir).diff_files, [])
예제 #7
0
 def testMultiPageSearch(self):
     tag = self.tagList[5]
     content = self.contentList[0]
     write.write("test-1", tags=tag, content=content, quiet=True)
     write.write("test-99", tags=tag, content=content, quiet=True)
     expected = [["# test-1\n", "{0} {1}  \n".format(write.time, tag)
                   + write.prepareContent(content)],
                  ["# test-99\n", "{0} {1}  \n".format(write.time, tag)
                    + write.prepareContent(content)]]
     self.assertEquals(expected, search.search(tag))
예제 #8
0
파일: jrny.py 프로젝트: DetonDev/jrny
def main(args):
    """ select appropriate response """

    if args.status == True:
        status.status()

    elif args.write == True:
        write.write()

    else:
        parser.print_help()
예제 #9
0
def makerandom(target):
    global quality
    ind = []
    for i in range(config.IND_SIZE):
        ind.append(random.random())
    config.listToConfig(ind)
    config.init()
    melody.generate()
    write.write([melody.melody], [melody.rhythm])
    # print sum(melody.rhythm)
    rewrite("output.mid", target, 0)
예제 #10
0
def sentence():
    if tk.token.code == CodeTable['IDENTIFIER']:
        assipro.assipro()
    elif tk.token.code == CodeTable['IF']:
        ifsent.ifsent()
    elif tk.token.code == CodeTable['WHILE']:
        whilsent.whilsent()
    elif tk.token.code == CodeTable['READ']:
        read.read()
    elif tk.token.code == CodeTable['WRITE']:
        write.write()
    elif tk.token.code == CodeTable['BEGIN']:
        compsent.compsent()
예제 #11
0
def evaluate(individual):
    global tim
    config.listToConfig(individual)
    config.init()
    x = 0
    for i in range(config.evaluationToAverage):
        tim += time.process_time()
        melody.generate()
        write.write([melody.melody], [melody.rhythm])
        write.save()
        track = miditotxt.rewrite('output.mid')
        tim -= time.process_time()
        x += discriminator.evaluate(track)
    return x/config.evaluationToAverage,
예제 #12
0
 def run(self):
     try:
         for copied in write.write(self.source, self.destination):
             self.value += copied
             if self.stop: return
     except Exception as ex:
         self.ex = ex
예제 #13
0
def solver(task):

    start = time.time()

    output = []

    buildings, antennas, reward = read(path + task)

    for i in range(min(len(buildings), len(antennas))):
        antennas[i].x = buildings[i].x
        antennas[i].y = buildings[i].y
        output.append(antennas[i])

    write('output/' + str(task.split('.')[0]) + '.txt', output)

    print(task, str(time.time() - start))
예제 #14
0
def tracker(name):

    if exist(name):
        app = increment(name)

        image = write(app["count_visited"])

        try:
            response = make_response(
                send_file(BytesIO(image),
                          attachment_filename="logo.jpg",
                          mimetype="image/jpg"))

            # Disable caching
            response.headers["Pragma-Directive"] = "no-cache"
            response.headers["Cache-Directive"] = "no-cache"
            response.headers[
                "Cache-Control"] = "no-cache, no-store, must-revalidate"
            response.headers["Pragma"] = "no-cache"
            response.headers["Expires"] = "0"
            return response
        except:
            pass
    else:
        return "Not found"
예제 #15
0
def main():

    status()
    dump_data()

    # Updates everything
    insts = get_insts()
    update(insts)

    for inst in insts:
        r = do_thing(inst, Settings.INTERVAL)
        r.to_csv('{}/{}.csv'.format(Settings.PATH_RESULTS, inst), index=False)

    for inst in insts:
        write(inst, '{}/{}.csv'.format(Settings.PATH_RESULTS, inst))

    status()
예제 #16
0
def normalize(in_path, out_path):
    print 'Reading concept data'
    concepts = list(read_ontology())
    
    concept_ids, concept_names, concept_map, concept_vectors, tfidf_vectorizer = build_tfidf(concepts)
    reverse_concept_map = {concept_ids[i]:concept_names[i] for i in range(len(concept_names))}
    print 'Making predictions'
    
    devel_data = read(in_path)
    
    devel_tuples = []
    for entity_id, data in devel_data.items():
        entity_span = data[0]
        for ann in data[1:]:
            devel_tuples.append((entity_id, entity_span, ann))
    devel_entity_ids = [d[0] for d in devel_tuples]
    devel_spans = [d[1] for d in devel_tuples]
    
    # Acronym expansion
    if settings.ENTITY_TYPE == 'Bacteria':
        from collections import defaultdict
        doc_entities = defaultdict(list)
        for i, entity_span in enumerate(devel_spans):
            if len(entity_span) >= 5 and not entity_span.isupper():
                doc_entities[devel_entity_ids[i].split('___')[0]].append(entity_span)
        
        for i, entity_span in enumerate(devel_spans):
            if len(entity_span) < 5 or entity_span.isupper():
                #print 'Too small entity: %s' % entity_span
                entity_vect = tfidf_vectorizer.transform([entity_span])
                prev_entities = doc_entities[devel_entity_ids[i].split('___')[0]]
                if len(prev_entities) > 0:
                    prev_entity_acronyms = [''.join([l[0] for l in e.split()]) for e in prev_entities]
                    doc_vects = tfidf_vectorizer.transform(prev_entity_acronyms)
                    best_hit = numpy.argmax(cosine_similarity(entity_vect, doc_vects), axis=1)[0]
                    new_span = doc_entities[devel_entity_ids[i].split('___')[0]][best_hit]
                    #print 'Entity: %s, expansion: %s' % (entity_span, new_span)
                    devel_spans[i] = new_span
    
    devel_vectors = tfidf_vectorizer.transform(devel_spans)
    sims = cosine_similarity(devel_vectors, concept_vectors)
    devel_hits = numpy.argmax(sims, axis=1)
    predicted_labels = [concept_ids[i] for i in devel_hits]

    write(list(zip(devel_entity_ids, predicted_labels)), out_path)
예제 #17
0
	def displayStats(self):
		if self.tests_failed:
			bg_colour="#ff0000"
			fg_colour="#ffffff"
		else:
			bg_colour="#00ff00"
			fg_colour="#000000"
		
		tests_passed=self.tests_completed - self.tests_failed
		
		output="<table cellpadding=4 width=100%><tr><td bgcolor='" + bg_colour + "'><font face='arial' size=4 color='" + fg_colour + "'><b>"
		output+=self.getNameFmt() + "Passed " + tests_passed + "/" + self.tests_completed + " tests"
		
		if self.tests_failed:
			output+=" (" + self.tests_failed + " failed)"
			
		output+="</b></font></td></tr></table>"
		
		write(output)
예제 #18
0
def solver(task):

    start = time.time()

    output = []

    buildings, antennas, reward = read(path + task)

    antennas.sort(key=lambda x: x.speed, reverse=True)
    buildings.sort(key=lambda x: x.speed_weight, reverse=True)

    for i in range(min(len(buildings), len(antennas))):

        antennas[i].x = buildings[i].x
        antennas[i].y = buildings[i].y
        output.append(antennas[i])

    write('output/' + str(task.split('.')[0]) + '.txt', output)

    print(task, str(time.time() - start))
    def displayStats(self):
        if self.tests_failed:
            bg_colour = "#ff0000"
            fg_colour = "#ffffff"
        else:
            bg_colour = "#00ff00"
            fg_colour = "#000000"

        tests_passed = self.tests_completed - self.tests_failed

        output = "<table cellpadding=4 width=100%><tr><td bgcolor='" + bg_colour + "'><font face='arial' size=4 color='" + fg_colour + "'><b>"
        output += self.getNameFmt(
        ) + "Passed " + tests_passed + "/" + self.tests_completed + " tests"

        if self.tests_failed:
            output += " (" + self.tests_failed + " failed)"

        output += "</b></font></td></tr></table>"

        write(output)
예제 #20
0
def osascript(applescript, flags=None):
    """osascript applescript code or file
    """
    args = ["osascript"]
    if applescript and isinstance(applescript, list):
        applescript = "\n".join(applescript)
    temp = programfile = None
    if applescript and os.path.exists(applescript):
        programfile = applescript
    else:
        temp = programfile = tempfile()
        write(temp, applescript)
    try:
        if flags:
            args += ["-s", flags]
        if programfile:
            args.append(programfile)
        returncode, stdout, stderr = subopen(args)
        return (returncode, stdout, stderr)
    finally:
        rm(temp)
    def fail(self, msg=None):
        self.startTest()
        self.tests_failed += 1

        if not msg:
            msg = "assertion failed"
        else:
            msg = str(msg)

        octothorp = msg.find("#")
        has_bugreport = octothorp >= 0 and msg[octothorp + 1].isdigit()
        if has_bugreport:
            name_fmt = "Known issue"
            bg_colour = "#ffc000"
            fg_colour = "#000000"
        else:
            bg_colour = "#ff8080"
            fg_colour = "#000000"
            name_fmt = "Test failed"
        output = "<table style='padding-left:20px;padding-right:20px;' cellpadding=2 width=100%><tr><td bgcolor='" + bg_colour + "'><font color='" + fg_colour + "'>"
        write(output)
        title = "<b>" + self.getNameFmt(name_fmt) + "</b>"
        write(title + msg)
        output = "</font></td></tr></table>"
        output += "\n"
        write(output)
        if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
            from __pyjamas__ import JS
            JS("""if (typeof @{{!console}} != 'undefined') {
                if (typeof @{{!console}}.error == 'function') @{{!console}}.error(@{{msg}});
                if (typeof @{{!console}}.trace == 'function') @{{!console}}.trace();
            }""")
        return False
예제 #22
0
파일: UnitTest.py 프로젝트: audreyr/pyjs
    def fail(self, msg=None):
        self.startTest()
        self.tests_failed+=1

        if not msg:
            msg="assertion failed"
        else:
            msg = str(msg)

        octothorp = msg.find("#")
        has_bugreport = octothorp >= 0 and msg[octothorp+1].isdigit()
        if has_bugreport:
            name_fmt = "Known issue"
            bg_colour="#ffc000"
            fg_colour="#000000"
        else:
            bg_colour="#ff8080"
            fg_colour="#000000"
            name_fmt = "Test failed"
        output="<table style='padding-left:20px;padding-right:20px;' cellpadding=2 width=100%><tr><td bgcolor='" + bg_colour + "'><font color='" + fg_colour + "'>"
        write(output)
        title="<b>" + self.getNameFmt(name_fmt) + "</b>"
        write(title + msg)
        output="</font></td></tr></table>"
        output+= "\n"
        write(output)
        if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
            from __pyjamas__ import JS
            JS("""if (typeof @{{!console}} != 'undefined') {
                if (typeof @{{!console}}.error == 'function') @{{!console}}.error(@{{msg}});
                if (typeof @{{!console}}.trace == 'function') @{{!console}}.trace();
            }""")
        return False
예제 #23
0
파일: Simulation.py 프로젝트: timjrd/mrsep
    def new(self, root_dir, strains, aligned, sample):
        out_dir = root_dir + "/" + sample[0]

        os.makedirs(out_dir, exist_ok=True)

        # sample_json = out_dir + "/sample.json"
        # w.write(sample_json, w.json(s.to_json(sample)))

        sample_fasta = out_dir + "/sample.fasta"
        w.write(sample_fasta, w.fasta(s.to_fasta(sample)))

        art_prefix = out_dir + "/art"
        art = os.environ['ART_ILLUMINA']
        subprocess.run([
            art, "--in", sample_fasta, "--out", art_prefix, "--seqSys", "HS20",
            "--len", "100", "--fcov", "100"
        ],
                       stdout=subprocess.DEVNULL)
        take_ref = False
        art_output = r.read(art_prefix + ".aln", r.aln(take_ref))

        instance = Instance().new(strains, aligned, art_output)
        # w.write(out_dir + "/instance.json", w.json(instance.to_json()))
        w.write(out_dir + "/instance.txt", w.text(instance.to_text()))
        w.write(out_dir + "/instance.stats.json", w.json(instance.stats()))
예제 #24
0
 def setUp(self):
     self.tempPath = tempfile.mkdtemp(prefix="diariumSearchTest-")
     config.journalPath = self.tempPath
     self.numberOfFiles = 100
     self.tagList = list()
     self.contentList = list()
     for j in range(10):
         self.tagList.append(''.join(random.choice(string.ascii_letters) for k in range(10)))
         self.contentList.append(''.join(random.choice(string.ascii_letters) for k in range(100)))
     for i in range(self.numberOfFiles):
         name = "test-{0}".format(i)
         for j in range(10):
             write.write(name, tags=str(j), content=str(i), quiet=True)
     write.write("0001-01-01", content="Start of datesearch", quiet=True)
     write.write("0015-01-01", content="Middle of datesearch", quiet=True)
     write.write("0031-01-01", content="End of datesearch", quiet=True)
예제 #25
0
def solver(task):

    start = time.time()

    duration, n_intersec, n_streets, n_cars, bonus, streets, cars, intersections = read(
        path + task + '.txt')

    output = []

    for intersec in intersections:
        intersec_streets = intersec.streets_in
        intersec_streets.sort(key=lambda x: x.cars, reverse=True)

        schedule_pairs = [
            SchedulePair(street_in, 1) for street_in in intersec_streets
        ]
        output.append(Schedule(schedule_pairs, intersec))

    write('./output/' + task + '.txt', output)

    # score = judge(output)

    print(task, str(time.time() - start))
예제 #26
0
파일: UnitTest.py 프로젝트: audreyr/pyjs
    def displayStats(self):
        if self.tests_failed:
            bg_colour="#ff0000"
            fg_colour="#ffffff"
        else:
            bg_colour="#00ff00"
            fg_colour="#000000"

        tests_passed=self.tests_completed - self.tests_failed
        if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
            output="<table cellpadding=4 width=100%><tr><td bgcolor='" + bg_colour + "'><font face='arial' size=4 color='" + fg_colour + "'><b>"
        else:
            output = ""
        output+=self.getNameFmt() + "Passed %d " % tests_passed + "/ %d" % self.tests_completed + " tests"

        if self.tests_failed:
            output+=" (%d failed)" % self.tests_failed

        if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
            output+="</b></font></td></tr></table>"
        else:
            output+= "\n"

        write(output)
예제 #27
0
파일: UnitTest.py 프로젝트: wkornewald/pyjs
    def fail(self, msg=None):
        self.startTest()
        self.tests_failed += 1

        if not msg:
            msg = "assertion failed"
        else:
            msg = str(msg)

        has_bugreport = False
        for issue in issue_re.findall(msg):
            # TODO/XXX/HACK: The findall() method in pyjs is buggy and also returns
            # the leading '#' character, so strip it as a workaround.
            issue = issue.lstrip('#')
            print issue, issues.get(issue)
            if issue in issues and issues[issue] != 'Fixed':
                has_bugreport = True
                break

        if has_bugreport:
            name_fmt = "Known issue"
            bg_colour = "#ffc000"
            fg_colour = "#000000"
        else:
            bg_colour = "#ff8080"
            fg_colour = "#000000"
            name_fmt = "Test failed"
        output = "<table style='padding-left:20px;padding-right:20px;' cellpadding=2 width=100%><tr><td bgcolor='" + bg_colour + "'><font color='" + fg_colour + "'>"
        write(output)
        title = "<b>" + self.getNameFmt(name_fmt) + "</b>"
        write(title + msg)
        output = "</font></td></tr></table>"
        output += "\n"
        write(output)
        if sys.platform in ['mozilla', 'ie6', 'opera', 'oldmoz', 'safari']:
            from __pyjamas__ import JS
            JS("""if (typeof @{{!console}} != 'undefined') {
                if (typeof @{{!console}}.error == 'function') @{{!console}}.error(@{{msg}});
                if (typeof @{{!console}}.trace == 'function') @{{!console}}.trace();
            }""")
        return False
예제 #28
0
 def setUp(self):
     self.localDir = tempfile.mkdtemp(suffix="local")
     self.remoteDir = tempfile.mkdtemp(suffix="remote")
     config.journalPath = self.localDir
     self.localContent = ["tag1, tag2, tag3", "LoremIpsum\nDolorSit amet\nLOCAL\nLOCAl"]
     self.sharedContent = ["tag2, tag4", "Share the Lorem Ipsum\nShare IT!"]
     self.remoteContent = ["tag4, tag5", "Remote\nStuff"]
     write.time = datetime.datetime.strftime(datetime.datetime.strptime("00:00:00", "%H:%M:%S"), config.timeFormat)
     write.write(name="1900-01-01", tags=self.localContent[0], content=self.localContent[1], quiet=True)
     write.time = datetime.datetime.strftime(datetime.datetime.strptime("10:00:00", "%H:%M:%S"), config.timeFormat)
     write.write(name="1841-01-01", tags=self.sharedContent[0], content=self.sharedContent[1], quiet=True)
     config.journalPath = self.remoteDir
     write.write(name="1841-01-01", tags=self.sharedContent[0], content=self.sharedContent[1], quiet=True)
     write.time = datetime.datetime.strftime(datetime.datetime.strptime("11:00:00", "%H:%M:%S"), config.timeFormat)
     write.write(name="1841-01-01", tags=self.remoteContent[0], content=self.remoteContent[1], quiet=True)
     write.write(name="1800-01-01", tags=self.remoteContent[0], content=self.remoteContent[1], quiet=True)
     write.write(name="1900-01-01", tags=self.remoteContent[0], content=self.remoteContent[1], quiet=True)
예제 #29
0
def set(channel, ONorOFF):
    # AWGoutput.set		- set desired channel to ON or OFF
    Command = ":OUTP" + str(channel) + " " + str(ONorOFF)
    return write.write(AWGadd, Command)
예제 #30
0
 def annotate_dir(self, wypluwka_dir, output_dir, save_gzipped=True):
     tmp_name = self._tmp_name(output_dir, save_gzipped)
     out = self._output_for(tmp_name, save_gzipped)
     write.write(out, self._annotations(wypluwka_dir))
     out.close()
     shutil.move(tmp_name, self._out_name(output_dir, save_gzipped))
예제 #31
0
count = {}

# Create an array of note sequences for each song
while i < 60:
    if (i == 33) or (i == 34):
        i += 1
    else:
        array.array(i, notes)
        i += 1

# Map note transitions for all songs
while j < 60:
    if (j == 32) or (j == 33) or (j == 34):
        j += 1
    else:
        compare.compare(j, count, notes)
        j += 1

# Generate probability matrix
while co < 12:
    compare.probability(co, count)
    co += 1

# Write 60 measures of song
while k < 60:
    write.write(p, count)
    k += 1

# Display song as musicXML
song.show()
예제 #32
0
파일: main.py 프로젝트: fenimore/edifice
    if args.draw and args.filename:
        logging.info(f"Drawing Inky {args.filename}")
        image = prepare(inky_display, args.filename)
        draw(inky_display, image)

    if args.write:
        logging.info(f"Writing Inky lines from stdin")
        font = ImageFont.truetype(args.font, args.font_size)
        # font = ImageFont.truetype(FredokaOne, args.font_size)
        lines = fit_lines(
            "\n".join(sys.stdin.readlines()).strip(),
            font,
            inky_display.WIDTH,
            padding=args.font_padding * 2,
        )
        logging.info(f"First Line: {lines[0]}...")
        image = draw_lines(
            inky_display,
            lines,
            font,
            origin=(args.font_padding, args.font_padding),
        )
        write(inky_display, image)

    if args.weather:
        logging.info("Plotting weather")
        filename = args.filename or "/tmp/weather_forecast.png"
        save_png(filename)
        image = prepare(inky_display, filename)
        draw(inky_display, image)
예제 #33
0
from read import read
from execute import execute
from write import write
from scipy.stats import random_correlation


if __name__ == "__main__":
    
    ### Read inputs ###
    # Tasks:
    # 1 - select your input folder
    # 2 - select your input file name
    inputFilePath = ''
    inputFileName = ''
    sheetName = 'Input'
    read(inputFilePath, inputFileName, sheetName)
    
    ### Execute operations ###
    execute()
    
    ### Write output ###
    # Tasks:
    # 1 - select your output folder
    # 2 - select your output file name
    outputFilePath = ''
    outputFileName = ''
    write(outputFilePath, outputFileName)

예제 #34
0
def set(frequency):
    # AWGrefClock.set		- set frequency of reference clock
    Command = ":ROSC:FREQ " + str(frequency)
    return write.write(AWGadd, Command)
예제 #35
0
파일: cfg.py 프로젝트: Adaline1009/todo
 def save(self, path="setup.cfg"):
     """save to `setup.cfg` file"""
     value = self.string()
     write.write(path, value)
     return self
예제 #36
0
def set(channel, voltage):
    # AWGvoltage.set		- set voltage of channel
    Command = "VOLT" + str(channel) + " " + str(voltage)
    return write.write(AWGadd, Command)
예제 #37
0
 def testSingleTagSearch(self):
     tag = self.tagList[7]
     content = self.contentList[1]
     write.write("test-42", tags=tag, content=content, quiet=True)
     self.assertEquals(["# test-42\n", "{0} {1}  \n".format(write.time, tag) +
                        write.prepareContent(content)], search.search(tag)[0])
예제 #38
0
# Create an array of note sequences for each song
while i < 60:
	if (i == 33) or (i == 34):
		i += 1
	else:
		notearray.array(i, notes)
		i += 1

# Map note transitions for all songs
while j < 60:
	if (j == 32) or (j == 33) or (j == 34):
		j += 1
	else:
		compare.compare(j, count, notes)
		j += 1

# Generate probability matrix
while co < 12:
	compare.probability(co,count)
	co += 1

# Write 60 measures of song
while k < 60:
	write.write(p, count, song)
	k+=1

# Display song as musicXML
song.show()

예제 #39
0
    def __call__(self, x, previous_controller, previous_weights, prev_read):

        with tf.variable_scope("concat", reuse=(self.step > 0)):
            x = tf.layers.Flatten()(x)
            NTM_Input = tf.concat([x, prev_read], axis=1)

        with tf.variable_scope("controller", reuse=(self.step > 0)):
            controller_output, controller_state = self.controller(
                NTM_Input, previous_controller)

        with tf.variable_scope("parameter_feedforward", reuse=(self.step > 0)):
            parameter_weight = tf.get_variable(
                'parameter_weight', [
                    controller_output.get_shape()[1], 5 + 3 *
                    (self.memory.get_shape()[1])
                ],
                initializer=tf.contrib.layers.xavier_initializer())
            #parameter weight is determined by controller outputs and the memory M dimension M is multiplied by three because
            #of the key vector and the two add and erase vectors
            parameter_bias = tf.get_variable(
                'parameter_bias', [5 + 3 * (self.memory.get_shape()[1])],
                initializer=tf.contrib.layers.xavier_initializer())

            parameters = tf.nn.xw_plus_b(controller_output, parameter_weight,
                                         parameter_bias)

        #head_parameter = parameters
        #erase_add = tf.split(parameters[self.memory.get_shape()[1]+1+1+3+1], 2, axis=1)
        head_parameter = parameters[:self.memory.get_shape()[1] + 1 + 1 + 3 +
                                    1 + 1]
        erase_add = parameters[self.memory.get_shape()[1] + 1 + 1 + 3 + 1 + 1:]
        #Form focus vectors

        k = tf.tanh(head_parameter[0][0:self.memory.get_shape()[1]])
        beta = tf.sigmoid(head_parameter[0][self.memory.get_shape()[1]]) * 10
        g = tf.sigmoid(head_parameter[0][self.memory.get_shape()[1] + 1])
        s = tf.nn.softmax(
            head_parameter[0][self.memory.get_shape()[1] +
                              2:self.memory.get_shape()[1] + 2 + 3])
        gamma = tf.log(tf.exp(head_parameter[0][-1]) + 1) + 1
        with tf.variable_scope('addressing_head'):
            print(k.get_shape())
            print(self.memory.get_shape())
            print(tf.reshape(self.memory, [80, 100]).get_shape())
            #tf.gather_nd(self.memory_vector,[1,j])
            #ad = addressing.addressing(k, beta, g, s,gamma, self.memory, previous_weights)
            inter_memory = tf.reshape(self.memory, [80, 100])
            print("...")
            print(inter_memory.shape.as_list())
            print("...")
            ad = addressing.addressing(k, beta, g, s, gamma, inter_memory,
                                       previous_weights, self.sess)
            w = ad.address()
        #Reading
        with tf.variable_scope("read_vector"):
            read_vector = read.reading_function(w, self.memory)

        #Writing
        erase_vector = tf.sigmoid(erase_add[0], axis=1)
        add_vector = tf.tanh(erase_add[1], axis=1)
        with tf.variable_scope("write_vector"):
            comp_mem = write.write(w, erase_vector, add_vector, self.memory)
        self.memory = comp_mem

        #Going from controller to NTM

        with tf.graph_argument.variable_scope("output_feedforward",
                                              reuse=(self.step > 0)):
            output_weight = tf.get_variable('output_weight',
                                            [controller_output.shape()[1]])
            output_bias = tf.get_variable('output_bias', [output_dim])
            output = tf.nn.xw_plus_b(controller_output, output_weight,
                                     output_bias)

        self.step += 1

        return output, controller_state, read_vector, w
예제 #40
0
    exit()

while(1):
    count = input("How many pictures do you have?\n")
    try:
        count = int(count)
        break
    except ValueError:
        print("This value is not valid! Try again!")
        time.sleep(2)

a = ask.ask(count)
picArray = []
for i in range(count):
    if len(picArray)>0:
        a.printHeader(i, True, picArray[-1].strTime)
        path = a.askPath()
        sumSecTime = sum(pic.secTime for pic in picArray)
        #print(sumSecTime)
    else:
        a.printHeader(i, False, "")
        path = a.askPath()
        sumSecTime = 0
        
    print()
    strTime = a.askTime(sumSecTime)
    picObject = pic(strTime, path, sumSecTime)
    picArray.append(picObject)

write.write(picArray)
예제 #41
0
import os
import write
import check
import move

arr = []
for w in range(9):
    w += 1
    arr.append("%s" % w)

player1 = input("Nick 1: ")
char1 = ("X")
player2 = input("Nick 2: ")
char2 = ("0")
write.write(arr)
a = 0
while a in range(9):
    move.next(arr, char1, player1)
    write.write(arr)
    if check.check(arr, char1, player1) == True:
        break
    move.next(arr, char2, player2)
    write.write(arr)
    if check.check(arr, char2, player2) == True:
        break
    if a == 8:
        print("Remis!")
        break
예제 #42
0
파일: main.py 프로젝트: KnowNo/blog-3
import read
import write

print "before write"
read.read()

write.write()

print "\nafter write"
read.read()
예제 #43
0
def simulate(filepath,
             filedir,
             fullfilename,
             write=1,
             analyze=1,
             makefig=1,
             diffuse=1,
             antibunch=1,
             pulsed=0,
             numlines=10**7,
             maxlines=10**8,
             endtime=10**12,
             temp=298,
             concentration=2 * 10**-8,
             dabsXsec=3.6 * 10**-10,
             labsXsec=3.6 * 10**(-10),
             k_demission=1000000,
             k_sem=10000,
             emwavelength=815,
             r=10,
             eta=8.9 * 10**(-13),
             n=1.3,
             k_tem=1,
             k_fiss=1,
             k_trans=200000,
             reprate=1,
             wavelength=532,
             laserpwr=0.5,
             pulselength=80,
             foclen=310000,
             NA=1.4,
             darkcounts=1,
             sensitivity=0.1,
             nligands=1,
             deadtime=70000,
             afterpulse=0,
             order=2,
             mode="t2",
             gnpwr=20,
             numbins=4096,
             pulsebins=99,
             channels=3,
             seq=0,
             mL1=0,
             picyzoom=100,
             timestep=200):

    suffix = ".txt"
    if not os.path.isdir(filepath):
        os.mkdir(filepath)

    if not os.path.isdir(filepath + "RawData/"):
        os.mkdir(filepath + "RawData/")
        os.mkdir(filepath + "Figures/")

    if not os.path.isdir(filepath + "RawData/" + filedir):
        os.mkdir(filepath + "RawData/" + filedir)
        os.mkdir(filepath + "Figures/" + filedir)
        os.mkdir(filepath + "RawData/" + filedir + fullfilename)
        os.mkdir(filepath + "Figures/" + filedir + fullfilename)

    elif not os.path.isdir(filepath + "RawData/" + filedir + fullfilename):
        os.mkdir(filepath + "RawData/" + filedir + fullfilename)
        os.mkdir(filepath + "Figures/" + filedir + fullfilename)

    os.chdir(filepath + "RawData/" + filedir + fullfilename)

    print(os.getcwd())
    if write == 1:
        w.write(filepath, filedir, fullfilename, antibunch, diffuse, pulsed,
                numlines, maxlines, endtime, temp, concentration, dabsXsec,
                labsXsec, k_demission, k_fiss, k_trans, k_sem, k_tem,
                emwavelength, r, eta, n, reprate, wavelength, laserpwr,
                pulselength, foclen, NA, darkcounts, sensitivity, nligands,
                deadtime, afterpulse, timestep, channels, seq, mL1)

    if analyze == 1:
        a.analyze(filepath, filedir, fullfilename, numlines, order, mode,
                  gnpwr, numbins, pulsebins, channels, makefig, m.makeafig,
                  pulsed, picyzoom, reprate)

    elif makefig == 1:  #only really used if it crashed part way through analysis
        #nm.figs(filepath, file, filoutpath, savename, fontsize, color, sfactor, xzoom, yzoom, log, pulsed)

        file = fullfilename
        fileoutname = file + "gnpwr15"
        c = isbf(fullfilename)
        filename = "fig"

        m.makeafig("g2",
                   filename, [-1, -1], [-1, -1],
                   0,
                   pulsed,
                   filepath=filepath,
                   filedir=filedir + file + "/",
                   fileoutdir=fileoutname + ".g2.run/",
                   color=c)
        filename = "20mszoom"
        m.makeafig("g2",
                   filename, [-20000000, 20000000], [-1, -1],
                   0,
                   pulsed,
                   filepath=filepath,
                   filedir=filedir + file + "/",
                   fileoutdir=fileoutname + ".g2.run/",
                   color=c)
        filename = "200uszoom"
        m.makeafig("g2",
                   filename, [-200000, 200000], [-1, -1],
                   0,
                   pulsed,
                   filepath=filepath,
                   filedir=filedir + file + "/",
                   fileoutdir=fileoutname + ".g2.run/",
                   color=c)
        filename = "log"
        m.makeafig("g2",
                   filename, [-1, -1], [-1, -1],
                   1,
                   pulsed,
                   filepath=filepath,
                   filedir=filedir + file + "/",
                   fileoutdir=fileoutname + ".g2.run/",
                   color=c)
예제 #44
0
str_style_fill.alignment = Alignment(horizontal='center', vertical='center')
str_style_fill.border = Border(left=Side(style='thin'),
                               right=Side(style='thin'),
                               top=Side(style='thin'),
                               bottom=Side(style='thin'))
str_style_fill.fill = PatternFill('solid', fgColor='E5E5E5')

wb.add_named_style(title_style)
wb.add_named_style(num_style)
wb.add_named_style(num_style_fill)
wb.add_named_style(str_style)
wb.add_named_style(str_style_fill)

rens = rens_list(cur, '前线')

write(wb, rens, '整体')
write(wb, rens, '车险')
write(wb, rens, '非车险')

write_zhong_zhi(wb, cur, rens, '分公司营业一部')
write_zhong_zhi(wb, cur, rens, '曲靖')
write_zhong_zhi(wb, cur, rens, '文山')
write_zhong_zhi(wb, cur, rens, '大理')
write_zhong_zhi(wb, cur, rens, '保山')
write_zhong_zhi(wb, cur, rens, '版纳')
write_zhong_zhi(wb, cur, rens, '怒江')
write_zhong_zhi(wb, cur, rens, '昭通')

rens = rens_list(cur, '后线')
write(wb, rens, '整体', '后线')
wb.move_sheet('后线人员整体保费排名', offset=-8)
예제 #45
0
 def testMultiTagSearch(self):
     tags = "{0}, {1}, {2}".format(self.tagList[1], self.tagList[9], self.tagList[2])
     content = self.contentList[2]
     write.write("test-13", tags=tags, content=content, quiet=True)
     self.assertEquals(["# test-13\n", "{0} {1}  \n".format(write.time, tags) +
                        write.prepareContent(content)], search.search(tags)[0])