Example #1
0
 def func_switch(self, args):
     length = len(args)
     if length > 1:
         raise NotImplementedError
     else:
         twitter_users = TwitterUser.get_by_jid(self._google_user.jid)
         twitter_users_name = [u.twitter_name for u in twitter_users if u.twitter_name is not None]
         if not length:
             return (
                 _("NOW_USING") % self._google_user.enabled_user
                 + "\n"
                 + _("ALL_TWITTER_USERS_NAME") % "\n".join(twitter_users_name)
             )
         elif _check_username(args[0]):
             twitter_users_name_ci = [x.lower() for x in twitter_users_name]
             twitter_name_ci = args[0].lower()
             if twitter_name_ci in twitter_users_name_ci:
                 i = twitter_users_name_ci.index(twitter_name_ci)
                 if (
                     not self._google_user.enabled_user
                     and self._google_user.display_timeline
                     and self._google_user.msg_template.strip()
                 ):
                     try:
                         flag = xmpp.get_presence(self._google_user.jid)
                     except (xmpp.Error, DeadlineExceededError):
                         flag = False
                     if flag:
                         Db.set_datastore(Session(key_name=self._google_user.jid, shard=self._google_user.shard))
                 self._google_user.enabled_user = twitter_users_name[i]
                 return _("ENABLED_TWITTER_USER_CHANGED") % self._google_user.enabled_user
     return _("NOT_ASSOCIATED_TWITTER_USER")
Example #2
0
 def __init__(self, db_filename, sound_directory=None):
     Db.__init__(self, db_filename)
     if sound_directory is not None:
         self._sound_directory = sound_directory
     else:
         self._sound_directory = os.path.join(
             roslib.packages.get_pkg_dir('robot_eup'), 'sounds', '')
Example #3
0
def parse_status(status):
  if 'retweeted_status' in status and _user.official_retweet:
    status = status['retweeted_status']
  msg_dict = {'content': unescape(status['text']), 'id': str(status['id'])}
  if 'user' in status:
    msg_dict['username'] = status['user']['screen_name']
    Db.set_cache(status)
  elif 'sender' in status:
    msg_dict['username'] = status['sender_screen_name']
  else:
    msg_dict['username'] = ''
  if msg_dict['username'] and _user.bold_username:
    msg_dict['username'] = '******' % msg_dict['username']
  username = _user.enabled_user
  username_at = "@" + username
  short_id = None
  if username_at in msg_dict['content']:
    if _user.bold_username:
      msg_dict['content'] = msg_dict['content'].replace(username_at, '*%s*' % username_at)
  if 'user' in status:
    short_id = generate_short_id(status['id'])
  msg_dict['shortid'] = '#' + str(short_id) if short_id is not None else ''
  utc = pytz.utc
  t = parsedate(status['created_at'])[:6]
  t = datetime(*t)
  utc_dt = utc.localize(t)
  tz = pytz.timezone(_user.timezone)
  t = tz.normalize(utc_dt.astimezone(tz))
  msg_dict['time'] = t.strftime(_user.date_format.encode('UTF-8')).decode('UTF-8')
  if 'source' in status:
    source = re.match(r'<a .*>(.*)</a>', status['source'])
    msg_dict['source'] = source.group(1) if source else status['source']
  else:
    msg_dict['source'] = ''
  return Template(unicode(_user.msg_template)).safe_substitute(msg_dict)
Example #4
0
def load_evolutionary_dependencies_from_db():
	db = Db()
	repository_id = constants.repository_map[args.repository]
	types = 'CN,CM,FE,MT'
	if args.coarse_grained:
		types = 'CL,IN'
	graphs_ed = {}
	cursor = db.query("""select g.id, g.source, g.max_entities, g.min_confidence, 
			g.min_support, g.min_date, g.types, de.entidade1, de.entidade2, e.caminho
		from dependencias_evolucionarias de 
			inner join grafos_de g on de.grafo = g.id 
			inner join entidades e on de.entidade2 = e.id 
		where g.repositorio = %s and g.types = %s""", 
		(repository_id,types))
	for (id, source, max_entitites, min_confidence, min_support, min_date, types, entity1, entity2, e2_path) in cursor:
		if id not in graphs_ed:
			graphs_ed[id] = {
				'source': source, 
				'max_entitites': max_entitites, 
				'min_confidence': min_confidence, 
				'min_support': min_support, 
				'min_date': min_date, 
				'types': types,
				'dependencies': {}
			}
		if entity1 not in graphs_ed[id]['dependencies']:
			graphs_ed[id]['dependencies'][entity1] = []
		entity2_java_name = to_java_convention(e2_path, args.repository, True)
		graphs_ed[id]['dependencies'][entity1].append(entity2_java_name)
	db.close()
	return graphs_ed
 def execute(self):
     db = Db()
     l = text_to_list(self.file_contents)
     d = list_to_dict(l)
     db.update_word_counts(d, self.doc_type)
     db.update_doctype_count(self.count, self.doc_type)
     return self.count
Example #6
0
 def process(self, message):
   global _locale
   jid = message.sender.split('/')[0]
   self._google_user = GoogleUser.get_by_jid(jid)
   if self._google_user is None:
     self._google_user = GoogleUser.add(jid)
   _locale = self._google_user.locale
   self._twitter_user = Dummy()
   self._api = Dummy()
   if self._google_user.enabled_user:
     self._twitter_user = TwitterUser.get_by_twitter_name(self._google_user.enabled_user, self._google_user.jid)
     if self._twitter_user is None:
       self._google_user.enabled_user = ''
     else:
       self._api = twitter.Api(consumer_key=config.OAUTH_CONSUMER_KEY,
                               consumer_secret=config.OAUTH_CONSUMER_SECRET,
                               access_token_key=self._twitter_user.access_token_key,
                               access_token_secret=self._twitter_user.access_token_secret)
   self._utils = Utils(self._google_user.jid)
   try:
     result = self.parse_command(message.body)
   except NotImplementedError:
     result = _('INVALID_COMMAND')
   except twitter.TwitterInternalServerError:
     result = _('INTERNAL_SERVER_ERROR')
   except twitter.TwitterAuthenticationError:
     self._google_user.retry += 1
     if self._google_user.retry >= config.MAX_RETRY:
       GoogleUser.disable(self._google_user.jid)
     else:
       Db.set_datastore(self._google_user)
     result = _('NO_AUTHENTICATION')
   return result
Example #7
0
 def func_on(self, args):
     if len(args):
         for a in args:
             if a == "home":
                 self._google_user.display_timeline |= MODE_HOME
             elif a == "mention":
                 self._google_user.display_timeline |= MODE_MENTION
             elif a == "dm":
                 self._google_user.display_timeline |= MODE_DM
             elif a == "list":
                 self._google_user.display_timeline |= MODE_LIST
     s = Session.get_by_key_name(self._google_user.jid)
     if (
         not s
         and self._google_user.display_timeline
         and self._google_user.enabled_user
         and self._google_user.msg_template.strip()
     ):
         try:
             flag = xmpp.get_presence(self._google_user.jid)
         except (xmpp.Error, DeadlineExceededError):
             flag = False
         if flag:
             Db.set_datastore(Session(key_name=self._google_user.jid, shard=self._google_user.shard))
     modes = []
     if self._google_user.display_timeline & MODE_LIST:
         modes.append("list")
     if self._google_user.display_timeline & MODE_HOME:
         modes.append("home")
     if self._google_user.display_timeline & MODE_MENTION:
         modes.append("mention")
     if self._google_user.display_timeline & MODE_DM:
         modes.append("dm")
     return _("ON_MODE") % ", ".join(modes)
Example #8
0
 def execute( self ):
     self.server.timeout = int( self.timeout )
     if not Db.fetch( "SELECT * FROM settings WHERE key='timeout'" ):
         Db.execute( "INSERT INTO settings VALUES ('timeout', ?, 'INT' ) ", ( self.timeout, ), commit=True )
     else:
         Db.execute( "UPDATE settings SET value=? WHERE key='timeout'", ( self.timeout, ), commit=True )
     print self.DONE
def tryCountQuery():
    tableName = "test.sanityTable"
    def clear(t):
        db = Db()
        db.activate()
        db.applySql("DROP TABLE IF EXISTS %s;" %(t))

    pmap = makePmap()
    q = "SELECT %s FROM %s %s;" % ("count(*)", "LSST.Object", "LIMIT 10")
    a = HintedQueryAction(q, 
                              {"db" : "test"},  # Use test db.
                              pmap, 
                              lambda e: None, tableName)
        
    assert a.getIsValid()
    a.chunkLimit = 6
    print "Trying q=",q
    clear(tableName)
    print a.invoke() 
    print a.getResult()
    db = Db()
    db.activate()
    db.applySql("select * from %s;" % tableName) #could print this

    clear(tableName)
Example #10
0
class Announcement:
    def __init__(self, max_clients, db_name, db_host, db_port, secret):
        self.sequence = secret
        self.base64_alt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

        self.db = Db(self, db_name, db_host, db_port)
        self.announces = self.db.load_announces()
        self.announces_time = int(time.time())

        log.msg('Announcement __init__')
        log.msg(self.announces)

        self.crypt = Crypt(self.sequence)

    def get_announce(self, protocol, game_name):
        result = self.announces.get(game_name, {'result': '0'})

        j = json.dumps(result)
        c = self.crypt.crypt(j)

        log.msg('Send data to client')
        protocol.writeData(c)
        protocol.transport.loseConnection()

        # refresh announces
        if int(time.time()) - self.announces_time > 15:
            self.announces = self.db.load_announces()
            log.msg('Announces updated')
            self.announces_time = int(time.time())
Example #11
0
 def process(self):
     global _locale
     try:
         message = xmpp.Message(self.request.POST)
     except xmpp.InvalidMessageError:
         return
     jid = message.sender.split("/")[0]
     self._google_user = GoogleUser.get_by_jid(jid)
     if self._google_user is None:
         self._google_user = GoogleUser.add(jid)
     _locale = self._google_user.locale
     if self._google_user.enabled_user:
         self._twitter_user = TwitterUser.get_by_twitter_name(self._google_user.enabled_user, self._google_user.jid)
         self._api = Dummy()
         if self._twitter_user is None:
             self._google_user.enabled_user = ""
         else:
             self._api = twitter.Api(
                 consumer_key=config.OAUTH_CONSUMER_KEY,
                 consumer_secret=config.OAUTH_CONSUMER_SECRET,
                 access_token_key=self._twitter_user.access_token_key,
                 access_token_secret=self._twitter_user.access_token_secret,
             )
             try:
                 self._user = self._api.verify_credentials()
                 if not self._user:
                     raise twitter.TwitterAuthenticationError
             except twitter.TwitterAuthenticationError:
                 self._google_user.retry += 1
                 if self._google_user.retry >= config.MAX_RETRY:
                     GoogleUser.disable(self._google_user.jid)
                     xmpp.send_message(self._google_user.jid, _("NO_AUTHENTICATION"))
                 else:
                     Db.set_datastore(self._google_user)
                 return
             else:
                 if self._google_user.retry > 0:
                     self._google_user.retry = 0
                 if self._twitter_user.twitter_name != self._user["screen_name"]:
                     self._twitter_user.twitter_name = self._user["screen_name"]
                     self._google_user.enabled_user = self._user["screen_name"]
     else:
         self._twitter_user = Dummy()
         self._api = Dummy()
         self._user = Dummy()
     utils.set_jid(self._google_user.jid)
     result = self.parse_command(message.body)
     if result is None:
         return
     if result:
         while CapabilitySet("xmpp").is_enabled():
             try:
                 message.reply(result)
             except xmpp.Error:
                 pass
             else:
                 break
     IdList.flush(self._google_user.jid)
     Db.set_datastore(self._google_user)
def prets_fetchall():
  db = Db()
  result = db.select("SELECT * FROM prets")
  db.close()
  
  resp = make_response(json.dumps(result))
  resp.mimetype = 'application/json'
  return resp
Example #13
0
 def post_update(self, status, in_reply_to_status_id=None):
   url = '%s/statuses/update.json' % self.base_url
   data = {'status': status}
   if in_reply_to_status_id:
     data['in_reply_to_status_id'] = in_reply_to_status_id
   data = self._fetch_url(url, post_data=data)
   Db.set_cache(data)
   return data
Example #14
0
 def getVercode(teleNum):
     time.sleep(5)
     #在xnmsg数据库中查询对应手机号的短信内容
     content=Db("xnmsg").sql("SELECT content FROM sms_sendlog_his WHERE mobile="+teleNum+" ORDER BY id DESC LIMIT 1 ")
     #将短信中的验证码过滤出来,抽取字符串中的数字用filter(str.isdigit, item)
     code_zc=filter(str.isdigit,content.encode('UTF-8'))
     return code_zc
     print code_zc
Example #15
0
 def setupIndexes(self):
     p = PartitionGroup()
     db = Db()
     db.activate()
     db.makeIfNotExist(db=metadata.getMetaDbName())
     #logger.inf(p.tables)
     for (t,d) in p.tables.items():
         if d.has_key("index"):
             self._makeIndex(t, p.partitionCols, d["index"])
Example #16
0
 def __commit_string(self, text):
     self.commit_text(ibus.Text(text))
     status = text != self.__preedit_string
     self.__preedit_string = u""
     self.__preedit_word   = u""
     self.__atEnglish      = False
     self.__update()
     if status:
         Db.updateDb(text)
Example #17
0
    def generate_other_users( self, limit=10 ):
        users = self.chomik.generate_list( limit, to_file=False )
        for user in users if users else []:

            self.chomik.sleep( self.server.timeout )
            self.chomik.invite( user )

            if not Db.fetchone( "SELECT * FROM other_users WHERE login=?", ( user, ) ):
                Db.execute( "INSERT INTO other_users ( login ) VALUES ( ? )", ( user, ), commit=True )
Example #18
0
def afficher_utilisateurs():
    db=Db()

    result=db.select('SELECT * FROM utilisateurs')
    db.close()

    resp = make_response(json.dumps(result),200)
    resp.mimetype = 'application/json'
    return resp
Example #19
0
 def __init__(self, db_filename):
     Db.__init__(self, db_filename)
     corpus_file = os.path.join(roslib.packages.get_pkg_dir("robot_eup"), "speech/", "") + "commands.corpus"
     f = open(corpus_file, "r")
     self._commands = f.readlines()
     f.close()
     for c in self._commands:
         command = c.rstrip()
         self.set(command)
Example #20
0
 def test_insert_row_when_add_new_word_list(self):
     db = Db(self.conn, self.sql)
     db.setup(3)
     word_list = ['one', 'two', 'three']
     db.add_word(word_list)
     
     execute_args = self.conn.stub_cursor.execute_args
     self.assertEqual(len(execute_args), 6)
     self.assertEqual(execute_args[4], ('select_count_for_words_sql 3', word_list))
     self.assertEqual(execute_args[5], ('insert_row_for_words_sql 3', word_list + [1]))
Example #21
0
def suppr_utilisateurs(id) :
    db=Db()

    result = db.execute('DELETE FROM utilisateurs WHERE id = %(id)s', {
    'id' : id
    })
    db.close()

    resp = make_response(json.dumps(result),200)
    resp.mimetype='application/json'
    return resp
Example #22
0
 def signupCheck(self):
     username = self.username.text()
     password = self.password.text()
     email = self.email.text()
     if self.checkFields(username,email,password):
         self.showMessage("Error", "All fields must be filled")
     else:
         getDb = Db()
         result = getDb.insertUser(username,email,password)
         self.showMessage("Success","Registration successul")
         self.clearField()
Example #23
0
	def set_doc_types(self, doc_type1, doc_type2):
		if doc_type1 == doc_type2:
			raise ValueError('Please enter two different doc_types')

		d = Db().get_doc_type_counts()
		
		if doc_type1 and doc_type2 not in d.keys():
			raise ValueError('Unknown doc_type: ' + doc_type2)

		self.doc_type1 = doc_type1
		self.doc_type2 = doc_type2
Example #24
0
 def post(self):
   global _locale
   try:
     message = xmpp.Message(self.request.POST)
   except xmpp.InvalidMessageError:
     return
   jid = message.sender.split('/')[0]
   self._google_user = GoogleUser.get_by_jid(jid)
   if self._google_user is None:
     self._google_user = GoogleUser.add(jid)
   _locale = self._google_user.locale
   if self._google_user.enabled_user:
     self._twitter_user = TwitterUser.get_by_twitter_name(self._google_user.enabled_user, self._google_user.jid)
     self._api = Dummy()
     if self._twitter_user is None:
       self._google_user.enabled_user = ''
     else:
       self._api = twitter.Api(consumer_key=config.OAUTH_CONSUMER_KEY,
                               consumer_secret=config.OAUTH_CONSUMER_SECRET,
                               access_token_key=self._twitter_user.access_token_key,
                               access_token_secret=self._twitter_user.access_token_secret)
       try:
         self._user = self._api.verify_credentials()
       except twitter.TwitterAuthenticationError:
         self._google_user.retry += 1
         if self._google_user.retry >= config.MAX_RETRY:
           GoogleUser.disable(self._google_user.jid)
           xmpp.send_message(self._google_user.jid, _('NO_AUTHENTICATION'))
         else:
           Db.set_datastore(self._google_user)
         return
       else:
         if self._google_user.retry > 0:
           self._google_user.retry = 0
         try:
           if self._twitter_user.twitter_name != self._user['screen_name']:
             self._twitter_user.twitter_name = self._user['screen_name']
             self._google_user.enabled_user = self._user['screen_name']
         except TypeError:
           logging.error('%s: %s' % (jid, unicode(self._user)))
           return
   else:
     self._twitter_user = Dummy()
     self._api = Dummy()
     self._user = Dummy()
   utils.set_jid(self._google_user.jid)
   result = self.parse_command(message.body)
   if result is None:
     return
   if result:
     message.reply(result)
   IdList.flush(self._google_user.jid)
   Db.set_datastore(self._google_user)
Example #25
0
def getIdRecipeByName(RecipeName):
    query_select = "SELECT Recipe_id FROM Recipe WHERE Recipe_name LIKE \'" + str(
        RecipeName) + "\'"

    db = Db()
    result = db.select(query_select)
    recipe_id = ""

    for id_recipe in result:
        recipe_id = id_recipe['recipe_id']

    return recipe_id
Example #26
0
    def registerWallet(username):
        db = Db()
        id = db.querySelectOne(
            'SELECT id FROM users WHERE username="******" LIMIT 1' % username)

        if not id is False:
            db.queryInsert(
                "INSERT INTO wallets(user_id, BTC, ETH, LTC, USD) VALUES (%s, %s, %s, %s, %s)",
                (id[0], 0, 0, 0, Config.startUsdMoney))
            return True
        else:
            return False
Example #27
0
 def loginBtnClick(self):
     username = self.username.text()
     password = self.password.text()
     getDb = Db()
     result = getDb.loginCheck(username, password)
     if (result):
         self.showMainPage()
         self.clearField()
         print(result)
     else:
         print("password wrong")
         self.showMessage("Warning", "Invalid Username and Password")
Example #28
0
 def list_filters(self):
     db = Db()
     sql = "select * from filter where participant = %s;"
     data = [self.email()]
     result = db.query(sql, data)
     tmp_list = []
     for row in result:
         tmp_row = {}
         for k, v in row.items():
             tmp_row[k] = v
         tmp_list.append(tmp_row)
     return tmp_list
Example #29
0
 def test_get_word_counts_works_correctly(self):
     db = Db(self.conn, self.sql)
     db.setup(3)
     word_list = ['i', 'like']
     self.conn.stub_cursor.execute_results = [[['dogs',  1], ['cats',  2], ['frogs', 3]]]
     
     word_counts = db.get_word_count(word_list)
     
     self.assertEqual(word_counts, {'dogs' : 1, 'cats' : 2, 'frogs' : 3})
     execute_args = self.conn.stub_cursor.execute_args
     self.assertEqual(len(execute_args), 5)
     self.assertEqual(execute_args[4], ('select_words_and_counts_sql 3', word_list))
Example #30
0
def getIdPlayerByName(PlayerName):
    query_select = "SELECT Player_id FROM Player WHERE Player_name LIKE \'%s\'" % (
        PlayerName)

    db = Db()
    result = db.select(query_select)
    player_id = ""

    for id_player in result:
        player_id = id_player['player_id']

    return player_id
Example #31
0
  def get(self, cron_id):
    def add_task_by_jid(jid):
      self.jids.append(jid)
      if len(self.jids) >= USERS_NUM_IN_TASK:
        flush_jids()
      if len(self.tasks) >= 100:
        flush_tasks()

    def flush_jids():
      if self.jids:
        self.tasks.append(taskqueue.Task(url='/worker', params={'jid': self.jids}))
        self.jids = list()

    def flush_tasks():
      def db_op():
        while db.WRITE_CAPABILITY:
          try:
            self.queues[self.queue_pointer].add(self.tasks)
          except taskqueue.TransientError:
            continue
          break

      if self.tasks:
        db.run_in_transaction(db_op)
        self.tasks = list()
        self.queue_pointer = (self.queue_pointer + 1) % TASK_QUEUE_NUM

    cron_id = int(cron_id)
    self.queues = [taskqueue.Queue('fetch' + str(id)) for id in xrange(TASK_QUEUE_NUM)]
    self.queue_pointer = cron_id % TASK_QUEUE_NUM
    self.tasks = list()
    self.jids = list()
    from db import GoogleUser, Db
    data = GoogleUser.get_all(shard=cron_id)
    try:
      for u in data:
        if u.display_timeline or u.msg_template.strip():
          time_delta = int(time()) - u.last_update
          if time_delta >= u.interval * 60 - 30:
            try:
              flag = xmpp.get_presence(u.jid)
            except xmpp.Error:
              flag = False
            if not flag:
              continue
            Db.set_cache(u)
            add_task_by_jid(u.jid)
      flush_jids()
      flush_tasks()
    except DeadlineExceededError:
      self.response.clear()
      self.response.set_status(500)
      self.response.out.write("This operation could not be completed in time...")
Example #32
0
def getUserMore(uid):
    d = Db()
    connect = d.getConnection()
    try:
        with connect.cursor() as cursor:
            sql = "SELECT * FROM `user_more` where uid = %s limit 1"
            cursor.execute(sql, uid)
            result = cursor.fetchone()
            # print(result)
            return result
    except:
        return 0
Example #33
0
 def loginCheck(self):
     username = self.txtUsername.text()
     password = self.txtPassword.text()
     getDb = Db()
     result = getDb.loginCheck(username,password)
     if(result):
         self.welcomePage()
         self.clearField()
         print(result)
     else:
         print("password wrong")
         self.showMessage("Warning","Invalid Username and Password")
Example #34
0
 def post(self):
     jid = self.request.get("from").split("/")[0]
     s = Session.get_by_key_name(jid)
     if not s:
         u = GoogleUser.get_by_jid(jid)
         if u and u.enabled_user and u.display_timeline and u.msg_template.strip():
             try:
                 Db.set_datastore(Session(key_name=jid, shard=u.shard))
             except CapabilityDisabledError:
                 try:
                     xmpp.send_presence(jid, presence_type=xmpp.PRESENCE_SHOW_AWAY)
                 except xmpp.Error:
                     pass
Example #35
0
 def get_for_customer(customer_id, include_user=False):
     '''Return a list of Call objects for the given customer.
     (Bonus: if include_user is True, add a 'user' attribute/property
     to each Call object, containing all the info about the user who
     created the Call object.)'''
     db = Db()
     query = 'SELECT customer_id, user_id, call_message, call_id, call_time FROM phone_call WHERE customer_id = ?'
     db.execute(query, (customer_id, ))
     rows = db.fetchall()
     call_list = []
     for row in rows:
         call_list.append(Call.build_from_row(row))
     return call_list
Example #36
0
    def getUserList():
        userList = []
        db = Db()
        userListResponse = db.querySelect(
            "SELECT id, username, email, password, name, surrname, register_date FROM users ORDER BY id"
        )

        for id, username, email, password, name, surrname, registerDate in userListResponse:
            user = User(id, username, email, password, name, surrname,
                        registerDate)
            userList.append(user)

        return userList
Example #37
0
def get_raw_data(symbol, print_sample=True):

    model = Db()
    records = model.get_data(symbol)

    data = pd.DataFrame(
        data=records,
        columns=['open_val', 'high_val', 'low_val', 'close_val', 'volume'])
    data = data.drop(0, axis=0)
    if print_sample:
        print(data.head(5))
        print(data.count())
    return data.to_numpy()
Example #38
0
    def checkLoginAndPassword(login, password):
        userList = {}
        db = Db()
        passwordHashed = db.querySelectOne(
            'SELECT password FROM users WHERE username="******" OR email="%s" LIMIT 1'
            % (login, login))

        if passwordHashed is False:
            return False
        elif sha256_crypt.verify(password, passwordHashed[0]):
            return True
        else:
            return False
Example #39
0
    def get_all():
        '''Get a list of Customer objects - one for each row in the 
        relevant table in the database.'''
        db = Db()
        query = "SELECT * FROM customers"

        db.execute(query)
        rows = db.fetchall()
        customers = []
        for row in rows:
            customer = Customer.build_from_row(row)
            customers.append(customer)
        return customers
Example #40
0
    def setUp(self):
        """ Set up test fixtures """

        # Set up mongod daemon
        self.devnull = open(os.devnull,'w')
        self.mongod = subprocess.Popen(PATH_TO_MONGOD,stdout=self.devnull) 
        
        # Create Db instance which we will test
        uri = 'mongodb://localhost:27017'
        self.db_test = Db(uri,'wya_test')

        # Create a second interface to the same collection to verify 
        self.db_verify = MongoClient(uri)['wya_test']
Example #41
0
 def delete_readings(cls, recs):
     logger.debug(f'recs: len={len(recs)}')
     rec_cnt = 0
     for r in recs:
         Db.exec(
             'insert into _Readings_arch select * from Readings where dtime_sec = ? and meter_id = ?',
             (r.dtime_sec, r.meter_id))
         # logger.debug(f'moved {cnt} records from Readings to _Readings_arch')
         rec_cnt += Db.exec(
             'delete from Readings where dtime_sec = ? and meter_id = ?',
             (r.dtime_sec, r.meter_id))
     logger.debug(f'deleted {rec_cnt} from Readings')
     return
def prets_fetchone(id):
  db = Db()
  result = db.select("SELECT * FROM prets WHERE id = %(id)s", {
    'id': id
  })
  db.close()
  
  if len(result) < 1:
    return make_response("Not found", 404)
  
  resp = make_response(json.dumps(result))
  resp.mimetype = 'application/json'
  return resp
Example #43
0
	def set_doctypes(self, doctype1, doctype2):
		if doctype1 == doctype2:
			raise ValueError('Please enter two different doctypes')

		d = Db().get_doctype_counts()
		if doctype1 not in d.keys():
			raise ValueError('Unknown doctype: ' + doctype1)

		if doctype2 not in d.keys():
			raise ValueError('Unknown doctype: ' + doctype2)

		self.doctype1 = doctype1
		self.doctype2 = doctype2
Example #44
0
 def login(self, username, password):
     '''If we have a user with the given user name and password, return True.
     Otherwise, return False.'''
     db = Db()
     data = (username, )
     db.execute('select * from user where username = ?', data)
     row = db.fetchone()
     if row['password'] == password:
         print('true')
         return True
     else:
         print('false')
         return False
Example #45
0
    def test_update_row_when_add_repeated_word_list(self):
        db = Db(self.conn, self.sql)
        db.setup(3)
        row_count = 10
        word_list = ['one', 'two', 'three']
        self.conn.stub_cursor.fetchone_results.append([row_count])

        db.add_word(word_list)
        
        execute_args = self.conn.stub_cursor.execute_args
        self.assertEqual(len(execute_args), 6)
        self.assertEqual(execute_args[4], ('select_count_for_words_sql 3', word_list))
        self.assertEqual(execute_args[5], ('update_count_for_words_sql 3', [row_count + 1] + word_list))
Example #46
0
 def login(self, username, password):
     '''If we have a user with the given user name and password, return True.
     Otherwise, return False.'''
     db = Db()
     data = (username, password)
     query = "SELECT username, password FROM user WHERE username = ? AND password = ?"
     db.execute(query, data)
     user = db.fetchone()
     if user is not None:
         session['username'] = user[0]
         return True
     else:
         return False
Example #47
0
def join_game():
    '''
	Cette route permet au client de se connecter à
	une partie
	'''
    #Recupération de la donnée
    data = request.get_json()

    #On détermine si la donnée peut être traité.
    if (isValidData(data) == False):
        return bad_request()

    if not ('name' in data):
        return bad_request()

    if ((data['name'] == '') or (data['name'].isspace() == True)):
        return bad_request()

    #La donnée peut être traitée.
    db = Db()

    isInbd = is_present_pseudo_indb(data['name'])

    #Le joueur est déjà présent dans la base de données
    if (isInbd == True):
        #On le connecte en lui renvoyant ses données
        player = db.select(
            "SELECT * FROM Player WHERE (ingame_player = %(id)s AND name_player = %(name)s)",
            {
                "id": default_game,
                "name": data['name']
            })

        resp = {
            "name": data['name'],
            "location": {
                "latitude": player[0]['lat_player'],
                "longitude": player[0]['lon_player']
            },
            "info": get_player_infos(player[0]['id_player'], default_game,
                                     "prod")
        }
        return to_make_response(resp)
    db.close()

    #Le joueur n'est pas présent dans la base de données
    #Alors on le crée, on le connecte et on envoie les données voulues au client
    resp = join_new_player(data['name'], default_game)
    if (resp == -1):
        return internal_server_error()
    return to_make_response(resp)
    def single_whorl_uniqueness(whorl_name, whorl_value):
        db = Db()
        db.connect()

        md5_whorl_value = FingerprintHelper.value_or_md5(
            {whorl_name: whorl_value})[whorl_name]

        try:
            try:
                count = db.get_whorl_value_count(whorl_name, md5_whorl_value,
                                                 config.epoched)
            except TypeError:
                return {
                    'status':
                    "Error: that value has not yet been recorded for '" +
                    whorl_name + "'"
                }

            total = db.get_total_count(config.epoched)
        finally:
            db.close()

        uniqueness = {
            'bits': round(-log(count / float(total), 2), 2),
            'one_in_x': round(float(total) / count, 2)
        }

        return uniqueness
 def _record_whorls(whorls):
     db = Db()
     db.connect()
     # actually update the fingerprint table...
     db.record_fingerprint(whorls)
     md5_whorls = FingerprintHelper.value_or_md5(whorls)
     db.update_totals(md5_whorls)
    def post(self):
        parser = reqparse.RequestParser()

        for k in Advertisement.json_keys:
            parser.add_argument(k)
        args = parser.parse_args()

        db = Db()

        new_ad = Advertisement.from_json(args)

        new_ad = db.add_advertisement(new_ad)

        return new_ad.to_json()
Example #51
0
 def user_info(self, wait_time=1):
     google = OAuth2Session(client_id, token=self.token())
     if self.token()['expires_at'] < time() + 10:
         google = self.refresh_token()
         if google == 'refresh_error':
             return 'refresh_error'
     r = google.get('https://www.googleapis.com/oauth2/v1/userinfo')
     if r.status_code == 200:
         data = r.json()
         if self._name != data['name']:
             db = Db()
             sql = 'UPDATE participant SET name = %s WHERE email = %s;'
             params = [data['name'], self._email]
             db.query(sql, params)
             self._name = data['name']
         if self._email != data['email']:
             db = Db()
             sql = 'UPDATE participant SET name = %s WHERE email = %s;'
             params = [data['email'], self._email]
             db.query(sql, params)
             self._email = data['email']
         return r.json()
     elif r.status_code == 429:
         if wait_time <= 8:
             sleep(wait_time)
             return self.user_info(wait_time*2)
         else:
             print(r.status_code, r.text)
             return False
     else:
         print(r.status_code, r.text)
         return False
Example #52
0
 async def post(self):
     data = await self.request.post()
     car_info = Db().collection.find_one(
         {"VIM": self.request.match_info['vim']}, {"_id": 0})
     context = {"car": car_info, "vim": self.request.match_info['vim']}
     j_data = {
         "manufacturer": data['manufacturer'],
         "model": data['model'],
         "year_of_issue": data['year_of_issue'],
         "colour": data['colour'],
         "VIM": data['VIM'],
     }
     Db().update_document({"VIM": data['VIM']}, j_data)
     return context
Example #53
0
def get_available_ingredients(player_cash):
    db = Db()
    ingredient_datas = db.select(
        "SELECT name_ingredient, price_ingredient FROM Ingredient")
    db.close()

    availableIngredients = []
    for ingredient in ingredient_datas:
        if (float(ingredient['price_ingredient']) <= float(player_cash)):
            availableIngredients.append({
                "name": ingredient['name_ingredient'],
                "price": ingredient['price_ingredient']
            })
    return availableIngredients
Example #54
0
    def get_all():
        query = "SELECT * FROM customer"
        db = Db()
        db.execute(query)
        objects = db.fetchall()
        print(objects)
        new_list = []
        for an_object in objects:
            info = Customer.build_from_row(an_object)
            new_list.append(info)

        print(new_list)
        return new_list
        '''Get a list of Customer objects - one for each row in the 
Example #55
0
    def addContact(self):
        first_name = self.first_name
        last_name = self.last_name
        tel = self.tel
        email = self.email
        url = self.url
        notes = self.notes

        db = Db()
        # a contact must have at least a telephone number and a name
        if ((first_name is not None and first_name != "")
                or (last_name is not None and last_name != "")
                and tel is not None and tel != ""):
            db.addContact(first_name, last_name, tel, email, url, notes)
Example #56
0
    def get_all():
        query = ("SELECT customer_id, user_id, call_time, notes, call_id "
                 "FROM phone_call "
                 "ORDER BY last_name, first_name")
        db = Db()
        db.execute(query)
        rows = db.fetchall()

        calls = []
        for call in calls:
            call = Call.build_from_row(row)
            calls.append(call)

        return calls
 def _record_whorls(whorls, signatures):
     db = Db()
     db.connect()
     # actually update the fingerprint table...
     db.record_fingerprint(whorls, signatures, FingerprintHelper.fingerprint_expansion_keys)
     md5_whorls = FingerprintHelper.value_or_md5(whorls)
     db.update_totals(md5_whorls, signatures)
def etat():
    db = Db()

    etats = db.select("SELECT * FROM equipe;")
    montableau = []

    db.close()
    for i in range(0, len(etats)):
        montableau.append(etats[i]['etat'])

    mapetitereponse = {"objet": montableau}
    return json.dumps(mapetitereponse), 200, {
        'Content-Type': 'application/json'
    }
def create_and_store(pc):
    counter2 = 1
    endtg = '<'
    db = Db("CityExpenses")
    db.create_table()
    for city in CITIES:

        r = requests.get("https://www.numbeo.com/cost-of-living/in/" + city)
        soup = BeautifulSoup(r.text, features="lxml")
        counter = 0
        pricing = {}
        b = soup.body
        for i in b.find_all('td', class_="tr_highlighted"):
            data = str(i).split('>')[1]
            data = data[0:data.index(endtg)]
            if "span" not in data and len(data) > 1:
                counter += 1

                if counter % 2 != 0:
                    pricing[data] = 0
                    prev = data
                else:
                    pricing[prev] = float(''.join(
                        [i for i in data if i.isdigit() or i == '.']))
        one_apr = pricing["Apartment (1 bedroom) Outside of Centre "]
        three_apr = pricing["Apartment (3 bedrooms) Outside of Centre "]
        province = get_province(city, pc)
        description = wiki_data(city)
        db.insert_into(city, one_apr, three_apr, description, province)
        counter2 += 1
    db.close_database()
Example #60
0
    def test_get_word_counts_works_correctly(self):
        db = Db(self.conn, self.sql)
        db.setup(3)
        word_list = ['i', 'like']
        self.conn.stub_cursor.execute_results = [[['dogs', 1], ['cats', 2],
                                                  ['frogs', 3]]]

        word_counts = db.get_word_count(word_list)

        self.assertEqual(word_counts, {'dogs': 1, 'cats': 2, 'frogs': 3})
        execute_args = self.conn.stub_cursor.execute_args
        self.assertEqual(len(execute_args), 5)
        self.assertEqual(execute_args[4],
                         ('select_words_and_counts_sql 3', word_list))