Ejemplo n.º 1
0
    def get_aurin(self, region, types):
        mapping = {
            'income': "income_num(aud)",
            'labor': "labour_force_num",
            'participation': "Participation_rate%",
            'unemployment': "Unemployment_rate%",
            'highedu': "higher_education_rate%",
            'male': "Male",
            'female': "Female"
        }
        db = CloudantDatabase(self.client, 'aurin', partitioned=False)

        if self.dic is None:
            self.dic = {
                '_'.join(filter(lambda x: x[0] != '(',
                                key.split())).lower().replace('-', '_'): key
                for key in db['aurin_data'].keys()
            }

        if region[-1] == ')':
            re = 'unincorporated_vic'
        else:
            re = region.lower().replace(' ', '_').replace('-', '_')

        if re in self.dic:
            if types == 'all':
                return {
                    key: db['aurin_data'][self.dic[re]][value]
                    for key, value in mapping.items()
                }
            return db['aurin_data'][self.dic[re]].get(mapping.get(types, ""),
                                                      -1)
        else:
            return -1
Ejemplo n.º 2
0
    def get_sentiment_user(self, db, date_begin, date_end):
        db = CloudantDatabase(self.client, db, partitioned=False)
        days = get_days(date_begin, date_end)

        while not db.exists():
            time.sleep(0.1)

        results = {'negative': 0, 'neutral': 0, 'positive': 0}
        cou = 0
        hash_count = {}
        related = 0
        hash_cou = 0
        for tweet_data in db:
            results[tweet_data['simple_sentiment_label']] += 1
            cou += 1
            flag = 0
            for hash in tweet_data['hashtags']:
                hash_cou += 1
                hash = hash.lower()
                if 'covid' in hash or 'corona' in hash or ('19' in hash and 'co' in hash) \
                        or 'home' in hash or 'lock' in hash or 'safe' in hash:
                    flag = 1

                hash_count[hash] = hash_count.get(hash, 0) + 1

            related += flag

        results['count'] = cou
        results['hashtags'] = sorted(hash_count.items(),
                                     key=lambda item: item[1],
                                     reverse=True)
        results['coronavirus_related'] = related
        results['hashtag_count'] = hash_cou
        db.delete()
        return results
Ejemplo n.º 3
0
 def update_schedule_status(self, doc_id, to_value):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_SCHEDULE_DATABASE_NAME'])
     remote_doc = Document(database, doc_id)
     remote_doc.update_field(action=remote_doc.field_set,
                             field='status',
                             value=to_value)
Ejemplo n.º 4
0
 def update_user_info(self, doc_id, update_field, to_value):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_USER_DATABASE_NAME'])
     remote_doc = Document(database, doc_id)
     remote_doc.update_field(action=remote_doc.field_set,
                             field=update_field,
                             value=to_value)
Ejemplo n.º 5
0
 def get_cloudant_doc(itemID):
     client = Cloudant.iam(app.config["USER"],
                           app.config["APIKEY"],
                           connect=True)
     client.connect()
     database = CloudantDatabase(client, "marketplace-history-database")
     with Document(database,
                   document_id=f"marketplace-history-{itemID}") as document:
         return (document)
Ejemplo n.º 6
0
    def get_tweet_count_today(self, region, date=datetime.datetime.today()):
        db = CloudantDatabase(self.client,
                              self.get_region(region),
                              partitioned=True)
        counts = 0

        for re in db.get_partitioned_view_result(date, '_design/tweet_count',
                                                 'tweet_count'):
            counts += re['value']
        return {'count': counts}
Ejemplo n.º 7
0
 def get_user_info(self, emailAddress):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_USER_DATABASE_NAME'])
     selector = {'emailAddress': {'$eq': emailAddress}}
     try:
         res = database.get_query_result(selector)[0]
     except Exception as e:
         raise
     else:
         return res[0]
Ejemplo n.º 8
0
    def get_all_overview(self):
        db = CloudantDatabase(self.client, 'daily_increase', partitioned=False)
        results = {}

        for day_data in db:
            results[day_data['_id']] = {
                key: value
                for key, value in day_data.items()
                if key != '_id' and key != '_rev'
            }

        return results
Ejemplo n.º 9
0
 def create_index(cls):
     """
     Create an Indexs for the "page_id" attribute
     """
     with cloudant(USERNAME, PASSWORD, url=URL) as client:
         clouddb = CloudantDatabase(client, DBNAME)
         clouddb.create_query_index(index_name='pageid-index',
                                    index_type='text',
                                    fields=[{
                                        "name": "page_id",
                                        "type": "string"
                                    }])
Ejemplo n.º 10
0
    def get_corona(self, region, date_begin, date_end):
        db = CloudantDatabase(self.client,
                              self.get_region(region),
                              partitioned=True)
        days = get_days(date_begin, date_end)

        counts = 0
        for day in days:
            for re in db.get_partitioned_view_result(
                    day, '_design/coronavirus_related', 'coronavirus_related'):
                counts += re['value']
        return {'count': counts}
Ejemplo n.º 11
0
    def get_sentiment(self, region, date_begin, date_end):
        db = CloudantDatabase(self.client,
                              self.get_region(region),
                              partitioned=True)
        days = get_days(date_begin, date_end)

        counts = {'negative': 0, 'neutral': 0, 'positive': 0}
        for day in days:
            for re in db.get_partitioned_view_result(day,
                                                     '_design/sentiment_count',
                                                     'sentiment_count',
                                                     group_level=1):
                counts[re['key']] += re['value']
        return counts
Ejemplo n.º 12
0
 def get_user_tasks(self, emailAddress):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_REQUEST_DATABASE_NAME'])
     if not database.exists():
         database = self.client.create_database(
             self.app.config['CLOUDANT_NOSQL_DB_REQUEST_DATABASE_NAME'])
     selector = {'user': {'$eq': emailAddress}}
     try:
         res = database.get_query_result(selector)
     except Exception as e:
         raise
     else:
         return res
Ejemplo n.º 13
0
    def __enter__(self):
        """
        Runs when the control flow enters the with() statement.
        Creates the Cloudant client instant and the Cloudant database instant.

        To connect to the world readable database, I had to use the 'admin_party' flag.
        """
        self.client = Cloudant(" ",
                               " ",
                               admin_party=True,
                               url=self.url,
                               connect=True)

        self.db = CloudantDatabase(self.client, self.db_name)

        return self
Ejemplo n.º 14
0
 def write_to_schedule(self, schedule_record):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_SCHEDULE_DATABASE_NAME'])
     append_info = {
         "status": 'active',
         "failure_counts": "0",
         "submit time": time.ctime()
     }
     new_document = schedule_record.copy()
     new_document.update(append_info)
     if database.exists():
         database.create_document(new_document)
     else:
         database = self.client.create_database(
             self.app.config['CLOUDANT_NOSQL_DB_SCHEDULE_DATABASE_NAME'])
         database.create_document(new_document)
Ejemplo n.º 15
0
    def get_overview(self, date_begin, date_end):
        db = CloudantDatabase(self.client, 'daily_increase', partitioned=False)
        days = get_days(date_begin, date_end)

        results = {}
        keys = db.keys(remote=True)

        for day in days:
            if day in keys:
                res = db[day]
                results[day] = {
                    key: value
                    for key, value in res.items()
                    if key != '_id' and key != '_rev'
                }

        return results
Ejemplo n.º 16
0
 def is_authorized(self, emailAddress, report_level, request_access):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_USER_DATABASE_NAME'])
     selector = {'emailAddress': {'$eq': emailAddress}}
     try:
         res = database.get_query_result(selector)[0]
     except Exception:
         return False
     else:
         if res and \
                 ((res[0]['approved_country_accesses'] and \
                 request_access in res[0]['approved_country_accesses']) \
                 or (res[0]['approved_company_accesses'] and \
                 request_access in res[0]['approved_company_accesses'])):
             return True
         else:
             return False
Ejemplo n.º 17
0
def main():
    client = Cloudant(config.username, config.password, account=config.account)

    client.connect()

    dbs = client.all_dbs()

    output = []
    for db in dbs:
        print 'Retrieving stats for {0}...'.format(db)
        db = CloudantDatabase(client, db)
        print "db: " + json.dumps(db)
        output.append(db.doc_count())

        print json.dumps(output, indent=4)
        print json.dumps(sort(output), indent=4)

    client.disconnect()
Ejemplo n.º 18
0
 def write_to_request(self, document, user=None, status=None):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_REQUEST_DATABASE_NAME'])
     append_info = {
         "user": user,
         "status": status,
         "failure_counts": "0",
         "submit time": time.ctime()
     }
     new_document = document.copy()
     new_document.update(append_info)
     if database.exists():
         database.create_document(new_document)
     else:
         database = self.client.create_database(
             self.app.config['CLOUDANT_NOSQL_DB_REQUEST_DATABASE_NAME'])
         database.create_document(new_document)
Ejemplo n.º 19
0
 def write_to_mail(self, to, sender, subject, confirm_link, requester):
     database = CloudantDatabase(
         self.client,
         self.app.config['CLOUDANT_NOSQL_DB_MAIL_DATABASE_NAME'])
     doc = {
         "to": to,
         "sender": sender,
         "subject": subject,
         "confirm_link": confirm_link,
         "requester": requester,
         "status": 'submitted',
         "submit time": time.ctime()
     }
     if database.exists():
         database.create_document(doc)
     else:
         database = self.client.create_database(
             self.app.config['CLOUDANT_NOSQL_DB_MAIL_DATABASE_NAME'])
         database.create_document(doc)
Ejemplo n.º 20
0
def patient_details():
    if (request.method == "POST"):
        allergies = request.form["allergies"]
        immunizations = request.form["immunizations"]
        observations = request.form["observations"]
        procedures = request.form["procedures"]
        careplans = request.form["careplans"]
        medications = request.form["medications"]
        current = request.form["current"]
        #flash("Patient Details Successfully Updated !!!",category="success")

        ## code to store this info in the database
        username = "******"
        apikey = "HAltxJaD5Sr4VsbAVB4-rYLfWdrWOkW0fWuqzQFP_Ra_"
        client = Cloudant.iam(username, apikey, connect=True)

        db_name = "patient_details"
        p_details = CloudantDatabase(client, db_name)

        date_v = str(date.today())
        encounter_id = str(session["user_id"]) + '_' + date_v
        if p_details.exists():

            patient_document = {
                "allergies": allergies,
                "immunizations": immunizations,
                "observations": observations,
                "procedures": procedures,
                "careplans": careplans,
                "medications": medications,
                "current": current,
                "encounter_id": encounter_id,
                "date": date_v
            }
            p_details.create_document(patient_document)
        #flash("Data Added Successfully !")
        client.disconnect()
        flash("Patient Details Successfully Updated !!!", category="success")

        return redirect(url_for("patient_details"))

    return render_template("p_details.html")
Ejemplo n.º 21
0
    def init_user(self, userinfo, status='active'):

        database = CloudantDatabase(
            self.client,
            self.app.config['CLOUDANT_NOSQL_DB_USER_DATABASE_NAME'])
        doc = {
            "emailAddress": userinfo.get('emailAddress'),
            "firstName": userinfo.get('firstName'),
            "lastName": userinfo.get('lastName'),
            "uid": userinfo.get('uid'),
            "approved_country_accesses": None,
            "approved_company_accesses": None,
            "pending_country_accesses": None,
            "pending_company_accesses": None,
            "status": status,
            "init time": time.ctime()
        }
        if database.exists():
            database.create_document(doc)
        else:
            return False
Ejemplo n.º 22
0
    def get_hashtag_overview(self, region, date_begin, date_end, top):
        db = CloudantDatabase(self.client,
                              self.get_region(region),
                              partitioned=True)
        days = get_days(date_begin, date_end)

        results = {}
        for day in days:
            tmp_re = db.get_partitioned_view_result(day,
                                                    '_design/hashtag_count',
                                                    'hashtag_count',
                                                    group_level=1,
                                                    limit=1000)
            for re in tmp_re[:]:
                results[re['key'].lower()] = results.get(re['key'].lower(),
                                                         0) + re['value']
        if top:
            return sorted(results.items(),
                          key=lambda item: item[1],
                          reverse=True)[:top]
        else:
            return sorted(results.items(),
                          key=lambda item: item[1],
                          reverse=True)
 def __get_db(self, **connection_parameters):
     try:
         _client = CouchDB(**connection_parameters)
         return CloudantDatabase(_client, 'airportdb')
     except Exception as e:
         print(e)
Ejemplo n.º 24
0
 def select_db(self, db_name):
     self.couch_db = CouchDatabase(self.client, db_name)
     if not self.couch_db.exists():
         self.couch_db.create()
     self.db = self.client[db_name]
     self.c_db = CloudantDatabase(self.client, db_name)