コード例 #1
0
ファイル: sat_cruncher.py プロジェクト: mablhq/k8s-demos
def update_tile_list(tile_id):
    tiles_ref = db.reference('tiles')
    try:
        tiles_ref.push(tile_id)
        print 'Transaction completed'
    except db.TransactionError:
        print 'Transaction failed to commit'
コード例 #2
0
ファイル: sat_cruncher.py プロジェクト: mablhq/k8s-demos
def update_firebase_counts():
    proc_cnt_ref = db.reference('statistics/processedCount')
    try:
        proc_cnt_ref.transaction(increment_value)
        print 'Transaction completed'
    except db.TransactionError:
        print 'Transaction failed to commit'
コード例 #3
0
ファイル: sat_cruncher.py プロジェクト: mablhq/k8s-demos
def update_firebase_sizes(size_bytes):
    global DATA_SIZE
    DATA_SIZE = size_bytes

    proc_cnt_ref = db.reference('statistics/processedBytes')
    try:
        proc_cnt_ref.transaction(increment_datasize)
        print 'Transaction completed'
    except db.TransactionError:
        print 'Transaction failed to commit'
コード例 #4
0
import RPi.GPIO as g
from time import time, sleep
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
from firebase_admin import storage
from picamera import PiCamera
import random
cred = credentials.Certificate('/home/pi/pkrpi.json')
firebase_admin.initialize_app(
    cred, {
        'databaseURL': 'https://evilwatchdog.firebaseio.com/',
        'storageBucket': 'evilwatchdog.appspot.com'
    })

ref = db.reference('direction')
ref_logs = db.reference('logs').child('log_images')
ref_auto = db.reference('auto')
ref_feed = db.reference('live_feed')
bucket = storage.bucket()


def click_pic():
    stop()
    camera = PiCamera()
    t = int(time() * 1000)
    camera.capture(str(t) + '.jpeg')
    print('Image Captured')
    blob = bucket.blob('logs/' + str(t) + '.jpeg')
    blob.upload_from_filename(str(t) + '.jpeg')
    print('Image Uploaded')
コード例 #5
0
 async def get(self):
     result = db.reference('').get()
     self.write(result)
コード例 #6
0
def saveFirebase(event, uid):
    ref = db.reference('/registration-' + uid)
    ref.push(json.loads(event.as_json_string()))
コード例 #7
0
def saveToFirebase(catalog, event):
    ref = db.reference(catalog)
    ref.push(json.loads(event.as_json_string()))
コード例 #8
0
ファイル: kor_ona_example.py プロジェクト: Eunno-An/WuHan
 def change_dead(self, dead):
     ref = db.reference('/main/fatality')
     if (dead > ref.get()):
         ref.set(dead)
コード例 #9
0
import matplotlib.animation as animation
from matplotlib import style
import matplotlib.pyplot as plt
#-------------------------------------------Data Processing--------------------------------------------------------------
import pandas as pd
import numpy as np
#-------------------------------------------Fire Base Part-------------------------------------------------------------
import firebase_admin
from firebase_admin import db
from firebase_admin import credentials
cred = credentials.Certificate(
    "./teenscancode-caee5-firebase-adminsdk-ip0g2-e7d0d8e474.json")
default_app = firebase_admin.initialize_app(
    cred, {'databaseURL': 'https://teenscancode-caee5.firebaseio.com'})

Sensor_1_ref = db.reference('Sensor_1')
Sensor_2_ref = db.reference('Sensor_2')
ONOFF_ref = db.reference('ONOFF')
Difference_ref = db.reference('Difference')
Temperature_ref = db.reference('Temperature')
Altitude_ref = db.reference('Altitude')
Humidity_ref = db.reference('Humidity')
AQ_ref = db.reference('AQ')
AQ_stat_ref = db.reference('AQ_stat')
UV_ref = db.reference('UV')
#--------------------------------------------Other-----------------------------------------------------------------
import time
import datetime
import requests
#-----------------------------------------MatplotlibFigureSetup--------------------------------------------------------------
f_1 = Figure(figsize=(6, 4), dpi=80)
コード例 #10
0
def getName(name, language):
    if language == 'de':
        if ' ' in name:
            return name[0].lower() + name[1:]
        else:
            return name
    else:
        return name.lower()

if __name__ == "__main__":
    cred = credentials.Certificate(constants.certificate_firebase)
    firebase_admin.initialize_app(cred, {
        'databaseURL': 'https://abherbs-backend.firebaseio.com'
    })
    refCount = db.reference('plants_to_update/count')
    count = refCount.get()

    filepath = 'plants_to_upload.txt'
    with open(filepath) as fp:
        for line in fp:
            items = line.rstrip().split(';')
            print(items[2].strip())
            add_plant(
                id=count,
                order=items[0].strip(),
                family=items[1].strip(),
                plant=items[2].strip(),
                wikidata=items[3].strip(),
                flowering_from=items[4].strip(),
                flowering_to=items[5].strip(),
コード例 #11
0
import re
import os
import json
import glob
import shutil
from tqdm import tqdm
import firebase_admin
from firebase_admin import db
from firebase_admin import credentials

theme = "face"
image_dir = "/Users/yutatanamoto/tanamoto/research/art/children-drawing-analysis/children-drawing"
cred = credentials.Certificate("./key.json")
firebase_admin.initialize_app(
    cred, {
        'databaseURL':
        'https://children-drawing-annotation-default-rtdb.firebaseio.com'
    })
image_ref = db.reference('images')
images = image_ref.order_by_child('submitted_at').start_at(16).limit_to_first(
    10).get()
additional_images = {}
for image_id, image_content in images.items():
    new_key = "re_{}".format(image_id)
    additional_images[new_key] = image_content
    additional_images[new_key]["submitted_at"] = None
    image_path = "./images/{}.jpg".format(image_id)
    target_image_path = os.path.join("./images", "{}.jpg".format(new_key))
    shutil.copy(image_path, target_image_path)
image_ref.update(additional_images)
コード例 #12
0
 def test_query(self, override_app):
     user_ref = db.reference('_adminsdk/python/protected', override_app)
     with pytest.raises(db.ApiCallError) as excinfo:
         user_ref.order_by_key().limit_to_first(2).get()
     self.check_permission_error(excinfo)
コード例 #13
0
 def init_ref(self, path):
     admin_ref = db.reference(path)
     admin_ref.set('test')
     assert admin_ref.get() == 'test'
コード例 #14
0
ファイル: app.py プロジェクト: scc-gatech/infra-nebula
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask
    return celery


gh = Github(os.getenv('GITHUB_ACCESS_TOKEN'))

cred = credentials.Certificate(os.path.join(os.path.dirname(__file__), '.firebase-admin.json'))
firebase_app = firebase_admin.initialize_app(cred, options={
    "databaseURL": "https://sc17-gatech-optica.firebaseio.com"
})
root = db.reference()
whitelist_ref = root.child('whitelist')

app = Flask(__name__)
# csrf = CSRFProtect(app)
SESSION_TYPE = 'redis'
app.config.from_object(__name__)
Session(app)
app.config.update(
    CELERY_BROKER_URL='redis://localhost:6379',
    CELERY_RESULT_BACKEND='redis://localhost:6379'
)
celery = make_celery(app)

db = Redis()
store = memoize.redis.wrap(db)
コード例 #15
0
def location():
    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon


lines = open("log.txt").readlines()
cred = credentials.Certificate('hack101-b26f1b2127fd.json')
firebase_admin.initialize_app(
    cred, {'databaseURL': 'https://hack101-46d94.firebaseio.com'})

root = db.reference()

push_data = {}
count = 0
for line in lines:
    data = line.split('\t')
    mac = data[1]
    name = data[2]
    lat, lon = location()
    singnal_strength = data[4]

    print(mac + ":" + name + ":" + singnal_strength)

    if mac not in push_data:
        push_data[mac] = {
            "name": name,
コード例 #16
0
def add_route_to_db(request):
    """
    Function to add route which was built for some device to Firebase Database
    :param request: Flask request that contains json with route info:
    {
        "device_id": int
        "nodes": [
            {
              "id": ...
              "lat": ...
              "lng": ...
            },
            ...
        ],
        "traffic_signals" : [
            {
                "id": int
                "lat": double
                "lng": double
                "state": bool
            },
            ...
        ],
        "duration": time in seconds,
        "distance": distance in meters
    }
    :return: str with json wrote to db or 'Bad request'
    """
    route_json = request.get_json()
    cred = credentials.Certificate(json.loads(getenv("FIREBASE_CRED")))
    firebase_app = firebase_admin.initialize_app(
        cred,
        options={'databaseURL': 'https://green-waves.firebaseio.com/'},
        name="ROUTE")
    print(type(route_json), route_json)
    if route_json and route_json.get('device_id') and route_json.get(
            'nodes') and route_json.get('traffic_signals') is not None:
        ref = db.reference('devices', firebase_app)
        device_id = route_json['device_id']
        device = ref.child(device_id)
        last_route_id = device.get('last_route_id')[0].get(
            'last_route_id', -1) + 1 if device.get('last_route_id')[0] else 0
        print('id', last_route_id)
        device.child('last_route_id').set(last_route_id)
        # routes = device.get('routes')
        route = device.child('routes').child(str(last_route_id))

        nodes = route.child('nodes')
        i = 0
        for node in route_json['nodes']:
            nodes.child(str(i)).set(node)
            i += 1

        traffic_signals = route.child('traffic_signals')
        i = 0
        for traffic_signal in route_json['traffic_signals']:
            traffic_signals.child(str(i)).set(traffic_signal)
            i += 1

        route.child('duration').set(route_json.get('duration', ""))
        route.child('distance').set(route_json.get('distance', ""))

        firebase_admin.delete_app(firebase_app)
        return f'Updated route for {device_id}', 200
    else:
        firebase_admin.delete_app(firebase_app)
        error = 'Bad request: %s%s%s%s not presented' % (
            'no data' if not route_json else '', 'no device id'
            if not route_json and not route_json.get('device_id') else '',
            'no nodes' if not route_json and not route_json.get('nodes') else
            '', 'no traffic signals'
            if not route_json and not route_json('traffic_signals') else '')
        print(error)
        return error, 400
コード例 #17
0
def add_plant_v2(order, family, plant, wikidata, id, flowering_from, flowering_to, height_from, height_to):
    origin = path.join(constants.plantsdir, family, plant, 'sources.txt')
    target = path.join(constants.storagedir, order, family, plant.replace(' ', '_'))

    photo_urls = []
    names = plant.split(' ')
    name = names[0][0].lower() + names[len(names) - 1][0].lower()
    photo_count = 1
    while path.exists(path.join(target, name + str(photo_count) + constants.extension)):
        photo_urls.append(
            '/'.join([order, family, plant.replace(' ', '_'), name + str(photo_count) + constants.extension]))
        photo_count += 1

    source_urls = []
    sources = open(origin, 'r')
    for line in sources:
        source_urls.append(urllib.parse.unquote(line.strip()))

    wikilinks = {}
    wikilinks['data'] = 'https://www.wikidata.org/wiki/' + wikidata

    freebase_id = ''
    gbif_id = ''
    usda_id = ''
    ipni_id = ''

    with urllib.request.urlopen('https://www.wikidata.org/wiki/Special:EntityData/' + wikidata + '.json') as url_data:
        data = json.loads(url_data.read().decode())
        sitelinks = data['entities'][wikidata]['sitelinks']
        if 'commonswiki' in sitelinks.keys():
            wikilinks['commons'] = sitelinks['commonswiki']['url']
        if 'specieswiki' in sitelinks.keys():
            wikilinks['species'] = sitelinks['specieswiki']['url']

        claims = data['entities'][wikidata]['claims']
        if 'P646' in claims.keys():
            freebase_id = claims['P646'][0]['mainsnak']['datavalue']['value']
        if 'P846' in claims.keys():
            gbif_id = claims['P846'][0]['mainsnak']['datavalue']['value']
        if 'P1772' in claims.keys():
            usda_id = claims['P1772'][0]['mainsnak']['datavalue']['value']
        if 'P961' in claims.keys():
            ipni_id = claims['P961'][0]['mainsnak']['datavalue']['value']
            if ipni_id == '161931-2':
                ipni_id = '508578-1'
            elif ipni_id == '597506-1':
                ipni_id = '597505-1'

    taxons = []
    apg_iv = {}
    if 'species' in wikilinks.keys():
        species = wikilinks['species']
        with urllib.request.urlopen(species) as url_species:
            bs = BeautifulSoup(url_species.read().decode('utf8'), features='lxml')
            tag = bs('p')
            for i in range(0,2):
                elem = tag[i]
                taxons.extend([y.strip() for y in [x for x in elem.text.split('\n') if x]])

        taxon_count = 0
        taxons.reverse()
        for taxon in taxons:
            if ':' in taxon and not taxon.startswith('Species') and not taxon.startswith('Variet') and not taxon.startswith('Subspecies'):
                if taxon.startswith('Ordo'):
                    taxon_names = constants.apgiv_names[order].split('/')
                    taxon_names.reverse()
                    taxon_values = constants.apgiv_values[order].split('/')
                    taxon_values.reverse()
                    for i in range(len(taxon_names)):
                        apg_iv['{:0>2d}'.format(taxon_count) + '_' + taxon_names[i]] = taxon_values[i]
                        taxon_count += 1
                    break
                else:
                    line = taxon.split(': ')
                    line_value = line[1].split(' ')
                    apg_iv['{:0>2d}'.format(taxon_count) + '_' + line[0]] = line_value[len(line_value)-1]
                    taxon_count += 1

    plant_v2 = {
        'APGIV': apg_iv,
        'floweringFrom': int(flowering_from),
        'floweringTo': int(flowering_to),
        'id': id,
        'illustrationUrl': '/'.join(
            [order, family, plant.replace(' ', '_'), plant.replace(' ', '_') + constants.extension]),
        'heightFrom': int(height_from),
        'heightTo': int(height_to),
        'name': plant,
        'photoUrls': photo_urls,
        'sourceUrls': source_urls,
        'wikilinks': wikilinks,
    }
    if freebase_id:
        plant_v2['freebaseId'] = freebase_id
    if gbif_id:
        plant_v2['gbifId'] = gbif_id
    if usda_id:
        plant_v2['usdaId'] = usda_id
    if ipni_id:
        plant_v2['ipniId'] = ipni_id

    ref_plant = db.reference('plants_v2/' + plant)
    ref_plant.update(plant_v2)
    return ipni_id
コード例 #18
0
    'MediumVioletRed', 'MintCream', 'MistyRose', 'Moccasin', 'NavajoWhite',
    'OldLace', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed', 'Orchid',
    'PaleGoldenRod', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed',
    'PapayaWhip', 'PeachPuff', 'Peru', 'Pink', 'Plum', 'PowderBlue', 'Purple',
    'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Green', 'SandyBrown',
    'SeaGreen', 'SeaShell', 'Sienna', 'Silver', 'SkyBlue', 'SlateBlue',
    'SlateGray', 'SlateGrey', 'Snow', 'SpringGreen', 'SteelBlue',
    'GreenYellow', 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat',
    'White', 'WhiteSmoke', 'Yellow', 'YellowGreen'
]

cred = credentials.Certificate(
    'lehigh-line-count-firebase-adminsdk-fl2v4-bad2be6139.json')
app = firebase_admin.initialize_app(cred)
ref = db.reference(path='/',
                   app=None,
                   url='https://lehigh-line-count.firebaseio.com/')
ref.set({'counter': '0', 'timestamp': str(datetime.datetime.now())})


def save_image_array_as_png(image, output_path):
    """Saves an image (represented as a numpy array) to PNG.

  Args:
    image: a numpy array with shape [height, width, 3].
    output_path: path to which image should be written.
  """
    image_pil = Image.fromarray(np.uint8(image)).convert('RGB')
    with tf.gfile.Open(output_path, 'w') as fid:
        image_pil.save(fid, 'PNG')
コード例 #19
0
                    faculty = subject_faculty[subject]
                    faculty_id = faculty['faculty_id']

                    print(subject_faculty)
                    db.reference('Map').child('Subject_Emotions').child(
                        faculty_id).child(date).child(subject).set({
                            "present":
                            present_count,
                            "absent":
                            absent_count,
                            "emotions":
                            count_subject_emotions
                        })

                    print(subject_emotion)
                db.reference('Map').child('Attendance').child(date).child(
                    subject).set({
                        "present": present_count,
                        "absent": absent_count,
                        "emotions": count_subject_emotions
                    })


#
# user_student_generation()
#user_faculty_generation()
#attendance_generation()

id_list = db.reference('Map').child('Students').child("Comp").child("BE").get()
print(id_list)
コード例 #20
0
ファイル: kor_ona_example.py プロジェクト: Eunno-An/WuHan
 def change_out(self, out):
     ref = db.reference('/outDiag')
     if (out != ref.get()):
         ref.set(out)
コード例 #21
0
def attendance_generation():
    start_date = '2018-03-1'
    end_date = '2018-04-01'
    d1 = datetime.datetime.strptime(start_date, "%Y-%m-%d")
    d2 = datetime.datetime.strptime(end_date, "%Y-%m-%d")
    d = d2 - d1
    branch = "Comp"
    year = "BE"
    id_list = db.reference('Map').child('Students').child(branch).child(
        year).get()
    timetable = db.reference('timetable').child(branch).child(year).get()
    subject_faculty = db.reference('Map').child('Subjects').child(
        branch).child(year).get()
    print(subject_faculty)

    weekdays = [
        "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
        "Sunday"
    ]

    emotions = ['happy', 'angry', 'fear', 'neutral', 'sadness', 'disgust']
    for day in range(0, d.days):
        current_date = d1 + datetime.timedelta(day)
        week_day = current_date.weekday()
        day = weekdays[week_day]

        r = random.randrange(7, 10)
        random.shuffle(id_list)
        present_today = id_list[:r]

        if day != weekdays[-2] and day != weekdays[-1]:
            date = datetime.datetime.strftime(current_date, "%Y%m%d")
            for time, subject in timetable[day].items():
                r = random.randrange(5, len(present_today))
                random.shuffle(present_today)

                present_for_subject = present_today[:r]
                present_count = 0
                absent_count = 0
                subject_emotion = []
                for id in id_list:
                    if id in present_for_subject:
                        present_count += 1
                        random.shuffle(emotions)
                        p_emotion = emotions[-1]
                        p_subject = subject
                        print((id, p_emotion, p_subject))
                        db.reference('Attendance').child(branch).child(
                            year).child(date).child(id).child(time).set({
                                "emotion":
                                p_emotion,
                                "subject":
                                subject
                            })
                        db.reference('Map').child('Student_Present').child(
                            id).child(date).child(subject).set(
                                {"emotion": p_emotion})
                        subject_emotion.append(p_emotion)
                    else:
                        absent_count += 1
                        db.reference('Map').child('Student_Absent').child(
                            id).child(date).child(subject).set(
                                {"emotion": "NULL"})

                count_subject_emotions = Counter(subject_emotion)

                if subject in subject_faculty.keys():
                    faculty = subject_faculty[subject]
                    faculty_id = faculty['faculty_id']

                    print(subject_faculty)
                    db.reference('Map').child('Subject_Emotions').child(
                        faculty_id).child(date).child(subject).set({
                            "present":
                            present_count,
                            "absent":
                            absent_count,
                            "emotions":
                            count_subject_emotions
                        })

                    print(subject_emotion)
                db.reference('Map').child('Attendance').child(date).child(
                    subject).set({
                        "present": present_count,
                        "absent": absent_count,
                        "emotions": count_subject_emotions
                    })
コード例 #22
0
ファイル: kor_ona_example.py プロジェクト: Eunno-An/WuHan
 def change_ing(self, ing):
     ref = db.reference('/main/ing')
     if (ing != ref.get()):
         ref.set(ing)
コード例 #23
0
import numpy as np
import tensorflow as tf
import cv2
import time
import imutils
import firebase_admin
from firebase_admin import db
from firebase_admin import credentials
cred = credentials.Certificate('C:/Users/LattePanda/Desktop/opencv/java1d-78754-firebase-adminsdk-tfjza-bbde21376c.json')
default_app = firebase_admin.initialize_app(cred, {'databaseURL' : "https://java1d-78754.firebaseio.com/"})
ref = db.reference('meeting_room1')

class DetectorAPI:
    def __init__(self, path_to_ckpt):
        self.path_to_ckpt = path_to_ckpt

        self.detection_graph = tf.Graph()
        with self.detection_graph.as_default():
            od_graph_def = tf.GraphDef()
            with tf.gfile.GFile(self.path_to_ckpt, 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')

        self.default_graph = self.detection_graph.as_default()
        self.sess = tf.Session(graph=self.detection_graph)

        # Definite input and output Tensors for detection_graph
        self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
        # Each box represents a part of the image where a particular object was detected.
        self.detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
コード例 #24
0
def saveToFirebase(event):
    ref = db.reference('/report')
    ref.push(json.loads(event.as_json_string()))
コード例 #25
0
# This file contains all the utility functions required by other files


# imports
import base64
import random
import os
from PIL import Image, ImageFilter
import json
import firebase_admin
from firebase_admin import db

ref = db.reference('vitask')

CAPTCHA_DIM = (180, 45)
CHARACTER_DIM = (30, 32)
#Above values were checked from various captchas

"""
---------------------------------------
Functions for Captcha solver begin here
---------------------------------------
"""

def save_captcha(captchasrc,username):
    """
    Downloads and save a random captcha from VTOP website in the path provided
    Defaults to `/captcha`
    num = number of captcha to save
    """
    base64_image = captchasrc[23:]
コード例 #26
0
import datetime
import json
from time import time
from urllib.parse import urlparse
from requests import post
import firebase_admin
from dateutil.parser import parse
from firebase_admin import credentials
from firebase_admin import db
from requests import post
from tornado.web import RequestHandler

cred = credentials.Certificate('CERTIFICATE_FILE')
firebase_admin.initialize_app(
    cred, {'databaseURL': 'https://ids-hackathor.firebaseio.com/'})
ref = db.reference('')
intrusion_ref = db.reference('intrusions')

with open('payloads.json', encoding="utf8") as f:
    loaded = json.load(f)
    XSS = loaded['XSS']
    TRAVERS = loaded['TRAVERS']

VIRUSTOTAL = 'API_KEY'
DOMAIN = "bilkent.com"


def send_ref(ip, param, val, type):
    ref.push({
        "ip": ip,
        "type": type,
コード例 #27
0
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

sense.clear()

cred = credentials.Certificate('private_key/private_key.json')
firebase_admin.initialize_app(
    cred, {'databaseURL': 'https://character-generator-4d751.firebaseio.com/'})

i = 0
on = [130, 30, 100]
off = [0, 0, 0]

ref = db.reference().child('characters')
snapshot = ref.get()


def listener(event):
    # print(event.data)
    loopval = event.data


db.reference('/loopstatus').listen(listener)
sense.clear()

while True:
    loopstatus = db.reference('loopstatus')
    loopval = loopstatus.get()
    print(loopval)
コード例 #28
0
ファイル: data.py プロジェクト: RaymondLZhou/smart-pharmacy
 def deleteUser (self, id):
     db.reference('arka/user/' + id).delete()
コード例 #29
0
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred = credentials.Certificate('/home/pi/iot/cred.json')
# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(
    cred, {'databaseURL': 'https://porterointeligente-e1e18.firebaseio.com/'})

abrir_puerta = db.reference('abrirpuerta')
cerrar_puerta = db.reference('cerrarpuerta')
mic_android = db.reference('micandroid')

datos = []

datos.append(abrir_puerta.get())
datos.append(cerrar_puerta.get())
datos.append(mic_android.get())

index = 0
while index < len(datos):
    print datos[index],
    index = index + 1
コード例 #30
0
ファイル: views.py プロジェクト: watchNlearn/CCServer
from email.mime.text import MIMEText
from django.http import HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from firebase_admin import credentials
from firebase_admin import db
from paypalrestsdk import Payout
# Fetch the service account key JSON file contents

#cred = credentials.Certificate('')
#cred = credentials.Certificate('')
cred = credentials.Certificate({s})
# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {})

ref = db.reference()


#PayPal use is fully functional (with proper id) but is not used in the final project
def getAccessToken():
    url = 'https://api.sandbox.paypal.com/v1/oauth2/token'
    client_id = ''
    secret = ''
    header = {
        'Accept': 'application/json',
        'Accept-Language': 'en_US',
        'content-type': 'application/x-www-form-urlencoded'
    }
    data = {
        'grant_type': '',
    }
コード例 #31
0
ファイル: app.py プロジェクト: PhanTranHung/bao_ve_cay_trong
import os
import cv2
import numpy as np
from tensorflow.keras.models import load_model
from firebase_admin import credentials, initialize_app, db

app = Flask(__name__)
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}

# Initialize Firestore DB
cred = credentials.Certificate(
    'plant-e7169-firebase-adminsdk-vv9mb-c8a6f499fe.json')
default_app = initialize_app(
    cred, {'databaseURL': 'https://plant-e7169-default-rtdb.firebaseio.com'})
# db = firestore.client()
disease_ref = db.reference('disease')


def allowed_file(filename):
    extension = filename.rsplit('.', 1)[1].lower()
    return '.' in filename and extension in ALLOWED_EXTENSIONS


def model():
    global model
    model = load_model('model.h5')


@app.route('/', methods=['GET'])
def home():
    return jsonify({
コード例 #32
0
ファイル: scrapecopy.py プロジェクト: magelon/webscrape
from selenium import webdriver
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred = credentials.Certificate('auth.json')
firebase_admin.initialize_app(
    cred, {'databaseURL': 'https://auth-7ba82.firebaseio.com'})

ref = db.reference('titles')
snapshot = ref.get()

print(snapshot)

import json
#data={'title':post.text}
#sent=json.dumps(data)
#result=firebase.post('/titles',sent)

#chrome_path="/Users/firoprochainezo/Desktop/chromedriver"
#driver=webdriver.Chrome(chrome_path)
#driver.get("https://sfbay.craigslist.org")
#driver.find_element_by_xpath("""//*[@id="hhh0"]/li[1]/a""").click()

#posts=driver.find_elements_by_class_name("result-title")
id = 0
#for post in posts:
#if "bedroom" in post.text:
#print(id,post.text)
#print(post.text)
#data={'title':post.text}
コード例 #33
0
ファイル: simulate_messages.py プロジェクト: kuprel/skinder
import firebase_admin
from firebase_admin import db
from time import time
import random
import lorem

creds = firebase_admin.credentials.Certificate('./dev/admin-cert.json')
kwargs = {'databaseURL': 'https://skinder-1.firebaseio.com'}
app = firebase_admin.initialize_app(creds, kwargs)

users0 = db.reference('users').get()
users = {
    k: v for k, v in users0.items()
    if 'keep' in v and v['keep'] and 'pics' in v
}
users = dict(list(users.items())[-10:])
users['0'] = users0['0']

getTime = lambda i, j: round(1000*(time()+i-3600*(j+1)))

chats = {
    userID: {
        'thumb': user['pics'][0]['link'],
        'messages': [
            {
                'txt': lorem.sentence(),
                'fromUser': random.choice([True, False]),
                'created': getTime(i, list(users).index(userID)),
            }
            for i in range(random.randint(3, 20))
        ]
コード例 #34
0
from google.auth.transport.requests import Request
from pprint import pprint
import firebasePython


app = Flask(__name__)
CORS(app)
api = Api(app)
http_token_auth = HTTPTokenAuth(scheme='Token')

app.config.from_pyfile("../config/app.default_settings")
app.config.from_envvar("POND_SERVICE_SETTINGS")

firebase_cred = credentials.Certificate(app.config["FIREBASE_CREDENTIAL"])
firebase_app = initialize_app(firebase_cred, {'databaseURL': app.config["FIREBASE_DATABASE_URL"]})
ref = db.reference()

transloadit_client = client.Transloadit(app.config['TRANSLOADIT_KEY'], app.config['TRANSLOADIT_SECRET'])

IMAGE_URI = 'imageUri'
VIDEO_URI = 'videoUri'
MIME = 'mime'
VIDEO_DURATION = 'duration'
PROCESSING_MSG = "the pond is singing and the pond is warm and the pond is starting to give form"


@http_token_auth.verify_token
def verify_token(token):
    if app.config["ENABLE_AUTH"]:
        try:
            auth.verify_id_token(token)
コード例 #35
0
ファイル: fbm.py プロジェクト: adi1001/MagnusCollective
	This code is developed for The Magnus Collective. 
	
	The below code retrieves data from firebase continuously using firebase-admin
	module, which assumes the path to json keyfile is pointed properly 
	Though future uses may see use of python-firebase at places so both modules are imported

'''

import firebase
import firebase_admin
from firebase import firebase
from firebase_admin import db
from firebase_admin import credentials


cred = credentials.Certificate("/path/to/Credentials.json")
firebase=firebase.FirebaseApplication('https://example.firebaseio.com/')
firebase_admin.initialize_app(cred, {'databaseURL': 'https://example.firebaseio.com/'})

#access the reference and child nodes 
reference = db.reference('/rflags')
child_reference = reference.child('rai')
#get the data from the node
request_from1 = child_reference.get()


print(request_from1)