Example #1
0
 def test_1_hour(self):
     self.assertEqual(
         set_time.calculate_time(3600).hour,
         datetime.utcnow().hour + 1)
     self.assertEqual(
         set_time.calculate_time(3600).minute,
         datetime.utcnow().minute)
Example #2
0
 def enable_preference(self, user_preference, user_row_id):
     enable_preference_query = \
         "INSERT INTO user_preference (user_row_id, preference_type, communication_type, source, status, " \
         "created_on, updated_on) " \
         "VALUES(%s, %s, %s, %s, %s, %s, %s) " \
         "ON DUPLICATE KEY UPDATE status = %s, updated_on = %s"
     query_response = self._repo.execute(enable_preference_query, [
         user_row_id, user_preference.preference_type,
         user_preference.communication_type, user_preference.source,
         user_preference.status,
         dt.utcnow(),
         dt.utcnow(), user_preference.status,
         dt.utcnow()
     ])
     return query_response
Example #3
0
    def run_tests(self):
        iso = Isotope.Schema().load(self.isotope)
        iso.name = "{} - test - {}".format(iso.name, str(datetime.utcnow()))
        iso.save()
        db.session.commit()

        self.calibration['isotope']['id'] = iso.id
        test_add_calibration(self.client, data=self.calibration)

        self.study['isotope']['id'] = iso.id
        study = test_add(self.client, data=self.study)
        study_id = study['id']

        for file in os.listdir(os.getcwd()):
            if '.json' not in file:
                fp = os.path.join(os.getcwd(), file)

                data = {
                    'study_id': study_id,
                    'filename': file,
                    'file_type_id': 2,
                    'ordinal_value': 1,
                    'file': (open(fp, "rb"), file)
                }

                test_upload_file(self.client, data=data)

        test_analyze(self.client, _id=study_id)
        test_delete(self.client, _id=study_id)
Example #4
0
    async def check_inactive_channel(self, server_id: str, channel_id: str, timeout: int):
        channel = self.bot.get_channel(channel_id)
        if channel is None:
            print('timeout check: cannot find channel', channel_id)
            return

        server = channel.server

        has_permissions = channel.permissions_for(server.me).manage_channels
        if not has_permissions:
            print('no manage channel permissions, disabling', channel_id)
            self.settings.set_inactivity_monitor_channel(server_id, channel_id, 0)
            return

        now = datetime.utcnow()
        last_spoke_at = self.channel_last_spoke.get(channel.id)
        time_delta = (now - last_spoke_at).total_seconds() if last_spoke_at else 9999
        time_exceeded = time_delta > timeout

        if time_exceeded and not channel.name.endswith(INACTIVE):
            new_name = channel.name + INACTIVE
            try:
                await self.bot.edit_channel(channel, name=new_name)
            except Exception as ex:
                print('failed to edit channel: ' + str(ex))
Example #5
0
    def is_container_created(self, containername):
        httpVerb = "HEAD"
        algorithm = 'AWS4-HMAC-SHA256'
        service = "s3"
        aws_request = "aws4_request"
        aws_access_key_id = self.user  #
        aws_secret_access_key = self.passwd  # 
        endpoint_url = self.url  # 
        host = self.url.split("/")[-1]  # 
        region = "us-east-1"

        # Create a date for headers and the credential string
        t = datetime.utcnow()
        amzdate = t.strftime('%Y%m%dT%H%M%SZ')
        datestamp = t.strftime('%Y%m%d')  # Date w/o time, used in credential scope

        canonical_uri = "/" + containername

        canonical_headers = 'host:' + host + "\n"  # + "x-amz-date:"+ amzdate + "\n"

        signed_headers = "host"  # "host;x-amz-content-sha256;x-amz-date"

        credential_scope = datestamp + '/' + region + '/' + service + '/' + aws_request

        # canonical_querystring = bucket_name+"/"+object_name
        canonical_querystring = 'X-Amz-Algorithm=AWS4-HMAC-SHA256'
        canonical_querystring += '&X-Amz-Credential=' + urllib.parse.quote_plus(
            aws_access_key_id + '/' + credential_scope)
        canonical_querystring += '&X-Amz-Date=' + amzdate
        canonical_querystring += '&X-Amz-Expires=' + str(120)
        canonical_querystring += '&X-Amz-SignedHeaders=' + signed_headers

        payload_hash = "UNSIGNED-PAYLOAD"  # ???????? hashlib.sha256(("").encode("utf-8")).hexdigest()

        canonical_request = httpVerb + "\n" + canonical_uri + "\n" + canonical_querystring + "\n" + canonical_headers + '\n' + signed_headers + "\n" + payload_hash

        string_to_sign = algorithm + "\n" + amzdate + "\n" + credential_scope + "\n" + hashlib.sha256(
            canonical_request.encode("utf-8")).hexdigest()

        # Create the signing key
        signing_key = self.getSignatureKey(aws_secret_access_key, datestamp, region, service)

        # Sign the string_to_sign using the signing_key
        signature = hmac.new(signing_key, (string_to_sign).encode("utf-8"), hashlib.sha256).hexdigest()

        canonical_querystring += '&X-Amz-Signature=' + signature

        # print(f"Canonical request: \n{canonical_request}")
        # print(f"String to Sign: \n{string_to_sign}")

        url = endpoint_url + canonical_uri + "?" + canonical_querystring

        try:
            response = requests.head(url)
            if response.ok:
                return True
            return False
        except requests.exceptions.ConnectionError as ce:
            logging.error(ce.strerror)
            return False
Example #6
0
    async def mod_message_watchdog_user(self, message):
        user_id = message.author.id
        server_id = message.server.id
        watchdog_channel_id = self.settings.getWatchdogChannel(server_id)
        user_settings = self.settings.getWatchdogUsers(server_id).get(user_id)

        if user_settings is None:
            return

        cooldown = user_settings['cooldown']
        if cooldown <= 0:
            return

        request_user_id = user_settings['request_user_id']
        reason = user_settings['reason'] or 'no reason'

        request_user = message.server.get_member(request_user_id)
        request_user_txt = request_user.mention if request_user else '???'

        now = datetime.utcnow()
        last_spoke_at = self.server_user_last[server_id].get(user_id)
        self.server_user_last[server_id][user_id] = now
        time_since = (now - last_spoke_at).total_seconds() if last_spoke_at else 9999

        report = time_since > cooldown
        if not report:
            return

        output_msg = '**Watchdog:** {} spoke in {} ({} monitored because [{}])\n{}'.format(
            message.author.mention, message.channel.mention,
            request_user_txt, reason, box(message.clean_content))
        await self._watchdog_print(watchdog_channel_id, output_msg)
Example #7
0
class Server(db.Model):
    __tablename__ = 'server'
    id = db.Column(db.Integer, primary_key=True)
    hostname = db.Column(db.String(30), index=True, default='', unique=True)
    os = db.Column(db.String(50), index=True, nullable=True, default='')
    manufacturer = db.Column(db.String(100), nullable=True, default='')
    manufacture_date = db.Column(db.Date)
    server_model = db.Column(db.String(50), nullable=True)
    sn = db.Column(db.String(50), nullable=True, default='')
    uuid = db.Column(db.String(50), index=True, default='')
    cpu_count = db.Column(db.Integer, nullable=True, default='')
    cpu_model = db.Column(db.String(50), nullable=True, default='')
    memory_size = db.Column(db.Integer, nullable=True, default='')
    memory_slots_count = db.Column(db.Integer, nullable=True, default='')
    memory_slot_use = db.Column(db.Integer, nullable=True, default='')
    memory_slot_info = db.Column(db.Text, nullable=True, default='')
    disk_info = db.Column(db.Text, nullable=True, default='')
    nic_info = db.Column(db.Text, nullable=True, default='')
    last_op_time = db.Column(db.DateTime,
                             nullable=True,
                             default=datetime.utcnow())
    dev_interface = db.Column(db.Integer, nullable=True, default=0)
    is_vm = db.Column(db.Integer, index=True, nullable=True, default=0)
    status = db.Column(db.Integer, nullable=False, index=True, default=1)
    product_id = db.Column(db.Integer, db.ForeignKey('product.id'), default=0)
    ops_interface = db.Column(db.Integer,
                              db.ForeignKey('people.id'),
                              default=0)
    idc_id = db.Column(db.Integer, db.ForeignKey('idc.id'), default=0)
    people = db.relationship('People')
    product = db.relationship('Product')
    idc = db.relationship('Idc')
Example #8
0
def sync(config, state, catalog):
    """ Sync data from tap source """
    if not bool(state):
        state = state_hash()
    # Loop over selected streams in catalog
    for stream in catalog.get_selected_streams(state):
        LOGGER.info('Syncing stream:' + stream.tap_stream_id)

        singer.write_schema(
            stream_name=stream.tap_stream_id,
            schema=stream.schema.to_dict(),
            key_properties=stream.key_properties,
        )

        current_time = datetime.utcnow().isoformat(sep='T',
                                                   timespec='milliseconds')
        filter_datetime = state.get(stream.tap_stream_id,
                                    {}).get('last_synced',
                                            '1970-01-01T00:00:00.000')
        # Sync records via API
        api_sync.sync(stream.tap_stream_id, filter_datetime)
        state[stream.tap_stream_id] = {
            'synced': True,
            'last_synced': current_time
        }
        singer.write_state(state)
Example #9
0
 async def on_ready(self):
     LOGGER.info('Bot is ready.')
     self.start_time = datetime.utcnow()
     await self.change_presence(activity=discord.Game(name=config.PLAYING))
     # make mentionable.
     self.command_prefix.extend(
         [f'<@!{self.user.id}> ', f'<@{self.user.id}> '])
Example #10
0
    def post(self, request, *args, **kwargs):
        request_data = request.data
        if 'email' in request_data:
            request_data['email'] = request_data.get('email').lower()
        serializer = self.get_serializer(data=request_data,
                                         context={'request': request})

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user

            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)

            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    response.data['token'],
                                    expires=expiration,
                                    httponly=True)
            return response

        return Response({'message': 'Invalid Password'},
                        status=status.HTTP_400_BAD_REQUEST)
Example #11
0
class Book(db.Model):

    __tablename__ = 'book'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(500), nullable=False, index=True)
    author = db.Column(db.String(350))
    avg_rating = db.Column(db.Float)
    format = db.Column(db.String(50))
    image = db.Column(db.String(100), unique=True)
    num_pages = db.Column(db.Integer)
    pub_date = db.Column(db.DateTime, default=datetime.utcnow())

    # Relationship

    pub_id = db.Column(db.Integer, db.ForeignKey('publication.id'))

    def __init__(self, title, author, avg_rating, book_format, image,
                 num_pages, pub_id):

        self.title = title
        self.author = author
        self.avg_rating = avg_rating
        self.format = book_format
        self.image = image
        self.num_pages = num_pages
        self.pub_id = pub_id

    def __repr__(self):
        return '{} by {}'.format(self.title, self.author)
Example #12
0
def make_payload(user):
    print("make_payload")
    return {
        'id_usuario': user.id_usuario,
        'email': user.email,
        'exp': (datetime.utcnow()+ app.config['JWT_EXPIRATION_DELTA']).isoformat()
    }
Example #13
0
    async def mod_message_watchdog_phrase(self, message):
        server_id = message.server.id
        watchdog_channel_id = self.settings.getWatchdogChannel(server_id)

        for phrase_settings in self.settings.getWatchdogPhrases(server_id).values():
            name = phrase_settings['name']
            cooldown = phrase_settings['cooldown']
            request_user_id = phrase_settings['request_user_id']
            phrase = phrase_settings['phrase']

            if cooldown <= 0:
                continue

            now = datetime.utcnow()
            last_spoke_at = self.server_phrase_last[server_id].get(name)
            time_since = (now - last_spoke_at).total_seconds() if last_spoke_at else 9999

            report = time_since > cooldown
            if not report:
                continue

            p = re.compile(phrase, re.IGNORECASE | re.MULTILINE | re.DOTALL)
            if p.match(message.clean_content):
                self.server_phrase_last[server_id][name] = now
                output_msg = '**Watchdog:** {} spoke in {} `(rule [{}] matched phrase [{}])`\n{}'.format(
                    message.author.mention, message.channel.mention,
                    name, phrase, box(message.clean_content))
                await self._watchdog_print(watchdog_channel_id, output_msg)
                return
Example #14
0
    async def timer(self, ctx, hours: int, minutes: int, *, event: str):
        conn, c = await load_db()

        # format !events timer h m "event"
        dt = datetime.utcnow()
        td = timedelta(hours=hours, minutes=minutes)
        dt = dt + td

        while True:
            event_id = random.randint(1, 99999)
            event_exists = await self.check_if_event_exists(event_id)
            if not event_exists:
                dt_long, dt_short = await self.make_string(dt)
                with conn:
                    c.execute(
                        "INSERT INTO events VALUES(:id, :title, :datetime, :creator_id, :guild_id)",
                        {
                            'id': event_id,
                            'title': event,
                            'datetime': dt_long,
                            'creator_id': ctx.author.id,
                            'guild_id': ctx.guild.id
                        })
                embed = await self.embed_handler(ctx,
                                                 dt,
                                                 event,
                                                 event_id,
                                                 update=False)
                await ctx.send(embed=embed)
                fmt = (ctx.message.author, event, event_id, dt_long)
                msg = 'An event was created by {0}.\n{1} [{2}]\n{3}'.format(
                    *fmt)
                await self.spam(ctx, msg)
Example #15
0
    async def mirror_msg_new(self, message):
        if message.author.id == self.bot.user.id or message.channel.is_private:
            return

        channel = message.channel
        mirrored_channels = self.settings.get_mirrored_channels(channel.id)

        if not mirrored_channels:
            return

        last_spoke, last_spoke_timestamp = self.settings.get_last_spoke(channel.id)
        now_time = datetime.utcnow()
        last_spoke_time = datetime.utcfromtimestamp(
            last_spoke_timestamp) if last_spoke_timestamp else now_time
        attribution_required = last_spoke != message.author.id
        attribution_required |= (
            now_time - last_spoke_time).total_seconds() > ATTRIBUTION_TIME_SECONDS
        self.settings.set_last_spoke(channel.id, message.author.id)

        attachment_bytes = None
        if message.attachments:
            # If we know we're copying a message and that message has an attachment,
            # pre download it and reuse it for every upload.
            attachment = message.attachments[0]
            if 'url' and 'filename' in attachment:
                url = attachment['url']
                filename = attachment['filename']
                async with aiohttp.ClientSession() as session:
                    async with session.get(url) as response:
                        attachment_bytes = io.BytesIO(await response.read())

        for dest_channel_id in mirrored_channels:
            try:
                dest_channel = self.bot.get_channel(dest_channel_id)
                if not dest_channel:
                    continue

                if attribution_required:
                    msg = 'Posted by **{}** in *{} - #{}*:'.format(message.author.name,
                                                                   message.server.name,
                                                                   message.channel.name)
                    await self.bot.send_message(dest_channel, msg)

                if attachment_bytes:
                    dest_message = await self.bot.send_file(dest_channel, attachment_bytes, filename=filename, content=message.content)
                    attachment_bytes.seek(0)
                elif message.content:
                    dest_message = await self.bot.send_message(dest_channel, message.content)
                else:
                    print('Failed to mirror message from ', channel.id, 'no action to take')

                self.settings.add_mirrored_message(
                    channel.id, message.id, dest_channel.id, dest_message.id)
            except Exception as ex:
                print('Failed to mirror message from ', channel.id, 'to', dest_channel_id, ':', ex)
                traceback.print_exc()

        if attachment_bytes:
            attachment_bytes.close()
Example #16
0
    def formatStrikeDateAndDateTime(self, date):
        numArray = date.split("/")
        strikeMonth = numArray[0].lstrip('0')
        strikeDay = numArray[1].lstrip('0')
        currentMonth = str(datetime.utcnow().strftime("%m")).lstrip('0')
        currentYear = str(datetime.utcnow().strftime("%Y"))

        if (strikeMonth < currentMonth):
            currentYear = str(int(currentYear) + 1)

        self.strikeDate = date

        strikeMonth = re.sub('[^0-9]', '', strikeMonth)
        strikeDay = re.sub('[^0-9]', '', strikeDay)

        self.strikeDateTime = self.getDateTimeObjectFromStrikeDate(
            strikeDay, strikeMonth, currentYear)
    def onUpdate(self):

        self.root.title(str(datetime.utcnow()))

        for ele in self._elements:
            ele.render(self.__canvas)

        self.after(1000, self.onUpdate)
Example #18
0
class Userlog(db.Model):
    __tablename__ = "userlog"
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))  # 定义外键
    ip = db.Column(db.String(100))
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())

    def __repr__(self):
        return "<Userlog %r>" % self.id
Example #19
0
 def now():
     now = datetime.utcnow()
     return DatetimePayload(year=now.year,
                            month=now.month,
                            date=now.day,
                            hour=now.hour,
                            minute=now.minute,
                            second=now.second,
                            meridiem=now.strftime("%p"))
Example #20
0
class Preview(db.Model):
    __tablename__ = 'preview'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(128), unique=True)
    logo = db.Column(db.String(255), unique=True)
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())

    def __repr__(self):
        return '<Preview %r>' % self.title
Example #21
0
class Tag(db.Model):
    __tablename__ = "tag"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True)
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())
    movies = db.relationship("Movie", backref="tag")

    def __repr__(self):
        return "<Tag %r>" % self.id
Example #22
0
class Userlog(db.Model):
    __tablename__ = 'userlog'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属会员ID
    ip = db.Column(db.String(128))  # 登陆IP
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())

    def __repr__(self):
        return '<Userlog %r>' % self.id
Example #23
0
class Tag(db.Model):
    __tablename__ = 'tag'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128), unique=True)
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())
    movies = db.relationship('Movie', backref='tag')  # 电影外键关联

    def __repr__(self):
        return '<Tag %r>' % self.name
Example #24
0
class Auth(db.Model):
    __tablename__ = 'auth'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    url = db.Column(db.String(255), unique=True)
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())

    def __repr__(self):
        return '<Auth %r>' % self.name
Example #25
0
class Moviecol(db.Model):
    __tablename__ = 'moviecol'
    id = db.Column(db.Integer, primary_key=True)
    movie_id = db.Column(db.Integer, db.ForeignKey('movie.id'))  # 所属电影ID
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))  # 所属用户ID
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())

    def __repr__(self):
        return '<Moviecol %r>' % self.id
Example #26
0
 def register_user_data(self, user):
     """ register user data """
     user_data = self.get_user_data_for_given_username(
         username=user.username)
     if bool(user_data):
         raise UserAlreadyExistException()
     query_parameters = [
         user.email, "", user.origin, user.name, user.email,
         user.email_verified, user.email_verified, "", "",
         dt.utcnow(),
         dt.utcnow()
     ]
     query_response = self._repo.execute(
         "INSERT INTO user (username, account_id, origin, name, email, email_verified, status, request_id, "
         "request_time_epoch, row_created, row_updated) "
         "VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
         query_parameters)
     return "SUCCESS"
Example #27
0
class Role(db.Model):
    __talbename__ = 'role'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    auths = db.Column(db.String(512))
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())
    admins = db.relationship("Admin", backref='role')  # 管理员外键关系关联

    def __repr__(self):
        return '<Role %r>' % self.name
Example #28
0
class Role(db.Model):
    __tablename__ = "role"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True)
    auths = db.Column(db.String(600))
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())
    admins = db.relationship("Admin", backref="role")

    def __repr__(self):
        return "<Role %r" % self.id
Example #29
0
class Oplog(db.Model):
    __tablename__ = "oplog"
    id = db.Column(db.Integer, primary_key=True)
    admin_id = db.Column(db.Integer, db.ForeignKey("admin.id"))
    ip = db.Column(db.String(100))
    reason = db.Column(db.String(600))
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())

    def __repr__(self):
        return "<Oplog %r>" % self.id
Example #30
0
class Comment(db.Model):
    __tablename__ = "comment"
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text)
    movie_id = db.Column(db.Integer, db.ForeignKey("movie.id"))
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    addtime = db.Column(db.DateTime, index=True, default=datetime.utcnow())

    def __repr__(self):
        return "<Comment %r>" % self.id