Beispiel #1
0
def cp_file2file(source_file, target_file, should_be_notice_files):
    if source_file.rsplit('.', 1)[1] not in allowedFileTypes:
        return
    if is_file_modified(source_file, target_file):
        if source_file in should_be_notice_files:
            if notice_if_cover_file(source_file, target_file):
                shutil.copy(source_file, target_file)
                with indent(6, quote=colored.clean('#')):
                    puts(
                        colored.cyan('Update %s ->  %s' %
                                     (cleaner_path(source_file),
                                      cleaner_path(target_file))))
        else:
            shutil.copy(source_file, target_file)
            with indent(6, quote=colored.clean('#')):
                puts(
                    colored.cyan('Auto update %s ->  %s' %
                                 (cleaner_path(source_file),
                                  cleaner_path(target_file))))
    elif is_file_modified(source_file, target_file) is None:
        shutil.copy(source_file, target_file)
        with indent(6, quote=colored.clean('#')):
            puts(
                colored.cyan(
                    'Copy %s ->  %s' %
                    (cleaner_path(source_file), cleaner_path(target_file))))
Beispiel #2
0
 def format(self, record):
     if record.levelno in (logging.WARNING, logging.CRITICAL,
                           logging.ERROR):
         record.msg = colored.red("[!] ") + colored.clean(record.msg)
     else:
         record.msg = colored.green("(i) ") + colored.clean(record.msg)
     return super(ColoredLevelFormatter, self).format(record)
Beispiel #3
0
def output_string(outputString, snippet_list=[]):
    if snippet_list:
        with indent(2):
            for item, snippet in zip(outputString, snippet_list):
                puts(colored.cyan('|'))
                puts(colored.cyan('\__>   ') + colored.clean(item))
                puts(colored.cyan('\__>   ') + colored.clean(snippet))
                puts(colored.cyan('|'))
    else:
        with indent(2):
            for item in outputString:
                puts(colored.cyan('|'))
                puts(colored.cyan('\__>   ') + colored.clean(item))
                puts(colored.cyan('|'))
Beispiel #4
0
def cp_file2file(source_file, target_file, should_be_notice_files):
    if source_file.rsplit('.', 1)[1] not in allowedFileTypes:
        return
    if is_file_modified(source_file, target_file):
        if source_file in should_be_notice_files:
            if notice_if_cover_file(source_file, target_file):
                shutil.copy(source_file, target_file)
                with indent(6, quote=colored.clean('#')):
                    puts(colored.cyan('Update %s ->  %s' % (cleaner_path(source_file), cleaner_path(target_file))))
        else:
            shutil.copy(source_file, target_file)
            with indent(6, quote=colored.clean('#')):
                puts(colored.cyan('Auto update %s ->  %s' % (cleaner_path(source_file), cleaner_path(target_file))))
    elif is_file_modified(source_file, target_file) is None:
        shutil.copy(source_file, target_file)
        with indent(6, quote=colored.clean('#')):
            puts(colored.cyan('Copy %s ->  %s' % (cleaner_path(source_file), cleaner_path(target_file))))
Beispiel #5
0
def test_compound_model_repr():
    HY_LIST_MODELS = (HyExpression, HyDict, HySet, HyList)
    with pretty(False):
        for model in HY_LIST_MODELS:
            assert eval(repr(model())).__class__ is model
            assert eval(repr(model([1, 2]))) == model([1, 2])
            assert eval(repr(model([1, 2, 3]))) == model([1, 2, 3])
        for k, v in PRETTY_STRINGS.items():
            # `str` should be pretty, even under `pretty(False)`.
            assert clean(str(hy.read_str(k))) == v
        for k in PRETTY_STRINGS.keys():
            assert eval(repr(hy.read_str(k))) == hy.read_str(k)
    with pretty(True):
        for model in HY_LIST_MODELS:
            assert eval(clean(repr(model()))).__class__ is model
            assert eval(clean(repr(model([1, 2])))) == model([1, 2])
            assert eval(clean(repr(model([1, 2, 3])))) == model([1, 2, 3])
        for k, v in PRETTY_STRINGS.items():
            assert clean(repr(hy.read_str(k))) == v
Beispiel #6
0
def test_compound_model_repr():
    HY_LIST_MODELS = (HyExpression, HyDict, HySet, HyList)
    with pretty(False):
        for model in HY_LIST_MODELS:
            assert eval(repr(model())).__class__ is model
            assert eval(repr(model([1, 2]))) == model([1, 2])
            assert eval(repr(model([1, 2, 3]))) == model([1, 2, 3])
        for k, v in PRETTY_STRINGS.items():
            # `str` should be pretty, even under `pretty(False)`.
            assert clean(str(hy.read_str(k))) == v
        for k in PRETTY_STRINGS.keys():
            assert eval(repr(hy.read_str(k))) == hy.read_str(k)
    with pretty(True):
        for model in HY_LIST_MODELS:
            assert eval(clean(repr(model()))).__class__ is model
            assert eval(clean(repr(model([1, 2])))) == model([1, 2])
            assert eval(clean(repr(model([1, 2, 3])))) == model([1, 2, 3])
        for k, v in PRETTY_STRINGS.items():
            assert clean(repr(hy.read_str(k))) == v
Beispiel #7
0
 def log(self, msg):
     """Store step message in instance message list.
     If verbose level is high enough, also print message to output
     """
     self.mutex.acquire()
     settings = Settings()
     if settings.verbose:
         print msg
     self.messages.append(colored.clean(msg))
     self.mutex.release()
Beispiel #8
0
def pull():
    global_conf = {}

    # 依据static.json获取app root
    try:
        app_root = get_app_root()
        with indent(2, quote=colored.clean('#')):
            puts(colored.blue('App root at: %s' % app_root))
    except NotFoundAppRoot:
        with indent(2, quote=colored.clean('#')):
            puts(colored.red('Not a app dir (or any of the parent directories)'))
        sys.exit(1)
    global_conf['app_root'] = app_root

    # 读取static.json
    try:
        static_conf = get_static_conf(app_root)
        static_conf = static_conf['staticpy']
    except json.decoder.JSONDecodeError, e:
        with indent(8, quote=colored.clean('#')):
            puts(colored.red('JSONDecodeError in static.json: %s' % e))
        sys.exit(1)
Beispiel #9
0
def pull():
    global_conf = {}

    # 依据static.json获取app root
    try:
        app_root = get_app_root()
        with indent(2, quote=colored.clean('#')):
            puts(colored.blue('App root at: %s' % app_root))
    except NotFoundAppRoot:
        with indent(2, quote=colored.clean('#')):
            puts(
                colored.red(
                    'Not a app dir (or any of the parent directories)'))
        sys.exit(1)
    global_conf['app_root'] = app_root

    # 读取static.json
    try:
        static_conf = get_static_conf(app_root)
        static_conf = static_conf['staticpy']
    except json.decoder.JSONDecodeError, e:
        with indent(8, quote=colored.clean('#')):
            puts(colored.red('JSONDecodeError in static.json: %s' % e))
        sys.exit(1)
Beispiel #10
0
def exit_choice(flag):
    while flag:
        continue_searching = raw_input(
            colored.clean('Search again? ') + '[' + colored.cyan('Y') + '/' +
            colored.green('N') + ']: ')
        if continue_searching.lower() == 'y':
            flag = True
            break
        elif continue_searching.lower() == 'n':
            flag = False
            exit_progress_bar()
            break
        else:
            flag = True
            print('Wrong input. Please try again.')
            space()
Beispiel #11
0
 def format(self, record):
     if record.levelno in (logging.WARNING, logging.CRITICAL, logging.ERROR):
         record.msg = colored.red("[!] ") + colored.clean(record.msg)
     else:
         record.msg = colored.green("(i) ") + colored.clean(record.msg)
     return super(ColoredLevelFormatter, self).format(record)
Beispiel #12
0
      if length > console_width:
        if length - console_width < len(path_disp):
          path_disp = '...%s' % path_disp[(length - console_width + 3):len(path_disp)]
        else:
          path_disp = ''
      #trim file name if we're still over
      length = len('%s%s%s%s' % (count, dl.audioCount, path_disp, filename)) + 5
      filename_disp = filename
      if length > console_width:
        if length - console_width < len(filename):
          filename_disp = '...%s' % filename[(length - console_width + 3):len(filename)]

      output = output_str % (count, dl.audioCount, colored.cyan(filename_disp), colored.white(path_disp))

      puts(output, False)
      puts(" " * (console_width - len(colored.clean(output))), False)
      puts("\r", False)
      sys.stdout.flush()
      try:
        convert(filename, folder['path'], folder['out_path'])
        count += 1
      except Exception, e:
        pass
        #puts(output, False)
        #puts(" " * (console_width - len(colored.clean(output))), True)
        ##puts(colored.red("Failed on file:"), filename)
        #puts(colored.red("path:"), folder['path'])
        #puts('%r' % e)
        #sys.exit(0)

puts(output, True)
    def update(self):
        # We have this already, but without the ' in the name.
        print '\n    Matching data base...'

        NewStars = []
        coordExo=coord.SkyCoord(ra=self.exoplanet['ra'].values, dec=self.exoplanet['dec'].values,unit=(u.deg,u.deg),frame='icrs')
        coordSC=coord.SkyCoord(ra=self.coordinates['ra'].values, dec=self.coordinates['dec'].values,unit=(u.hourangle,u.deg),frame='icrs')

        for i, exo_name in enumerate(self.exo_names):
            new = exo_name 
            starName=self.exoplanet['star_name'].values[i]
            tmp = new.lower().replace(' ', '').replace('-', '') 

            sep = coordExo[i].separation(coordSC).arcsecond
            ind=np.where(sep<5.)[0]

            if len(ind)==0:
                try:
                    # it didn't find by position but it finds by name
                    position=self.sc_names.index(tmp)
                except:
                    position=-1
                    # it didn't find by position and neither by name
                    if (tmp not in self.blacklist):
                        NewStars.append(new)

                #  REMOVE THE COMMENTS TO CHECK PROBLEMS IN POSITION
#                 if position>=0:

#                     result_table = Simbad.query_object(new)
#                     try:
#                         # check in Simbad the position and see where the coordinates are wrong
#                         ra=str(result_table['RA'][0])
#                         dec=str(result_table['DEC'][0])
#                         coordS=coord.SkyCoord(ra, dec, unit=(u.hourangle, u.degree), frame='icrs')
#                         sepES = coordExo[i].separation(coordS).arcsecond
#                         sepSCS = coordSC[position].separation(coordS).arcsecond

#                         if sepES>sepSCS:
# #                            print new,': has wrong position in Exoplanet.eu, it is: ',coordExo[i].ra.deg, coordExo[i].dec.deg,', but should be: ',coordS.ra.deg,coordS.dec.deg
#                             pass
#                         else:
#                            print new,': has wrong position in Sweet-Cat, it is: ',coordSC[position].ra.deg, coordSC[position].dec.deg,', but should be: ',coordS.ra.deg,coordS.dec.deg
#                     except:
#                         print 'Star not found in Simbad with this name ',new,'.\n Position in Exoplanet.eu:',coordExo[i].ra.deg, coordExo[i].dec.deg,'\n Position in SC: ',coordSC[position].ra.deg, coordSC[position].dec.deg
#                         with open('starnotfoundinsimbad.list', 'a') as f:
#                             f.write(new+'\n')

            #  REMOVE THE COMMENTS TO CHECK PROBLEMS WITH THE NAMES
            # else:
            #     position=ind[0]
            #     if (tmp not in self.sc_names):
            #         print new, ': has a different name in Sweet-Cat (',self.sc_names[position],')'
                        
        NewStars = sorted(list(set(NewStars)))
        Nstars = len(NewStars)

        if Nstars:
            puts('    '+colored.green(str(Nstars) + " new exoplanet available!"))
            writeFile('names.txt', '\n'.join(NewStars))
            updated=False
        else:
            puts(colored.clean('    No new updates available.'))
            updated=True

        # removing planets that are not in Exoplanet.eu anymore    
        NewStars = []

        for i, scname in enumerate(self.sc_names_orig):
            sep = coordSC[i].separation(coordExo).arcsecond
            ind=np.where(sep<5.)[0]
            if len(ind)==0:
                try:
                    # it didn't find by position but it finds by name
                    position=self.exo_names.index(scname)
                except:
                    position=-1
                    # it didn't find by position and neither by name
                    if (tmp not in self.blacklist):
                        NewStars.append(scname)

        NewStars = sorted(list(set(NewStars)))
        Nstars = len(NewStars)
        if Nstars:
            puts(colored.green('    '+str(Nstars) + " exoplanet has to be removed!"))
            print '\n    '.join(NewStars)
        else:
            puts(colored.clean('    No planet to remove.'))
            if updated:        
                puts(colored.clean('    SWEET-Cat is up to date'))
                puts(colored.green('    Great job :)'))
Beispiel #14
0
    def update(self):
        """
        Check the difference the exoplanet database (EU or NASA)
        and the SweetCat database
        INPUTS: self = exoplanet database in pandas dataframe
        OUTPUTS: names.txt = file with stars that are not in SweetCat but
                             stars are in the exoplanet database (EU or NASA)
                 fname_sc_day-month_hour:minute = new SWEET-Cat dabatase
                                                  with updated database label

        Prints the stars that are in SweetCat
        and that are not in the exoplanet database (EU or NASA)
        """

        # We have this already, but without the ' in the name.
        print('\n    Matching database ...')
        if self.nasa:
            print('    NASA exoplanet archive')
        else:
            print('    Extrasolar Planets Encyclopaedia')

        NewStars = []
        # Star corrdinates in the exoplanet database
        coordExo = coord.SkyCoord(ra=self.exoplanet['ra'].values,
                                  dec=self.exoplanet['dec'].values,
                                  unit=(u.deg, u.deg),
                                  frame='icrs')
        # Star coordinates in the SWEET-Cat database
        coordSC = coord.SkyCoord(ra=self.coordinates['ra'].values,
                                 dec=self.coordinates['dec'].values,
                                 unit=(u.hourangle, u.deg),
                                 frame='icrs')

        # -------------------------------------------------------
        # Adding stars that are not
        # in Exoplanet.EU nor NASA exoplanet archive
        # For stars which already are in one of the database,
        # only the database label is updated by this script
        # -------------------------------------------------------
        for i, exo_name in enumerate(self.exo_names):
            starName = exo_name
            # starIndex = self.exoplanet[self.exoplanet['pl_hostname'] == exo_name].index[0]
            # starName = self.exoplanet['star_name'].values[i]

            # Clean star name
            tmp = starName.lower().replace(' ', '').replace('-', '')

            # Check if the star in exoplanet database is in SWEET-Cat
            sep = coordExo[i].separation(coordSC).arcsecond
            ind = np.where(sep < 5.)[0]

            # Star is already in SWEET-Cat
            if len(ind) != 0.:
                ind_SC = ind[0]

                # Check if the name of the database (EU and/or NASA)
                # is written in the SWEET-CAT file, if not it's added
                if self.nasa:
                    if 'NASA' in self.SC.loc[ind_SC].database:
                        pass
                    else:
                        print('\nChecking star: ', starName,
                              '(found by position)')
                        # print(self.exoplanet.loc[starIndex][['pl_hostname', 'ra_str', 'dec_str']])
                        # print(self.SC.loc[ind_SC][['name', 'ra', 'dec', 'database', 'n3']])
                        print(' > adding NASA label')
                        self.SC.at[ind_SC, 'database'] = self.SC.at[
                            ind_SC, 'database'] + ',NASA'
                else:
                    if 'EU' in self.SC.loc[ind_SC].database:
                        pass
                    else:
                        print('\nChecking star: ', starName,
                              '(found by position)')
                        print(' > adding EU label')
                        self.SC.at[ind_SC,
                                   'database'] = self.SC.at[ind_SC,
                                                            'database'] + ',EU'

            if len(ind) == 0:
                try:
                    # it didn't find by position but it finds by name
                    position = self.sc_names.index(tmp)

                    # Check the name of the database (EU and/or NASA)
                    if self.nasa:
                        if 'NASA' in self.SC.loc[position].database:
                            pass
                        else:
                            print('\nChecking star: ', starName, i,
                                  '(found by name)')
                            print(' > adding NASA label')
                            self.SC.at[position, 'database'] = self.SC.at[
                                position, 'database'] + ',NASA'
                    else:
                        if 'EU' in self.SC.loc[position].database:
                            pass
                        else:
                            print('\nChecking star: ', starName, i,
                                  '(found by name)')
                            print(' > adding EU label')
                            self.SC.at[position, 'database'] = self.SC.at[
                                position, 'database'] + ',EU'

                except:
                    position = -1
                    # it didn't find by position and neither by name
                    if (tmp not in self.blacklist):
                        NewStars.append(starName)

                #  REMOVE THE COMMENTS TO CHECK PROBLEMS IN POSITION


#                 if position>=0:

#                     result_table = Simbad.query_object(new)
#                     try:
#                         # check in Simbad the position and see where the coordinates are wrong
#                         ra=str(result_table['RA'][0])
#                         dec=str(result_table['DEC'][0])
#                         coordS=coord.SkyCoord(ra, dec, unit=(u.hourangle, u.degree), frame='icrs')
#                         sepES = coordExo[i].separation(coordS).arcsecond
#                         sepSCS = coordSC[position].separation(coordS).arcsecond

#                         if sepES>sepSCS:
# #                            print new,': has wrong position in Exoplanet.eu, it is: ',coordExo[i].ra.deg, coordExo[i].dec.deg,', but should be: ',coordS.ra.deg,coordS.dec.deg
#                             pass
#                         else:
#                            print new,': has wrong position in Sweet-Cat, it is: ',coordSC[position].ra.deg, coordSC[position].dec.deg,', but should be: ',coordS.ra.deg,coordS.dec.deg
#                     except:
#                         print 'Star not found in Simbad with this name ',new,'.\n Position in Exoplanet.eu:',coordExo[i].ra.deg, coordExo[i].dec.deg,'\n Position in SC: ',coordSC[position].ra.deg, coordSC[position].dec.deg
#                         with open('starnotfoundinsimbad.list', 'a') as f:
#                             f.write(new+'\n')

#  REMOVE THE COMMENTS TO CHECK PROBLEMS WITH THE NAMES
# else:
#     position=ind[0]
#     if (tmp not in self.sc_names):
#         print new, ': has a different name in Sweet-Cat (',self.sc_names[position],')'

        NewStars = sorted(list(set(NewStars)))
        Nstars = len(NewStars)

        if Nstars:
            puts('    ' +
                 colored.green(str(Nstars) + " new exoplanet available!"))
            writeFile('names.txt', '\n'.join(NewStars))
            updated = False
        else:
            puts(colored.clean('\n    No new updates available.'))
            updated = True

        # -------------------------------------------------------
        # Removing planets that are not
        # in Exoplanet.EU and NASA exoplanet archive anymore
        # -------------------------------------------------------
        print('\n    Checking for stars to remove ...')
        NewStars = []

        for i, scname in enumerate(self.sc_names_orig):
            # Clean star name
            tmp = starName.lower().replace(' ', '').replace('-', '')

            # Check if the star in SWEET-Cat is in exoplanet database
            sep = coordSC[i].separation(coordExo).arcsecond
            ind = np.where(sep < 5.)[0]

            if len(ind) == 0:
                try:
                    # it didn't find by position but it finds by name
                    position = self.exo_names_clean.index(tmp)

                except:
                    # Star in Sweet-Cat is not found
                    # in the exoplanet database (EU or NASA)
                    position = -1

                    # Check if the star is not from the other database
                    if self.nasa:
                        if 'EU' in self.SC.loc[i].database:
                            # Star is in EU
                            # Star will not be removed from SWEET-Cat
                            if 'NASA' in self.SC.loc[
                                    i].database and scname != 'Barnards':
                                # Removing NASA label from database column
                                print(' > Removing NASA label')
                                self.SC.at[i, 'database'] = self.SC.at[
                                    i,
                                    'database'].replace('NASA',
                                                        '').replace(',', '')
                            continue
                    else:
                        if 'NASA' in self.SC.loc[i].database:
                            # Star is in NASA
                            # Star will not be removed from SWEET-Cat
                            if 'EU' in self.SC.loc[
                                    i].database and scname != 'Barnards':
                                # Removing EU label from database column
                                print(scname)
                                print(' > Removing EU label')
                                self.SC.at[i, 'database'] = self.SC.at[
                                    i,
                                    'database'].replace('EU',
                                                        '').replace(',', '')
                            continue

                    # it didn't find by position and neither by name
                    # star is not from the other database
                    if (tmp not in self.blacklist):
                        NewStars.append(scname)

        NewStars = sorted(list(set(NewStars)))
        Nstars = len(NewStars)
        if Nstars:
            puts(
                colored.green('    ' + str(Nstars) +
                              " exoplanet has to be removed!"))
            print('\n    '.join(NewStars))
        else:
            puts(colored.clean('\n    No star to remove.'))
            if updated:
                puts(colored.clean('    SWEET-Cat is up to date'))
                puts(colored.green('    Great job :)'))

        # Date and time
        timestr = time.strftime("%d-%m-%H:%M")
        filename = os.path.splitext(self.fname_sc)[0] + '_' + timestr + '.rdb'

        # Convert Tefferr column to integers
        self.SC['Tefferr'] = self.SC['Tefferr'].fillna('-111111')
        self.SC['Tefferr'] = self.SC['Tefferr'].astype(int).replace(
            -111111, 'NULL')
        # Replace NaN by NULL
        self.SC.fillna(value='NULL', inplace=True)

        # Write new SWEET-Cat database
        print('\n    Writing the file: ', filename)
        self.SC.to_csv(filename, sep='\t', index=False, header=False)
Beispiel #15
0
def main():
    try:
        db = DBRepository()
        flag = True
        while flag:
            while True:
                clear_screen()
                puts(
                    colored.green('SEARCHING ENGINE') +
                    colored.clean('\n -by Three Legged Spider'))
                space(1)
                raw_user_query = raw_input(
                    colored.yellow("Enter your query: "))
                if len(raw_user_query) >= 1:
                    break
                else:
                    print('Enter valid query')
                    time.sleep(0.5)
                    continue

            user_query = query_preprocessor(raw_user_query)
            # print(user_query)
            common_docs, unique_docs = db.search_double_query(user_query)

            # print(common_docs)
            # space(3)
            # print(unique_docs)
            if common_docs == 0:
                space(1)
                print('No results found')
                space(2)
                exit_choice(flag)
            elif common_docs != 0:
                # print(common_docs)
                proximity_dict = {}
                if len(user_query) > 1:
                    proximity_dict = db.get_proximity(list(common_docs),
                                                      user_query)
                    # print(docs_dict)

                    proximity_dict = proximity(list(common_docs),
                                               proximity_dict)
                    sorted(proximity_dict,
                           key=lambda x: (proximity_dict[x]['final_score']),
                           reverse=True)

                    common_docs = set(proximity_dict.keys())

                final_document_list, final_url_list = final_list_creation(
                    common_docs, unique_docs, 5)

                if len(user_query) == 1:
                    position_dict = db.position_for_one_word(
                        list(final_document_list), user_query[0])
                else:
                    unique_doc_positions1 = db.position_for_one_word(
                        list(final_document_list), user_query[0])
                    unique_doc_positions2 = db.position_for_one_word(
                        list(final_document_list), user_query[1])

                text_snippet = []

                for doc in list(final_document_list):
                    text_snippet.append(get_snippet(doc, user_query))

                # if len(user_query)==1:
                #     for doc in list(final_document_list):
                #         text_snippet.append(get_snippet(doc, position_dict[doc]['pos_w1']))
                # else:
                #     for doc in list(final_document_list):
                #         # space()
                #         # print(doc)
                #         if doc in common_docs:
                #             # print('in common')
                #             print(min(proximity_dict[doc]['pos_w1']), min(proximity_dict[doc]['pos_w2']))
                #             text_snippet.append(get_snippet(doc, min(proximity_dict[doc]['pos_w1']), \
                #                 min(proximity_dict[doc]['pos_w2'])))
                #         elif doc in unique_docs:
                #             # print('in unique')

                #             if doc in unique_doc_positions1.keys():
                #                 print(unique_doc_positions1[doc]['pos_w1'])
                #                 a = get_snippet(doc, unique_doc_positions1[doc]['pos_w1'])
                #                 text_snippet.append(a)
                #             elif doc in unique_doc_positions2.keys():
                #                 print(unique_doc_positions2[doc]['pos_w1'])
                #                 a = get_snippet(doc, unique_doc_positions2[doc]['pos_w1'])
                #                 text_snippet.append(a)
                #             else:
                #                 print('Something is wrong')

                print(colored.cyan('Google Results: '))
                output_string(google_search(user_query))
                space(1)
                print(colored.cyan("Search Results:"))
                output_string(final_url_list, text_snippet)
                # output_string(final_url_list)
                space(1)

                # weight_list = db.weigths_of_the_output(final_document_list, user_query)
                # print(weight_list)

                ground_truth = [
                    int(x) for x in raw_input(
                        'List of relevance score for each result by Google seperated by space: '
                    ).split()
                ]
                relevance_score = [
                    int(x) for x in raw_input(
                        'List of relevance score for each results seperated by space: '
                    ).split()
                ]

                N_list = NDCG.ndcg_at_k(relevance_score, 5)
                N_list_with_ground_truth = NDCG.ndcg_score(ground_truth,
                                                           relevance_score,
                                                           k=5)

                space(1)
                print('NDCG without Ground Truth: ' + str(N_list))
                print('NDCG with Ground Truth: ' +
                      str(N_list_with_ground_truth))

                space(1)
                exit_choice(flag)

    except (KeyboardInterrupt, SystemExit):
        print('Exit by User')
Beispiel #16
0
            puts(
                colored.red(
                    'Not a app dir (or any of the parent directories)'))
        sys.exit(1)
    global_conf['app_root'] = app_root

    # 读取static.json
    try:
        static_conf = get_static_conf(app_root)
        static_conf = static_conf['staticpy']
    except json.decoder.JSONDecodeError, e:
        with indent(8, quote=colored.clean('#')):
            puts(colored.red('JSONDecodeError in static.json: %s' % e))
        sys.exit(1)
    except KeyError:
        with indent(8, quote=colored.clean('#')):
            puts(colored.red('"staticpy" key not in static.json'))
        sys.exit(1)

    global_conf['host_dict'] = defaultHostDict
    if 'hostDict' in static_conf:
        for k, v in static_conf['hostDict'].iteritems():
            global_conf['host_dict'].setdefault(k, v + '%s.git')
        del static_conf['hostDict']

    # 遍历repo
    for repo_name, conf_json in static_conf.iteritems():
        with indent(4, quote=colored.clean('#')):
            puts(colored.clean('** ' * 10))
            puts(colored.yellow('Processing %s' % repo_name))
    def update(self):
        """
        Check the difference the exoplanet database (EU or NASA)
        and the SweetCat database
        INPUTS: self = exoplanet database in pandas dataframe
        OUTPUTS: names.txt = file with stars that are not in SweetCat but
                             stars are in the exoplanet database (EU or NASA)
        Prints the stars that are in SweetCat
        and that are not in the exoplanet database (EU or NASA)
        """

        # We have this already, but without the ' in the name.
        print('\n    Matching data base...')

        NewStars = []
        coordExo = coord.SkyCoord(ra=self.exoplanet['ra'].values,
                                  dec=self.exoplanet['dec'].values,
                                  unit=(u.deg, u.deg),
                                  frame='icrs')
        coordSC = coord.SkyCoord(ra=self.coordinates['ra'].values,
                                 dec=self.coordinates['dec'].values,
                                 unit=(u.hourangle, u.deg),
                                 frame='icrs')

        for i, exo_name in enumerate(self.exo_names):
            starName = exo_name
            # starName = self.exoplanet['star_name'].values[i]

            # Clean star name
            tmp = starName.lower().replace(' ', '').replace('-', '')

            sep = coordExo[i].separation(coordSC).arcsecond
            ind = np.where(sep < 5.)[0]

            if len(ind) == 0:
                try:
                    # it didn't find by position but it finds by name
                    position = self.sc_names.index(tmp)

                except:
                    position = -1
                    # it didn't find by position and neither by name
                    if (tmp not in self.blacklist):
                        NewStars.append(starName)


                #  REMOVE THE COMMENTS TO CHECK PROBLEMS IN POSITION
#                 if position>=0:

#                     result_table = Simbad.query_object(new)
#                     try:
#                         # check in Simbad the position and see where the coordinates are wrong
#                         ra=str(result_table['RA'][0])
#                         dec=str(result_table['DEC'][0])
#                         coordS=coord.SkyCoord(ra, dec, unit=(u.hourangle, u.degree), frame='icrs')
#                         sepES = coordExo[i].separation(coordS).arcsecond
#                         sepSCS = coordSC[position].separation(coordS).arcsecond

#                         if sepES>sepSCS:
# #                            print new,': has wrong position in Exoplanet.eu, it is: ',coordExo[i].ra.deg, coordExo[i].dec.deg,', but should be: ',coordS.ra.deg,coordS.dec.deg
#                             pass
#                         else:
#                            print new,': has wrong position in Sweet-Cat, it is: ',coordSC[position].ra.deg, coordSC[position].dec.deg,', but should be: ',coordS.ra.deg,coordS.dec.deg
#                     except:
#                         print 'Star not found in Simbad with this name ',new,'.\n Position in Exoplanet.eu:',coordExo[i].ra.deg, coordExo[i].dec.deg,'\n Position in SC: ',coordSC[position].ra.deg, coordSC[position].dec.deg
#                         with open('starnotfoundinsimbad.list', 'a') as f:
#                             f.write(new+'\n')

            #  REMOVE THE COMMENTS TO CHECK PROBLEMS WITH THE NAMES
            # else:
            #     position=ind[0]
            #     if (tmp not in self.sc_names):
            #         print new, ': has a different name in Sweet-Cat (',self.sc_names[position],')'

        NewStars = sorted(list(set(NewStars)))
        Nstars = len(NewStars)

        if Nstars:
            puts('    '+colored.green(str(Nstars) + " new exoplanet available!"))
            writeFile('names.txt', '\n'.join(NewStars))
            updated=False
        else:
            puts(colored.clean('    No new updates available.'))
            updated=True

        # removing planets that are not in Exoplanet.eu anymore    
        NewStars = []

        for i, scname in enumerate(self.sc_names_orig):
            sep = coordSC[i].separation(coordExo).arcsecond
            ind=np.where(sep<5.)[0]
            if len(ind)==0:
                try:
                    # it didn't find by position but it finds by name
                    position=self.exo_names.index(scname)
                except:
                    position=-1
                    # it didn't find by position and neither by name
                    if (tmp not in self.blacklist):
                        NewStars.append(scname)

        NewStars = sorted(list(set(NewStars)))
        Nstars = len(NewStars)
        if Nstars:
            puts(colored.green('    '+str(Nstars) + " exoplanet has to be removed!"))
            print('\n    '.join(NewStars))
        else:
            puts(colored.clean('    No planet to remove.'))
            if updated:        
                puts(colored.clean('    SWEET-Cat is up to date'))
                puts(colored.green('    Great job :)'))
Beispiel #18
0
sys.path.insert(0, os.path.abspath('..'))
args = Args()

q = 'y'
while (q == 'y') or (q == 'Y'):
    os.system('cls')

    f = Figlet(font='slant')
    d = Figlet(font='doom')
    print(f.renderText("NBA TEAMS"))

    print('>>> Introducing the 2019 NBA Team Rosters!')
    print('                                   Version 4.1.19d\n')

    puts(colored.yellow('Group 2'))
    puts(colored.clean('Eugenio, Jared Bryce B.'))
    puts(colored.clean('Cajipe,  Ralph Henrik I.'))
    puts(colored.clean('Finessa, Carl Ryan\n'))

    puts(colored.cyan('[1] - Add Team '))
    puts(colored.red('[2] - Delete Team'))
    puts(colored.green('[3] - Update Team'))
    puts(colored.yellow('[4] - View Team'))
    puts(colored.magenta('[5] - Search Team'))
    puts(colored.cyan('[6] - Exit\n'))

    choice = int(input('>>> Enter Choice: '))
    if choice == 1:
        os.system('cls')
        a = input('Enter Team Name: ')
        b = input('Enter Starting Point Guard: ')
Beispiel #19
0
    except NotFoundAppRoot:
        with indent(2, quote=colored.clean('#')):
            puts(colored.red('Not a app dir (or any of the parent directories)'))
        sys.exit(1)
    global_conf['app_root'] = app_root

    # 读取static.json
    try:
        static_conf = get_static_conf(app_root)
        static_conf = static_conf['staticpy']
    except json.decoder.JSONDecodeError, e:
        with indent(8, quote=colored.clean('#')):
            puts(colored.red('JSONDecodeError in static.json: %s' % e))
        sys.exit(1)
    except KeyError:
        with indent(8, quote=colored.clean('#')):
            puts(colored.red('"staticpy" key not in static.json'))
        sys.exit(1)

    global_conf['host_dict'] = defaultHostDict
    if 'hostDict' in static_conf:
        for k, v in static_conf['hostDict'].iteritems():
            global_conf['host_dict'].setdefault(k, v + '%s.git')
        del static_conf['hostDict']

    # 遍历repo
    for repo_name, conf_json in static_conf.iteritems():
        with indent(4, quote=colored.clean('#')):
            puts(colored.clean('** ' * 10))
            puts(colored.yellow('Processing %s' % repo_name))