Пример #1
0
 def __init__(self, location, user_id=None):
     """Initialize user with location and user_id"""
     self.basecamp_location = None
     self.basecamp_name = None
     self.basecamp_set = False
     self.location = location
     self.user_id = user_id
     self.yakarma = None
     # Set endpoint to nearest server if required
     if settings.LOCATIONIZE_ENDPOINT:
         locationize_endpoint(self.location)
     # If no user ID specified, register new user
     if self.user_id is None:
         self.user_id = helper.generate_id(dashes=False, upper=True)
         # Do not register with Parse if APPID or CLIENTKEY is missing
         if None in [settings.PARSE_APPID, settings.PARSE_CLIENTKEY]:
             self.register(parse_register=False)
         else:
             self.register()
         # Log user ID in file if required
         if settings.LOG_USERIDS:
             with open("userids", "a") as userid_file:
                 userid_file.write(self.user_id + "\n")
     # Update user properties from server
     self.update()
Пример #2
0
 def __init__(self, location, user_id=None):
     """Initialize user with location and user_id"""
     self.basecamp_location = None
     self.basecamp_name = None
     self.basecamp_set = False
     self.location = location
     self.user_id = user_id
     self.yakarma = None
     # Set endpoint to nearest server if required
     if settings.LOCATIONIZE_ENDPOINT:
         locationize_endpoint(self.location)
     # If no user ID specified, register new user
     if self.user_id is None:
         self.user_id = helper.generate_id(dashes=False, upper=True)
         # Do not register with Parse if APPID or CLIENTKEY is missing
         if None in [settings.PARSE_APPID, settings.PARSE_CLIENTKEY]:
             self.register(parse_register=False)
         else:
             self.register()
         # Log user ID in file if required
         if settings.LOG_USERIDS:
             with open("userids", "a") as userid_file:
                 userid_file.write(self.user_id + "\n")
     # Update user properties from server
     self.update()
Пример #3
0
def register_user(user):
    """Return raw response data from registering user"""
    params = [("accuracy", user.location.accuracy),
              ("deviceID", generate_id(dashes=False, upper=True)),
              ("lat", user.location.latitude),
              ("long", user.location.longitude), ("token", get_token()),
              ("userID", user.user_id), ("userLat", user.location.latitude),
              ("userLong", user.location.longitude)]
    return _send("GET", settings.YIKYAK_ENDPOINT, "registerUser", params)
Пример #4
0
def register_user(user):
    """Return raw response data from registering user"""
    params = [("accuracy", user.location.accuracy),
              ("deviceID", generate_id(dashes=False, upper=True)),
              ("lat", user.location.latitude),
              ("long", user.location.longitude),
              ("token", get_token()),
              ("userID", user.user_id),
              ("userLat", user.location.latitude),
              ("userLong", user.location.longitude)]
    return _send("GET", settings.YIKYAK_ENDPOINT, "registerUser", params)
Пример #5
0
def shorten():
    url = request.form.get("url")
    while True:
        _id = helper.generate_id()
        exist = ShortUrl.query.filter_by(_id=_id).first()
        if not exist:
            break
    item = ShortUrl(_id=_id, url=url)
    db.session.add(item)
    db.session.commit()
    flash(url_for("main.open", id=_id, _external=True))
    return redirect(url_for("main.home"))
Пример #6
0
def start(input):
    """
    /games/
     POST method for creating a game
     Parameters:
      + `duration` (required): the time (in seconds) that specifies the duration of
         the game
      + `random` (required): if `true`, then the game will be generated with random
         board.  Otherwise, it will be generated based on input.
      + `board` (optional): if `random` is not true, this will be used as the board
         for new game. If this is not present, new game will get the default board
         from `test_board.txt`
     Response:
     type: object
         properties:
           id:
             type: integer
           token:
             type: string
           duration:
             type: integer
           board:
             type: string
    """
    duration = input.get("duration")
    random = input.get("random")
    board = input.get("board", None)
    start_time = datetime.datetime.now()
    end_time = start_time + datetime.timedelta(seconds=duration)
    id = generate_id()
    token = generate_token()
    if random:
        board = generate_board()
    else:
        board = "T, A, P, *, E, A, K, S, O, B, R, S, S, *, X, D"

    create_new_game(start_time, end_time, duration, board, token, id)
   
    result = {
            'id': id,
            'token': token,
            'duration': duration,
            'board': board
    }

    return prepare_response(result, 201)
Пример #7
0
def register_user(user_id):
    """Register a user with Yik Yak's Parse service. Create a new installation
    and add user_id to it. Return installation ID and object ID"""
    # Installation ID
    iid = generate_id()
    # Create installation and check for errors
    response = _create_installation(iid)
    try:
        object_id = response.json()["result"]["data"]["objectId"]
    except (KeyError, ValueError):
        raise ParsingResponseError("Error creating installation", response)
    # Save user and check for errors and consistency
    response = _save_user(user_id, iid, object_id)
    try:
        if response.json()["result"]["data"]["channels"][0][1:-1] != user_id:
            raise ParsingResponseError("Error saving user", response)
    except (KeyError, ValueError):
        raise ParsingResponseError("Error saving user", response)
    return iid, object_id
Пример #8
0
def register_user(user_id):
    """Register a user with Yik Yak's Parse service. Create a new installation
    and add user_id to it. Return installation ID and object ID"""
    # Installation ID
    iid = generate_id()
    # Create installation and check for errors
    response = _create_installation(iid)
    try:
        object_id = response.json()["result"]["data"]["objectId"]
    except (KeyError, ValueError):
        raise ParsingResponseError("Error creating installation", response)
    # Save user and check for errors and consistency
    response = _save_user(user_id, iid, object_id)
    try:
        if response.json()["result"]["data"]["channels"][0][1:-1] != user_id:
            raise ParsingResponseError("Error saving user", response)
    except (KeyError, ValueError):
        raise ParsingResponseError("Error saving user", response)
    return iid, object_id
Пример #9
0
def _send(method, data, iid):
    """Send data associated with an installation (ID: iid) to Yik Yak's Parse
    service using specified method. Return the response"""
    url = urljoin(settings.PARSE_ENDPOINT, method)
    data = {
            "classname": "_Installation",
            "data": data,
            "osVersion": settings.ANDROID_VERSION,
            "appBuildVersion": settings.PARSE_BUILD,
            "appDisplayVersion": settings.YIKYAK_VERSION,
            "v": settings.PARSE_VERSION_LETTER + settings.PARSE_VERSION,
            "iid": iid,
            "uuid": generate_id()
            }
    json_data = json.dumps(data)
    auth = OAuth1(settings.PARSE_APPID, settings.PARSE_CLIENTKEY)
    user_agent = "Parse Android SDK %s (com.yik.yak/%s) API Level %s"
    user_agent %= (settings.PARSE_VERSION, settings.PARSE_BUILD,
                   settings.PARSE_API_LEVEL)
    headers = {"Accept-Encoding": "gzip", "User-Agent": user_agent}
    return REQUEST("POST", url, data=json_data, auth=auth, headers=headers)
Пример #10
0
def _send(method, data, iid):
    """Send data associated with an installation (ID: iid) to Yik Yak's Parse
    service using specified method. Return the response"""
    url = urljoin(settings.PARSE_ENDPOINT, method)
    data = {
        "classname": "_Installation",
        "data": data,
        "osVersion": settings.ANDROID_VERSION,
        "appBuildVersion": settings.PARSE_BUILD,
        "appDisplayVersion": settings.YIKYAK_VERSION,
        "v": settings.PARSE_VERSION_LETTER + settings.PARSE_VERSION,
        "iid": iid,
        "uuid": generate_id()
    }
    json_data = json.dumps(data)
    auth = OAuth1(settings.PARSE_APPID, settings.PARSE_CLIENTKEY)
    user_agent = "Parse Android SDK %s (com.yik.yak/%s) API Level %s"
    user_agent %= (settings.PARSE_VERSION, settings.PARSE_BUILD,
                   settings.PARSE_API_LEVEL)
    headers = {"Accept-Encoding": "gzip", "User-Agent": user_agent}
    return REQUEST("POST", url, data=json_data, auth=auth, headers=headers)
Пример #11
0
from model.fc_model import UnrealModel
#from model.base import BaseModel
from train.experience import Experience
from train.adam_applier import AdamApplier
from train.rmsprop_applier import RMSPropApplier
from train.base_trainer import BaseTrainer
from train.aux_trainer import AuxTrainer
from queuer import RunnerThread
from settings.options import get_options

# get command line args
flags = get_options("training")
# setup logger
logger = logging.getLogger('StRADRL.main')

RUN_ID = generate_id()
if flags.training_name:
    TRAINING_NAME = flags.training_name
else:
    TRAINING_NAME = RUN_ID
LOG_LEVEL = 'debug'
CONTINUE_TRAINING = False

USE_GPU = True
visualise = False


def printflags():
    logger.info("------ flags: ------")
    for name in flags.__dict__['__flags']:
        logger.info("{}: {}".format(name, flags.__dict__['__flags'][name]))
Пример #12
0
def deploy():

    # Script
    start_time = time.time()

    # Connect to the ComodIT API
    client = Client(config.endpoint, config.username, config.password)
    env = client.get_environment(config.organization, 'Openshift')
    
    # Configure environment
    try:
      env.settings().create("domain", config.domain)
    except:
      print "Did not reconfigure domain since a setting was already defined. Run teardown if you wanted to cleanup first"

    # Deploy Openshift Broker
    try:
      broker = env.get_host('Openshift Broker')
    except EntityNotFoundException:
      broker = create_host(env, 'Openshift Broker', config.platform, config.distribution, [])
      print "Deploying Openshift Broker"
      broker.provision()
      broker.refresh()

    # Wait for Broker to be deployed and retrieve IP
    if broker.state == "PROVISIONING":
      print "Waiting for Broker to be deployed"
      broker.wait_for_state('READY', config.time_out)
      if broker.state == "PROVISIONING":
          raise Exception("Timed out waiting for host to be provisioned.")

    # Get the broker IP address
    broker_ip = broker.get_instance().wait_for_property("ip.eth0", config.time_out)
    if broker_ip is None:
        raise Exception("Failed to retrieve the host IP")

    # Configure broker
    print "Installing the Bind server"
    broker.install("openshift-bind-server", {"dns_records": [{"host":"broker", "type": "A", "ttl": "180", "target": broker_ip}]})
    track_changes(broker)

    # Update environment settings with nameserver
    env.settings().create("nameserver", broker_ip)

    # Configure Network
    print "Reconfiguring network"
    broker.install("openshift-dhcp-dns-config", {"hostname": "broker"})
    track_changes(broker)
    
    # Install Mongo
    print "Installing MongoDB"
    mongo_pw = generate_id(12)
    broker.install("openshift-mongodb", {"smallfiles": True, "secure": True, "users": [{"database": "openshift", "username": "******", "password": mongo_pw}]})
    track_changes(broker)

    # Install RabbitMQ
    print "Installing RabbitMQ"
    broker.install("openshift-rabbitmq-server", {})
    track_changes(broker)

    # Install Mcollective client
    print "Installing MCollective Client"
    broker.install("openshift-mcollective-client", {})
    track_changes(broker)

    # Install Broker
    print "Installing Openshift Broker"
    broker.install("openshift-broker", {"mongo_database": "openshift", "mongo_user": "******", "mongo_password": mongo_pw})
    track_changes(broker)

    # Cleanup changes
    broker.changes().clear()

    # Get broker public hostname
    public_hostname = broker.get_instance().wait_for_address(config.time_out)
    print "Openshift broker deployed at %s" % public_hostname

    total_time = time.time() - start_time
    print "Deployment time: " + str(total_time)
Пример #13
0
def create_room(message):
    room_id = helper.generate_id(rooms)
    rooms[room_id] = Room(room_id, message.from_user.id)
    bot.send_message(chat_id=message.chat.id,
                     text='Комната создана.\nId комнаты - ' + str(room_id))
    _enter_room(message, room_id)