Пример #1
0
def success(name, training):
    structure_dict = {}
    training_list = []
    response = table.scan(FilterExpression=Attr('student').eq(name))
    items = response['Items']

    if training:
        training_list.append('siarhei_beliakou/playpit-labs-' + training +
                             '/master')
    else:
        # Add all training list
        for i in items:
            training_list.append(i.get('training'))
        training_list = set(training_list)  # full training list

    for i in training_list:
        structure_dict[i] = {}
    # Add all module for each training
    for tn in structure_dict.keys():
        module_list = []
        module_dict = {}
        for i in items:
            if i.get('training') == tn:
                module_list.append(i.get('module'))
        module_list = set(module_list)  ## for training
        for i in module_list:
            module_dict[i] = {}
        structure_dict[tn] = module_dict

    # Add all task for each module for each training
    for tn in structure_dict.keys():
        for mn in structure_dict[tn]:
            task_dict = {}
            task_list = []
            for i in items:
                if i.get('module') == mn and i.get('training') == tn:
                    task_list.append(i.get('task'))
            taks_list = set(task_list)  ## for training
            for i in task_list:
                task_dict[i] = {}
            structure_dict[tn][mn] = task_dict

    # Add max score for each task
    for tn in structure_dict.keys():
        for mn in structure_dict[tn]:
            for ti in structure_dict[tn][mn]:
                score_list = []
                for i in items:
                    if i.get('module') == mn and i.get(
                            'training') == tn and i.get('task') == ti:
                        score_list.append(int(i.get('score')))
                score_list = max(score_list)
                structure_dict[tn][mn][ti] = score_list

    # Add max task value for each module
    for tn in structure_dict.keys():
        for mn in structure_dict[tn]:
            for i in items:
                if i.get('module') == mn and i.get('training') == tn:
                    task_max = int(i.get('task_max'))
            structure_dict[tn][mn]['task_max'] = task_max - 1

    module_list = sorted(module_list)
    training_name_stat = training_list[0]

    out_put_json = {name: {}}
    result_dict = {}
    for m in module_list:
        list_score_tasks = []
        for ti in structure_dict[training_name_stat][m]:
            if ti != 'task_max':
                list_score_tasks.append(
                    structure_dict[training_name_stat][m][ti])
        to_table = str(
            int(
                sum(list_score_tasks) /
                structure_dict[training_name_stat][m]['task_max']))
        result_dict[m] = to_table
    out_put_json[name] = result_dict
    to_send = out_put_json
    return jsonify(to_send)
Пример #2
0
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(flask.json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

app.json_encoder = DecimalEncoder

dataresponse = mocktable.scan(
           # AttributesToGet=('amount','areix_category','currency_code','made_on'),
            FilterExpression=Attr("amount").lte(0)
            )


def get_cashrebate(category):
    cash_rebate = cardresponse['Item']['benefits'][category]['cash_rebate']
    if cash_rebate != "None":
        cash_rebate = cash_rebate.split('%')
        cash_rebate = float(cash_rebate[0])/100
        return cash_rebate
    elif cash_rebate == "None":
        cash_rebate = 0
        return cash_rebate

def get_mile(category):
    
Пример #3
0
 def get_data_with_attr(self, key, attr):
     resp = self.table.scan(FilterExpression=Attr('Name').eq(key)
                            & Attr('Address').eq(attr))
     return resp['Items'][0]
Пример #4
0
import boto3
from boto3.dynamodb.conditions import Key, Attr
GATE_TABLE_PK = 'id'

store_id = 'store001'
date = '20200221'
STATUS_ENTER = 'enter'
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('SessionTable')

ke = Key(GATE_TABLE_PK).eq(store_id + '/' + date + '/' + STATUS_ENTER)
fe = Attr('isExited').eq(False)
response = table.query(KeyConditionExpression=ke, FilterExpression=fe)
print(response[u'Items'])
Пример #5
0
def handle(event, context):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table(config.dynamodb_table)

    now = int(calendar.timegm(time.gmtime()))

    # Read the blacklist of verses we've posted recently

    response = table.scan(
        FilterExpression=Attr('last_updated').gt(now - BLACKLIST_SECS))
    for i in response['Items']:
        print "Adding %s to blacklist (posted %.1f days ago)" % (
            i["verse"], (now - i["last_updated"]) / (60 * 60 * 24))
        BLACKLIST.add(i['verse'])

    # Read the XML verses file

    doc = None
    with open('proverbs.xml') as fd:
        doc = xmltodict.parse(fd.read())

    root = doc['bible']['b']['c']

    # Keep track of number of verses per chapter and the total number

    chapters = {}
    verses = 0

    for chapter in root:
        chapters[chapter["@n"]] = len(chapter["v"])
        verses += len(chapter["v"])

    # Pick a verse to post, skip duplicates and blacklisted verses

    while True:
        chapter_idx = random.randint(1, len(chapters))
        verse_idx = random.randint(1, len(root[chapter_idx - 1]['v']))
        verse_key = "%s:%s" % (chapter_idx, verse_idx)
        if verse_key not in BLACKLIST:
            break

    verse = root[chapter_idx - 1]['v'][verse_idx - 1]['#text']

    # Post to twitter

    new_status = "%s (Proverbs %s:%s NIV)" % (verse, chapter_idx, verse_idx)
    print("status: %s" % new_status)

    t = twitter.Twitter(
        auth=twitter.OAuth(config.access_key, config.access_secret,
                           config.consumer_key, config.consumer_secret))
    results = t.statuses.update(status=new_status)

    # Update DynamoDB with tinmestamp for the verse we just posted

    table.update_item(Key={
        "verse": "%s:%s" % (chapter_idx, verse_idx),
    },
                      UpdateExpression='SET last_updated = :val1',
                      ExpressionAttributeValues={
                          ':val1': now,
                      })

    return "OK"
from boto3.dynamodb.conditions import Key  # used when the condition is related to the key of the item.
from boto3.dynamodb.conditions import Attr  # used when the condition is related to an attribute
from _2_using_exist_table import table

print('------------------querying')
response = table.query(
    KeyConditionExpression=Key('username').eq('janedoe')
)
items = response['Items']
print(items)

print('------------------scanning')
response = table.scan(
    FilterExpression=Attr('age').lt(27)
)
items = response['Items']
print(items)

print('------------------multi condition')
response = table.scan(
    FilterExpression=Attr('first_name').begins_with('J') & Attr('account_type').eq('super_user')
)
items = response['Items']
print(items)

print('-----------------conditions of a nested attribute')
response = table.scan(
    FilterExpression=Attr('address.state').eq('CA')
)
items = response['Items']
print(items)
    def execute(self):
        def decimal_default(obj):
            if isinstance(obj, decimal.Decimal):
                return float(obj)
            raise TypeError

        self._logger_.info("{}, version {}",
                           str(self.__class__).split(".")[-1],
                           self.properties[ACTION_VERSION])
        self._logger_.debug("Implementation {}", __name__)

        self._logger_.info(INFO_EXPORTING_FROM, self.task_table)

        scanned_count = 0
        items_to_export = []
        last_export_time_ts = 0

        # fetch last_export_time after which when entries can be exported
        try:
            s3_get_client = get_client_with_retries("s3", ["get_object"],
                                                    context=self._context_,
                                                    session=self._session_,
                                                    logger=self._logger_)
            resp = s3_get_client.get_object_with_retries(
                Bucket=self.S3Bucket,
                Key=self.S3Prefix + LAST_EXPORT_KEY,
                _expected_boto3_exceptions_=["NoSuchKey"])
            last_export_time_ts = int(resp['Body'].read())
            self._logger_.info("last export time response {}",
                               last_export_time_ts)
        except ClientError:
            self._logger_.info(INFO_NO_TIME_FOUND)

        self._logger_.info(
            INFO_EXPORTING_AFTER,
            self._datetime_.fromtimestamp(last_export_time_ts).isoformat())

        #  status of to be exported items for scan expression
        export_status = [
            handlers.STATUS_COMPLETED, handlers.STATUS_FAILED,
            handlers.STATUS_TIMED_OUT
        ]
        table = self._session_.resource("dynamodb").Table(self.task_table)
        add_retry_methods_to_resource(table, ["scan"], context=self._context_)

        # noinspection PyPep8
        args = {
            "Select":
            "ALL_ATTRIBUTES",
            "FilterExpression":
            (Attr(handlers.TASK_TR_CREATED_TS).gt(last_export_time_ts).__or__(
                Attr(handlers.TASK_TR_UPDATED_TS).gt(last_export_time_ts))
             ).__and__(Attr(
                 handlers.TASK_TR_STATUS).is_in(export_status)).__and__(
                     Attr(handlers.TASK_TR_INTERNAL).eq(False))
        }
        self._logger_.debug("table.scan arguments {}", args)

        # scan for items to export
        while True:

            if self.time_out():
                break

            resp = table.scan_with_retries(**args)

            self._logger_.debug("table.scan result {}", resp)

            items_to_export += resp.get("Items", [])[:]
            scanned_count += resp["ScannedCount"]

            if "LastEvaluatedKey" in resp:
                args["ExclusiveStartKey"] = resp["LastEvaluatedKey"]
            else:
                break

        # set new export time
        export_str = ''
        last_export_time_ts = int(time())
        s3_put_client = get_client_with_retries("s3",
                                                methods=["put_object"],
                                                context=self._context_,
                                                session=self._session_,
                                                logger=self._logger_)

        # not a dryrun and any items to export were found
        if not self.dryrun and len(items_to_export) > 0:
            if len(items_to_export) > 0:
                self._logger_.debug("put_object items {}", items_to_export)
                for item in items_to_export:
                    export_str += json.dumps(dict(item),
                                             default=decimal_default,
                                             separators=(',', ':')) + '\n'
                last_export_time_dt = self._datetime_.fromtimestamp(
                    last_export_time_ts)
                export_object_key = EXPORT_OBJECT_KEY_TEMPLATE.format(
                    self.S3Prefix, last_export_time_dt.year,
                    last_export_time_dt.month, last_export_time_dt.day,
                    last_export_time_dt.hour, last_export_time_dt.minute)
                resp = s3_put_client.put_object_with_retries(
                    Bucket=self.S3Bucket,
                    Key=export_object_key,
                    Body=export_str)
                self._logger_.debug("put_object response {}", resp)

        # export new last_export_time to S3
        self._logger_.debug("put_object response {}", str(last_export_time_ts))
        resp = s3_put_client.put_object_with_retries(
            Bucket=self.S3Bucket,
            Key=self.S3Prefix + LAST_EXPORT_KEY,
            Body=str(last_export_time_ts))
        self._logger_.debug("put_object response {}", resp)

        return {
            "items-scanned": scanned_count,
            "items-exported": len(items_to_export)
        }
Пример #8
0
            print("Processing " + hb.BucketID())
            hb.ProcessEvent()
            nextEvent = hb.NextBucketStart()

            mb = aggregate.MinuteBucket(nextEvent, values)
            hb = aggregate.HourBucket(nextEvent, mb, values)

if sys.argv[1] == "migrateminutes":
    dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
    table = dynamodb.Table('EnergyMonitor.Minute')

    lastEvaluted = None
    while True:
        if lastEvaluted is None:
            response = table.scan(
                FilterExpression=Attr("bucket_id").contains("Z"),
                ProjectionExpression="bucket_id")
        else:
            response = table.scan(
                FilterExpression=Attr("bucket_id").contains("Z"),
                ProjectionExpression="bucket_id",
                ExclusiveStartKey=lastEvaluted)

        items = response['Items']

        for item in items:
            bucketToReAgg = item['bucket_id']
            print(bucketToReAgg)
            eventTime = datetime.strptime(
                bucketToReAgg, "%Y-%m-%dT%H:%MZ").replace(tzinfo=timezone.utc)
            values = {
    def handle(self, handler_input):
        slots = handler_input.request_envelope.request.intent.slots
        trash = slots['trash'].value
        attr = handler_input.attributes_manager.persistent_attributes

        if not attr:
            speech_text = "はじめに、収集エリアの設定を行います。おすまいの区を教えてください"
            card_title = "初期設定"
            card_body = "お住いの区を教えてください"
            reprompt = "おすまいの区を教えてください"

            handler_input.response_builder.speak(
                speech_text).ask(reprompt).set_card(
                    SimpleCard(card_title,
                               card_body)).set_should_end_session(False)
            return handler_input.response_builder.response

        if attr['ward_calno'] is not None:
            # 燃やせるゴミ
            if trash == '燃やせる' or trash == '燃える' or trash == '燃やせるゴミ' or trash == '燃えるゴミ' or trash == '可燃物' or trash == '可燃' or trash == '燃やせるごみ' or trash == '燃えるごみ':
                TrashNo = 1
            # 燃やせないゴミ,乾電池、ライター
            if trash == '燃やせない' or trash == '燃えない' or trash == '燃やせないゴミ' or trash == '燃えないゴミ' or trash == '不燃物' or trash == '不燃' or trash == '電池' or trash == '乾電池' or trash == 'ライター' or trash == '燃やせないごみ' or trash == '燃えないごみ':
                TrashNo = 2
            # プラ
            if trash == 'プラ' or trash == 'プラ容器' or trash == 'プラスチック' or trash == 'プラスティック' or trash == 'プラゴミ' or trash == '発泡スチロール' or trash == '発泡':
                TrashNo = 3
            # ビン、カン、ペット
            if trash == 'ペット' or trash == 'ペットボトル' or trash == 'びん' or trash == '缶' or trash == '空き缶' or trash == 'スチール缶' or trash == 'アルミ缶':
                TrashNo = 4
            # 雑がみ
            if trash == '雑がみ' or trash == '紙' or trash == '包装紙' or trash == '模造紙' or trash == 'レシート' or trash == '箱':
                TrashNo = 5
            # 枝、葉、草
            if trash == '枝' or trash == '葉っぱ' or trash == '葉' or trash == '草' or trash == '雑草' or trash == '枝葉':
                TrashNo = 6

        response = table.query(KeyConditionExpression=Key('WardCalNo').eq(
            attr['ward_calno']),
                               FilterExpression=Attr('TrashNo').eq(TrashNo))

        when = response['Items'][0]['Date']
        slicemonth = when[5:7]
        sliceday = when[8:10]
        monthday = str(slicemonth) + "月" + str(sliceday) + "日"

        date = datetime.datetime.strptime(when, '%Y-%m-%d')
        weekday = date.strftime("%A")
        if weekday == "Sunday":
            youbi = "日曜日"
        elif weekday == "Monday":
            youbi = "月曜日"
        elif weekday == "Tuesday":
            youbi = "火曜日"
        elif weekday == "Wednesday":
            youbi = "水曜日"
        elif weekday == "Thursday":
            youbi = "木曜日"
        elif weekday == "Friday":
            youbi = "金曜日"
        elif weekday == "Saturday":
            youbi = "土曜日"

        TrashNo = response['Items'][0]['TrashNo']

        if TrashNo == 1:
            jptrashname = '燃やせるごみ、スプレー缶類'
        elif TrashNo == 2:
            jptrashname = '燃やせないごみ、乾電池、ライター'
        elif TrashNo == 3:
            jptrashname = '容器プラ'
        elif TrashNo == 4:
            jptrashname = 'びん、缶、ペット'
        elif TrashNo == 5:
            jptrashname = '雑がみ'
        elif TrashNo == 6:
            jptrashname = '枝、葉、くさ'

        speech_text = "次の{}は、{}、{}です。".format(jptrashname, monthday, youbi)

        handler_input.response_builder.speak(speech_text).set_card(
            SimpleCard(jptrashname, monthday)).set_should_end_session(True)
        return handler_input.response_builder.response
Пример #10
0
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb', region_name='ap-southeast-1')
table = dynamodb.Table('table-name')

result_item = []
# Find item that does not contain value
result_data = table.scan(
    FilterExpression= ~Attr('item').contains("value1") & ~Attr('item').contains("value2") ,
)

#print result_data

result_item.extend(result_data['Items'])
print len(result_data['Items'])

while 'LastEvaluatedKey' in result_data:
    result_data = table.scan(
        FilterExpression= ~Attr('item').contains("value1") & ~Attr('item').contains("value2") ,
        ExclusiveStartKey=result_data['LastEvaluatedKey']
    )
    result_item.extend(result_data['Items'])

Пример #11
0
def get_all_usernames():
    table = dynamodb_resource.Table(profile_table_name)
    response = table.scan(
        FilterExpression=Attr("ScanUntil").gt(int(time.time())))
    return response['Items']
        "header-customerRegion": "SP",
        "header-supplierRegion": "SP",
        "header-customerClassification": "Revendedor",
        "header-freightType": "CIF",
        "header-paymentCondition": "28",
        "item-externalProductID": "none",
        "item-ncm": "none"
    }
}

# BOXTER
# scanFilter = Attr('accountID').eq('ca5c091c-889f-4804-8284-e0e9db251c93') & Attr('externalProductID').exists()
# scanFilter = Attr('accountID').eq('ca5c091c-889f-4804-8284-e0e9db251c93') & Attr('externalProductID').eq('12.01.01.001')

# FIT
scanFilter = Attr('accountID').eq('26a83fe1-f868-4a68-9f68-8e2cf622b2bb') & Attr('externalProductID').exists()
# scanFilter = Attr('accountID').eq('26a83fe1-f868-4a68-9f68-8e2cf622b2bb') & Attr('externalProductID').eq('12.01.01.001')

session = boto3.Session(profile_name='tangotech')
dynamodb = session.resource('dynamodb')
productsTable = dynamodb.Table('productsDB-livetplug')

response = productsTable.scan(FilterExpression=scanFilter)
products = response['Items']

if products:
    for product in products:
        if product['externalProductID']:
            dataInput['obligatoryData']['item-externalProductID'] = product['externalProductID']  
        
        if product['ncm']:
Пример #13
0
def lambda_handler(event, context):
    # TODO implement
    #print(event)
    matchid = event['MatchId']
    registeration_fee = event['Fee']
    limit_on_players  = event['limit'] #To set the limit on the number of players
    
    #print(type(matchid))
    dynamodb = boto3.resource('dynamodb') 
    match_table = dynamodb.Table('dr11-publicmatch') 
    matchResponse  = match_table.scan( 
        FilterExpression = Attr('MatchId').eq(str(matchid)) 
    ) 
    Date =  matchResponse['Items'][0]['Date']
    Hours =  matchResponse['Items'][0]['Hours']
    Minutes =  matchResponse['Items'][0]['Minutes']
    team1 =  matchResponse['Items'][0]['Team'] 
    team2 =  matchResponse['Items'][0]['Team2'] 
    leagueid = matchResponse['Items'][0]['LeagueId'] 
    status = matchResponse['Items'][0]['Status'] 
    count = 0
    team1_list =  matchResponse['Items'][0]['Team1 Players']
    myteam1 = set()
    for i in range(len(team1_list)):
        myteam1.add(team1_list[i])
            
    team2_list =  matchResponse['Items'][0]['Team2 Players']
    myteam2 = set()
    for i in range(len(team2_list)):
        myteam2.add(team2_list[i])
        
    print(myteam1)
    print(myteam2)
    #print(matchResponse)
   
    dynamodb1 = boto3.resource('dynamodb') 
    match_table1 = dynamodb1.Table('dr11-privatematch') 
    LeagueId = leagueid
    MatchId = matchid
    Fee = registeration_fee
    Team1 = team1
    Team2 = team2
    #new_list = old_list.copy()
    #new_list = list(old_list)
    #Team1_Players = []
    #Team1_Players = team1_list.copy()
    #print(Team1_Players)
    #Team2_Players = []
    #Team2_Players = team2_list.copy()
    #print(Team2_Players)
    priid = str(random.randint(1, 10000))
    
    response = match_table1.put_item(
     Item={
        'LeagueId': LeagueId,
        'MatchId': MatchId,
        'Fee' : Fee,
        'Team1' : Team1,
        'Team2' : Team2,
        'Status':status,
        'count1':str(count),
        'limit':limit_on_players,
        'PrivateId':priid,
        'Date':Date,
        'Hours':Hours,
        'Minutes':Minutes

    }
   )
    print(response)
    return {
        'statusCode': 200,
        'body': json.dumps('')
    }
Пример #14
0
def find_user(intent, session):
    session_attributes = {}

    # Get First Name from Intent and create first name variations for searching
    if "First_Name" in intent["slots"]:
        first_name_alexa = intent["slots"]["First_Name"]["value"]
        first_name_alexa_lc = first_name_alexa.lower()
        first_name_two_letters = first_name_alexa_lc[0:2]
        first_name_first_letter = first_name_alexa_lc[0:1]

    # Get Last Name from Intent and create last name variations for searching
    if "Last_Name" in intent["slots"]:
        last_name_alexa = intent["slots"]["Last_Name"]["value"]
        last_name_alexa_lc = last_name_alexa.lower()
        last_name_two_letters = last_name_alexa_lc[0:2]
        last_name_first_letter = last_name_alexa_lc[0:1]

    # Query the table to look for name matches starting with highest probability search and
    # decreasing probability with subsequent searches

    if "First_Name" in intent["slots"] and "Last_Name" in intent["slots"]:
        dbresponse = table.query(
            TableName=table_name,
            IndexName=index_name,
            KeyConditionExpression=Key('First_Name').eq(first_name_alexa_lc)
            & Key('Last_Name').eq(last_name_alexa_lc),
        )

        if dbresponse['Count'] == 0:
            dbresponse = table.scan(
                TableName=table_name,
                IndexName=index_name,
                FilterExpression=Key('First_Name').eq(first_name_alexa_lc)
                & Attr('Last_Name').begins_with(last_name_two_letters),
            )

            if dbresponse['Count'] == 0:
                dbresponse = table.scan(
                    TableName=table_name,
                    IndexName=index_name,
                    FilterExpression=Attr('First_Name').begins_with(
                        first_name_two_letters)
                    & Attr('Last_Name').begins_with(last_name_two_letters),
                )

                if dbresponse['Count'] == 0:
                    dbresponse = table.scan(
                        TableName=table_name,
                        IndexName=index_name,
                        FilterExpression=Attr('First_Name').begins_with(
                            first_name_two_letters) &
                        Attr('Last_Name').begins_with(last_name_first_letter),
                    )

                    if dbresponse['Count'] == 0:
                        dbresponse = table.scan(
                            TableName=table_name,
                            IndexName=index_name,
                            FilterExpression=Attr('First_Name').begins_with(
                                first_name_first_letter)
                            & Attr('Last_Name').begins_with(
                                last_name_two_letters),
                        )

                        if dbresponse['Count'] == 0:
                            dbresponse = table.query(
                                TableName=table_name,
                                IndexName=index_name,
                                KeyConditionExpression=Key('First_Name').eq(
                                    first_name_alexa_lc),
                            )

                            if dbresponse['Count'] == 0:
                                dbresponse = table.scan(
                                    TableName=table_name,
                                    IndexName=index_name,
                                    FilterExpression=Attr('Last_Name').eq(
                                        last_name_alexa_lc),
                                )

                                if dbresponse['Count'] == 0:
                                    dbresponse = table.scan(
                                        TableName=table_name,
                                        IndexName=index_name,
                                        FilterExpression=Attr('First_Name').
                                        begins_with(first_name_first_letter)
                                        & Attr('Last_Name').begins_with(
                                            last_name_first_letter),
                                    )

                                    if dbresponse['Count'] == 0:

                                        return no_user_found()

        if dbresponse['Count'] == 1:

            # Find Office ID in database associated with the first name
            global office_id
            global first_name_db
            global last_name_db
            office_id = dbresponse[u'Items'][0][u'Office']
            first_name_db = dbresponse[u'Items'][0][u'First_Name']
            last_name_db = dbresponse[u'Items'][0][u'Last_Name']

            return ask_for_confirmation(first_name_db, last_name_db, office_id)

        else:

            return multi_user_found()

    elif "First_Name" in intent["slots"] and not "Last_Name" in intent["slots"]:
        dbresponse = table.query(
            TableName=table_name,
            IndexName=index_name,
            KeyConditionExpression=Key('First_Name').eq(first_name_alexa_lc),
        )

        if dbresponse['Count'] == 0:
            dbresponse = table.scan(
                TableName=table_name,
                IndexName=index_name,
                FilterExpression=Attr('First_Name').begins_with(
                    first_name_two_letters),
            )

            if dbresponse['Count'] == 0:
                dbresponse = table.scan(
                    TableName=table_name,
                    IndexName=index_name,
                    FilterExpression=Attr('First_Name').begins_with(
                        first_name_first_letter),
                )

                if dbresponse['Count'] == 0:
                    return no_user_found()

        if dbresponse['Count'] == 1:
            # Find Office ID in database associated with the first name
            office_id = dbresponse[u'Items'][0][u'Office']
            first_name_db = dbresponse[u'Items'][0][u'First_Name']
            last_name_db = dbresponse[u'Items'][0][u'Last_Name']

            return ask_for_confirmation(first_name_db, last_name_db, office_id)

        else:

            return multi_user_found()

    elif "Last_Name" in intent["slots"] and not "First_Name" in intent["slots"]:
        dbresponse = table.query(
            TableName=table_name,
            IndexName=index_name,
            KeyConditionExpression=Key('Last_Name').eq(last_name_alexa_lc),
        )

        if dbresponse['Count'] == 0:
            dbresponse = table.scan(
                TableName=table_name,
                IndexName=index_name,
                FilterExpression=Attr('Last_Name').begins_with(
                    last_name_two_letters),
            )

            if dbresponse['Count'] == 0:
                dbresponse = table.scan(
                    TableName=table_name,
                    IndexName=index_name,
                    FilterExpression=Attr('Last_Name').begins_with(
                        last_name_first_letter),
                )

                if dbresponse['Count'] == 0:

                    return no_user_found()

        if dbresponse['Count'] == 1:
            # Find Office ID in database associated with the first name
            office_id = dbresponse[u'Items'][0][u'Office']
            first_name_db = dbresponse[u'Items'][0][u'First_Name']
            last_name_db = dbresponse[u'Items'][0][u'Last_Name']

            return ask_for_confirmation(first_name_db, last_name_db, office_id)

        else:

            return multi_user_found()

    else:

        return no_user_found()
Пример #15
0
def user_scores(username):
    table = get_scores_table()

    response = table.scan(FilterExpression=Attr('username').eq(username))

    return {'code': 'success', 'results': response['Items']}
Пример #16
0
import boto3
import json
from boto3.dynamodb.conditions import Key, Attr
import pandas as pd

import numpy as np
import pandas as pd
import scipy

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('wi_table')
response = table.scan(
    FilterExpression=Attr('timestamp').begins_with('2020-05-06')
    & Attr('object').eq('PET') & Attr('robot').eq('R19'))
items = response['Items']
print(items[0])
timestamp = []
for i in range(len(items)):

    x = items[i]
    x_ts = x.get('timestamp')
    x_ts = x_ts.split(' ')
    x_ts = x_ts[1]
    timestamp.append(x_ts)
print(timestamp)

timestamp_col = {'timestamp': timestamp}
df = pd.DataFrame(timestamp)
print(df.min())
print(df.max())
Пример #17
0
    def upsert_user_in_supplier(self, supplier_id, obj):
        """
        Add or update a new or existing user in a supplier object
        """

        # checks
        attributes = ["email", "name", "role"]
        for key in list(obj.keys()):
            if key not in attributes:
                del obj[key]

        for key, val in obj.items():
            if type(val) != str:    # all are strings
                raise BadParameters

        for key in attributes:
            if key not in obj:
                raise MissingRequiredKey(key)

        # get supplier obj
        supplier = self._storage.get('brewoptix-suppliers', supplier_id)
        if supplier:
            supplier = clean(supplier)
        else:
            raise NoSuchEntity

        if not self.is_current_user_admin(supplier_id):
            raise NotAnAdminUser

        name = obj["name"]
        email = obj["email"]

        # get by user email
        query = {
            'KeyConditionExpression': Key('email').eq(email),
            'FilterExpression':
                Attr('latest').eq(True) & Attr('active').eq(True),
            'IndexName': 'by_email'
        }

        users_resp = self._storage.get_items("brewoptix-users", query)

        user_is_new = True

        # if exists get user_id and add to supplier data
        if users_resp['Count'] > 0:
            user = users_resp['Items'][0]
            user_obj = clean(user)
            user_id = user_obj["entity_id"]
            user_is_new = False
        else:
            # get Machine-to-machine access token
            resp = requests.post(
                os.environ['AUTH0_DOMAIN'] + '/oauth/token',
                json={
                    'grant_type': 'client_credentials',
                    'client_id': os.environ['AUTH0_MANAGEMENT_API_CLIENT_ID'],
                    'client_secret': os.environ['AUTH0_MANAGEMENT_API_CLIENT_SECRET'],
                    'audience': os.environ['AUTH0_AUDIENCE'],
                    'scope': 'create:users'
                },
                headers={
                    'content-type': "application/json"
                }

            )

            body = resp.json()

            if all(k in body for k in [
                'access_token',
                'scope',
                'expires_in',
                'token_type'
            ]):
                pass  # to the next section of code
            elif 'error_description' in body:
                raise Auth0UnknownError(body['error_description'])
            else:
                raise Auth0UnableToAccess

            access_token = body['access_token']

            resp = requests.post(
                os.environ['AUTH0_DOMAIN'] + "/api/v2/users",
                json={
                    'email': email,
                    'name': name,
                    'password': generate_random_password(),
                    'email_verified': True,
                    'blocked': False,
                    'connection': os.environ['AUTH0_CONNECTION'],
                },
                headers={
                    'Authorization': 'Bearer {TOKEN}'.format(TOKEN=access_token),
                    'content-type': "application/json"
                })

            body = resp.json()
            print(body)

            if 'statusCode' in body and body['statusCode'] != 201 and 'error' in body:
                raise Auth0UnknownError(body['message'])

            if all(k in body for k in [
                'user_id',
                'email'
            ]):
                user_id = body['user_id'][6:]

            # else create user (in auth0 using management API)
            for _ in range(1000):
                affiliate_id = generate_affiliate_id()

                query = {
                    'KeyConditionExpression':
                        Key('affiliate_id').eq(affiliate_id),
                    'IndexName': 'by_affiliate_id'
                }

                response = self._storage.get_items("brewoptix-users", query)

                if response['Count'] <= 0:
                    break

            name_parts = name.split(" ")
            if len(name_parts) >= 2:
                firstname = name_parts[0]
                lastname = name_parts[1]
            else:
                firstname = name_parts[0]
                lastname = ""

            user_obj = {
                'entity_id': user_id,
                'user_id': user_id,
                'firstname': firstname,
                'lastname': lastname,
                'email': email,
                'affiliate_id': affiliate_id
            }

            user_obj = self._storage.save("brewoptix-users", user_obj)
            self.sns_publish("users", user_obj)  # publish notification

        # save supplier obj
        if "users" not in supplier:
            supplier["users"] = []

        user_info_obj = {
            "user_id": user_id,
            "name": obj["name"],
            "role": obj["role"],
            "email": obj["email"]
        }

        user_exists = False
        existing_user_index = 0
        for i, user in enumerate(supplier["users"]):
            if user["user_id"] == user_id:
                # user already there in suppliers
                user_exists = True
                existing_user_index = i
                break

        if user_exists:
            supplier["users"][existing_user_index] = user_info_obj
        else:
            supplier["users"].append(user_info_obj)

        supplier_obj = self._storage.save("brewoptix-suppliers", supplier)
        self.sns_publish("suppliers", supplier)  # publish notification

        self.add_supplier_to_app_metadata(supplier_id, obj["role"], user_id=user_id)

        if user_is_new:
            self._auth0.trigger_password_reset(obj["email"])

        return user_info_obj
#item is a dictionary, with family member as the key. Let's get the value from the item returned.
fact = item['fact']
print("The fact is " + fact)

# Let's put an item into the PozFamily table.

table.put_item(
  Item={
        'family_member': 'Tyler',
        'fact': 'Tyler is a Hokie!',
    }
)
"""

# Find all of the facts about Tyler
response = table.scan(FilterExpression=Attr('family_member').eq('Tyler'))
items = response['Items']
print(items)
#
# let's extract some of the items
print("family member is " + items[0]['family_member'])
print("family fact is " + items[0]['fact'])

#
# Let's use a scan and get all of the family facts that exist.
#
response = table.scan()
items = response['Items']
print items
# Get the number of facts returned, which would be the size of the list.
print(type(items))
Пример #19
0
def get_ddb_data(esk=None, profile_match_only=False, image_id='', hash_keys_only=False):

    get_ddb_data_logger = logging.getLogger('aws_utils.get_ddb_data')
    get_ddb_data_logger.info("In get_ddb_data ...")
    
    dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
    table = dynamodb.Table("cerebro_media")

    if profile_match_only:
        fe = Attr('profile_matched').exists()
    elif image_id:
        fe = Key('external_image_id').eq(str(image_id))
    else:
        fe = None
    #fe = Key('profile').begins_with("serena");

    if hash_keys_only:
        #
        pe = "#external_image_id, #epoch"
        # Expression Attribute Names for Projection Expression only.
        ean = { "#external_image_id": "external_image_id", "#epoch": "epoch" }
    else:
        pe = None
        ean = None

        # defaults if needed
        '''
        pe = "#epoch, #current_time, #external_image_id, #profile"
        # Expression Attribute Names for Projection Expression only.
        ean = { "#epoch": "epoch", "#current_time": "current_time", "#external_image_id": "external_image_id", "#profile": "profile" }
        '''

    if esk:
        if fe and not (pe or ean):
            scanned_data = table.scan(
                FilterExpression=fe,
                ExclusiveStartKey=esk
                )
        elif fe and (pe and ean):
            scanned_data = table.scan(
                FilterExpression=fe,
                ProjectionExpression=pe,
                ExpressionAttributeNames=ean,                
                ExclusiveStartKey=esk
                )            
        else:
            scanned_data = table.scan(
                ExclusiveStartKey=esk
                )            
    else:
        if fe and not (pe or ean):
            scanned_data = table.scan(
                FilterExpression=fe
                )
        elif fe and (pe and ean):
            scanned_data = table.scan(
                FilterExpression=fe,
                ProjectionExpression=pe,
                ExpressionAttributeNames=ean
                )            
        else:
            scanned_data = table.scan(
                )            

    return scanned_data, table
def get_messages(id):
    chats = boto3.resource('dynamodb').Table('chats')
    result = chats.scan(FilterExpression=Attr('id').eq(id))
    items = result.get('Items', [])
    return flask.make_response(json.dumps(items), 200,
                               {'Content-Type': 'application/json'})
Пример #21
0
        playerDict['Date'] = currentDate.strftime('%m/%d/%Y')
        playerDict['Status'] = players['status']
        playersList.append(playerDict)

if not playersList:
    print('No data today!')

else:

# Grab Past Week Info

    dynamodb = boto3.resource('dynamodb',aws_access_key_id=accessKey, aws_secret_access_key=secretKey, region_name='us-east-2')

    dytable = dynamodb.Table('WatchListPlayers')

    response = dytable.scan(FilterExpression=Attr("Date").gt(oneWeekAgo))

    items = response['Items']
    last_weeks_players = [x['Name'] for x in items]
    count_wk_players = []
    for x in set(last_weeks_players):
        wk_dict = dict()
        wk_dict['Player'] = x
        wk_dict['Count'] = last_weeks_players.count(x)
        count_wk_players.append(wk_dict)

# Combine dictionaries

    index_by_player = {d['Player']: d['Count'] for d in count_wk_players}

    for d in playersList:
Пример #22
0
 def run_query(entity_id, **kwargs):
     return self._client.Table(self._table).query(
         KeyConditionExpression=Key('entity_id').eq(entity_id),
         FilterExpression=Attr('latest').eq(True)
         & Attr('active').eq(True),
         **kwargs)
Пример #23
0
def wallet_transfer(event, context):
    user_wallet_table = boto3.resource('dynamodb').Table(
        os.environ['USER_WALLET_TABLE'])
    history_table = boto3.resource('dynamodb').Table(
        os.environ['PAYMENT_HISTORY_TABLE'])
    body = json.loads(event['body'])

    try:
        from_wallet = user_wallet_table.update_item(
            ExpressionAttributeNames={
                '#A': 'amount',
            },
            ExpressionAttributeValues={
                ':a': body['transferAmount'],
            },
            Key={
                'userId': body['fromUserId'],
            },
            ReturnValues='ALL_NEW',
            UpdateExpression='SET #A = #A - :a',
            ConditionExpression=Attr('amount').gte(0),
        )
        # ConditionalCheckFailed
    except Exception as e:
        print(e)
        return {
            'statusCode': 400,
            'body': json.dumps({'errorMessage': 'There was not enough money.'})
        }

    to_wallet = user_wallet_table.update_item(
        ExpressionAttributeNames={
            '#A': 'amount',
        },
        ExpressionAttributeValues={
            ':a': body['transferAmount'],
        },
        Key={
            'userId': body['toUserId'],
        },
        ReturnValues='ALL_NEW',
        UpdateExpression='SET #A = #A + :a',
    )

    history_table.put_item(
        Item={
            'walletId': from_wallet['Attributes']['walletId'],
            'transactionId': body['transactionId'],
            'useAmount': body['transferAmount'],
            'locationId': body['locationId'],
            'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        })
    history_table.put_item(
        Item={
            'walletId': to_wallet['Attributes']['walletId'],
            'transactionId': body['transactionId'],
            'chargeAmount': body['transferAmount'],
            'locationId': body['locationId'],
            'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        })
    requests.post(os.environ['NOTIFICATION_ENDPOINT'],
                  json={
                      'transactionId': body['transactionId'],
                      'userId': body['fromUserId'],
                      'useAmount': body['transferAmount'],
                      'totalAmount': int(from_wallet['Attributes']['amount']),
                      'transferTo': body['toUserId']
                  })
    requests.post(os.environ['NOTIFICATION_ENDPOINT'],
                  json={
                      'transactionId': body['transactionId'],
                      'userId': body['toUserId'],
                      'chargeAmount': body['transferAmount'],
                      'totalAmount': int(to_wallet['Attributes']['amount']),
                      'transferFrom': body['fromUserId']
                  })

    return {
        'statusCode':
        202,
        'body':
        json.dumps({'result': 'Accepted. Please wait for the notification.'})
    }
Пример #24
0
 def get_all_items(self, obj_type, **kwargs):
     return self._client.Table(self._table).scan(
         FilterExpression=Attr('latest').eq(True) & Attr('active').eq(True)
         & Attr('obj_type').eq(obj_type),
         **kwargs)
Пример #25
0
def lambda_handler(event, context):

    #
    # To do: Run all rule from this type, run only single rule from this type
    #
    #

    # Initialize iterator used in bulk load.
    esBulkMessagesGv = []
    esBulkComplianceMessagesGv = []

    # Mark start of function execution.
    timerDict = {}
    timerDict["lambda_handler : Started Processing"] = int(time.time())
    consoleLog(
        "lambda_handler : Started Processing @ {0} {1}:{2}:{3}".format(
            datetime.now().strftime("%Y-%m-%d"),
            datetime.now().hour,
            datetime.now().minute,
            datetime.now().second), "INFO", esLogLevelGv)

    # If any errors are found reading environment variables, don't continue.
    if configError == True:
        consoleLog(
            "lambda_handler : Not executing, configuration error detected.",
            "ERROR", esLogLevelGv)
        return

    # Connect to Elasticsearch
    esClient = connectES(esEndPointEv)
    consoleLog("lambda_handler : Elasticsearch connection.", "DEBUG",
               esLogLevelGv)

    # Connect to DynamoDB
    dynamodb_client = boto3.resource('dynamodb')
    dynamodb_table = dynamodb_client.Table(DynamoDBname)
    consoleLog(
        "Dynamo table MonitorLizard status = " + dynamodb_table.table_status,
        "DEBUG", esLogLevelGv)

    # Connect to SNS
    sns = boto3.client('sns')

    if TEST_SNS:
        response = sns.publish(
            TopicArn=SnsTopicArn,
            Message='Test message from Monitor Lizard',
        )
        consoleLog("Sent test SNS message.", "INFO", esLogLevelGv)
        return

    #
    # Execute rules of type "Login anomaly"
    #

    consoleLog("Executing rule type " + RuleType, "INFO", esLogLevelGv)

    response = dynamodb_table.scan(
        FilterExpression=Attr('RuleType').eq(RuleType))

    if len(TEST_RULE):
        print("Executing TEST_RULE only ")
        runRule(esClient, dynamodb_table, sns, TEST_RULE, RuleType)
        return

    for Rule in response["Items"]:
        print()

        if not Rule["RuleActive"]:
            print(
                "Skipping SIEM rule because rule has been deactivated (RuleActive=false)"
            )
            continue

        if Rule["LastRun"] + (Rule["RunScheduleInMinutes"] * 60) < int(
                time.time()):

            print("Executing rule: " + Rule["RuleId"])

            runRule(esClient, dynamodb_table, sns, Rule["RuleId"],
                    Rule["RuleType"])

            # Updateing SIEM rule last run time stamp
            response = dynamodb_table.update_item(
                Key={
                    'RuleId': Rule["RuleId"],
                    'RuleType': Rule["RuleType"]
                },
                UpdateExpression="set LastRun=:l",
                ExpressionAttributeValues={':l': int(time.time())},
                ReturnValues="UPDATED_NEW")
        else:
            print("--------------------------")

            if (TEST_IGNORE_LASTRUN):
                runRule(esClient, dynamodb_table, sns, Rule["RuleId"],
                        Rule["RuleType"])
            else:
                print("Skipping SIEM rule because of LastRun setting: " +
                      Rule["RuleId"])

    return {'statusCode': 200, 'body': json.dumps("ok")}
Пример #26
0
def grab_jobs(tag):
    table = dynamodb.Table('jobs')
    response = table.scan(
        FilterExpression=Attr('tags').contains(tag)
    )
    return response['Items']
Пример #27
0
def calculation(psid,product_id):
    dataresponse = mocktable.query(
    KeyConditionExpression=Key('psid').eq(psid),
    ProjectionExpression='amount, areix_category, currency_code, made_on',
    FilterExpression=Attr("amount").lte(0))
    global cardresponse
    cardresponse = cardinfotable.get_item(
            Key={
                'product_id': product_id,
        }
        )
    data = pd.DataFrame(dataresponse['Items'])
    #data.drop(columns=['mode', 'psid','Created_at','account_id','account_name','category','mode','provider_name','status','transaction_id','updated_at','description'])

    day = []
    week = []
    month = []
    quarter = []
    year = []

    for i in data['made_on']:
        day.append(i)
        a = i.split('-')
        y = a[0]
        year.append(y)
        m = date(int(y), int(a[1]), 1).strftime('%b')
        w = date(int(a[0]), int(a[1]), int(a[2])).isocalendar()[1]
        week.append('W'+str(w)+' '+m+' '+y)
        month.append(m + ' '+ y)
        quarter.append('Q'+str(math.ceil(int(a[1])/3))+' '+y)
        
    data['Week'],data['Date'],data['Month'],data['Quarter'],data['Year'],data['Cash Rebate'],data['Asia Mile ($)'],data['Total']=[week,day,month,quarter,year,np.nan,np.nan,np.nan]

        ######Calculating rewards
    for i in range(data.shape[0]):
        category = data.iloc[i]["areix_category"]

        #if data.iloc[i]["currency_code"] != "HKD":
         #   local = "Local"
        #else:
         #   local = "Overseas"
        
        data.at[i,'Cash Rebate'] = -(get_cashrebate(category)*float(data.iloc[i]["amount"]))
        data.at[i,'Asia Mile ($)'] = -(get_mile(category)*float(data.iloc[i]["amount"]))
        data.at[i,'Total'] = data.iloc[i]["Cash Rebate"] + data.iloc[i]["Asia Mile ($)"]
        
    datesorted_df = data.sort_values(by='Date')
    
    dodsavedamount = pd.pivot_table(data,index=['Date','areix_category'], values=['Total'],aggfunc=np.sum)
    dodsavedamount = dodsavedamount.to_dict()['Total']
    def dict_val():
        return {'Dining & Beverage':0.0,'Financials':0,'Healthcare':0.0,'Home':0.0,'Leisure':0.0,'Others':0.0,'Shopping':0.0,'Transportation':0.0,'Sum':0.0}
    dodres = defaultdict(dict_val)
    for i,j in dodsavedamount.items():
        dodres[i[0]][i[1]] = j
        dodres[i[0]]['Sum'] += j    

    
    wowsavedamount = pd.pivot_table(data,index=['Week','areix_category'], values=['Total'],aggfunc=np.sum)
    wowsavedamount = wowsavedamount.to_dict()['Total']    
    wowres = defaultdict(dict_val)
    for i,j in wowsavedamount.items():
        wowres[i[0]][i[1]] = j
        wowres[i[0]]['Sum'] += j    

    
    momsavedamount = pd.pivot_table(data,index=['Month','areix_category'], values=['Total'],aggfunc=np.sum)
    momsavedamount = momsavedamount.to_dict()['Total']    
    momres = defaultdict(dict_val)
    for i,j in momsavedamount.items():
        momres[i[0]][i[1]] = j
        momres[i[0]]['Sum'] += j    

    
    qoqsavedamount = pd.pivot_table(data,index=['Quarter','areix_category'], values=['Total'],aggfunc=np.sum)
    qoqsavedamount = qoqsavedamount.to_dict()['Total']    
    qoqres = defaultdict(dict_val)
    for i,j in qoqsavedamount.items():
        qoqres[i[0]][i[1]] = j
        qoqres[i[0]]['Sum'] += j    

    
    yoysavedamount = pd.pivot_table(data,index=['Year','areix_category'], values=['Total'],aggfunc=np.sum)
    yoysavedamount = yoysavedamount.to_dict()['Total']    
    yoyres = defaultdict(dict_val)
    for i,j in yoysavedamount.items():
        yoyres[i[0]][i[1]] = j
        yoyres[i[0]]['Sum'] += j    
    output ={}
    output['dod'],output['wow'],output['mom'],output['qoq'],output['yoy'] = dodres,wowres,momres,qoqres,yoyres

    return output
Пример #28
0
def end_raid_provider_association_handler(event, context):
    """
    End a provider association to a RAiD
    :param event:
    :param context:
    :return:
    """
    try:
        raid_handle = urllib.unquote(urllib.unquote(event["pathParameters"]["raidId"]))

    except:
        logger.error('Unable to validate RAiD parameter: {}'.format(sys.exc_info()[0]))
        return web_helpers.generate_web_body_response(
            '400',
            {'message': "Incorrect path parameter type formatting for RAiD handle. Ensure it is a URL encoded string"},
            event
        )

    try:
        environment = event['requestContext']['authorizer']['environment']

        # Initialise DynamoDB
        dynamo_db = boto3.resource('dynamodb')
        raid_table = dynamo_db.Table(settings.get_environment_table(settings.RAID_TABLE, environment))

        # Check if RAiD exists
        query_response = raid_table.query(KeyConditionExpression=Key('handle').eq(raid_handle))

        if query_response["Count"] != 1:
            return web_helpers.generate_web_body_response('400', {
                'message': "Invalid RAiD handle provided in parameter path. "
                           "Ensure it is a valid RAiD handle URL encoded string"}, event)

        # Interpret and validate request body
        body = json.loads(event["body"])

        if "endDate" in body:
            try:
                end_date = datetime.datetime.strptime(body["endDate"], "%Y-%m-%d %H:%M:%S")
            except ValueError as e:
                logger.error('Unable to capture date: {}'.format(e))
                return web_helpers.generate_web_body_response('400', {
                    'message': "Incorrect date format, should be yyyy-MM-dd hh:mm:ss"}, event)
        else:
            # Get current datetime
            end_date = raid_helpers.get_current_datetime()

        if "name" not in body:
            return web_helpers.generate_web_body_response('400', {
                'message': "'name' must be provided in your request body to end an association"}, event)

        # Update DynamoDB put to end association
        association_index_table = dynamo_db.Table(
            settings.get_environment_table(
                settings.ASSOCIATION_TABLE, environment
            )
        )

        existing_provider_query_parameters = {
            'IndexName': 'HandleNameIndex',
            'ProjectionExpression': "startDate, endDate",
            'FilterExpression': Attr('endDate').not_exists(),
            'KeyConditionExpression': Key('handle-name').eq('{}-{}'.format(raid_handle, body['name']))
        }

        provider_query_response = association_index_table.query(**existing_provider_query_parameters)
        existing_provider = provider_query_response["Items"][0]

        # Get existing item
        update_response = association_index_table.update_item(
            Key={
                'startDate': existing_provider['startDate'],
                'handle': raid_handle
            },
            UpdateExpression="set endDate = :e",
            ExpressionAttributeValues={
                ':e': end_date
            },
            ReturnValues="ALL_NEW"
        )

        return web_helpers.generate_web_body_response('200', {
            'name': body['name'],
            'startDate': existing_provider['startDate'],
            'endDate': end_date
        }, event)

    except:
        logger.error('Unable to end a provider to a RAiD association: {}'.format(sys.exc_info()[0]))
        return web_helpers.generate_web_body_response('500', {
            'message': "Unable to perform request due to error. Please check structure of the body."}, event)
Пример #29
0
def scan_as_fname(table, token):
    return table.scan(FilterExpression=Attr('_fname').contains(token))['Items']
def lambda_handler(event, context):

    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table("Hotspotdetail")

    todayDate = date.today()
    td = timedelta(1)
    d = todayDate + td
    upperDate = '%s' % d
    td = timedelta(3)
    d = todayDate - td
    lowerDate = '%s' % d

    # gets the uri from the url
    hotspots = []
    path = event['path']
    # path = "/invoke/112XTwrpTBHjg4M1DWsLTcqsfJVZCPCYW2vNPJV7cZkpRg3JiKEg"
    x = path.split("/")
    hotspots.append(x[2])

    response = table.query(
        #   FilterExpression= Attr("Witnesses").between(1,5),
        KeyConditionExpression=Key('Hotspot').eq(hotspots[0])
        & Key('WitnesseTime').between(lowerDate, upperDate))
    occurOne = occurTwo = occurThree = occurFour = occurMore = 0

    data = table.query(FilterExpression=Attr("Witnesses").eq(1),
                       KeyConditionExpression=Key("Hotspot").eq(hotspots[0])
                       & Key("WitnesseTime").between(lowerDate, upperDate))
    occurOne = len(data['Items'])

    data = table.query(FilterExpression=Attr("Witnesses").eq(2),
                       KeyConditionExpression=Key("Hotspot").eq(hotspots[0])
                       & Key("WitnesseTime").between(lowerDate, upperDate))
    occurTwo = len(data['Items'])

    data = table.query(FilterExpression=Attr("Witnesses").eq(3),
                       KeyConditionExpression=Key("Hotspot").eq(hotspots[0])
                       & Key("WitnesseTime").between(lowerDate, upperDate))
    occurThree = len(data['Items'])

    data = table.query(FilterExpression=Attr("Witnesses").eq(4),
                       KeyConditionExpression=Key("Hotspot").eq(hotspots[0])
                       & Key("WitnesseTime").between(lowerDate, upperDate))
    occurFour = len(data['Items'])

    data = table.query(FilterExpression=Attr("Witnesses").between(5, 25),
                       KeyConditionExpression=Key("Hotspot").eq(hotspots[0])
                       & Key("WitnesseTime").between(lowerDate, upperDate))
    occurMore = len(data['Items'])

    onetofour = occurOne + occurTwo + occurThree + occurFour
    witnesseDict = {
        "Witnesses_1": occurOne,
        "Witnesses_2": occurTwo,
        "Witnesses_3": occurThree,
        "Witnesses_4": occurFour,
        "Witnesses_5_and_up": occurMore,
        "Total_Witnesses_from_1_to_4": onetofour,
        "Total_Witnesses": onetofour + occurMore
    }
    WitnesseshtmlList = """let array = %s;""" % witnesseDict
    hotspotName = """\nlet hotspotName = "%s";""" % hotspots[0]
    htmlTop = """
        <!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>WifiMist</title>
  <link rel="stylesheet" href="https://heliumfrontend.s3.amazonaws.com/newStyle.css">
  <script src="https://code.highcharts.com/highcharts.js"></script>
  <script src="https://code.highcharts.com/modules/exporting.js"></script>
  <script src="https://code.highcharts.com/modules/export-data.js"></script>
  <script src="https://code.highcharts.com/modules/accessibility.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.js" integrity="sha512-otOZr2EcknK9a5aa3BbMR9XOjYKtxxscwyRHN6zmdXuRfJ5uApkHB7cz1laWk2g8RKLzV9qv/fl3RPwfCuoxHQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

</head>
<body>
<h1><span class="peach">Witnesse Count</pan></h1>
<h2><span class="peach">for past 3 days</span></h2>
<table class="container">
	<thead>
		<tr>
			<th>  Hotspot </th>
			<th>1 Wit</th>
			<th>2 Wit</th>
			<th >3 Wit</th>
			<th >4 Wit</th>
			<th >5 and up</th>
			<th >Wit 1-4</th>
			<th >Total</th>
  		</tr>
  <tbody id="myTable">
	</thead>
</table>
</div>
        <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
        <h1><span class="peach">24 Hrs & 30 Day Rewards</pan></h1>

        <figure class="highcharts-figure">
          <div id="con7day" ></div>
          </figure>
          <figure class="highcharts-figure">
          <div id="con30day" ></div>
          
        </figure>
        <script>
    """
    htmlBottom = """
        let url30day = 'https://api.helium.io/v1/hotspots/' + hotspotName + '/rewards/sum?min_time=-30%20day&bucket=day'
        let url1day = 'https://api.helium.io/v1/hotspots/' + hotspotName + '/rewards/sum?min_time=-1%20day&bucket=hour'
        let name = 'https://api.helium.io/v1/hotspots/' + hotspotName
        let totalArray30day = []
        let timeArray30day = []
        let list30Day = []
        let totalArray1day = []
        let timeArray1day = []
        let list1Day = []

        axios.get(name)
            .then(response => {
                let hName = response.data.data['name'];
                
                buildTable(array, hName);
            }, error => {
                console.log(error);
            })
        
        axios.get(url30day)
            .then(response => {
                var count = 0;
                for (let i = response.data.data.length - 1; i >= 0; i--) {
                    var reward = response.data.data[i]['total'];
                    var data = response.data.data[i]['timestamp'];
                    var time = data.split("T")
                    totalArray30day.push(reward)
                    timeArray30day.push(time[0])
                    list30Day.push([timeArray30day[count],totalArray30day[count]])
                    count++;
                }
                buildGraph2(list30Day)
                
            }, error => {
                console.log(error);
            })
        // for 7 days
        axios.get(url1day)
            .then(response => {
                var count = 0;
                for (let i = response.data.data.length - 1; i >= 0; i--) {
                    var reward = response.data.data[i]['total'];
                    var time = response.data.data[i]['timestamp'];
                    totalArray1day.push(reward)
                    timeArray1day.push(time)
                    list1Day.push([timeArray1day[count], totalArray1day[count]])
                    count++;
                }
                
                buildGraph(list1Day)
            }, error => {
                console.log(error);
            })
        
        
        
        function buildTable(data, hName) {
            let table = document.getElementById("myTable");
            let row = `<tr>
                <td>${hName}</td>
                <td>${data.Witnesses_1}</td>
                <td>${data.Witnesses_2}</td>
                <td>${data.Witnesses_3}</td>
                <td>${data.Witnesses_4}</td>
                <td>${data.Witnesses_5_and_up}</td>
                <td>${data.Total_Witnesses_from_1_to_4}</td>
                <td>${data.Total_Witnesses}</td>
            </tr>`;
            table.innerHTML += row;
    
        }
    function buildGraph(list7Day) {
    Highcharts.chart("con7day", {
        chart: {
            backgroundColor: "#2C3446",
            type: "column",
        },
        title: {
            text: "24 Hour Reward",
            style: {
                color: "#FB667A",
                font: 'bold 16px "Trebuchet MS", Verdana, sans-serif',
            },
        },

        xAxis: {
            type: "category",
            labels: {
                rotation: -45,
                style: {
                    fontSize: "13px",
                    fontFamily: "Verdana, sans-serif",
                },
            },
        },
        yAxis: {
            min: 0,
            title: {
                text: "HNT",
            },
        },
        plotOptions: {
            series: {
                borderColor: "#FB667A",
            },
        },
        legend: {
            enabled: false,
        },
        tooltip: {
            pointFormat: "HNT: <b>{point.y:.1f} HNT</b>",
        },
        series: [{
            name: "HNT",
            data: list7Day,
            color: "#FB667A",
            dataLabels: {
                enabled: true,
                rotation: -90,
                color: "#FFFFFF",
                align: "right",
                format: "{point.y:.1f}", // one decimal
                y: 20, // 10 pixels down from the top
                style: {
                    fontSize: "13px",
                    fontFamily: "Verdana, sans-serif",
                },
            },
        }, ],
    });
}

function buildGraph2(list30Day) {
    Highcharts.chart("con30day", {
        chart: {
            backgroundColor: "#2C3446",
            type: "column",
        },
        title: {
            text: "30 Day Reward",
            style: {
                color: "#FB667A",
                font: 'bold 16px "Trebuchet MS", Verdana, sans-serif',
            },
        },
        xAxis: {
            type: "category",
            labels: {
                rotation: -45,
                style: {
                    fontSize: "13px",
                    fontFamily: "Verdana, sans-serif",
                },
            },
        },
        yAxis: {
            min: 0,
            title: {
                text: "HNT",
            },
        },
        plotOptions: {
            series: {
                borderColor: "#FB667A",
            },
        },
        legend: {
            enabled: false,
        },
        tooltip: {
            pointFormat: "HNT: <b>{point.y:.1f} HNT</b>",
        },
        series: [{
            name: "HNT",
            data: list30Day,
            color: "#FB667A",
            dataLabels: {
                enabled: true,
                rotation: -90,
                color: "#2C3446",
                align: "right",
                format: "{point.y:.1f}", // one decimal
                y: 5, // 10 pixels down from the top
                style: {
                    fontSize: "10px",
                    fontFamily: "Verdana, sans-serif",
                },
            },
        }, ],
    });
}
        </script>
        </body>
        </html>
    """

    finalhtml = htmlTop + WitnesseshtmlList + hotspotName + htmlBottom
    return {
        "statusCode": 200,
        "headers": {
            'Content-Type': 'text/html'
        },
        "body": finalhtml
    }