Example #1
0
 def __init__(self, *args, **kwargs):
     fk_fs_type = kwargs.get('fk_fs_type', None)
     if fk_fs_type != None:
        self.fk_fs_type = uuid.uuid()
     fs_uuid = kwargs.get('fs_uuid', None)
     if fs_uuid != None:
        self.fs_uuid = uuid.uuid()
    def test_simple_add(self):

        # Add one slot together with a timespan
        allocation = Allocation(raster=15, resource=uuid())
        allocation.start = datetime(2011, 1, 1, 15)
        allocation.end = datetime(2011, 1, 1, 15, 59)
        allocation.group = uuid()

        reservation = uuid()

        slot = ReservedSlot(resource=allocation.resource)
        slot.start = allocation.start
        slot.end = allocation.end
        slot.allocation = allocation
        slot.reservation = reservation
        allocation.reserved_slots.append(slot)

        # Ensure that the same slot cannot be doubly used
        anotherslot = ReservedSlot(resource=allocation.resource)
        anotherslot.start = allocation.start
        anotherslot.end = allocation.end
        anotherslot.allocation = allocation
        anotherslot.reservation = reservation

        Session.add(anotherslot)
        self.assertRaises(IntegrityError, Session.flush)
Example #3
0
def get_visitor_id():
    prev_visitors= set(os.listdir(results_dir))

    new_id= uuid().hex
    while new_id in prev_visitors: new_id=uuid().hex

    return new_id
Example #4
0
 def __init__(self, *args, **kwargs):
     fk_block = kwargs.get('fk_block', None)
     if fk_block != None:
        self.fk_block = uuid.uuid()
     name_FileSystemType = kwargs.get('name_FileSystemType', None)
     if name_FileSystemType != None:
        self.name_FileSystemType = uuid.uuid()
def add_something(resource=None):
    resource = resource or uuid()
    allocation = Allocation(raster=15, resource=resource, mirror_of=resource)
    allocation.start = datetime(2011, 1, 1, 15)
    allocation.end = datetime(2011, 1, 1, 15, 59)
    allocation.group = uuid()

    Session.add(allocation)
 def _create_allocation(self):
     allocation = Allocation(raster=15, resource=uuid())
     allocation.start = datetime(2011, 1, 1, 15, 00)
     allocation.end = datetime(2011, 1, 1, 16, 00)
     allocation.group = str(uuid())
     allocation.mirror_of = allocation.resource
     Session.add(allocation)
     return allocation
Example #7
0
def getLock(name = None):
	if not name:
		name = str(uuid())
		while name in locks:
			name = str(uuid())
	if not name in locks:
		locks[name] = SingleLock() if name[0] == '#' else ReentLock()
	return locks[name]
Example #8
0
 def test_export(self):
     commitish = uuid().hex
     dest = '/home/' + uuid().hex
     self.git.export(commitish, dest)
     self.subprocess.assertExistsCommand(
         lambda c: c.startswith('git archive') and commitish in c)
     self.subprocess.assertExistsCommand(
         lambda c: dest in c)
Example #9
0
 def test_local_config(self):
     k = uuid().hex
     v = uuid().hex
     self.git.set_local_config(k, v)
     self.subprocess.assertLastCommandStartsWith('git config')
     self.subprocess.assertLastCommandContains(k)
     pred = lambda c: c.startswith('git config') and k in c
     self.subprocess.provideResult(pred, v)
     self.assertEqual(v, self.git.get_local_config(k))
Example #10
0
 def write(self):
     message_header = ET.Element('MessageHeader')
     self.__add_element_with_text(message_header, "MessageThreadId", str(uuid()))
     self.__add_element_with_text(message_header, "MessageId", str(uuid()))
     message_header.append(self.sender.write())
     message_header.append(self.recipient.write())
     created_date = ET.SubElement(message_header, "MessageCreatedDateTime")
     created_date.text = d.datetime.now().replace(microsecond=0).isoformat()+ "Z" 
     return message_header
Example #11
0
    def setUp(self):
        super(TestUserTransaction, self).setUp()
        self.currency = CurrencyModel.query.filter_by(code='USD').first()
        self.fee = FeeModel.query.get(1)

        n = uuid().hex
        self.user_a = self.create_user(n, '%s %s' % (n[:16], n[16:]))
        self.user_a_balance = self.create_balance(user=self.user_a, currency_code='USD')

        self.campaign_a = self.create_campaign(uuid().hex, uuid().hex)
        self.campaign_a_balance = self.create_balance(campaign=self.campaign_a, currency_code='USD')
Example #12
0
    def setUp(self):
        super(TestExternalLedgerEntryWithFullName, self).setUp()
        self.currency = CurrencyModel.query.filter_by(code='USD').first()
        self.fee = FeeModel.query.get(1)

        n = uuid().hex
        self.user = self.create_user(n, '%s %s' % (n[:16], n[16:]))
        self.user_balance = self.create_balance(user=self.user, currency_code='USD')

        self.campaign = self.create_campaign(uuid().hex, uuid().hex)
        self.campaign_balance = self.create_balance(campaign=self.campaign, currency_code='USD')
Example #13
0
    def make_commit(self):
        """
        Makes a random commit in the current branch.
        """
        fragment = uuid().hex[:8]
        filename = join(self.repodir, fragment)
        with open(filename, 'w') as fh:
            fh.write(uuid().hex)

        self.repo.index.add([basename(filename)])
        self.repo.index.commit('Adding {0}'.format(basename(filename)))
Example #14
0
File: IRC.py Project: Peping/Lal
    def __init__(self, server, port=6667, nick="", realname=""):
        self.server = server
        self.port = 6667
        self.nickname = nick
        self.realname = nick
        self.conn = None
        self.version = "IRC python generic custom bot 2014"

        self.events= {
                      "ctcp":{
                              uuid(): lambda is_request, origin, command, message: None if command.upper()!="PING" else self.ctcp_reply(origin,command,(message,)),
                              uuid(): lambda is_request, origin, command, message: None if command.upper()!="VERSION" else self.ctcp_reply(origin,command,(self.version,))
                             }
                      }
Example #15
0
    def setUp(self):
        self.SMTP_patcher = patch("pooldlib.api.communication.mail.smtplib")
        self.SMTP_patcher.start()
        self.email = email.Email(None, None)
        self.addCleanup(self.SMTP_patcher.stop)

        self.username_a = uuid().hex
        self.name_a = "%s %s" % (self.username_a[:16], self.username_a[16:])
        self.email_a = "*****@*****.**" % self.username_a
        self.user_a = self.create_user(self.username_a, self.name_a, self.email_a)

        self.username_b = uuid().hex
        self.name_b = "%s %s" % (self.username_b[:16], self.username_b[16:])
        self.email_b = "*****@*****.**" % self.username_b
        self.user_b = self.create_user(self.username_b, self.name_b, self.email_b)
Example #16
0
def getCounter(name = None, start = 0, unique = False):
	if name:
		base = name
		idx = 1
		while unique and name in counters:
			idx += 1
			name = "%s-%d" % (base, idx)
	else:
		name = str(uuid())
		while name in counters:
			name = str(uuid())

	if not name in counters:
		counters[name] = Counter(start)
	return counters[name]
Example #17
0
File: IRC.py Project: Peping/Lal
    def add_handler(self, event_name, handler):
        id= uuid()
        if event_name in self.events.keys():
            self.events[event_name][id] = handler
        else: self.events[event_name] = {id: handler}

        return id
Example #18
0
    def open(self):
        print "New connection opened."
        self._id = str(uuid())
        self.write_message(self._id)

        WSTask.connections[self._id] = self
        print WSTask.connections
Example #19
0
def get_path (session_key, filename = None):

    if not filename: filename = str (uuid ())
    path_to = os.path.join (settings.MEDIA_DATA, session_key)
    if not os.path.exists (path_to): os.mkdir (path_to)

    return os.path.join (path_to, filename)
Example #20
0
    def _parse_geoms (self, root_xml):
        for geom_xml in root_xml.iterfind ('library_geometries/geometry'):
            mesh_xml = geom_xml.find ('mesh')
            poly_xml = mesh_xml.find ('polylist')

            assert all (int(v) == 3 for v in poly_xml.find ('vcount').text.split ()),\
                'Mesh {} is not triangulated'.format (geom_xml.attrib['name'])

            inputs = {}
            for input_xml in poly_xml.iterfind ('input'):
                input = self.Input (input_xml.attrib['source'].lstrip ('#'), int (input_xml.attrib['offset']))
                inputs[input_xml.attrib['semantic']] = input

            input_xml = mesh_xml.find ("vertices[@id='{}']/input[@semantic='POSITION']".format (inputs['VERTEX'].source))
            input = self.Input (input_xml.attrib['source'].lstrip ('#'), inputs['VERTEX'].offset)
            inputs['POSITION'] = input
            del inputs['VERTEX']

            vertices = self._parse_source (mesh_xml, inputs['POSITION'].source)
            normals = self._parse_source (mesh_xml, inputs['NORMAL'].source)

            faces = []
            stride = len (inputs)
            faces_idx = map (int, poly_xml.find ('p').text.split ())
            for i in xrange (0, len (faces_idx), stride * 3):
                face_vertices = []
                face_normals = []
                for j in xrange (i, i + stride * 3, stride):
                    face_vertices.append (faces_idx[j + inputs['POSITION'].offset])
                    face_normals.append (faces_idx[j + inputs['NORMAL'].offset])
                faces.append (self.Face (face_vertices, face_normals))

            geom = self.Geometry (str (uuid ()), faces, vertices, normals)
            self.geoms[geom_xml.attrib['id']] = geom
    def setupClass(cls):
        """SFTP (RSE/PROTOCOLS): Creating necessary directories and files """
        # Creating local files
        cls.tmpdir = tempfile.mkdtemp()
        cls.user = uuid()

        with open("%s/data.raw" % cls.tmpdir, "wb") as out:
            out.seek((1024 * 1024) - 1)  # 1 MB
            out.write('\0')
        for f in MgrTestCases.files_local:
            os.symlink('%s/data.raw' % cls.tmpdir, '%s/%s' % (cls.tmpdir, f))

        # Load local credentials from file
        with open('etc/rse-accounts.cfg') as f:
            data = json.load(f)
        credentials = data['LXPLUS']
        lxplus = pysftp.Connection(**credentials)
        with open('etc/rse_repository.json') as f:
            prefix = json.load(f)['LXPLUS']['protocols']['supported']['sftp']['prefix']
        lxplus.execute('mkdir %s' % prefix)
        lxplus.execute('dd if=/dev/urandom of=%s/data.raw bs=1024 count=1024' % prefix)
        cls.static_file = 'sftp://lxplus.cern.ch:22%sdata.raw' % prefix
        protocol = mgr.create_protocol(mgr.get_rse_info('LXPLUS'), 'write')
        for f in MgrTestCases.files_remote:
            tmp = protocol.parse_pfns(protocol.lfns2pfns({'name': f, 'scope': 'user.%s' % cls.user}).values()[0]).values()[0]
            for cmd in ['mkdir -p %s' % ''.join([tmp['prefix'], tmp['path']]), 'ln -s %sdata.raw %s' % (prefix, ''.join([tmp['prefix'], tmp['path'], tmp['name']]))]:
                lxplus.execute(cmd)
        lxplus.close()
Example #22
0
def canvas1(name=None, x=750, y=535):
    """
    creates a new TCanvas 750px wide, usual aspect ratio
    """
    title = name or str(uuid())
    c =  ROOT.TCanvas(title, title, x, y)
    return c
Example #23
0
    def start(self, process=False, link=None):
        """
        Start a new thread or process that invokes this manager's
        ``run()`` method. The invocation of this method returns
        immediately after the task or process has been started.
        """

        if process:
            # Parent<->Child Bridge
            if link is not None:
                from circuits.net.sockets import Pipe
                from circuits.core.bridge import Bridge

                channels = (uuid(),) * 2
                parent, child = Pipe(*channels)
                bridge = Bridge(parent, channel=channels[0]).register(link)

                args = (child,)
            else:
                args = ()
                bridge = None

            self.__process = Process(target=self.run, args=args, name=self.name)
            self.__process.daemon = True
            self.__process.start()

            return self.__process, bridge
        else:
            self.__thread = Thread(target=self.run, name=self.name)
            self.__thread.daemon = True
            self.__thread.start()

            return self.__thread, None
Example #24
0
 def tempname(self):
     name = os.path.join(tempfile.gettempdir(), uuid().hex)
     yield name
     try:
         self.unlink(name)
     except OSError:
         pass
def generate():
    width = 720
    height = 300
    white = (255, 255, 255)

    rexp = ["sin(pi*i/x)","cos(pi*i/x)"][randint(0,1)]
    gexp = ["cos((pi*i*j)/x)","sin((pi*i*j)/x)"][randint(0,1)]
    bexp = ["sin(pi*j/x)","cos(pi*j/x)"][randint(0,1)]
    tileSize = randint(2,5) 
    x = float([3,5,7,11,13,17,19,21][randint(0,7)]) 

    image = Image.new("RGB", (width, height), white)
    draw = ImageDraw.Draw(image)

    for i in xrange(0,720,tileSize):
        for j in xrange(0,480,tileSize):
            r = int(eval(rexp)*1000%255)
            g = int(eval(gexp)*1000%255)
            b = int(eval(bexp)*1000%255)

            tileColor = "#"+hex(r)[2:].zfill(2)+hex(g)[2:].zfill(2)+hex(b)[2:].zfill(2)
            draw.rectangle([(i,j),(i+tileSize,j+tileSize)], tileColor, None)

    path = "static/img/"
    fileName = str(uuid().int)+".jpg"
    image.save(path+fileName, 'JPEG')

    return path+fileName
Example #26
0
    def put(self):
        """ Upload an ECG datafile to the server.
        The file should be labled as "data" when uploaded

        Example URL **PUT http://hrsdb/ecgdata**

        Example response::

            {
              "response": {
                "id": 1
              }
            }
        """

        args = self.put_parser.parse_args(strict=True)
        ecgfile = args.data

        # Save the file on disk using a uuid
        filename = "%s%s.dat" % (self.file_prefix, uuid())
        ecgfile.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename))

        # Create a new database record for this file
        with open_session() as session:
            ecgdata = ECGData(filename)
            session.add(ecgdata)
            session.flush()
            session.commit()

            print(ecgdata.id)

            return gen_response({"id": ecgdata.id})
Example #27
0
    def new_id():
        """Generate a new graph element id.

        :return: new graph element id.
        :rtype: str
        """
        return str(uuid())
Example #28
0
 def __init__(self, *args, **kwargs):
     super(YahooContactImporter, self).__init__(*args, **kwargs)
     self.request_token_url = REQUEST_TOKEN_URL
     self.request_auth_url = REQUEST_AUTH_URL
     self.token_url = TOKEN_URL
     self.oauth_timestamp = int(time())
     self.oauth_nonce = md5("%s%s" % (uuid(), self.oauth_timestamp)).hexdigest()
Example #29
0
def pre_save_parameter(sender, **kwargs):

    # the object can be accessed via kwargs 'instance' key.
    parameter = kwargs['instance']

    if parameter.name.units.startswith('image') \
            and parameter.name.data_type == ParameterName.FILENAME:
        if parameter.string_value:
            from base64 import b64decode
            from os import mkdir
            from os.path import exists, join
            from uuid import uuid4 as uuid

            exp_id = parameter.getExpId()

            dirname = join(settings.FILE_STORE_PATH, str(exp_id))
            filename = str(uuid())
            filepath = join(dirname, filename)

            b64 = parameter.string_value
            modulo = len(b64) % 4
            if modulo:
                b64 += (4 - modulo) * '='

            if not exists(dirname):
                mkdir(dirname)
            f = open(filepath, 'w')
            try:
                f.write(b64decode(b64))
            except TypeError:
                f.write(b64)
            f.close()
            parameter.string_value = filename
Example #30
0
def login_post():
	username = req.POST.get("username")
	password = req.POST.get("password")
	meta = get_twbot_meta(c)

	valid = True
	if username == meta["username"]:
		if not password_matches(password.encode(), meta["password"]):
			valid = False
	else:
		valid = False

	if valid:
		# generate a UUID (Universally Unique IDentifier). Each one is unique
		# except in exceptional circumstances, and so it will be infeasible for
		# someone to forge one that authenticates them into the system
		session = str(uuid())

		resp.set_cookie("session", session, httponly=True)
		c.execute("UPDATE meta SET session = ?;", (session,))
		conn.commit()

		b.redirect("/questions")
	else:
		b.redirect("/login?" + urlencode({"message": "Incorrect login"}))
Example #31
0
def _serialize_criteria(criteria_root, criteria_list):
    """
    Serialize rubric criteria as XML, adding children to the XML
    with root node `criteria_root`.

    We don't make any assumptions about the contents of `criteria_list`,
    and we handle unexpected inputs gracefully.

    Args:
        critera_root (lxml.etree.Element): The root node of the tree.
        criteria_list (list): List of criteria dictionaries.

    Returns:
        None
    """

    # Sort the criteria by order number, then serialize as XML
    for criterion in _sort_by_order_num(criteria_list):
        criterion_el = etree.SubElement(criteria_root, 'criterion')

        # Criterion name (default to a UUID)
        criterion_name = etree.SubElement(criterion_el, u'name')
        if 'name' in criterion:
            criterion_name.text = six.text_type(criterion['name'])
        else:
            criterion_name.text = six.text_type(uuid().hex)

        # Criterion label (default to the name, then an empty string)
        criterion_label = etree.SubElement(criterion_el, 'label')
        criterion_label.text = six.text_type(criterion.get('label', criterion.get('name', u'')))

        # Criterion prompt (default to empty string)
        criterion_prompt = etree.SubElement(criterion_el, 'prompt')
        criterion_prompt.text = six.text_type(criterion.get('prompt', u''))

        # Criterion feedback disabled, optional, or required
        # If disabled, do not set the attribute.
        if criterion.get('feedback') in ["optional", "required"]:
            criterion_el.set('feedback', criterion['feedback'])

        # Criterion options
        options_list = criterion.get('options', None)
        if isinstance(options_list, list):
            _serialize_options(criterion_el, options_list)
Example #32
0
    def connectProxy(self):
        """
            initialize thrift rpc client,
            check for ssl, check auth,
            setup dispatcher,
            connect error signals,
            check server version
        """
        if self.internal: return True

        err = None
        try:
            client = ThriftClient(self.host, self.port, self.user,
                                  self.password)
        except WrongLogin:
            err = _("bad login credentials")
        except NoSSL:
            err = _("no ssl support")
        except NoConnection:
            err = _("can't connect to host")
        if err:
            if not Connector.firstAttempt:
                self.emit(SIGNAL("errorBox"), err)
            Connector.firstAttempt = False
            return False

        self.proxy = DispatchRPC(self.mutex, client)
        self.connect(self.proxy, SIGNAL("connectionLost"), self,
                     SIGNAL("connectionLost"))

        server_version = self.proxy.getServerVersion()
        self.connectionID = uuid().hex

        if not server_version == SERVER_VERSION:
            self.emit(
                SIGNAL("errorBox"),
                _("server is version %(new)s client accepts version %(current)s"
                  ) % {
                      "new": server_version,
                      "current": SERVER_VERSION
                  })
            return False

        return True
Example #33
0
    def setUpClass(cls):
        """XROOTD (RSE/PROTOCOLS): Creating necessary directories and files """

        # Getting info for the test environment
        rse_id, prefix, hostname, port = cls.get_rse_info()

        try:
            os.mkdir(prefix)
        except Exception as e:
            print(e)

        # Creating local files
        cls.tmpdir = tempfile.mkdtemp()
        cls.user = uuid()

        with open("%s/data.raw" % cls.tmpdir, "wb") as out:
            out.seek((1024 * 1024) - 1)  # 1 MB
            out.write(b'\0')
        for f in MgrTestCases.files_local:
            shutil.copy('%s/data.raw' % cls.tmpdir, '%s/%s' % (cls.tmpdir, f))

        protocol = rsemanager.create_protocol(rsemanager.get_rse_info(rse_id),
                                              'write')
        protocol.connect()

        os.system('dd if=/dev/urandom of=%s/data.raw bs=1024 count=1024' %
                  prefix)
        cls.static_file = 'xroot://%s:%d/%s/data.raw' % (hostname, port,
                                                         prefix)
        cmd = 'xrdcp %s/data.raw %s' % (prefix, cls.static_file)
        execute(cmd)

        for f in MgrTestCases.files_remote:
            path = protocol.path2pfn(
                prefix + protocol._get_path('user.%s' % cls.user, f))
            cmd = 'xrdcp %s/data.raw %s' % (prefix, path)
            execute(cmd)

        for f in MgrTestCases.files_local_and_remote:
            shutil.copy('%s/data.raw' % cls.tmpdir, '%s/%s' % (cls.tmpdir, f))
            path = protocol.path2pfn(
                prefix + protocol._get_path('user.%s' % cls.user, f))
            cmd = 'xrdcp %s/%s %s' % (cls.tmpdir, f, path)
            execute(cmd)
Example #34
0
    def __launch_worker(self, task_data, index):
        url = task_data['url']
        token = str(uuid.uuid4())
        try:
            # prepare log path
            o = urlparse.urlparse(url)
            host = o.netloc
            dir_path_name = os.path.join(self.__log_dir, token)
            while os.path.exists(dir_path_name):
                token = str(uuid.uuid())
                dir_path_name = os.path.join(self.__log_dir, token)
            os.makedirs(dir_path_name)

            # prepar args
            args = ['phantomjs']
            args[1:1] = [
                self.__worker_script_path, url,
                str(self.__user_agent)
            ]

            # start worker process
            worker = subprocess.Popen(
                args,
                stdout=open(os.path.join(dir_path_name, 'stdout.txt'), 'w'),
                stderr=open(os.path.join(dir_path_name, 'stderr.txt'), 'w'))
            worker_info = {
                'timestamp': int(time.time()),
                'index': index,
                'process': worker,
                'url': url,
                'path': dir_path_name
            }
            #(,task.url, index, worker, dir_path_name)
            #time.sleep(1)

            # update worker info
            self.__total_worker_instances += 1
            self.__workers.append(worker_info)
            logger.info("[MAIN] successfully run " + url + ' : ' +
                        str(worker_info['index']) + " withpid:" +
                        str(worker.pid) + ", dir_path:" + dir_path_name)
        except Exception as e:
            logger.error("failed to launch worker " + str(e))
Example #35
0
    def __create_new_file(self, db_session, repository_id, language):
        """Create new file record in database if not exists

        Args:
            db_session:
^^
            repository_id:
            language:

        Returns: created file

        """
        file_orm = File(
            id=uuid().hex,
            repository_id=repository_id,
            language=language
        )
        db_session.add(file_orm)
        return file_orm
Example #36
0
async def job_lifecycle_wait(session):
    job_id = str(uuid())
    json_dict = create_payload(job_id)

    async with session.post(f'{_SHEPHERD_URL}/start-job',
                            json=json_dict) as resp:
        assert resp.status == 200

    async with session.get(f'{_SHEPHERD_URL}/jobs/{job_id}/status') as resp:
        assert resp.status == 200

    async with session.get(
            f'{_SHEPHERD_URL}/jobs/{job_id}/wait_ready') as resp:
        assert resp.status == 200

    async with session.get(f'{_SHEPHERD_URL}/jobs/{job_id}/result') as resp:
        response = await resp.text()
        response = json.loads(response)
        assert response['result'] == '42'
Example #37
0
    def test_wrong_credentials(self):
        container = str(uuid())
        conn_string = \
            'DefaultEndpointsProtocol=https;AccountName={};AccountKey={}'.\
            format("testaccount", "wrongsecret")
        store = AzureBlockBlobStore(conn_string=conn_string,
                                    container=container,
                                    create_if_missing=False)

        if hasattr(store, 'block_blob_service'):
            from azure.storage.common.retry import ExponentialRetry
            store.block_blob_service.retry = ExponentialRetry(
                max_attempts=0).retry
        else:
            store.blob_container_client._config.retry_policy.total_retries = 0

        with pytest.raises(IOError) as exc:
            store.put(u"key", b"data")
        assert u"Incorrect padding" in str(exc.value)
Example #38
0
def test_not_kicked_during_game(db_session):
    game = WurwolvesGame(GAME_ID)

    # Add four players
    player_ids = [uuid() for _ in range(4)]
    roles = [
        PlayerRole.MEDIC,
        PlayerRole.VILLAGER,
        PlayerRole.SPECTATOR,
        PlayerRole.WOLF,
    ]
    for p in player_ids:
        game.join(p)

    db_session = game._session

    game.start_game()

    for p, r in zip(player_ids, roles):
        game.set_player_role(game.get_player_id(p), r)

    timeout_player_id = player_ids[0]
    villager_id = player_ids[1]
    spectator_id = player_ids[2]
    wolf_id = player_ids[3]

    # Kill the medic with the wolf
    game.wolf_night_action(wolf_id, timeout_player_id)
    # Have the idler do something too
    game.medic_night_action(timeout_player_id, wolf_id)

    # Set medic to have joined ages ago
    timeout_player = game.get_player(timeout_player_id)
    db_session.add(timeout_player)
    timeout_player.last_seen = datetime(1, 1, 1)
    db_session.commit()
    db_session.expire_all()

    # Keepalive one of the other players, which should not kick the idler since it's a game
    game.player_keepalive(wolf_id)

    db_session.expire_all()
    assert game.get_player(timeout_player_id)
Example #39
0
    def get_path(self, state: GameState) -> Path:
        """
        Get the path of a state. The path is determined by the filepath
        attribute of the sate.

        If the filepath attribute is None, an unique UUID is generated and
        stored as the filepath.

        :param state: the state to get the path
        :return: the path where the state is saved
        """
        path = state.filepath
        if path is None:
            logger.warning(
                "filepath for state '%s' was not set, creating uuid", state)
            path = self.save_dir / (str(uuid()) + ".json")
            state.filepath = path
            logger.warning("uuid filepath for state '%s': '%s'", state, path)
        return path
Example #40
0
    def __create_new_order_single(cls) -> Fix.Messages.NewOrderSingle:
        """
        Create a new order single
        :return: New order single
        """
        new_order_single = Fix.Messages.NewOrderSingle()
        instmt = cls.__create_instrument()
        side = Fix.Tags.Side.Values.BUY
        new_order_single.Instrument.Symbol.value = instmt.instmt_name
        new_order_single.Instrument.SecurityExchange.value = instmt.exchange
        new_order_single.Price.value = TRiskManager.price
        new_order_single.TriggeringInstruction.TriggerPrice.value = TRiskManager.price
        new_order_single.Side.value = side
        new_order_single.ClOrdID.value = uuid()
        new_order_single.OrderQtyData.OrderQty.value = TRiskManager.qty
        new_order_single.OrdType.value = Fix.Tags.OrdType.Values.LIMIT
        new_order_single.TimeInForce.value = Fix.Tags.TimeInForce.Values.DAY

        return new_order_single
Example #41
0
def canvas3(name=None):
    """
    TCanvas with 4 pads -- top 2 for histograms, bottom 2 for errors
    """
    title = name or str(uuid())
    c = ROOT.TCanvas(title, title, 750, 400)
    pads = [
        # name, title, x1, y1, x2, y2, color, bordersize, bordermode
        ROOT.TPad(c.GetName() + '_pad1', '', 0.0, 0.3, 0.5, 1.0, 10, 5, 0),
        ROOT.TPad(c.GetName() + '_pad2', '', 0.5, 0.3, 1.0, 1.0, 10, 5, 0),
        ROOT.TPad(c.GetName() + '_pad3', '', 0.0, 0.0, 0.5, 0.3, 10, 5, 0),
        ROOT.TPad(c.GetName() + '_pad4', '', 0.5, 0.0, 1.0, 0.3, 10, 5, 0)
    ]
    for i, p in enumerate(pads):
        p.SetNumber(i + 1)
        p.SetCanvas(c)
        p.Draw()
        ROOT.SetOwnership(p, False)
    return c
Example #42
0
def error_response(code, error, message):
    """
    Returns a error response.

    @param code: Status code.
    @param error: Error type.
    @param message: Error message.
    @return: Response.
    """
    response = make_response(
        render_template(
            'generic_error.xml',
            response_type='Response',
            error=error,
            message=message,
            request_id=uuid()
        )
    )
    return _create_response(response, int(code))
Example #43
0
    def _render_node(self, node):
        if isinstance(node, (str, numbers.Number)) or node is None:
            node_id = uuid()
        else:
            node_id = id(node)
        node_id = str(node_id)

        if node_id not in self._rendered_nodes:
            self._rendered_nodes.add(node_id)
            if isinstance(node, dict):
                self._render_dict(node, node_id)
            elif isinstance(node, list):
                self._render_list(node, node_id)
            else:
                self._graph.node(node_id,
                                 label=self._escape_dot_label(
                                     self._shorten_string(repr(node))))

        return node_id
    def __init__(self,
                 user_agent,
                 token=None,
                 token_updater=None,
                 hardware_id=None):
        """
        :type token: Optional[Dict[str, str]]
        :type token_updater: Optional[Callable[[str], None]]
        """
        self.user_agent = user_agent

        self.hardware_id = hardware_id
        if self.hardware_id is None:
            self.hardware_id = str(uuid())

        self.token_updater = token_updater
        self._oauth = OAuth2Session(
            client=LegacyApplicationClient(client_id=OAuth.CLIENT_ID),
            token=token)
Example #45
0
def process_background_image(imgfile, dirname=None):
    """
    Scales image. This images are then used as background for location and 
    profile pages. 
    
    Function takes image file (usually from request.FILES['file']) as argument
    and changes it's size and name. If `dirname` is provided as path relative
    to MEDIA_ROOT settings, image will be saved on this path. If not ,`img`
    folder will be used instead.
    """
    img = Image.open(imgfile)
    pathname = dirname or 'img'
    dirname = os.path.join(settings.MEDIA_ROOT, pathname)
    imgname = str(uuid()) + str(len(os.listdir(dirname))) + '.jpg'
    if img.size[0] > settings.BACKGROUND_IMAGE_SIZE:
        img.thumbnail(
            (settings.BACKGROUND_IMAGE_SIZE, settings.BACKGROUND_IMAGE_SIZE))
    img.save(os.path.join(dirname, imgname), 'JPEG')
    return File(open(os.path.join(dirname, imgname)))
Example #46
0
    def schedule(self, task, metadata=None):
        """Schedule a task for later execution.

        The task is saved to the `{directory}/todo` directory. Use
        `run` to execute all the tasks in the `{directory}/todo}
        directory.

        If you want, you can attach metadata to the task, which you
        can retrieve as `task.metadata` after the task has been run.

        """

        if metadata is not None:
            task.metadata = metadata

        taskfilename = (str(uuid()) + '.pkl')
        with (self._directory / 'todo' / taskfilename).open('wb') as f:
            dill.dump(task, f)
        self._log('schedule', taskfilename)
Example #47
0
def insert_category(category_name, user_id, category_type, **kwargs):
    """Insert Category."""
    sess = kwargs.get('sess')

    category_id = str(uuid())
    new_category = Category(category_id=category_id,
                            user_id=user_id,
                            category_name=category_name,
                            category_type=category_type,
                            category_order=0,
                            create_time=int(time.time()))

    sess.add(new_category)
    sess.commit()

    return dict(result=1,
                status=0,
                msg='Successfully.',
                data=dict(category_id=category_id))
Example #48
0
    def test_send_cross_group_not_allowed(self):
        new_room_id = str(uuid())
        self.create_and_join_room()
        self.create_channel_and_room(room_id=new_room_id, room_name='asdf')
        self.remove_owner()
        self.remove_owner_channel()

        self.set_acl({ApiActions.CROSSROOM: {
            'disallow': ''
        }},
                     room_id=new_room_id)

        activity = self.activity_for_message()
        activity['target']['objectType'] = 'room'
        activity['target']['id'] = new_room_id
        activity['actor']['url'] = BaseTest.ROOM_ID

        response_data = request.on_message(as_parser(activity))
        self.assertEqual(False, response_data[0])
Example #49
0
    def __init__(self, name, port=5555, *args, **kwargs):
        """Initialize broker state."""
        super(MDPBroker, self).__init__(name, *args, **kwargs)
        self.blockdiag_config["shape"] = "cloud"
        self.port = port
        self.broker_identity = uuid().get_hex()
        self.services = {}
        self.workers = {}
        self.context = zmq.Context()
        self.broker_socket = self.context.socket(zmq.ROUTER)
        self.broker_socket.linger = 0
        self.broker_socket.identity = self.broker_identity
        self.poller = zmq.Poller()
        self.poller.register(self.broker_socket, zmq.POLLIN)

        self.logger.info(
            "MDPBroker {0} initialized. Client/Worker ID will be {1}".format(
                self.broker_identity, self.broker_identity))
        self.bind(self.port, *args, **kwargs)
Example #50
0
    def share_data(self,
                   data,
                   shared_id=None,
                   share_extended=False,
                   cache=False):
        """Set input data as a shared data with input shared id.

        :param data: one data
        :param str shared_id: unique shared id. If None, the id is generated.
        :param bool share_extended: if True (False by default), set shared
            value to all shared data with input data
        :param bool cache: use query cache if True (False by default).

        :return: shared_id value (generated if None)
        """

        result = str(uuid()) if shared_id is None else shared_id

        # get an iterable version of input data
        if isinstance(data, dict):
            data_to_share = [data]
        else:
            data_to_share = data

        for dts in data_to_share:
            # update extended data if necessary
            if share_extended:
                path, name = self.get_path_with_name(dts)
                extended_data = self.get(path=path, names=name, shared=True)
                # decompose extended data into a list
                dts = []
                for ed in extended_data:
                    dts.append(ed)
            else:
                dts = [dts]

            for dt in dts:
                path, name = self.get_path_with_name(dt)
                dt[CompositeStorage.SHARED] = result
                self.put(path=path, name=name, data=dt, cache=cache)

        return result
Example #51
0
    def __init__(
        self,
        obj: AssemblyObjects = None,
        loc: Optional[Location] = None,
        name: Optional[str] = None,
        color: Optional[Color] = None,
        metadata: Optional[Dict[str, Any]] = None,
    ):
        """
        construct an assembly

        :param obj: root object of the assembly (default: None)
        :param loc: location of the root object (default: None, interpreted as identity transformation)
        :param name: unique name of the root object (default: None, resulting in an UUID being generated)
        :param color: color of the added object (default: None)
        :param metadata: a store for user-defined metadata (default: None)
        :return: An Assembly object.


        To create an empty assembly use::

            assy = Assembly(None)

        To create one constraint a root object::

            b = Workplane().box(1,1,1)
            assy = Assembly(b, Location(Vector(0,0,1)), name="root")

        """

        self.obj = obj
        self.loc = loc if loc else Location()
        self.name = name if name else str(uuid())
        self.color = color if color else None
        self.metadata = metadata if metadata else {}
        self.parent = None

        self.children = []
        self.constraints = []
        self.objects = {self.name: self}

        self._solve_result = None
Example #52
0
 def __enter__(self):
     super(ProcessingContext, self).__enter__()
     # Get the DRS facet keys from pattern
     self.facets = self.cfg.get_facets('directory_format')
     # Check if --commands-file argument specifies existing file
     self.check_existing_commands_file()
     # Raise error when %(version)s is not part of the final directory format
     if 'version' not in self.facets:
         raise NoVersionPattern(self.cfg.get('directory_format'),
                                self.facets)
     # Consider hard-coded elements in directory format
     idx = 0
     for pattern_element in self.cfg.get('directory_format').strip().split(
             "/"):
         try:
             # If pattern is %(...)s, get its index in the list of facets
             key = re.match(re.compile(r'%\(([\w]+)\)s'),
                            pattern_element).groups()[0]
             idx = self.facets.index(key)
         except AttributeError:
             # If pattern is not %(...)s, generate a uuid()
             key = str(uuid())
             # Insert hard-coded string in self.facets to be part of DRS path
             self.facets.insert(idx + 1, key)
             # Set the value using --set-value
             self.set_values[key] = pattern_element
             # Add the uuid to the ignored keys
             IGNORED_KEYS.append(key)
     self.pattern = self.cfg.translate('filename_format')
     # Init DRS tree
     self.tree = DRSTree(self.root, self.version, self.mode,
                         self.commands_file)
     # Init data collector
     self.sources = Collector(sources=self.directory)
     # Init file filter
     # Only supports netCDF files
     self.sources.FileFilter.add(regex='^.*\.nc$')
     # And exclude hidden files
     self.sources.FileFilter.add(regex='^\..*$', inclusive=False)
     # Get number of sources
     self.nbsources = len(self.sources)
     return self
Example #53
0
    def post(self, *_args, **_kwargs):
        params = yield self.check_auth()

        file_meta = self.request.files
        file_list = []
        for fp in file_meta['file']:
            filename, ext = os.path.splitext(fp['filename'])

            ext = ext.lower()
            image_id = uuid().hex
            md5_code = md5(fp['body']).hexdigest()
            sha1_code = sha1(fp['body']).hexdigest()

            exist = self.image.find_one({
                'md5_code': md5_code,
                'sha1_code': sha1_code
            })
            if exist:
                file_list.append(
                    dict(image_id=exist.get('image_id'),
                         path=exist.get('path'),
                         name=filename + ext))
                continue

            self.image.insert(
                dict(image_id=image_id,
                     user_id=params.user_id,
                     md5_code=md5_code,
                     sha1_code=sha1_code,
                     name=filename + ext,
                     path='/image/' + image_id + ext,
                     update_time=int(time.time())))

            qcos_bucket.put_object(path='/image/' + image_id + ext.lower(),
                                   body=fp['body'])

            file_list.append(
                dict(image_id=image_id,
                     path='/image/' + image_id + ext,
                     name=filename + ext))

        self.success(dict(file_list=file_list))
Example #54
0
def output():
    uid = str(uuid())
    fontsize = request.args['fontsize']
    choice = request.args['choice']
    text1 = request.args['text1']
    text2 = request.args['text2']
    X1 = int(request.args['X1'])
    Y1 = int(request.args['Y1'])
    useD = request.args['useD']

    basedir = os.path.dirname(__file__)
    im = Image.open(os.path.join(basedir, 'static/images', choice))
    width, height = im.size
    xConst = width / 700
    yConst = height / 700
    newX = xConst * X1
    newY = yConst * Y1
    '''
    img cont  = 700px
    '''
    draw = ImageDraw.Draw(im)
    font = ImageFont.truetype(
        os.path.join(basedir, 'fonts', 'Roboto-Regular.ttf'), int(fontsize))
    draw.text((int(newX), int(newY)), text1, (0, 0, 0), font=font)
    if useD == "True":
        X2 = int(request.args['X2'])
        Y2 = int(request.args['Y2'])
        newX2 = xConst * X2
        newY2 = yConst * Y2
        draw.text((int(newX2), int(newY2)), text2, (0, 0, 0), font=font)
    path = os.path.join(basedir, 'static/memes', '{}.jpg'.format(uid))
    im.save(path)
    app.logger.debug('X1: %s', X1)
    app.logger.debug('Y1: %s', Y1)
    return render_template('output.html',
                           fontsize=fontsize,
                           text1=text1,
                           text2=text2,
                           X1=X1,
                           Y1=Y1,
                           uid=uid,
                           id=id)
def get_content_prop():
    content_properties = {
        'coll_id': None,
        'scope': 'test_scope',
        'name': 'test_file_name_%s' % str(uuid()),
        'min_id': 0,
        'max_id': 100,
        'content_type': ContentType.File,
        'status': ContentStatus.New,
        'bytes': 1,
        'md5': None,
        'adler32': None,
        'processing_id': None,
        'storage_id': None,
        'retries': 0,
        'path': None,
        'expired_at': datetime.datetime.utcnow().replace(microsecond=0),
        'collcontent_metadata': {'id': 123}
    }
    return content_properties
Example #56
0
def new_article():
    # 新建文章
    if request.method == 'POST':
        article_id = uuid().hex
        article_title = request.form['title']
        article_content = request.form['content']
        article_poster = request.form['poster']
        article_created = int(time())

        r.zadd('time', {article_id: article_created})
        r.zadd('votes', {article_id: 0})
        r.hset('article:' + article_id, 'title', article_title)
        r.hset('article:' + article_id, 'content', article_content)
        r.hset('article:' + article_id, 'created', article_created)
        r.hset('article:' + article_id, 'poster', article_poster)
        r.hset('article:' + article_id, 'votes', 0)

        return redirect('/')

    return render_template('new.html')
Example #57
0
    def enrich(extra: dict) -> dict:
        if 'id' in extra:
            ActivityBuilder.warn_field('id', extra)
        else:
            extra['id'] = str(uuid())

        if 'published' in extra:
            ActivityBuilder.warn_field('published', extra)
        else:
            extra['published'] = datetime.utcnow().strftime(
                ConfigKeys.DEFAULT_DATE_FORMAT)

        if 'provider' in extra:
            ActivityBuilder.warn_field('provider', extra)
        else:
            extra['provider'] = {
                'id': environ.env.config.get(ConfigKeys.ENVIRONMENT, 'testing')
            }

        return extra
Example #58
0
def add_photo(request, rock_id):
    photo_file = request.FILES.get('photo-file', None)

    if photo_file:

        s3 = boto3.client('s3')

        key = uuid.uuid().hex[:6] + photo_file.name[photo_file.name.rfind('.'):]

        try: 
            s3.upload_fileobj(photo_file, BUCKET, key)

            url = f"{S3_BASE_URL}{BUCKET}/{key"

            photo = photo(url=url, rock_id=rock_id)

            photo.save()
        except:
            print('An error occured uploading file to s3')
    return redirect('detail', rock_id=rock_id)
Example #59
0
def upload_file_for(cls):
    if 'file' not in request.files:
        abort(400)

    file = request.files['file']
    if file.filename == '':
        abort(400)

    if file:
        file_extension = _file_extension(file.filename)

        if file_extension == None or file_extension not in config.get(
                'uploads', 'extensions'):
            abort(400)

        filename = str(uuid()) + '.' + file_extension
        file.save(os.path.join(cls.path(), filename))

        return cls(filename=filename)
        return jsonify(uploaded_file)
Example #60
0
    def put(self, *_args, **_kwargs):
        res = self.check_auth(3)
        if not res:
            return
        else:
            _user_id, _params = res

        args = self.parse_json_arguments(['message', 'chat_id'])

        self.message_list.insert_one({
            'msg_id': uuid().hex,
            'message': args.message,
            'chat_id': args.chat_id,
            'msg_time': int(time.time() * 1000),
            'date': datetime.utcnow(),
            'nickname': _params.nickname,
            'user_ip': _params.user_ip
        })
        res = dict(result=1, status=0, msg='successfully.', data=None)
        self.finish_with_json(res)