Exemple #1
0
def edit():
    """Edit view

    Returns a view of the edit page. The edit page is a list of
    all the currently existing projects in the database.

    Returns
    -------
    render_template

    """
    db = data.load("data.json")
    # Delete project
    if request.method == "POST":
        p_id = request.form["delete"]
        data.remove_project(db, int(p_id))
        data.save(db, "data.json")

        # Remove file
        if os.path.isdir(app.config["PROJECT_IMAGE_DIR"] + p_id + "/"):
            rmtree(app.config["PROJECT_IMAGE_DIR"] + p_id + "/")

        flash("Project deleted.", "success")

    all_projects = data.search(db, search="")
    table_fields = [
        "project_id", "project_name", "short_description", "course_id"
    ]
    return render_template("add.html", **locals())
Exemple #2
0
def unfollow(username, message, privileges):
    if message == "!unfollow":
        user = data.get_element(username, main_users)
        if user is not None:
            user_privileges = int(user[eUser.privileges])
        else:
            user_privileges = 0
        if user_privileges >= privileges:
            if data.has(main_channel_list, "#"+username):
                try:
                    shutil.rmtree(config.PATH+"channel/#"+username)
                    for key in main_channel_list:
                        if key[0] == "#"+username:
                            main_channel_list.remove(key)
                            data.save(config.PATH+"channel/channel.csv", main_channel_list)
                            break
                except OSError:
                    main_whisper.whisper(username, "Something went wrong. Please contact a Bot_Omb developer!")
                for i in range(len(bot_threads)):
                    if "#"+username == bot_threads[i].getName():
                        shutdown(bot_threads[i])
                        break
                main_whisper.whisper(username, "It seems like, it is time to say goodbye!")
            else:
                main_whisper.whisper(username, "First things first. If you want me to unfollow your chat, I have to follow first.")
        else:
            main_whisper.whisper(username, "Your privileges level is not high enough to perform this command! You need at least a level of {0}.".format(privileges))  
    def respondToUserInput(self, event):
        if self.transitionTimer < 64:
            return self

        for e in self.menu_list.handle(event):
            if e.type == graphics.userInterface.BUTTONCLICKED \
            or (event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN \
            and self.menu_list.buttons[0].active == True):

                transitionTimer = 0
                display = pygame.display.get_surface()
                static = display.copy()

                blackness = pygame.Surface((data.config.WIDTH, data.config.HEIGHT))
                blackness.fill(0x000000)

                while transitionTimer <= 255:
                    display.blit(static, (0, 0))

                    blackness.set_alpha(transitionTimer, pygame.RLEACCEL)
                    display.blit(blackness, (0, 0))

                    transitionTimer += 1
                    pygame.display.flip()

                ranking = data.load("ranking")

                ranking.append((self.menu_list.getText("name"), self.score))
                ranking = sorted(ranking, key=itemgetter(1), reverse=True)[0:10]

                data.save(ranking, "ranking")

                return screen.Ranking(fadin=True, showCredits=self.color == 0x262626)

        return self
Exemple #4
0
def do_proof(model, which):
  (trX, trY, teX) = proof(which)
  (trX, teX) = normalize(trX, teX)
  model.fit(trX, trY)
  teY = model.predict_proba(teX)[:,1]
  save(teY, 'pred.csv')
  return model
Exemple #5
0
 def guard_add(self, username, message):
     guard_difficulty = message[message.rfind(' ')+1:len(message)]
     message = message[0:message.rfind(' ')]
     guard_name = message[message.rfind(' ')+1:len(message)]
     self.__guards.append([guard_name, guard_difficulty])
     data.save(config.PATH+"channel/"+self.__channel_name+"/bank/guards.csv", self.__guards)
     self.__channel.chat(self.__languages["lan"]["guard_add"].format(guard_name, guard_difficulty))
Exemple #6
0
 async def save_subscriptions():
     data_s = {}
     data_s['feeds'] = []
     for name, feed in feeds.items():
         channels = await feed.get_feed_channels()
         data_s["feeds"].append({'name': name, 'channels': channels})
         await asyncio.sleep(0.01)
     data.save(data_s)
Exemple #7
0
def test_save_book():
    library = data.modify_book('9780316038379', 'Twilight 2',
                               'Meyer Stephenie 2', '1/1/2020')
    data.save(library)  # save to file
    books = data.read_books()
    assert books[3]['title'] == 'Twilight 2'
    assert books[3]['author'] == 'Meyer Stephenie 2'
    assert books[3]['year_published'] == '1/1/2020'
Exemple #8
0
 def __greet(self, users):
     usernames = ""
     for i in range(len(users)):
         if i == 0:
             usernames += users[i]
         else:
             usernames += ", " + users[i]
         self.__greeted.append([users[i]])
     data.save(config.PATH+"channel/"+self.__name+"/greetings.csv", self.__greeted)
     self.__channel.chat(self.__language["greetings"].format(usernames))
Exemple #9
0
 async def save_searches():
     """Saves list of searches as JSON object"""
     data_s = {}
     data_s['searches'] = []
     for search in search_list:
         data_s["searches"].append(
             {'url': search.url,
              'channel_id': f"{search.channel.id}"})
         await asyncio.sleep(0.01)
     data.save(data_s)
Exemple #10
0
 def saveSystems(self, xmlfile):
     data.save(
         "ssys.xml",
         self.systems,
         "Systems",
         "ssys",
         True,
         {"jumps": "jump", "planets": "planet", "fleets": "fleet"},
         None,
         {"nebulae": "volatility"},
     )
def gen_dataset(size,maxedges,num_datapoints,num_strategies,weight):
  sumcount = 0
  i = len(data)
  data.append([])
#  for size in range(start_size,end_size):
  for point in range(0,num_datapoints):
    test = nash(0,generate_graph(size,maxedges,num_strategies,weight))
    data[i].append((size,test[1],test[3]))
    sumcount += test[3]
  print("Avg. deviations:", sumcount/num_datapoints)
  dt.save(data[i])
Exemple #12
0
 def saveState(self, recoverable):
     try:
         dt.save()                           # save the current state, so we can restore
         if not dt.config.has_section('general'):
             dt.config.add_section('general')
         dt.config.set('general', 'layout', dt.fileName)
         with open(appConfigFileName, 'w') as f:
             dt.config.write(f)
         IOT.disconnect(recoverable)                        # close network connection, for cleanup
     except:
         logging.exception('failed to save application state')
Exemple #13
0
    def __init__(self, fadin=False, showCredits=True):

        try: self.list = data.load("ranking")
        except: data.save([], "ranking")
        self.list = data.load("ranking")

        self.ranking_list = graphics.userInterface.Interface()
        self.ranking_list.addButton(0, "arrow_back.png", data.config.WIDTH * 0.1, data.config.HEIGHT * 0.1, mask="arrow_leftMask.png")
        self.ranking_list.addSlider(1, "slider.png", "slidermask.png", (0, 1000), 0, data.config.WIDTH * 0.75 + 180, data.config.HEIGHT * 0.55, vertical=True, visible=len(self.list) > 5)

        self.fadin = 256 if fadin else -1
        self.showCredits = showCredits
def TCP_connect(ip, port_number, time_out=2):
    TCPsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    TCPsocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    TCPsocket.settimeout(time_out)
    try:
        TCPsocket.connect((ip, port_number))
        if TCPsocket.connect:
            port_number = str(port_number)
            services = port_reader(port_number)
            save(ip, port_number, services)
            print(port_number + ": " + services)
    except:
        pass
Exemple #15
0
 def login(self, widget):
     account = Account(password=self.entry_password.props.text,
                       number=self.entry_number.props.text)
     if self.combobox_types.props.active == 1:
         account.type = Account.TELECOM
     elif self.combobox_types.props.active == 2:
         account.type = Account.CAMPUS
     else:
         print("erro")
     if self.checkbutton_savepassword.props.active:
         save(account)
     self.login_notify(
         login(account, self.checkbutton_autoconnect.props.active))
def generate_isa_pairs(s):
    logging.info('processing #{}, domain: {}'.format(s.index, s.domain))
    try:
        pairs = syntactic_extraction(s)
        for pair in pairs:
            document = {}
            # logging.info(pair)
            document['sup'], document['sub'] = pair
            document['type'] = s.domain
            document['location'] = s.index
            save(document)
    except Exception as e:
        logging.info(e)
        return False
    return True
Exemple #17
0
 def test_save(self):
     expected_response = 2
     data.connect = MagicMock(return_value=[self.conn, self.conn])
     data.prefetch_quote_ids = MagicMock()
     self.conn.fetchone = MagicMock(return_value=[2])
     received_response = data.save("I am a quote!")
     self.assertEqual(expected_response, received_response)
Exemple #18
0
def main():
    print_header()
    # player = start_choice()
    player = start()
    if not player:
        player = start_choice()
    info(player)
    sleep(2)
    active = True

    while active:
        option = menu()
        # Quest Option
        if option == "quest":
            if player.quest:  # check that a quest exists
                confirm = input("Start quest?: {} (y/n) \n>>>".format(
                    player.quest))
                if confirm.find("y") != -1:
                    # TODO: make a good system for this, cuz 2 lines of extra elifs per quest cant be great
                    print(
                        "[!]Warning: This version of Quest is in beta. Proceed with caution."
                    )
                    if player.quest == "Clap the Dragon":
                        quests.clap_the_dragon(player)
                    elif player.quest == "Dab on Turtles":
                        quests.battle_turtles(player, 5)
                else:
                    print("ok then")
            else:
                print("ok maybe next time")
        # Inventory Option
        elif option == "inventory":
            print("----{INVENTORY}----")
            if not player.inventory:  # if nothing exists in the inventory
                print("[*] Nothing!")
            else:
                for item in player.inventory:
                    print("[*] {} ({})".format(item, player.inventory[item]))
        # Shop Option
        elif option == "shop":
            shop.shop(player)
        # Exit Option
        elif option == "exit":
            print("See ya later!")
            data.save(player)
            active = False
Exemple #19
0
 def run(self):
     while self.__active:
         time.sleep(60)
         if self.__api.getOnlineState(self.__channel_name):
             self.__users = data.load(config.PATH+"channel/"+self.__channel_name+"/users.csv")
             if self.__active:
                 users_chat = self.__api.getChatters(self.__channel_name)
                 if users_chat is not None:
                     for i in range(len(users_chat)):
                         user = data.get_element(users_chat[i].lower(), self.__users)
                         if user is not None:
                             watched = int(user[eUser.watchtime]) + 1
                             if not data.update(users_chat[i].lower(), [None, None, None, None, None, None, None, watched], self.__users):
                                 self.__users.append([users_chat[i].lower(), 0, 100, False, 0, 0, 0, watched])
                         else:
                             watched = 1
                             self.__users.append([users_chat[i].lower(), 0, 100, False, 0, 0, 0, watched])
                     data.save(config.PATH+"channel/"+self.__channel_name+"/users.csv", self.__users)
	def train(self,LR=2e-4,B1=0.5,B2=0.999,iterations=50000,sample_frequency=10,
	sample_overlap=500,save_frequency=1000,domain_a="a",domain_b="b"):
		self.trainer_D = tf.train.AdamOptimizer(LR,beta1=B1,beta2=B2).minimize(self.l_disc,var_list=self.disc_params)
		self.trainer_G = tf.train.AdamOptimizer(LR,beta1=B1,beta2=B2).minimize(self.l_g,var_list=self.gen_params)

		with self.sess as sess:
			sess.run(tf.global_variables_initializer())
			if self.analytics:
				if not os.path.exists("logs"):
					os.makedirs("logs")	
				self.summary_writer = tf.summary.FileWriter(os.getcwd()+'/logs',graph=sess.graph)
			for i in range(iterations):
				realA = data.get_batch(self.batch_size,domain_a)
				realB = data.get_batch(self.batch_size,domain_b)
				op_list = [self.trainer_D,self.l_disc,self.trainer_G,self.l_g,self.merged_summary_op]

				_,dLoss,_,gLoss,summary_str = sess.run(op_list,feed_dict={self.x_a:realA,self.x_b:realB})	
			
				realA = data.get_batch(self.batch_size,domain_a)
				realB = data.get_batch(self.batch_size,domain_b)

				_,gLoss = sess.run([self.trainer_G,self.l_g],feed_dict={self.x_a:realA,self.x_b:realB})

				if i%10 == 0:
					self.summary_writer.add_summary(summary_str, i)

				print("Generator Loss: " + str(gLoss) + "\tDiscriminator Loss: " + str(dLoss)) 
			
				if i % sample_frequency == 0:
					realA = data.get_batch(1,domain_a)
					realB = data.get_batch(1,domain_b)
					ops = [self.g_ba,self.g_ab,self.g_aba,self.g_bab]
					out_a,out_b,out_ab,out_ba = sess.run(ops,feed_dict={self.x_a:realA,self.x_b:realB})
					data.save(self.gen_a_dir+"/img"+str(i%sample_overlap)+'.png',out_a[0])
					data.save(self.gen_b_dir+"/img"+str(i%sample_overlap)+'.png',out_b[0])
					data.save(self.rec_a_dir+"/img"+str(i%sample_overlap)+'.png',out_ba[0])
					data.save(self.rec_b_dir+"/img"+str(i%sample_overlap)+'.png',out_ab[0])
				if i % save_frequency == 0:
					if not os.path.exists(self.model_directory):
						os.makedirs(self.model_directory)
					self.saver.save(sess,self.model_directory+'/model-'+str(i)+'.ckpt')
					print("Saved Model")

		"""
		Restore previously saved weights from
		trained / in-progress model
		"""
		def restore():
			try:
				self.saver.restore(self.sess, tf.train.latest_checkpoint(self.model_directory))
			except:
				print("Previous weights not found")
Exemple #21
0
def follow(username, message, privileges):
    if message == "!follow":
        user = data.get_element(username, main_users)
        if user is not None:
            user_privileges = int(user[eUser.privileges])
        else:
            user_privileges = 0
        if user_privileges >= privileges:
            if not data.has(main_channel_list, "#"+username):
                try:
                    os.mkdir(config.PATH+"channel/"+"#"+username)
                    os.mkdir(config.PATH+"channel/"+"#"+username+"/bank")
                    
                    files = [
                     {"file_name" : "quotes.csv", "file_path" : config.PATH+"channel/#"+username+"/", "file_data" : ""},
                     {"file_name" : "guards.csv", "file_path" : config.PATH+"channel/#"+username+"/bank/", "file_data" : "Karl;20\nMark;50\nLisa;40\n"},
                     {"file_name" : "whitelist.csv", "file_path" : config.PATH+"channel/#"+username+"/", "file_data" : "bot_omb\nnightbot\ntipeeebot\nwizebot\nmikuia\nmoobot\n"},
                     {"file_name" : "commands.csv", "file_path" : config.PATH+"channel/#"+username+"/", "file_data" : ""},
                     {"file_name" : "announcements.csv", "file_path" : config.PATH+"channel/#"+username+"/", "file_data" : ""},
                     {"file_name" : "greetings.csv", "file_path" : config.PATH+"channel/#"+username+"/", "file_data" : ""},
                     {"file_name" : "settings.csv", "file_path" : config.PATH+"channel/#"+username+"/", "file_data" : "language_chat;english\nwarning_url;False\nwarning_caps;False\nwarning_long_text;False\ngreetings;False\ngreetings_interval;60\ncommand_mode;True\nbet_mode;True\nfollow_mode;True\nannounce_mode;True\nsmm_mode;True\npoll_mode;True\nrank_mode;True\nbank_mode;True\nwhitelist_mode;True\nwatchtime_mode;False\nquote_mode;False\nhelp;0\ncoins;0\ncommand_add;99\ncommand_remove;99\ncommand_show;99\nprivileges;99\nsetting;99\nsetting_show;99\nurl;99\nbet;0\nbet_start;99\nbet_stop;99\nbet_reset;99\nfollow;0\nfollow_member;0\nfollow_member_other;99\nunfollow;0\ninfo;0\nannounce_add;99\nannounce_remove;99\nannounce_show;99\nsmm_level_submit;99\nsmm_level_submit_other;99\nsmm_level_show;99\nsmm_level_next;99\npoll_start;99\npoll_vote;99\npoll_result;99\nlanguage;99\nupsince;0\nrank_add;99\nrank_remove;99\nrank_show;99\nrank_show_me;0\nbank_robbery;99\nbank_spy;99\nbank_robbery_flee;99\nbank_guard_add;99\nbank_guard_remove;99\nbank_guard_show;99\nwhitelist_add;99\nwhitelist_remove;99\nwhitelist_show;99\nclam_ask;99\nroulette;99\nwatchtime_me;99\nhug_random;99\nhug_other;99\nquote_add;99\nquote_remove;99\nquote_show;99\n"},
                     {"file_name" : "users.csv", "file_path" : config.PATH+"channel/#"+username+"/", "file_data" : username+";100;100;False;0;0;0\n"},
                     {"file_name" : "ranks.csv", "file_path" : config.PATH+"channel/#"+username+"/", "file_data" : ""}
                    ]
                    
                    data.create(files)
                    
                    main_channel_list.append(["#"+username])
                    data.save(config.PATH+"channel/channel.csv", main_channel_list)
                except OSError:
                    main_whisper.whisper(username, "Something went wrong. Please contact a Bot_Omb developer!")
                new_bot_thread = Bot_Omb(["#"+username])
                new_bot_thread.setName("#"+username)
                new_bot_thread.setDaemon(True)
                bot_threads.append(new_bot_thread)
                new_bot_thread.start()
                main_whisper.whisper(username, "I joined your stream! If you want to use my full power, you just need to make me a Mod. Otherwise the auto moderation function will not work.")
            else:
                main_whisper.whisper(username, "I already joined your Chat!")
        else:
            main_whisper.whisper(username, "Your privileges level is not high enough to perform this command! You need at least a level of {0}.".format(privileges)) 
Exemple #22
0
def config():
    """
    The main driver for a configuration session.  Prompts the user for all information required to send e-mail
    through whatever smtp service they choose to use.
    """
    user_data = data.create()
    print 11 * '-'
    print "Email Setup"
    print 11 * '-'
    user_data.username = raw_input("Please enter your email username: "******"SMTP Server address: ")
    user_data.smtp_port = get_smtp_port()
    user_data.tls = get_y_n("Use TLS? (Y/N): ")
    user_data.ssl = get_y_n("Use SSL? (Y/N): ")
    logging.info("Saving user data.")
    try:
        data.save(user_data)
    except IOError:
        logging.error("Could not save data to file.")
        print "Could not save data to file.  Please make sure your storage device is working and try again."
Exemple #23
0
def add_quote(quote):
    """Adds a quote to the database via the data layer.

		Arguments:
			- quote (unicode) the quote to be added to the database

		Returns:
			- message (string) a message indicating whether or not the quote has been
				added to the database
	"""
    s_quote = str(quote)
    id = data.save(s_quote)
    if id == -1:
        QUOTE_REQUESTS.labels(command_type="addquote", result="failure").inc()
        return "There was an error saving the quote"

    QUOTE_REQUESTS.labels(command_type="addquote", result="success").inc()
    return "Quote #{} saved".format(id)
Exemple #24
0
async def process_as_results_come_in():
    for url, req in run():
        response = await request_get(url, req)
        result = json.loads(response.decode('utf-8'))
        # logging.debug(result['results'])
        save("Jobs", *result['results'])
Exemple #25
0
async def process_as_results_come_in():
    for url, req in run():
        response = await request_get(url, req)
        result = json.loads(response.decode('utf-8'))
        # logging.debug(result['results'])
        save("Jobs", *result['results'])
Exemple #26
0
from gradewindow import GradeWindow
from data import root
from data import save
from data import student_dict

root.minsize(1368, 720)
GradeWindow()
root.mainloop()
save()

Exemple #27
0
while not login:
    try:
        inputUsername = WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.ID, "username")))
        inputPassword = driver.find_element_by_id("password")
        inputUsername.send_keys(username)
        inputPassword.send_keys(password)
        inputPassword.send_keys(Keys.RETURN)
    finally:
        login = True

if data.isEmpty():
    while True:
        c = input("Vuoi salvare i dati? [y o n]\n>")
        if c == "y":
            data.save(codicescuola, username, password)
            break
        if c == "n":
            break

# seconda pagina
try:
    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located(
            (By.ID, "menu-servizialunno:vot"))).click()
finally:
    pass

# terza pagina (Voti)
mediaPrimoQuad = 0.0
nVotiPrimoQuad = 0.0
    def save(self, to, path=None, save_coefficient=True, save_spectral=True,
             save_kinetic=True):
        """
        Save date to an open HDF5 file.

        Parameters
        ----------
        to: str or tables.File
            A file name or a parent HDF5 node to save to
        path : str, optional
            HDF5 name to save under
        save_coefficient : bool, optional
            Whether to save kinetic coefficients
        save_spectral : bool, optional
            Whether to save spectral data
        save_kinetic : bool, optional
            Whether to save kinetic data.

        Notes
        -----
        Geometry is saved in all cases.

        """

        if isinstance(to, str):
            file = tables.openFile(to, 'w')
            to = file.root
        else:
            file = None

        if path:
            to = data.create_group(to, path)

        try:
            data.save(to, 'geometry', self.geometry)
            if save_spectral:
                data.save(to, 'spectral', self.spectral)
            if save_coefficient:
                data.save(to, 'coefficient', self.coefficient)
            if save_kinetic:
                data.save(to, 'kinetic', self.kinetic)
            if self.G != None:
                data.save(to, 'G/G', self.G)
                data.save(to, 'G/E', self.G_E)
        finally:
            if file is not None:
                del to
                file.close()
Exemple #29
0
from classify import classify
import data
import random
import util

def run():
  data.load()
  server.connect()
  for (uid, message) in server.fetch()[:50]:
    try:
      #if message['from'] in data.contacted:
      #  logger.log("contacted", message)
      #else:
        scams = classify(message)
        if scams:
          scam = random.choice(scams)
          response = random.choice(data.responses[scam])
        else:
          response = random.choice(data.default)
        server.reply(message, response)
        data.contacted.add(message['from'])
        logger.log("classified", str(scams), message.as_string(), response)
        server.seen(uid)
    except Exception, e:
      print e
  server.disconnect()
  data.save()
      
if __name__ == '__main__':
  run()
Exemple #30
0
from sklearn import svm
from numpy import arange
from data import draft, proof, eval, save, normalize

#(trX, trY, teX) = proof()
#clf = svm.SVC(probability=True, kernel='rbf', C = 5.0, gamma = 0.1)
#clf.fit(trX, trY)
#teY_svm01 = clf.predict_proba(teX)[:,1]
#save(teY_svm01)

def do_svm(which = ''):
  (trX, trY, teX) = draft(which)
  (trX, teX) = normalize(trX, teX)

  clf = svm.SVC(probability=True)
  clf.fit(trX, trY)
  teY = clf.predict_proba(teX)[:,1]
  return teY
#save(teY)

print eval(do_svm('_f03'))

(trX, trY, teX) = proof('_f03')
(trX, teX) = normalize(trX, teX)

clf = svm.SVC(probability=True)
clf.fit(trX, trY)
teY = clf.predict_proba(teX)[:,1]

save(teY)
Exemple #31
0
import data

# Available offline datasets
old = data.file()

# Get the latest day. Will replace this day
start = data.pandas.to_datetime(old.index[-1])

print('Checking for data since {} ...'.format(start.strftime('%Y-%m-%d')))

# If today hasn't concluded, there is no need to update
if start >= data.yesterday():
    print('No new data is expected')
    quit()

# Retrieve the newer set using the same symbol set
symbols = old.columns.levels[1].tolist()
new = data.net(symbols, start=start)

# Verify if new row is different
u = old.iloc[-1]
v = new.iloc[0]
if new.shape[0] is 1 and all(u.sub(v).values < 1.0e-3):
    print('No change in data, skip saving data')
    quit()

# Concatenate the datasets and discard the last day of the offline data
print('Saving new data ...')
big = data.pandas.concat([old.iloc[:-1], new])
data.save(big)
Exemple #32
0
def _set_data(key, data, save=False):
    global doodle_data
    doodle_data[key] = data

    if save:
        dnd_data.save(__name__, doodle_data)
Exemple #33
0
 def savePlanets(self, xmlfile):
     data.save("planet.xml", self.planets, "Planets", "planet", True, {"commodities": "commodity"})
Exemple #34
0
	for i in range(iterations):

		realA = data.get_batch(BATCH_SIZE,domainA)
		realB = data.get_batch(BATCH_SIZE,domainB)

		_,dLoss = sess.run([trainer_D,l_disc],feed_dict={x_a:realA,x_b:realB})	
	
		_,gLoss = sess.run([trainer_G,l_g],feed_dict={x_a:realA,x_b:realB})
		
		realA = data.get_batch(BATCH_SIZE,domainA)
		realB = data.get_batch(BATCH_SIZE,domainB)

		_,gLoss = sess.run([trainer_G,l_g],feed_dict={x_a:realA,x_b:realB})

		print("Generator Loss: " + str(gLoss) + "\tDiscriminator Loss: " + str(dLoss)) 
		
		if i % sample_frequency == 0:
			out_a,out_b,out_ab,out_ba = sess.run([g_ba,g_ab,g_aba,g_bab],feed_dict={x_a:realA,x_b:realB})
			data.save(gen_a_dir+"/img"+str(i%sample_overlap)+'.png',out_a[0])
			data.save(gen_b_dir+"/img"+str(i%sample_overlap)+'.png',out_b[0])
			data.save(rec_a_dir+"/img"+str(i%sample_overlap)+'.png',out_ba[0])
			data.save(rec_b_dir+"/img"+str(i%sample_overlap)+'.png',out_ab[0])
		if i % save_frequency == 0:
			if not os.path.exists(model_directory):
				os.makedirs(model_directory)
			saver.save(sess,model_directory+'/model-'+str(i)+'.ckpt')
			print("Saved Model")



Exemple #35
0
def beat_the_dev(player):  # fight is somewhat broke nibba
    dev = Enemy("Heckin-doggo", 9999999, 1, 50000)
    sleep(2)
    print("\n-Heh...")
    sleep(3)
    print("-You think you can really clap me, eh?")
    sleep(3)
    print(
        "-I created this world. You are but another player object. Watch this."
    )
    sleep(3)
    print("[!] Your Health and Max Health have dropped to 1!")
    oldhealth = player.health
    oldmax = player.max_health
    oldweapon = player.weapon
    player.health = 1
    player.max_health = 1
    sleep(1)
    print("[!] You feel a noticeable lack of weapon...")
    player.weapon = "Fists"
    sleep(2)
    if "UNKOWN" in player.inventory:
        player.weapon = "UNKOWN"
        print("")
        print("[!] Equipped weapon.ERROR: Weapon Does not Exist!")
    print("Let's fight, if that's what you're here for. :)")
    result = battle(player, [dev])
    if result == "Lost":
        print("-Did you really think that was a good idea?  I didn't.")
        sleep(0.5)
        print("-Here's your stats back, by the way.")
        print(
            "[!] You feel whole and weighted again! Although you really didn't need those extra pounds back..."
        )
        player.health = oldhealth
        player.max_health = oldmax
        player.weapon = oldweapon
        return False
    elif result == "Won":
        print("-Holy frick how did you manage to do that?!?!")
        sleep(1)
        print("-Do, do you have some unknown powers?")
        sleep(1)
        print("-WAIT!!")
        sleep(3)
        print("-Do you... do you have the powers of UNKOWN?")
        sleep(2)
        print("-I thought I sealed those powers away in the title screen."
              "Apparently, I didn't do it that great, since here we are.")
        sleep(3)
        print(
            "-I'll give you 50000 more XP and 100,000G not to tell anyone about it, deal?"
        )
        deal = input("(y/n) \n>>>").lower().strip()
        if deal.find("ye") != -1 or deal == "y":
            player.money += 100000
            player.xp += 50000
            player.inventory.pop("UNKOWN")
            player.completed.append("Beat up the Developer")
            print("-Cool, also I completed the mission for ya.")
            print("-See ya later my guy")
            return True
        else:
            print(
                "-Well sucks to be you, I have the UNKOWN now. You need to pay attention to your pockets pal."
            )
            print(
                "[!] Everything in you inventory is missing! Maybe if you left now, you could retrieve your save."
            )
            sleep(1)
            print(
                "-Wait, WHAT?! Don't leave the game! DONT! IM GONNA SAVE IT RIGHT NOW. "
                "NO MONEY OR ANYTHING. ILL DELETE YOU!!!")
            print("[!] The game froze. Now's your chance!")
            sleep(5)
            print("I'll...")
            sleep(3)
            print("...dab...on...")
            sleep(7)
            print(
                "...YOUUUUUU!!@!!!23123#Fveqwy3543g?%%%% player.name!!!@313323"
            )
            sleep(1)
            print("[!] PLAYER {} NOT FOUND. COMMENCING FILE REMOVAL.".format(
                player.name))
            player.weapon = "Fists"
            player.money = 0
            player.health = 0
            player.xp = -1
            player.level = ": None!"
            player.quest = "do nothing. You don't exist."
            player.inventory = {
                "There's Nothing Here...":
                "You should just make a new save pal."
            }
            data.save(player)
            player.name = "DELETED"
            print("----{GAME SAVED}----")
            sleep(1)
            print("----{WORLD DELETED}----")
Exemple #36
0
    # 最適なクラスタ数を考える
    #############
    # picpath = './elbow.png'
    # vectors = data.load(vecpath)
    # elbow(vectors, picpath)
    # for i in range(2, 7):
    # 	silhouette(vectors, i)

    #############
    # k-means
    #############
    n_cluster = 4
    print('n_cluster:', n_cluster)
    mwelist = data.load(mwepath)
    vectors = data.load(vecpath)
    km = KMeans(n_clusters=n_cluster, random_state=43, n_jobs=-1)
    km.fit(vectors)

    cluster_labels = km.labels_
    cluster_to_words = defaultdict(list)
    for cluster_id, word in zip(cluster_labels, mwelist):
        cluster_to_words[cluster_id].append(word)

    for i, cluslist in cluster_to_words.items():
        cluspath = './result/clusterlist_' + str(i + 1) + '.pickle'
        data.save(cluspath, cluslist)
        print('-------------------')
        print(len(cluslist))
        # for clus in cluslist:
        # 	print(clus)
numpy arrays representing the participant data (for recent matches)

@authors : Azwad Sabik, Rohit Bhattacharya
@emails  : [email protected], [email protected]
"""

import data
import vectorize

SUMMONER_NAME = 'C9 Sneaky'
NUMBER_OF_MATCHES = 5

if __name__ == "__main__":    
    r = data.Retriever()
    md = r.retrieve_player_match_details(SUMMONER_NAME, NUMBER_OF_MATCHES)
    data.save(md, SUMMONER_NAME + '_match_details_dict')
    po = vectorize.get_participant_objects(md, summoner_name = SUMMONER_NAME)
    po_win = vectorize.get_participant_objects(md, winners = True,
                                                   summoner_name = SUMMONER_NAME)
    rs = vectorize.vectorize_participants_relevant_stats(po)
    rs_win = vectorize.vectorize_participants_relevant_stats(po_win)
    s0 = vectorize.vectorize_participants_segment_stats(po, 0)
    s0_win = vectorize.vectorize_participants_segment_stats(po_win, 0)
    s1 = vectorize.vectorize_participants_segment_stats(po, 1)
    s1_win = vectorize.vectorize_participants_segment_stats(po_win, 1)
    data.save(rs, SUMMONER_NAME + '_relevant_stats')
    data.save(rs_win, SUMMONER_NAME + '_relevant_stats_wins')
    data.save(s0, SUMMONER_NAME + '_segment_0_stats')
    data.save(s0_win, SUMMONER_NAME + '_segment_0_stats_wins')
    data.save(s1, SUMMONER_NAME + '_segment_1_stats')
    data.save(s1_win, SUMMONER_NAME + '_segment_1_stats_wins')
Exemple #38
0
import data


def words(str):
    return set(
        filter(lambda x: not x.isspace(),
               map(lambda x: x.encode('utf8'), jieba.cut_for_search(str))))


def buildList(pages):
    inverted = {}
    cnt = -1

    for page in pages:
        cnt += 1  # not only used to display progress
        page["title"] = HTMLParser.HTMLParser().unescape(page["title"])
        print "%d: working on %s %s" % (cnt, page["date"], page["title"])

        for word in (words(page['title']) | words(page['content'])):
            if not inverted.has_key(word):
                inverted[word] = []
            inverted[word].append(cnt)

    return inverted


if __name__ == '__main__':
    pages = data.load('pages')
    data.save('inverted', buildList(pages))
Exemple #39
0
eps = 0.0001
W = rand(N,N)*eps
X = rand(N,N)

for i in range(trY.shape[0]):
  l = identities[i][0]-1
  r = identities[i][1]-1
  X[l, r] = trY[i] + rand() * eps
  W[l, r] = 1.0

ntf = beta_ntf.BetaNTF(X.shape, n_components=2, beta=2, n_iter=90,verbose=True)

#ntf.fit(X)
ntf.fit(X, W)
U = ntf.factors_[0]
V = ntf.factors_[1]

teY = []
for i in range(trY.shape[0], trY.shape[0] + teX.shape[0]):
  l = identities[i][0]-1
  r = identities[i][1]-1
  teY.append(dot(U[l,:], V[r,:].T))

from numpy import max,min
m = min(teY)
x = max(teY)
teY = (teY-m)/(x-m)
teY = array(teY)

save(teY, 'pred_pmf02_iter90.csv')
Exemple #40
0
import random
import util


def run():
    data.load()
    server.connect()
    for (uid, message) in server.fetch()[:50]:
        try:
            #if message['from'] in data.contacted:
            #  logger.log("contacted", message)
            #else:
            scams = classify(message)
            if scams:
                scam = random.choice(scams)
                response = random.choice(data.responses[scam])
            else:
                response = random.choice(data.default)
            server.reply(message, response)
            data.contacted.add(message['from'])
            logger.log("classified", str(scams), message.as_string(), response)
            server.seen(uid)
        except Exception, e:
            print e
    server.disconnect()
    data.save()


if __name__ == '__main__':
    run()
Exemple #41
0
            try:
                html = load("http://news.tsinghua.edu.cn/" + item["htmlurl"])
                break
            except urllib2.HTTPError as err:
                print " ---- fails: HTTP ", err.reason
                if err.code == 404:
                    fails.append(item['title'])
                    html = ''
                    break
                print " ---- retry"
            except urllib2.URLError as err:
                print " ---- fails: ", err.reason
                print " ---- retry"

        result = re.search('<article.*?>(.*?)</article>', html, re.S)
        if (result == None):
            contentHtml = ''
        else:
            contentHtml = result.group(1)
        item["content"] = htmlToText(contentHtml)

    print " -- fails:"
    for item in fails:
        print " ---- ", item

    return index


if __name__ == '__main__':
    data.save('pages', loadPages(loadIndex()))
Exemple #42
0
 def test_save_fails(self):
     expected_response = -1
     data.connect = MagicMock(return_value=[self.conn, self.conn])
     self.conn.fetchone = MagicMock(side_effect=psycopg2.Error)
     received_response = data.save("I am a quote!")
     self.assertEqual(expected_response, received_response)
Exemple #43
0
def main():
    print_header()
    # player = start_choice()
    player = start()
    if not player:
        player = start_choice()
    info(player)
    sleep(1)
    active = True

    while active:
        option = menu()
        # Quest Option
        if option == "quest":
            if player.quest:  # check that a quest exists
                confirm = input("Start quest?: {} (y/n) \n>>>".format(
                    player.quest))
                if confirm.find("y") != -1:
                    # TODO: make a good system for this, cuz 2 lines of extra elifs per quest cant be great
                    # if player.quest == "Clap the Dragon":
                    #     quests.clap_the_dragon(player)
                    if player.quest == "Dab on Turtles":
                        quests.battle_turtles(player, 3)
                    elif player.quest == "Beat up the Developer":
                        quests.beat_the_dev(player)
                    elif player.quest == "Mess with Goblins":
                        quests.mess_with_goblins(player)
                    elif player.quest == "Ryan's Battle":  # test battle - only accessable via debug mode
                        quests.ryans_battle(player)
                    elif player.quest == "Defeat Ryan":
                        quests.defeat_ryan(player)
                    elif player.quest == "Defeat the Outlaws":
                        quests.defeat_outlaws(player)
                    else:
                        print("You don't have a quest!")
                else:
                    print(
                        "ok then be that way man all this work i do to launch quests and u be that way ok cool"
                    )
            else:
                print(
                    "You don't have a quest! Go find one before trying to start! There may be some in town..."
                )

        # Inventory Option
        elif option == "inventory":
            inventory.use_item(player)

        # Shop Option
        elif option == "shop":
            shop.shop(player)

        # Player Info
        elif option == "player":
            info(player)

        # Debug mode
        elif option == "debug":
            player.debug()

        # World Option
        elif option == "world":
            world.world_init(player)
            selection = world.select_world()
            if selection == "Test World":
                world.test_world(player)
            elif selection == "Start Town":
                world.start_world(player)
            elif selection == "Topshelf":
                world.topshelf(player)
            elif selection == "Ptonio" and "Ptonio" in player.metadata:
                world.ptonio(player)

        # Save the game!
        elif option == "save":
            data.save(player)
            data.save_settings(settings)
            print("[!] Saved game!")

        # I NEED HELP!!!
        elif option == "help":
            game_help()

        # Set some tings
        elif option == "settings":
            change_settings()

        # Exit Option
        elif option == "exit":
            # print("See ya later!")
            data.save(player)
            data.save_settings(settings)
            active = False
Exemple #44
0
def modify(project_id):
    """Modify view

    Returns a view of the modify page. The modify page supports both
    HTML GET and POST methods. The GET method is used to request
    the desired project, and is passed into the modify function through
    Flask's routing method. This data is then used to populate the
    fields on the page. The POST method is used to populate the WTForm
    instance, which is then used to edit the actual database.


    Parameters
    ----------
    project_id : int
        The integer representing the desired project_id key in
        the database.

    Returns
    ----------
    render_template

    """
    def allowed_file(filename):
        """ Decide if the file extension is acceptable
        
        Determines whether or not a filename is valid, 
        based upon the ALLOWED_EXTENSIONS field in app.config.

        Parameters
        ----------
        filename : str
           The name of the file to check.

        Return
        ---------
        bool

        """
        if filename.rsplit(".", 1)[1] in app.config["ALLOWED_EXTENSIONS"]:
            return True

    def file_upload():
        """ Save the file and make directories

        Function handles all of the os file path and os file saving
        implementations. It will return the name of all of the files
        so they can be put in a list within the project.

        Returns
        ---------
        list : list
           A list of all the filenames of the uploaded files.
                """
        if request.files:
            files = request.files.getlist("images")
            for f in files:
                if allowed_file(f.filename):
                    sec_filename = secure_filename(f.filename)

                    # Check if the project path exists, create it if it doesn't
                    if not os.path.isdir(app.config["PROJECT_IMAGE_DIR"] +
                                         str(form.project_id.data) + "/"):
                        os.mkdir(app.config["PROJECT_IMAGE_DIR"] +
                                 str(form.project_id.data) + "/")

                    # Save the file
                    f.save((os.path.join(
                        app.config["PROJECT_IMAGE_DIR"] +
                        str(form.project_id.data) + "/", sec_filename)))
                    flash("File " + sec_filename + " uploaded successfully.",
                          "success")
                else:
                    flash(
                        "Invalid file format. Valid formats are: " +
                        app.config["ALLOWED_EXTENSIONS"], "danger")
            return [f.filename for f in files]

    db = data.load("data.json")

    if project_id == "add":
        form = forms.ModifyFormAdd(request.form, database=db)
        # Add new project.
        if request.method == "POST" and form.validate():
            filenames = file_upload()
            db.append({})
            for k, v in form.data.items():
                if k == "techniques_used":
                    v = v.split(" ")
                    v = [x for x in v if x != ""]
                    db[-1][k] = v
                elif k == "images":
                    db[-1][k] = filenames
                else:
                    db[-1][k] = v
            data.save(db, "data.json")
            flash("Project modified successfully.", "success")

    elif (project_id.isdigit()
          and int(project_id) in [x["project_id"] for x in db]):
        # Get current project and its index
        project = data.search(db,
                              search=project_id,
                              search_fields=["project_id"])
        p_index = db.index(project[0])
        form = forms.ModifyForm(request.form, data=project[0], database=db)
        file_upload()
        # Modify the project.
        if request.method == "POST" and form.validate():
            flash("Project modified successfully.", "success")
            for k, v in form.data.items():
                if project[0][k] != v:
                    if k == "techniques_used":
                        v = v.split(" ")
                        v = [x for x in v if x != ""]
                project[0][k] = v
            data.save(db, "data.json")

    else:
        abort(404)

    # Instantiated WTForm of ModifyForm type
    class_kw = forms.class_kw

    return render_template("modify.html", **locals())
Exemple #45
0
subsets = []
aucs = []
(trX, trY, teX) = draft()
stop = 20
at = 0
for subset in findsubsets(range(11), 4):
  subsets.append(subset)
  auc = eval(dead_simple(trX, trY, teX, subset))[0]
  aucs.append(auc)
  print subset, eval(dead_simple(trX, trY, teX, subset))
  at += 1 
  if at == stop:
    break

from numpy import array, sum
aucs = array(aucs)
aucs = aucs / sum(aucs)

(trX, trY, teX) = proof()
prediction = None

for (subset, auc) in zip(subsets, aucs):
  print auc
  if prediction == None:
    prediction = dead_simple(trX, trY, teX, subset)*auc

  else:
    prediction += dead_simple(trX, trY, teX, subset)*auc
    
save(prediction, 'orders/first5.csv')
Exemple #46
0
 def reset(self):
     if self.isEditing:
         self.endEdit()
     dt.save()                     # first save the current layout, so we don't loose current data
     self._clearUI()
     IOT.disconnect(False)           # new layout, so close connection to previous