예제 #1
0
  def checkinTaskQueue(self, client, checkin_json, userId, checkinId, access_token):
    venue_id = checkin_json['venue']['id']

    urlParams = { 'userId' : userId, 'checkinId' : checkinId, 'access_token' : access_token }
    url = '%s/content?%s' % (utils.getServer(), urllib.urlencode(urlParams))

    message = 'Check in your friends'
    coreCheckin = self.checkinToCore(checkin_json)

    self.makeContentInfo( checkin_json = checkin_json,
                          content = json.dumps({'coreCheckin': coreCheckin}),
                          url = url,
                          text = message,
                          reply = True)
예제 #2
0
def getChampsMastery(idSum, key):
    try:
        server = utils.getServer()
        if server == None:
            print("Something went wrong getting server name.")
            return None, None

        url = f'https://{server}/lol/champion-mastery/v4/champion-masteries/by-summoner/{idSum}'
        headers = {"X-Riot-Token": key}
        res = requests.get(url, headers=headers)
        if res.status_code == 200:
            return res.json()
        else:
            print(f"Error[{res.status_code}]: {res.text}")
            return None, None
    except Exception as ex:
        print(f"Exception: {ex}")
        return None, None
예제 #3
0
	def __init__(self, path, mode = 'rtc'):
		
		self.mode = mode
		self.path = path
		host,port = utils.get_port(_config['nameserver'])
		self.server = utils.getServer(path, host, port)
	
		if self.server is None:
			print('File not found')

		self.modified = None 


		SpooledTemporaryFile.__init__(self, _config['max_size'], mode.replace('c',''))		

		host,port = utils.get_port(_config['lockserver'])
		if utils.Locked(path, host, port):
			print('File is locked')	
	
		if 'w' not in mode:
			host, port = utils.get_port(self.server)
			with closing(HTTPConnection(host,port)) as con:
				con.request('GET', filepath)
				response = con.getresponse()
				self.modified = response.getheader('Last-Modified')
				status = response.status

				if status not in (200,204):
					print('Error occured',status)
			
				if status !=  204:
					self.write(response.read())

				if 'r' in mode:
					self.seek(0)

				self.lockid = ''

		if 'a' in mode or 'w' in mode:
			host,port = utils.get_port(_config['lockserver'])
			self.lockid = int(utils.Locked(path, host, port))

		if 'c' in mode:
			File._cache[path] = self
예제 #4
0
def getSummonerInfoByName(name, key):
    try:
        server = utils.getServer()
        if server == None:
            print("Something went wrong getting server name.")
            return None, None
        url = f'https://{server}/lol/summoner/v4/summoners/by-name/{name}'
        headers = {"X-Riot-Token": key}
        res = requests.get(url, headers=headers)
        if res.status_code == 200:
            print("Status response: Ok!")
            j = res.json()
            # print(f"Info summoner: {j}")
            return j['id'], j['summonerLevel']
        else:
            print(f"Error[{res.status_code}]: {res.text}")
            return None, None
    except Exception as ex:
        print(f"Exception: {ex}")
        return None, None
예제 #5
0
  def getAuthdStatus(self):

    # Allow cross domain access from http://www.herewithfriends.com and http://herewithfriends.appspot.com
    if (self.request.headers.get('Origin') == "http://www.herewithfriends.com"
        and self.request.headers.get('Host') == "herewithfriends.appspot.com"):
      self.response.headers.add_header("Access-Control-Allow-Origin", "http://www.herewithfriends.com")
      self.response.headers.add_header("Access-Control-Allow-Credentials", "true")

    elif (self.request.headers.get('Origin') == "http://herewithfriends.appspot.com"
          and self.request.headers.get('Host') == "herewithfriends.appspot.com"):
      self.response.headers.add_header("Access-Control-Allow-Origin", "http://herewithfriends.appspot.com")
      self.response.headers.add_header("Access-Control-Allow-Credentials", "true")

    user_token = UserToken.get_from_cookie(self.request.cookies.get('session', None))
    is_authd = False
    name = ''
    settingsSummary = ''
    settingsLink = ''
    if user_token is not None and user_token.fs_id:
      client = utils.makeFoursquareClient(user_token.token)
      try:
        user = client.users()['user']
        tokenId = user['id']
        if (tokenId != user_token.fs_id):
          is_authd = False
          user_token.delete()
        else:
          is_authd = True
          name = (user.get('firstName', '') + ' ' + user.get('lastName', '')).strip(),
          settingsSummary = self.getPermissionsSummary(user_token.fs_id)
          settingsLink = "%s/settings?userId=%s&access_token=%s" % (
                          utils.getServer(), user_token.fs_id, user_token.token)

      except InvalidAuth:
        user_token.delete()

    self.response.out.write(json.dumps({'connected': is_authd,
                                        'name': name,
                                        'settingsSummary': settingsSummary,
                                        'settingsLink' : settingsLink}))
예제 #6
0
from PreProcess import PreProcess_ExtractEvents as pre_events, PreProcess_ExtractSessions as pre_sessions, PreProcess_items as pre_items
import matplotlib.pyplot as plt
# import seaborn as sns
import numpy as np
import Evaluation as evl
import os
import utils as utl
from sklearn import preprocessing as pre



month = 8
#
# path = "./evaluation_"+str(month)+"/"
# extractedMonths = [6,7,8,9]
#
# # for month in extractedMonths:
# #     server = utl.getServer(6379,month)
# #     numOfCategoriesDict, categoriesDistDict = evl.evaluateWithDb(server,str(month))
# #     utl.writeDictToFile(numOfCategoriesDict, path+"_"+str(month))


server = utl.getServer(6379, month)
utl.buildCsvFromDb(server, month)
  def checkinTaskQueue(self, client, checkin_json):
    venue_id = checkin_json['venue']['id']
    request = User.all().filter('id =', checkin_json['user']['id'])
    user = request.get()
    if not user:
      # If they say "office" in their check-in, set this as their office
      if not 'shout' in checkin_json:
        logging.info("No shout, bailing")
        return
      shout = checkin_json['shout']
      if shout.lower().find('office') < 0:
        logging.info("Not at office, bailing")
        return
      user = User()
      user.id = checkin_json['user']['id']
      user.office_id = venue_id
      user.clockin_dts = '[]'
      user.best_dt = '()'
      settings_url = utils.getServer() + CONFIG['auth_success_uri_mobile']
      params = { 'text' : 'Ohh, so this is where you work. Duly noted!',
                 'url' : settings_url}
      client.checkins.reply(checkin_json['id'], params)

    if venue_id != user.office_id:
      if venue_id == '4ef0e7cf7beb5932d5bdeb4e':
        #Easter egg!
        params = { 'text' : 'Foursquare HQ!? ' +
                  'I hear that place is full of sunshine and unicorns' }
        client.checkins.reply(checkin_json['id'], params)
      # They're not at the office
      return

    # What time is it?
    tz_offset = timedelta(minutes=checkin_json['timeZoneOffset'])
    dt = datetime.utcfromtimestamp(checkin_json['createdAt']) + tz_offset
    time_of_day = self.calculateTimeOfDay(dt)
    date_str = dt.date().isoformat()

    clockin_dts = json.loads(user.clockin_dts)
    if clockin_dts and date_str == clockin_dts[0]:
      # Already checked in to work today
      return

    avg_time = self.calculateAvg([x[1] for x in clockin_dts])
    diff = avg_time - time_of_day
    diff_minutes = diff / 60
    logging.info('diff_minutes: %d' % diff)
    best_time = json.loads(user.best_dt)
    if not best_time:
      best_dt = [date_str, time_of_day]
      user.best_dt = json.dumps(best_dt)

    message = None
    if (len(clockin_dts) > self.MOVING_AVG_WINDOW / 2
          and time_of_day < best_dt[0]):
      message = 'Whoa, earliest office check-in EVER. Go get \'em tiger!'
      best_dt = [date_str, time_of_day]
      user.best_dt = json.dumps(best_dt)
    elif diff_minutes > self.EARLY_BIRD_DELTA_MINUTES:
      if diff_minutes < 45:
        message = ('Look at you, clocking in %d minutes early today. Good job!'
                   % diff_minutes)
      elif diff_minutes < 115:
        message = 'Look at you, clocking in an hour early today. Good job!'
      else:
        message = ('Look at you, clocking in %d hours early today. Good job!'
                   % (diff_minutes / 60))
    if message:
      params = { 'text' : message}
      logging.info("message: %s" % message)
      client.checkins.reply(checkin_json['id'], params)

    # Update list of past clock-in times.    
    clockin_dts.insert(0, [date_str, time_of_day])
    if len(clockin_dts) > self.MOVING_AVG_WINDOW:
      clockin_dts.pop()
    user.clockin_times = json.dumps(clockin_dts)
    user.put()