示例#1
0
 def __init__(self): # основной запуск иконки
     Taskbar.__init__(self)
     icon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
     self.setIcon(icon)
     self.show()
     Read.init()
     win32gui.PumpMessages()
示例#2
0
def upload():
    # Panggil UploadForm dari form.py
    form = UploadForm()
    docList = renderDocList()
    global fileList , wordList , mVec
    
    # Jika ada file tersubmit, ambil nama file (secured oleh werkzeug) , cek ekstensinya jika .txt, simpan file ke folder test
    if form.validate_on_submit():
        for files in form.file.data :
            filename = secure_filename(files.filename)
            file_ext = os.path.splitext(filename)[1]
            if file_ext != '.txt':
                flash(f'Format of file(s) uploaded is not allowed (.txt only), file submission canceled!' , 'danger')
                return redirect(url_for('upload'))
            files.save('../test/' + filename)
        flash(f'File(s) added!' , 'success')

        # Karena ada input file baru, database kamus di-update
        # Menampung semua nama file ke dalam suatu variabel list fileList
        fileList = []
        for root, dirs, files in os.walk('../test', topdown=False):
            for name in files :
                dir = os.path.join(root,name).split('\\')  # Mengambil hanya nama filenya, tidak bersama direktori yang displit oleh \
                fileList.append(dir[1])

        contentList = []
        for name in fileList :
            # Menampung tiap konten dalam tiap file, melakukan cleaning, konversi ke token, menghapus stopword, dan lemmatize
            content = Read.readfile('../test/'+name)
            content = Read.cleaning(content)
            content = Read.token(content)
            content = Preprocessing.stopwords(content)
            content = Preprocessing.stemming(content)

            # Menggabungkan semua konten menjadi satu list
            contentList.append(content)

        # Membuat variabel penampung kata-kata yang ada di dokumen
        wordList = []
        for content in contentList :
            for word in content :
                if word not in wordList :
                    wordList.append(word)

        # Membuat variabel penampung jumlah kemunculan tiap kata pada tiap data
        mVec = [[0 for x in range(len(wordList))] for y in range(len(fileList))]
        j = 0
        for content in contentList :
            for word in content :
                for i in range(len(wordList)) :
                    if word == wordList[i] :
                        mVec[j][i] = mVec[j][i] + 1
            j = j + 1

        return redirect(url_for('upload'))
    return render_template('upload.html', form=form, docs = docList)
示例#3
0
 def __init__(self):
     reader = readers()
     print(reader)
     if not reader:
         print("Reader NOT CONNECTED")
         print("Connect reader please, and try again")
         Read.exit_app()
     else:
         print("Приложите карту ")
         app_init()
示例#4
0
 def write_head(self):
     with open(self.__outvcf, 'w') as fi:
         ##header
         fi.write("{}".format(Read.Readvcf(self.__invcf).header))
         #samples行
         samples = Read.Readvcf(self.__invcf).samples.split('|')
         newsamples = []
         for group_name in self.__grp_dict:
             for i in self.__grp_dict[group_name]['index']:
                 newsamples.append(samples[i])
         fi.write(
             "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t{}\n".
             format("\t".join(newsamples)))
示例#5
0
    def main(self):
        if not self.__invcf:
            print('Use --help for command line help')
            return
        try:
            os.makedirs(args.work_dir)
        except:
            pass
            #print ('%s exists' %(args.work_dir))

        self.get_group()
        self.write_head()
        low_dp, high_dp = self.__depth.split(',')
        vcfinfo = Read.Readvcf(self.__invcf).extract
        #pool = mp.Pool(1) #启动多线程池
        for each in vcfinfo:
            self.run_filter(each, self.__grp_dict, low_dp, high_dp)
            #pool.apply_async(self.run_filter, args=(each, self.__grp_dict, low_dp, high_dp))#函数写入到多线程池
        """
		print('Waiting for all subprocesses done...')
		pool.close()
		pool.join()
		print('All subprocesses done.')
		pool.terminate()
		"""

        print("低/高深度标记次数: {}".format(self.__total_dp_num))
        print("Homogeneous标记次数: {}".format(self.__total_homogeneous_num))
def algrun():
    global t, list
    time_start = time.time()

    map = Map.Map()

    x, y = Read.Read()
    map.path[0] = x
    map.path[1] = y

    # state == 0: SA,  state == 1: LS
    state = 0

    if state == 0:
        # SA(map, T, Coolrate)
        alg = SA.SA(map, 100, 0.001)
        alg.run()
    elif state == 1:
        # LS(map, state), state = 0: LS1, state = 1: LS2, state = 2: 2-OPT
        alg = LS.LS(map, 2)
        alg.run()
    list.append(alg.path.distance())
    time_end = time.time()
    t += (time_end - time_start)
    print('totally cost', time_end - time_start, 's')
    def GetFile (self, FileName, Owner, user_conf, user_integ, logger, IsHoneyPot, Read) :

        logger.Put_Get_Audit(Owner, FileName, "Get", IsHoneyPot)

        path = ""
        if IsHoneyPot == 0 :
            self.dir = "Files/"
        else :
            self.dir = "Fake/Files/"

        # Check for path traversal attack
        if '\\' in FileName or '/' in FileName:
            return "Invalid file name\n"

        if self.FileNameCheck(FileName) == -1:
           return "File Not Found !!!\n"

        file = open(self.dir + FileName, "r")
        file_acl = file.readline()
        file_acl = file.readline()
        file.close()

        if self.OwnerCheck(Owner, FileName) == -1 and self._CheckDiscretionaryAccess(file_acl, Owner) == -1:
           return "Permission Denied !!!\n"

        if self._CheckDiscretionaryAccess(file_acl, Owner) == -1:
            return "Permission Denied!(By discretionary access control rules)\n"

        file_content = Read.ReadFromFile(Owner, FileName, user_conf, user_integ, logger, IsHoneyPot)

        os.remove(self.dir + FileName)

        return FileName + " Removed from Server Successfully !!!\n" + file_content
示例#8
0
def checkStorage(unitMap, status, sandbox):
    for unitNum in range(0, len(unitMap)):
        currentStatusData = Read.read('127.0.0.1', 0, registerSize, unitNum)
        print("[%d] %s" % (unitNum, currentStatusData))
        if (status[unitNum] is False):
            print("[X]read failed, ignore this unit.")
            continue

        # compare current status , it don't match old status, write to storage, and sent to sandbox.
        if (currentStatusData == status[unitNum]):
            continue

        if (sandboxON):
            sandboxAccept = sandbox.checkSandBox(unitNum, currentStatusData[0])
            if (sandboxAccept):
                if (sentToDevice(unitMap[unitNum], currentStatusData,
                                 unitNum)):
                    status[unitNum] = currentStatusData
                else:
                    print("[X]sent to device failed.")
            else:
                print("[!]dangerous action to device[%s]: %s" %
                      (unitMap[unitNum], currentStatusData))
                print("[!]Recovery to last status.")
                if (sentToDevice(unitMap[unitNum], status[unitNum], unitNum)):
                    print("[-]Recover success.")
                else:
                    print("[X]Recover failed.")
        else:
            print(currentStatusData, " <-> ", status[unitNum])
            if (sentToDevice(unitMap[unitNum], currentStatusData, unitNum)):
                status[unitNum] = currentStatusData
            else:
                print("[X]sent to device failed.")
示例#9
0
def main():
    reference = Reference(argv[1])
    reference.get_regions_index()
    print("Reference %s processed" % argv[1])
    with gzip.open(argv[2], 'rt') as sam_file:
        alignment = AlignmentInformation(reference)
        print("Processing alignment information in SAM file...")
        for line in sam_file.readlines(
        )[2:]:  # Information of reads alignment starts in 2nd line
            read = Read(line)
            if read.flag != 4 and read.quality == 255:
                '''
                Reads with flag value 4 (i.e. not aligned) and quality value different than 255 (optimal) 
                are not processed
                '''
                read.parse_cigar()
                read.get_aligned_sequence()
                for exon_range in reference.exons_index_list:
                    in_exons = read.is_aligned_to(exon_range)
                    if in_exons is True:  # Only exon information is accounted
                        alignment.update_count_dictionary(read)
                        break
        alignment.create_proportion_dictionary()
        print("Progressive analysis in progress...")
        progressive_analysis = ProgressiveAnalysis(
            alignment)  # Proportion_threshold value customizable, default=5
        print("%i genes/s detected" %
              len(list(progressive_analysis.result_alleles_dictionary.keys())))
        print("Combined analysis in progress...")
        combined_analysis = CombinedAnalysis(progressive_analysis, alignment)
        write_output_file(progressive_analysis, combined_analysis, argv[2],
                          argv[3])
        print("Analysis done, results written into output file: %s" % argv[3])
        sam_file.close()
    sam_file.close()
示例#10
0
def __main__():
    check_files_and_folders()
    socket = Socket.ServerSocket()
    connection = socket.Socket()
    sr = Server(connection, Cryptography.session_crypto(None), Registery.Registery(), Login.serverLogin(),
                Download.Download(), Upload.Upload(), List.List(), Read.Read(), Write.Write(),
                SessionKeyExchange.ServerSession(None),
                DACCommands.DACCommands(), Auditor.Auditor())
    sr.Handler()
示例#11
0
def launch(market):
    results = []
    if (market in ['Resources', 'Miner']):
        results.extend(
            Read.readingFrom(Settings.settings['Markets']['location']['otype'],
                             Settings.settings['Read']['mode']['texte'],
                             method='single_textline',
                             colors=['gray']))
        results.extend(
            Read.readingFrom(
                Settings.settings['Markets']['location']['title'],
                Settings.settings['Read']['mode']['texte'],
                method='single_textline',
            ))
        results.extend(
            Read.readingFrom(
                Settings.settings['Markets']['location']['un'],
                Settings.settings['Read']['mode']['kamas'],
                method='only_digits',
            ))
        results.extend(
            Read.readingFrom(
                Settings.settings['Markets']['location']['dix'],
                Settings.settings['Read']['mode']['kamas'],
                method='only_digits',
            ))
        results.extend(
            Read.readingFrom(
                Settings.settings['Markets']['location']['cent'],
                Settings.settings['Read']['mode']['kamas'],
                method='only_digits',
            ))

        results = Check.checkResources(results)
        results = Parse.parseResources(results)
        marketsToDb[market](results)

        return results
    elif (market == 'RollBack'):
        marketsToDb['RollBack']()
    elif (market == 'commitDB'):
        marketsToDb['commitDB']()
示例#12
0
 def info(self):
     msg = QtWidgets.QMessageBox()
     msg.setMaximumSize(QtCore.QSize(281, 16777215))
     msg.setGeometry(QtCore.QRect(510, 330, 581, 281))
     msg.setInformativeText("Hold the tag near the RFID reader")
     msg.setStandardButtons(QMessageBox.Ok)
     msg.exec_()
     ret = rd.rfid()
     print(ret)
     if ret == 1:
         self.choice()
示例#13
0
    def plotMeanVelocityComponent(RA, Retau, velocity_component):

        fig = plt.figure(1, figsize=(10, 30))
        gs = fig.add_gridspec(6, 14)
        fig.suptitle(
            'Mean velocity flow for $R_{\\tau}$ and different RA values for velocity compoment '
            + velocity_component)
        fig.subplots_adjust(hspace=1)
        for ii in range(len(RA)):
            ra = RA[ii]
            ncols = RA[ii] - 1

            ### Collect coordinates and mean velocity data
            usecase = str(ra) + '_' + str(Retau)

            zcoord, DIM_Z = Read.importCoordinates('z', usecase)
            ycoord, DIM_Y = Read.importCoordinates('y', usecase)

            U = Read.importMeanVelocity(DIM_Y, DIM_Z, usecase,
                                        velocity_component)

            ### Create subplots
            if (ncols == 0):
                ax = fig.add_subplot(gs[ii, 0])
            else:
                ax = fig.add_subplot(gs[ii, 0:ncols])

            ### Add contour graphs to subplots
            ax.contourf(U,
                        extent=(np.amin(zcoord), np.amax(zcoord),
                                np.amin(ycoord), np.amax(ycoord)),
                        cmap=plt.cm.Oranges)
            ax.set_title('RA = ' + str(ra))

            if (ii == m.ceil(len(RA) / 2)):
                ax.set_ylabel('z: spanwise (a. u.)')

            if (ii == len(RA) - 1):
                ax.set_xlabel('y: wall normal (a. u. )')

        plt.plot()
示例#14
0
 def __init__(self, invcf, grp_dict, grp_name="", samples_lst=[]):
     self.invcf = invcf
     self.all_samples_lst = Read.Readvcf(self.invcf).samples.split('|')
     self.grp_dict = grp_dict
     if grp_name:
         self.grp_name = grp_name
     else:
         self.grp_name = 'All'
     if len(samples_lst) > 1:
         self.samples_lst = samples_lst
     else:
         self.samples_lst = self.all_samples_lst
     self.handle_grp()
示例#15
0
def initial(unitMap, status):
    for unitNum in range(0, len(unitMap)):
        statusData = Read.read('127.0.0.1', 0, registerSize, unitNum)
        if (statusData == False):
            sys.exit("initial failed.")
        status.append(statusData)
    sandbox = None
    if (sandboxON):
        print("[-]The sandbox is ON!")
        sandbox = Sandbox.SandBox()
        return sandbox
    else:
        print("[!]The sandbox is current OFF!")
        return None
示例#16
0
def delegate(conn, user_in):
    user_in = user_in.lower()
    if user_in == "create":
        print("\n")
        return Create.Create(conn)
    elif user_in == "read":
        print("\n")
        return Read.Read(conn)
    elif user_in == "update":
        print("\n")
        return Update.Update(conn)
    elif user_in == "delete":
        print("\n")
        return Delete.Delete(conn)
    else:
        raise Exception("Invalid User input: " + user_in)
示例#17
0
def svm(w,data_pts,eta,lam,tau,d,weight,shuff=0,N=1,n=0):#,result,index): #,tau):
    l = len(w)
    fn = np.zeros(tau) # array of calculated loss functions for each local iteration (tau)

    for t in range(0, int(tau)):
        x, y = Read.Read(d, data_pts, weight, offset=0) # weight modifies yread Read(numPoints, data, weight, offset=0)
        wT = w.transpose()
        dfn = np.zeros(l)
        for j in range(0 , d):           
            if (1-y[j]*np.dot(wT, x[j]))<0:
                max = 0
            else:
                max = 1-y[j]*np.dot(wT, x[j])
            for i in range(0,l):
                dfn[i] += (lam*w[i]-(y[j]*x[j,i])*max)/d
            fn[t] += ((lam/2)*np.dot(w, wT)**2 + (max**2)/2)/d
        w = w - eta*dfn
    return w,fn
示例#18
0
def auth():
    authenticated = False
    while not authenticated:
        print("Waiting for admin card to authenticate ...")
        card = Read.main()
        print "Card read : " + card
        headers = {"Content-Type": "application/json"}
        payload = {"card_id": card}
        r = requests.post(URLAuth, data=json.dumps(payload), headers=headers)
        tokenRetour = json.loads(r.content)
        if "user" in tokenRetour and "role" in tokenRetour["user"] and (
                tokenRetour["user"]["role"] == "ROLE_SUPER_ADMIN"
                or tokenRetour["user"]["role"] == "ROLE_ADMIN"):
            print "AUTHENTICATED ! \n ROLE : " + tokenRetour["user"][
                "role"] + " \n Firstname : " + tokenRetour["user"]["firstname"]
            return tokenRetour["value"]
        elif "user" not in tokenRetour:
            print "La carte n'est pas lie a un compte"
        else:
            print "La carte n'a pas un role super admin ou admin "
示例#19
0
def svm(w,
        data_pts,
        eta,
        lam,
        tau,
        d,
        weight,
        shuff=0,
        N=1,
        n=0):  #,result,index): #,tau):
    l = len(w)
    fn = np.zeros(
        tau
    )  # array of calculated loss functions for each local iteration (tau)

    for t in range(0, int(tau)):
        if t > 0:  # execute shuffling after the first iteration
            if shuff == 1:
                np.random.shuffle(data_pts)
            elif shuff == 2:
                data_pts = Shuffle.rRobin(data_pts, N=N)
            elif shuff == 3:
                data_pts = Shuffle.segShift(data_pts, N=N)
        x, y = Read.Read(d, data_pts, weight,
                         offset=n)  # weight modifies yread
        wT = w.transpose()
        dfn = np.zeros(l)
        for j in range(0, d):
            if (1 - y[j] * np.dot(wT, x[j])) < 0:
                max = 0
            else:
                max = 1 - y[j] * np.dot(wT, x[j])

            for i in range(0, l):
                dfn[i] += (lam * w[i] - (y[j] * x[j, i]) * max) / d

            fn[t] += ((lam / 2) * np.dot(w, wT)**2 + (max**2) / 2) / d

        w = w - eta * dfn

    return w, fn
示例#20
0
def main( fq_file, n ):
	pos = 0
	with open( fq_file ) as f:
		for row in f:
			l = row.strip()
			if pos % 4 == 0:
				R = Read( l, trim_by=n )
			elif pos % 4 == 1:
				R.bases = l
			elif pos % 4 == 2:
				R.name_ = l
			elif pos % 4 == 3:
				R.quals = l
				R.remove_polyA()
				try:
					print R
				except TypeError:
					pass
			pos += 1
示例#21
0
 def reset(self):
     self.read_uid = ''
     self.button.setEnabled(False)
     self.button2.setEnabled(False)
     self.button3.setEnabled(False)
     self.button4.setEnabled(False)
     time.sleep(2)
     self.read_uid = Read.run()
     conn = sqlite3.connect("cul.db")
     cur = conn.cursor()
     cur.execute("select * from emp_list where uid = ?", (self.read_uid, ))
     rows = cur.fetchall()
     conn.close()
     if not rows:
         self.button.setEnabled(True)
         self.button4.setEnabled(True)
         self.label.setText("등록 되지않은 카드입니다.")
     else:
         self.button4.setEnabled(True)
         self.button2.setEnabled(True)
         self.button3.setEnabled(True)
         self.label.setText("반갑습니다")
示例#22
0
    '008_z005p037', '009_z004p485', '010_z003p984', '011_z003p528',
    '012_z003p017', '013_z002p478', '014_z002p237', '015_z002p012',
    '016_z001p737', '017_z001p487', '018_z001p259', '019_z001p004',
    '020_z000p865', '021_z000p736', '022_z000p615', '023_z000p503',
    '024_z000p366', '025_z000p271', '026_z000p183', '027_z000p101',
    '028_z000p000'
]

tag = TAGS[Snap]
#SIMREF =
sim = '/cosma5/data/Eagle/ScienceRuns/Planck1/L0025N0376/PE/REFERENCE/data/'
#sim = '/cosma5/data/Eagle/ScienceRuns/Planck1/L0100N1504/PE/REFERENCE/data/'
sim_name = 'L0025N0376_ref'
#sim_name = 'L0100N1504_ref'

L, a, h = R.Read_MainProp(sim, tag)
L *= (a / h)

################################ READ ####################################

pos_St, Mass_St, num_St, num_St_SH = R.Read_Particles(sim, tag)
NumOfSubhalos = R.Read_Haloes(sim, tag)
SubHalo_gr, SubHalo_sgr, SubHalo_pos = R.Read_Subhaloes(sim, tag)
ParticleID, Particle_Binding_Energy = R.Read_Particles_ID(sim, tag)
################################  MAIN  ##################################

Index_Range = F.Get_PartIndexRange(num_St, num_St_SH, NumOfSubhalos)
CenterOfPotential = F.Get_SubHaloCenter(SubHalo_gr, SubHalo_sgr, NumOfSubhalos,
                                        SubHalo_pos)

Sel_Group = []
class Seedbed(object):
    """Class Seedbed the hole seedbed at this time
    :parameter crusty: if this seedbed has a crusty top
    :parameter dry_crust: if this seed bed has a dry crust
    :parameter collisions: a count of collisions # TODO make this work - then use a list of collision objects
    :parameter run_day: the day after sowing that the seedbed is on now
    :parameter seed_tray: a set of instances of class seed in a list
    :parameter clod_bed: a set of instances of class clod in a list
    :parameter all_rain: the total accumulated rainfall so far in the test
    :parameter setup: an instance of the setup class that contains all the info on the sowing from the setup files

    :returns A seedbed object
    """
    crusty = False  # is the seed bead currently crusty
    dry_crust = False  # is the crust currently dry
    collisions = 0  # the number of times a clods or seed collide
    run_day = 0  # the day of the seed bed run
    seed_tray = list()  # a seed tray containing all the seed objects
    clod_bed = list()  # a try of the clods containing all the clod objects
    all_rain = 0  # Total rain fall
    setup = Read.setupSeedbed(
    )  # Read the setup 5 setup files and make an object of all the data

    def __init__(self):  # todo define clod limets
        """Initialise an instance of seedbed
        :parameter clod_no: the number of each clod - 1 indexed
        :parameter clod_set: the min size of the clod for a grouped lot of clods
        :parameter clod: the clod in this set
        :parameter clod_lims: an array representing the [L,h,l] for a clod
        :parameter clod_serf_prob: the result of a function call to find where the clod is stuck [False,False,False] for [prob_serf, stuck_serf, stuck_soil]
        :parameter Clod: the class that makes a clod object
        :parameter sd: a seed in this sowing
        :parameter Seed: the class that makes a Seed object
        """
        self.setup.sort_clods()
        clod_no = 0  # a unique clod number for each clod
        for clod_set in range(0, len(self.setup.clod_nos)):
            for clod in range(
                    0,
                    Clods.clod_numbers(self.setup.clod_nos[clod_set],
                                       self.setup.plot_xyz)):
                clod_no += 1  # update for each clod
                Write.run_summ("clod " + str(clod_no))
                clod_lims = Clods.clod_size(self.setup.clod_lims, clod_set)
                radi = (sum(clod_lims) / 3.0) / 2.0
                clod_serf_prob = Fun.clod_restriction(
                    self.setup.p_serf[clod_set],
                    self.setup.p_stuck_serf[clod_set],
                    self.setup.p_stuck_soil[clod_set])
                self.clod_bed.append(
                    Clods.Clod(
                        clod_no,
                        Fun.position_calc(
                            self.seed_tray, self.clod_bed,
                            self.setup.plot_xyz[2] - self.setup.sow_depth,
                            self.setup.plot_xyz, True, radi, clod_serf_prob),
                        self.setup.plot_xyz[2], clod_lims))
                #print self.clod_bed[clod]

        for sd in range(0, self.setup.no_seeds):
            self.seed_tray.append(
                Seeds.Seed(
                    sd + 1, self.setup.day_death, self.setup.therm_times,
                    self.setup.base_germ, self.setup.base_elong,
                    self.setup.base_wet,
                    Fun.position_calc(
                        self.seed_tray, self.clod_bed,
                        self.setup.plot_xyz[2] - self.setup.sow_depth,
                        self.setup.plot_xyz, False)))
            Write.run_summ("seed " + str(sd + 1) + " initialised")
            print self.seed_tray[sd]

    def next_day(self, day):
        """Calls other functions to make the next day proceed
        :param day: The day of the year to look up the rainfall
        :returns : objects
        """
        self.run_day += 1
        self.crusty_prob(day)
        Write.Seed_info(self.seed_tray, self.setup.no_seeds,
                        self.setup.sow_depth)  # germination info write out
        for sd in range(0, self.setup.no_seeds):
            self.seed_tray[sd].next_day(day, self.setup, self.clod_bed,
                                        self.crusty)
            print self.seed_tray[sd]

    def crusty_prob(self, day):
        """returns the probability of the seedling getting through the outer layer of soil
        :param day: The day of the year to look up the rainfall
        :keyword CRc: The rainfall needed cumulatively to produce a crust (default 12mm)
        :keyword DRc1: The recent rainfall needed to produce a crust (default 5mm)
        :keyword DRc2: The recent rainfall needed to make the crust soft and most (default 3.5mm)
        :returns prob: -1 for no crust or the probabilty of going thrugh the crust (1 for wet crust)
        """
        crust = False  # default no crust
        self.all_rain += self.setup.enviro_data_rain[
            day]  # increment total rain fall

        if self.all_rain > self.setup.crc:  # all rain more than amount of total rain to make a crust
            crust = True
        if self.setup.enviro_data_rain[
                day] > self.setup.drc1:  # Day rain more than day rain to make a crust
            crust = True
        if crust:
            if self.setup.enviro_data_rain[day] > self.setup.drc2:
                prob = 1  # crust is wet end seedling can emerge prob = 1
            else:
                prob = self.setup.p_dry_crust  # crust is dry emergence depends on seed power
        else:
            prob = -1

        self.crusty = prob
示例#24
0
    if (raw_xml == ""):
        print("XML file empty")
        sys.exit()

    bed_dict = LoadBed.LoadBedFile(bed_file_path)

    xml = bs4.BeautifulSoup(raw_xml, "html.parser")

    discordant_reads = xml.findAll("discordant_read_pair")
    softclip_reads = xml.findAll("softclip_read_pair")
    deletion_reads = xml.findAll("deletion_read_pair")

    read_list = []

    for x in softclip_reads:
        a = Read.Read()
        a.SetRead(x)
        read_list.append(a)

    for x in deletion_reads:
        a = Read.Read()
        a.SetRead(x)
        read_list.append(a)

    breakpoint_list = []
    breakpoint_dict = collections.defaultdict(int)

    read_list.sort(key=lambda x: x.left_coordinate)

    for x in read_list:
        entry = x.read.reference_name.string + ":" + str(x.left_coordinate)
示例#25
0
文件: Main.py 项目: hantke/Read_Eagle
################################  Vars ##################################################

Snap = int(sys.argv[1])
h = 0.6777
Mcut = 0.0
Rad = 0.05 # 30 pkpc
NBin = 50 # dx = 100 ppc
TAGS = ['000_z020p000','001_z015p132','002_z009p993','003_z008p988','004_z008p075','005_z007p050','006_z005p971','007_z005p487','008_z005p037','009_z004p485','010_z003p984','011_z003p528','012_z003p017','013_z002p478','014_z002p237','015_z002p012','016_z001p737','017_z001p487','018_z001p259','019_z001p004','020_z000p865','021_z000p736','022_z000p615','023_z000p503','024_z000p366','025_z000p271','026_z000p183','027_z000p101','028_z000p000']

tag = TAGS[Snap]
#sim='/cosma5/data/Eagle/ScienceRuns/Planck1/L0025N0752/PE/RECALIBRATED/data/'
sim = '/cosma5/data/Eagle/ScienceRuns/Planck1/L0100N1504/PE/REFERENCE/data/'
sim_name = 'L0100N1504_ref'

L,a,h = R.Read_MainProp(sim, tag)
L *= (a/h)



################################ READ ####################################

pos_St,Mass_St,num_St,num_St_SH = R.Read_Particles(sim, tag)
NumOfSubhalos = R.Read_Haloes(sim, tag)

################################  MAIN  ##################################


Index_Range = F.Get_PartIndexRange(num_St,num_St_SH,NumOfSubhalos)

Sel_Group 		= []
import Email
import GUI
import Randomizer
import Read
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.output(17, False)

cards = [35915910110]

Id = Read.Read()

if (Id in cards):
    message = Randomizer.random(4)
    Email.Email(message)
    GUI.Gui(message)

else:
    print "Access Denied"
    GPIO.cleanup()
    quit()
示例#27
0
<insert_size>414</insert_size>
<read_sequence>TAGGGGTGGGGGCGAGCTTTCACCATCGTGATGGACACTGAAGGAGCTCCCCACCCCCTGATCAGCCAGGAGGATGCAGTTACTATATTTAGAGTAGAAAATCACTCAGAGACATTGTCATTCAGCCTAGGTCATAAGGCTATTATGCAT</read_sequence>
<quality></quality>
<alignments>
<start_coordinate_1>chr2:29448016-29448090</start_coordinate_1>
<orientation_1>forward</orientation_1>
<match_coordinates_1>1-75</match_coordinates_1>
<bitscore_1>145</bitscore_1>
<length_1>75</length_1>
<flag_1>26</flag_1>
<start_coordinate_2>chr2:42493955-42493883</start_coordinate_2>
<orientation_2>reverse</orientation_2>
<match_coordinates_2>3-75</match_coordinates_2>
<bitscore_2>135</bitscore_2>
<length_2>73</length_2>
<flag_2>5</flag_2>
</alignments>
</read>
</softclip_read_pair>"""

    bp = Read.Read()
    xml = bs4.BeautifulSoup(raw_xml, "html.parser")
    bp.SetRead(xml)

    b = Break()
    b.AddRead(bp)

    b._FindConsensus()
    assert(b.GetLeftSequence() == "-----TAGGAGGACCGACTAGTCCCCCACCCCTCGAGGAAGTCACAGGTAGTGCTACCACTTTCGAGCGGGGGTGGGGAT-------------------------------------------------------------------------------------")
    assert(b.GetRightSequence() == "-----AGTTACTATATTTAGAGTAGAAAATCACTCAGAGACATTGTCATTCAGCCTAGGTCATAAGGCTATTATGCAT---------------------------------------------------------------------------------------")
示例#28
0
run = True

ardData = serial.Serial('COM4', 9600)

while (run):
    hookcd = 20
    lanterncd = 22
    flaycd = 9
    ultcd = 140

    hookmod = 2
    lanternmod = 2.5
    flaymod = 0
    ultmod = 20

    ab1, ab2, ab3, ult, cdr, lvl1, lvl2, lvl3, lvlult, run, Health, Mana = Read.parse(
    )

    hookexpect = 0

    if lvl1 > 0:
        hookexpect = (hookcd - (hookmod *
                                (lvl1 - 1))) * (1 - int(cdr[1:len(cdr)]) / 100)

    if var == 0:
        if (len(ab1) > 1):
            if (int(ab1[1:len(ab1)]) > hookexpect - 3 + var):
                if count > 1:
                    var = 5
                    print('miss')
                    ardData.write(b'1')
                    ardData.write(b'0')
示例#29
0
print "######################################################"
print "Starting the code!! Good Luck!!"
print "Package Load"
################################################ Pannel ################################################
print "Pannel load"
############################################### VARS ###################################################
print "Vars load"
Arr_Pos = []
Arr_Vel = []
Arr_Gnum = []
############################################### Init ###################################################
print "Init"
############################################### Read ###################################################
print "Read"
L, a, h = R.Read_MainProp_V01()
M_Group, Cen_Group, R_Group = R.Read_Halo_Prop_Sergio_V01()
Pos_DM, Vel_DM, num_DM, mass_DM = R.Read_Part_Prop_Sergio_V04()
R_Group = array(R_Group) / a
Cen_Group = array(Cen_Group) / a
Pos_DM = array(Pos_DM) / a

############################################### Part Sel ###################################################
print "Part Sel"
ID = where(M_Group > D.Mcut)[0] + 1

GroupID_DM, Particle_ID_DM = F.Get_PartGroupID(num_DM, ID)
Index = argsort(GroupID_DM)
Particle_ID_DM = Particle_ID_DM[Index]
GroupID_DM = GroupID_DM[Index]
示例#30
0
from Read import *
from metric import *
from cab import cab

taxis = [cab() for i in range(firstline([2]))]
availableTaxis=[i for i in taxis]
nfl = Read('a_example.in')
jobs = nfl.getJobs()

jobs_by_length = sorted(jobs, key = lambda x : distance([x[0], x[1]], [x[2], x[3]]))


jobs_by_start = sorted(jobs, key = lambda x : x[4])

counter=0
while(i<=10):
    for (job in jobs_by_start):
        if(len(availableTaxis)!=0):
            availableTaxis[0].assign(job)
        updateAvailableCabs(availableTaxis)
    counter+=1

def updateAvailableCabs(availableTaxis):
    availableTaxis=[if(i.isAvailable()) i for i in taxis]
示例#31
0
import re
import Read


print Read.read_email_from_gmail().email_body
link_pattern = re.compile('<a[^>]+href=\'(.*?)\'[^>]*>(.*)?</a>')
search = link_pattern.search(Read.email_body)
if search is not None:
    print("Link found! -> " + search.group(0))
else:
    print("No links were found.")
示例#32
0
文件: tasks.py 项目: mronian/ScanDB
def start(filename):
    Binarise.getBinary(filename)
    number_of_segments=RLSA.getSegments(filename.strip('.tif'))
    Read.getText(filename.strip('.tif'), number_of_segments)
示例#33
0
#
# No one except the Owners have the right to access or modify the code.
#
#########################################################################################################

# Owner     : SRM Team Humaniod, Kattankulathur
# Author    : Akarsh Shrivastava
# Maintainer: No one tries to maintain this.
#
# Yes I was so jobless that I did all this

import Read
from Dynamixel import Dynamixel
from time import sleep, time

# TODO- think of offsets

# constraints for m2,m5,m8 : -98 to  100
# constraints for m11      :  98 to -100

if __name__ == '__main__':
    dxl = Dynamixel()
    raw_input("press Enter to continue ")

    #Read.do_motion(dxl, "motions/stand_up.mot", 1)
    #Read.do_motion(dxl, "motions/left_turn.mot")
    #Read.do_motion(dxl, "motions/init_walk.mot", 1)
    #Read.do_motion(dxl, "motions/walk.mot")
    #Read.do_motion(dxl, "motions/sit_down.mot", 1)
    Read.do_motion(dxl, "motions/spot_march.mot")