Пример #1
0
 def do_load(self, event):
  """Load a script file."""
  dlg = wx.FileDialog(self, style = wx.FD_OPEN)
  if dlg.ShowModal() == wx.ID_OK:
   path = dlg.GetPath()
  else:
   path = None
  dlg.Destroy()
  if path:
   functions.load(path)
Пример #2
0
 def save_question(q):
     try:
         data = load(QUESTIONS_FILENAME)
     except FileNotFoundError:
         data = []
     data.append(q)
     save(QUESTIONS_FILENAME, data)
Пример #3
0
    async def cringe_words(self, ctx):
        cringe_words = functions.load("cringe_word_list.json")

        words = ""
        for word in cringe_words:
            words += f"`{word}`, "
        await ctx.send(words)
Пример #4
0
def main():
    '''
    load record data
    load vehicle data
    show main menu
    '''
    global debug, gui
    guiType = 0
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hdcg", ["help", "debug", "cli", "gtk"])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)


    for o,a in opts:
        if o in ("-d", "--debug"):
            debug=True
        elif o in ("-c", "--cli"):
            guiType = 0
        elif o in ("-g", "--gtk"):
            guiType = 1
        elif o in ("-h", "--help"):
            usage()
            exit()
        else:
            assert False, "unhandled option"

    if debug:
        print('#### DEBUG MODE ####')

    if guiType == 0:
        gui = CLI()
#    elif guiType == 1:
#        gui = GUI()

    FN.load()
    for v in FN.vehicles:
        FN.fuel_graph(v)
    FN.ppl_graph()
    FN.index()
    gui.start() 
Пример #5
0
    async def remove_cringe_word(self, ctx, word=None):
        if not word:
            return await ctx.send("Include in a word maybe???")

        cringe_words = functions.load("cringe_word_list.json")
        try:
            cringe_words.remove(word)
            functions.save("cringe_word_list.json", cringe_words)
            await ctx.send(f"`{word}` removed from cringe word list!")
        except:
            await ctx.send(f"`{word}` not in cringe word list!")
Пример #6
0
    async def add_cringe_word(self, ctx, word=None):
        if not word:
            return await ctx.send("Include in a word maybe???")

        cringe_words = functions.load("cringe_word_list.json")
        if word not in cringe_words:
            cringe_words.append(word)
            functions.save("cringe_word_list.json", cringe_words)
            await ctx.send(f"`{word}` added to cringe word list!")
        else:
            await ctx.send(f"`{word}` in cringe word list already!")
Пример #7
0
def feat_select(f):

    cp = load(read)
    (X, y, t) = cp.export_data(f)

    data = numpy.c_[X, y]
    cov = empirical_covariance(data, False)

    print cov

    for i in range(cov.shape[0] - 1):
        print cov[i, -1]
Пример #8
0
def process_audio(
    wav_file,
    length_in_seconds=12,
):
    array = process_track(load(wav_file))
    n = array.shape[1] / length_in_seconds
    temp = []
    tru_arr = np.transpose(
        array
    )  # because there are 128 arrays of frequencies for each timestamp we want arrays of 128 frequencies for each timestamp
    for i in range(0, length_in_seconds):
        temp.append(tru_arr[int(10 + (n * i))])
    return np.asarray(temp)
def read_multiple_net(accounts, adr):
    
    data, ids, usernames, color = [], [], [], []
    counter = 0
    for acc in accounts:
        path = adr+'/'+acc

        #read data for current user
        raw_data = functions.load_json_list(path+'/'+acc+'_complete.txt')
        base_usernames = functions.load(path+'/'+acc+'_usernames.txt')
        base_ids = functions.load(path+'/'+acc+'_ids.txt')
    
        #substitution usernames with user ids for current user
        temp_data, temp_ids, temp_usernames = prepare_data(raw_data, base_ids, base_usernames)
        data, ids, usernames, color = update_data(data, 
                                                  ids, 
                                                  usernames, 
                                                  temp_data, 
                                                  temp_ids, 
                                                  temp_usernames, 
                                                  color)
        counter+=1
        color = update_color(color, len(data), counter)
    return data, ids, usernames, color
Пример #10
0
    async def cringenamecheck(self, ctx, profile):
        functions.log(ctx.guild.name, ctx.author, ctx.command)

        account = functions.check_account_existence_and_return(profile)
        if account:
            embed = functions.default_embed()

            cringe_check_list = functions.load("cringe_word_list.json")
            cringe_score = 0
            cringe_rating = {
                0: "Not cringe!",
                1: "Maybe a little cringe?",
                2: "Little cringe.",
                3: "A bit cringe!",
                4: "Cringe!",
                5: "Quite cringe!",
                6: "Very cringe!",
                7: "Super cringe!",
                8: "Incredibly cringe!",
                9: "Ludicrously cringe!",
                10: "THE CRINGIEST!"
            }

            display_name = functions.id_to_display_name(account['account_id'])
            cringe_words = [
                ele for ele in cringe_check_list
                if (ele.casefold() in display_name.casefold())
            ]
            cringe_score = len(cringe_words) * 2

            for char in display_name:
                if not char.isalpha():
                    cringe_score += 1
                    cringe_words.append(char)

            if cringe_score > 10:
                cringe_score = 10

            embed.add_field(name=f"{account['username']}'s display name:",
                            value=f"```{display_name}```")
            embed.add_field(
                name="Cringe score",
                value=f"`{cringe_score}` ({cringe_rating[cringe_score]})",
                inline=False)

            flags = ""
            for flag in cringe_words:
                flags += f"`{flag}`, "

            if flags:
                embed.add_field(
                    name="Flags",
                    value=
                    f"||{flags}||\nThis command is just for fun, and not meant to shame anybody!",
                    inline=False)

            pfp = functions.id_to_pfp(account['account_id'], True)
            embed.set_author(name=f"🔗 {account['username']}'s profile",
                             url=f"https://rec.net/user/{account['username']}",
                             icon_url=pfp)
        else:
            embed = functions.error_msg(ctx,
                                        f"User `@{profile}` doesn't exist!")

        functions.embed_footer(ctx, embed)  # get default footer from function
        await ctx.send(embed=embed)
Пример #11
0
    async def cringebiocheck(self, ctx, profile):
        functions.log(ctx.guild.name, ctx.author, ctx.command)

        account = functions.check_account_existence_and_return(profile)
        if account:
            bio = functions.get_bio(account['account_id'])
            pfp = functions.id_to_pfp(account['account_id'], True)

            print(
                f"{ctx.command} > {account['account_id']}, {account['username']}, {bio}, {pfp}"
            )

            embed = functions.default_embed()
            embed.add_field(name=f"{account['username']}'s bio:",
                            value=f"```{bio}```")

            flags = ""
            cringe_check_list = functions.load("cringe_word_list.json")
            cringe_score = 0
            cringe_rating_dict = {
                0: "Not cringe!",
                1: "A little cringe!",
                2: "Cringe!",
                3: "Very cringe!",
                4: "Yikes..!",
                5: "Radically cringe!",
                6: "Super cringe!",
                7: "Mega cringe!",
                8: "Ultra cringe!",
                9: "THE CRINGIEST!",
                10: "All hope for humanity has been lost!"
            }

            if bio:
                split_bio = bio.split(" ")
                for word in split_bio:
                    for flag in cringe_check_list:
                        if flag.casefold() in word.casefold():
                            cringe_score += 1
                            flags += f"`{flag}`, "

                if cringe_score > len(cringe_rating_dict) - 1:
                    cringe_rating = cringe_rating_dict[len(cringe_rating_dict)
                                                       - 1]
                else:
                    cringe_rating = cringe_rating_dict[cringe_score]

                embed.add_field(name="Cringe score",
                                value=f"`{cringe_score}` ({cringe_rating})",
                                inline=False)

                if flags:
                    embed.add_field(
                        name="Flags",
                        value=
                        f"||{flags}||\nThis command is just for fun, and not meant to shame anybody!",
                        inline=False)

            embed.set_author(name=f"🔗 {account['username']}'s profile",
                             url=f"https://rec.net/user/{account['username']}",
                             icon_url=pfp)
        else:
            embed = functions.error_msg(ctx,
                                        f"User `@{profile}` doesn't exist!")

        functions.embed_footer(ctx, embed)  # get default footer from function
        await ctx.send(embed=embed)
Пример #12
0
import discord
import os
import functions
from discord.ext.commands import CommandNotFound
from discord.ext import commands

config = functions.load("config.json")

client = discord.Client()

# Setting up
#intents = discord.Intents(messages = True, guilds = True, reactions = True, members = True, presences = True)
#client = commands.Bot(command_prefix = '.', intents = intents, help_command=None, case_insensitive=True)
client = commands.Bot(command_prefix=config['prefix'],
                      help_command=None,
                      case_insensitive=True)


# When bot online
@client.event
async def on_ready():
    print("Bot is ready!")
    print('Servers connected to:')
    print(f"Servers: {len(client.guilds)}")
    for guild in client.guilds:
        print(f"-{guild.name}")
        print(f"{guild.owner}")
        print(f"Members: {len(guild.members)}\n")
    await client.change_presence(
        status=discord.Status.online,
        activity=discord.Game(".help | bit.ly/RecNetBot"))
Пример #13
0
user = '******'

alfa = 0.4
extracting_weights = False
plot = True
disjoint = False
bc_analysis = False
cc_analysis = False
jsc = False
sdi = False
entropy = False
w = [0.2, 0.5, 0.3]  #ret, qt, rep

path = 'EGOS DIRECTORY' + user
raw_data = functions.load_json_list(path + '/' + user + '_complete.txt')
base_usernames = functions.load(path + '/' + user + '_usernames.txt')
base_ids = functions.load(path + '/' + user + '_ids.txt')

data, ids, usernames = info_diff_func.prepare_data(raw_data, base_ids,
                                                   base_usernames)

print("\n===========", user, "===========\n")

#creating adjacency matrix
adj = info_diff_func.adjacency(ids, data)

#a simple directed graph using networkx
G = info_diff_func.simple_graph(adj)

#extracting links
one_way, two_way = info_diff_func.links(adj)
Пример #14
0
    print('Number of all datapoints:', all_numb)
    print('Percentage of positive: ', positive / all_numb * 100)
    print('Percentage of neutral: ', neutral / all_numb * 100)
    print('Percentage of negative: ', negative / all_numb * 100)

    # words

    print('')
    words = dataset.text.values
    words = strip_punctuation(words).split()
    print('Unique words in dataset: ', len(np.unique(words)))

    # plots for NN

    grid = load('grid-search')
    histories = load('histories')
    plt.clf()
    plt.figure(figsize=(5, 15))
    batch_sizes = [8, 64, 128, 256]
    learning_rates = [0.1, .05, 0.01, 0.001]
    plt.figure(figsize=(15, 10))
    plt.title('Neural Network accuracy')
    plt.ylabel('Accuracy')
    plt.xlabel('Epoch')

    for history in histories:

        plt.plot(history.history['val_acc'], alpha=1)
    #     plt.plot(history.history['acc'], alpha=0.8)
    labels = ['size=100', 'size=500', 'size=1000']
Пример #15
0
PickOne = StartIndex[0, TestNumber] + DifferentOne
X_test, y_test = X_test_cand[PickOne, :], y_test_cand[PickOne]

mean_vals = np.mean(X_train, axis=0)
std_val = np.std(X_train)

X_train_centered = (X_train - mean_vals) / std_val
X_valid_centered = X_valid - mean_vals
X_test_centered = (X_test - mean_vals) / std_val

del X_data, y_data, X_train, X_valid, X_test

g2 = tf.Graph()
with g2.as_default():
    tf.set_random_seed(random_seed)
    func.build_cnn()
    saver = tf.train.Saver()

with tf.Session(graph=g2) as sess:
    func.load(saver, sess, epoch=2, path='./model/')

    for index, i in enumerate(X_test_centered):
        print('No.', index, ' Start!')
        StartThreshold = 0.05
        NumberOfImage = 14
        threshold = [i * 0.05 + StartThreshold for i in range(NumberOfImage)]
        for j in threshold:
            correct, probabilities = TraceBack([i], [y_test[index]], TestNumber[index], \
                                            index, j, ShowNotSave=False)
            print('correct? :\n', correct[0], '\nprobabilities :\n',
                  probabilities, '\n\n')
Пример #16
0
def evaluate_config(ext_algo, reg_algo, sum_algo, red_algo, tradeoff, word_len, max_sent, f):

    features = []
    for i in f.keys():
        if f[i][1] == True:
            features.append(f[i][0])
    features = "-".join(features)

    idx = []
    for x in f.keys():
        if f[x][1] == True:
            idx.append(x)
    idx = sorted(idx)

    d_name = gen_name(ext_algo, reg_algo, red_algo, sum_algo)

    w2v_model = None
    if red_algo == "w2v" or red_algo == "cnn":
        print "\nLoading w2v model..."
        w2v_path = "../sentiment-mining-for-movie-reviews/Data/GoogleNews-vectors-negative300.bin"
        w2v_model = Word2Vec.load_word2vec_format(w2v_path, binary=True)  # C binary format

    print "\nLearn..."
    cp = load(read)
    (X, y, t) = cp.export_data(f)
    w = learn_relevance(X, y, reg_algo)

    print "\nInfo..."
    print "train shape: ", X.shape
    print "number of test collections: ", len(t)

    print "\nGenerate..."
    # sample_lead_1 = multi_lead(cp.collections['d301i'+'2005'], word_len, max_sent)
    # sample_lead_2 = multi_lead(cp.collections['D0601A'+'2006'], word_len, max_sent)
    # sample_regr = rel_summarize(cp.collections['d301i'+'2005'], w, word_len, max_sent, idx)
    # sample_mmr = mmr_summarize(cp.collections['d301i'+'2005'], w, ext_algo, red_algo, word_len, max_sent, tradeoff, idx)

    print "\nPrinting sample lead / regression..."
    # plot_summary(sample_lead_1)
    # plot_summary(sample_lead_2)
    # plot_summary(sample_regr)
    # plot_summary(sample_mmr)

    if store_test:

        print "\nGenerating summaries for test collections"
        os.mkdir(d_name)
        out_file = open(d_name + "/configurations", "w")
        out_file.write("features: " + features + "\next_algo: " + ext_algo + "\nsum_algo: " + sum_algo)
        if sum_algo != "lead":
            out_file.write("\nregression_algo: " + reg_algo)
        if sum_algo == "mmr":
            out_file.write("\nred_algo: " + red_algo + "\ntradeoff: " + str(tradeoff))

        start = time.time()
        for c in t:

            if sum_algo == "lead":
                summ = multi_lead(c, word_len, max_sent)
                out_file = open(d_name + "/" + c.code.lower() + "_" + sum_algo, "w")
            elif sum_algo == "rel":
                summ = rel_summarize(c, w, word_len, max_sent, idx)
                out_file = open(d_name + "/" + c.code.lower() + "_" + reg_algo + "-" + sum_algo, "w")
            elif sum_algo == "mmr":
                summ = mmr_summarize(c, w, ext_algo, red_algo, word_len, max_sent, tradeoff, idx, w2v_model)
                out_file = open(d_name + "/" + c.code.lower() + "_" + reg_algo + "-" + sum_algo + "-" + red_algo, "w")
            else:
                raise Exception("sum_algo: Invalid algorithm")

            if human_inspect:
                out_file.write("TOPIC\n")
                out_file.write(c.code + "; " + c.topic_title)
                out_file.write("\n\nDESCRIPTION\n")
                out_file.write(c.topic_descr)
                out_file.write("\n\nSUMMARY\n")
            for s in summ:
                out_file.write(s + "\n")

            out_file.close()

        print "summarize and store, test collections: %f seconds" % (time.time() - start)
Пример #17
0
def generate(piano, flute, out_path):
    write_wav(out_path, combine(load(piano), load(flute)), 40000)
Пример #18
0
def get_metrics_from_file(file):
    counts = {
        'atss_count': atss.ATSS(load(file)).count(),
        'bloc_count': bloc.BLOC(load(file)).count(),
        'bloc_count_rel': bloc.BLOC(load(file)).count(relative=True),
        'cloc': cloc.CLOC(load(file)).count(),
        'cloc_count_rel': cloc.CLOC(load(file)).count(relative=True),
        'dpt_count': dpt.DPT(load(file)).count(),
        'etp_count': etp.ETP(load(file)).count(),
        'loc_count': loc.LOC(load(file)).count(),
        'nbeh_count': nbeh.NBEH(load(file)).count(),
        'nbeh_count_rel': nbeh.NBEH(load(file)).count(relative=True),
        'nbl': nbl.NBL(load(file)).count(),
        'ncmd': ncmd.NCMD(load(file)).count(),
        'ndk_count': ndk.NDK(load(file)).count(),
        'ndk_occurrences': ndk.NDK(load(file)).count(occurrences=True),
        'ndm': ndm.NDM(load(file)).count(),
        'ndm_occurrences': ndm.NDM(load(file)).count(occurrences=True),
        'nemd_count_rel': nemd.NEMD(load(file)).count(relative=True),
        'nfl_count': nfl.NFL(load(file)).count(),
        'nfmd_count': nfmd.NFMD(load(file)).count(),
        'nfmd_count_rel': nfmd.NFMD(load(file)).count(relative=True),
        'nicd_count': nicd.NICD(load(file)).count(),
        'nierr_count': nierr.NIERR(load(file)).count(),
        'nimpr_count': nimpr.NIMPR(load(file)).count(),
        'nimpt_count': nimpt.NIMPT(load(file)).count(),
        'ninc_count': ninc.NINC(load(file)).count(),
        'nincr_count': nincr.NINCR(load(file)).count(),
        'ninct_count': ninct.NINCT(load(file)).count(),
        'nincv_count': nincv.NINCV(load(file)).count(),
        'nlk_count': nlk.NLK(load(file)).count(),
        'nlo_count': nlo.NLO(load(file)).count(),
        'nlp_count': nlp.NLP(load(file)).count(),
        'nmd_count': nmd.NMD(load(file)).count(),
        'nnnv_count_rel': nnnv.NNNV(load(file)).count(relative=True),
        'nnwv_count': nnwv.NNWV(load(file)).count(),
        'nnwv_count_rel': nnwv.NNWV(load(file)).count(relative=True),
        'nsh_count': nsh.NSH(load(file)).count(),
        'ntnn_count': ntnn.NTNN(load(file)).count(),
        'ntun_count_rel': ntun.NTUN(load(file)).count(relative=True),
        'nun_count_rel': nun.NUN(load(file)).count(relative=True)
    }
    return counts
Пример #19
0
import os
import wx
import teamsframe
import quizframe
from functions import load

app = wx.App()

if os.path.exists(quizframe.HISTORY_FILENAME) and os.path.isfile(
        quizframe.HISTORY_FILENAME):
    history = load(quizframe.HISTORY_FILENAME)
    frame = quizframe.QuizFrame(history)
else:
    frame = teamsframe.TeamsFrame()
frame.Show()
app.MainLoop()
Пример #20
0
"""
HangManGame
"""

print "        HangManGame, by PythonSnake"
print "             0.1 Beta Version     "

#import modules
import values
import random
import functions

username=raw_input("Hi. What's your name ? ")
score=0

if functions.load(values.savefile)!=False and username in functions.load(values.savefile).keys():
    s=functions.load(values.savefile)
    score+=s[username]
    print "I remember ya ! You had {0} points !".format(s[username])

functions.menu()

print "Guess the word ! You have 8 tries only though."

answer='y'

while answer.lower()[0]=='y':
#declaring variables
    count=0
    i=random.randrange(113810)
    word_to_guess=values.words[i]
Пример #21
0
 reactor = wxreactor.install()
 import log
 application.log_object = log.LogObject(application.name)
 parser = argparse.ArgumentParser(prog = application.name, description = 'A (very) basic command line MUD client.')
 if not hasattr(parser, 'version'):
  parser.add_argument('-v', '--version', action = 'version', version = application.version, help = 'Show version information')
 else:
  parser.version = application.version
 parser.add_argument('-l', '--log-file', metavar = 'file', type = argparse.FileType('w'), default = sys.stdout, help = 'The log file.')
 parser.add_argument('-L', '--log-level', metavar = 'level', choices = ['debug', 'info', 'warning', 'warning', 'error', 'critical'], default = 'info', help = 'Log level')
 parser.add_argument('file', nargs = '?', help = 'File to load commands from')
 args = parser.parse_args()
 logging.basicConfig(stream = args.log_file, level = args.log_level.upper())
 logger = logging.getLogger()
 import connection, command_parser, functions, wx, gui
 reactor.addSystemEventTrigger('after', 'shutdown', logger.debug, 'Reactor shutdown.')
 application.factory = connection.MyClientFactory()
 application.app = wx.App()
 reactor.registerWxApp(application.app)
 gui.MainFrame()
 reactor.addSystemEventTrigger('after', 'shutdown', application.frame.Close, True)
 application.frame.Show(True)
 application.frame.Maximize()
 if args.file:
  functions.load(args.file)
 reactor.run()
 try:
  application.log_object.flush()
 except Exception as e:
  logger.exception(e)
Пример #22
0
from text_colors import RED, GREEN, BLUE, CYAN, RESET  # grabs color variables
import kshell_exceptions as err

# This is the non-formatted version of the search
# command's success string. The curly braces represent
# empty spaces which can be formatted with format()
search_success_string = '''{}An instance of {}"{}"{} was found in
{}"{}"{}!
'''

# is_running is set to False when 'exit' is typed
is_running = True
echo_mode = False
version = "0.41 (In-Dev)"

fn.load()
txt.print_magenta(f"KShell Version {version}")
txt.print_magenta(
    "Echo mode is currently set to false; to turn it on, type 'echo-mode true'."
)
txt.print_magenta("To turn echo mode off, type 'echo-mode false'.")
txt.print_cyan(
    "Written in Python 3. Make sure to run with Python 3.6 (preferably 3.7) or higher."
)
txt.print_magenta(
    "Please enjoy! Report any bugs (Traceback errors, etc.) to [email protected]."
)
txt.print_magenta("See the documentation or type 'help' for more information.")
# while is_running is True, it loops
while is_running:
    # This is the prompt at which the user enters commands