def get_user(id):
    user = mongo.db.users.find_one({'_id': ObjectId(id)})
    response = json_util.dumps(user)
    return Response(response, mimetype="application/json")
Exemplo n.º 2
0
def generate_hatchlings(mother, father):
    """Return list of new rancho hatchlings based on parents."""
    egg_count = randint(6, 10)  # 6-10 hatchlings per brood
    species = mother['species']  # parents should be same species
    rancho_sexes = ['Male', 'Female']  # pick random from this
    hatchlings = []  # list will contain the brood's hatchlings

    for count in range(1, egg_count):
        # Stat generation: between parents' stats, +/-20, 0<= stat<= 100
        hardiness = randint(
            min(int(mother['stats']['hardiness']),
                int(father['stats']['hardiness'])) - 20,
            max(int(mother['stats']['hardiness']),
                int(father['stats']['hardiness'])) + 20)
        if hardiness > 100:
            hardiness = 100
        elif hardiness < 0:
            hardiness = 0

        dexterity = randint(
            min(int(mother['stats']['dexterity']),
                int(father['stats']['dexterity'])) - 20,
            max(int(mother['stats']['dexterity']),
                int(father['stats']['dexterity'])) + 20)
        if dexterity > 100:
            dexterity = 100
        elif dexterity < 0:
            dexterity = 0

        docility = randint(
            min(int(mother['stats']['docility']),
                int(father['stats']['docility'])) - 20,
            max(int(mother['stats']['docility']),
                int(father['stats']['docility'])) + 20)
        if docility > 100:
            docility = 100
        elif docility < 0:
            docility = 0

        conformation = randint(
            min(int(mother['stats']['conformation']),
                int(father['stats']['conformation'])) - 20,
            max(int(mother['stats']['conformation']),
                int(father['stats']['conformation'])) + 20)
        if conformation > 100:
            conformation = 100
        elif conformation < 0:
            conformation = 0

        stats = {
            'hardiness': str(hardiness),
            'dexterity': str(dexterity),
            'docility': str(docility),
            'conformation': str(conformation)
        }
        needs = {
            'food': 100,
            'water': 100,
            'health': 100,
            'happiness': 100,
            'last_cared': datetime.now(),
            'cared_by': mother['owner'],
            'cared_by_id': ObjectId(mother['user_id'])
        }
        ancestry = {
            'mother_name': mother['name'],
            'mother_id': mother['_id'],
            'father_name': father['name'],
            'father_id': father['_id']
        }
        rancho_sex = choice(rancho_sexes)
        rancho = {
            'name': 'Hatchling Rancho',
            'bio': rancho_sex + ' ' + species,
            'xp': 0,
            'level': 0,
            'stats': stats,
            'needs': needs,
            'ancestry': ancestry,
            'species': species,
            'sex': rancho_sex,
            'owner': mother['owner'],
            'user_id': ObjectId(mother['user_id'])
        }
        rancho_id = ranchos.insert_one(rancho).inserted_id
        hatchlings.append(rancho_id)
    return hatchlings
Exemplo n.º 3
0
def edit_task(task_id):
    the_task = mongo.db.tasks.find_one({"_id": ObjectId(task_id)})
    categories = mongo.db.categories.find()
    return render_template("edittask.html",
                           task=the_task,
                           categories=categories)
Exemplo n.º 4
0
    processed = []
    for db in data:
        db["_id"] = {"$oid": mongo_id_for_database(db["id"], db["type"])}
        processed.append(db)

    LOGGER.debug("  Inserting index links into collection from %s...",
                 CONFIG.index_links_path)
    links_coll.collection.insert_many(
        bson.json_util.loads(bson.json_util.dumps(processed)))

    LOGGER.debug(
        "  Adding Materials-Consortia providers to links from optimade.org...")
    providers = get_providers()
    for doc in providers:
        links_coll.collection.replace_one(
            filter={"_id": ObjectId(doc["_id"]["$oid"])},
            replacement=bson.json_util.loads(bson.json_util.dumps(doc)),
            upsert=True,
        )

    LOGGER.debug("Done inserting index links!")

# Add CORS middleware first
app.add_middleware(CORSMiddleware, allow_origins=["*"])

# Then add required OPTIMADE middleware
for middleware in OPTIMADE_MIDDLEWARE:
    app.add_middleware(middleware)

# Add exception handlers
for exception, handler in OPTIMADE_EXCEPTIONS:
Exemplo n.º 5
0
def delete_category(category_id):
    mongo.db.categories.remove({"_id": ObjectId(category_id)})
    flash("Category Successfuly Deleted")
    return redirect(url_for("get_categories"))
class SpecialCustomer(m.EmbeddedDocument):
	registered_date=m.DateTimeField(default=datetime.datetime.now)
	oid=m.ObjectIdField(default=lambda: ObjectId())
	customerid=m.ObjectIdField(required=True)
	note=m.StringField(default="N/A")
	warning_level=m.IntField(default=0)
Exemplo n.º 7
0
def history_items(item, oid, num, t=1):
    """
    The canvas's history
    item: server -- cpu, mem, load<1, 5, 15>
          web -- total connect lookup
    """
    if item in ('cpu', 'mem', 'load_1', 'load_5', 'load_15'):
        father, son = db.server, db.server_status
        id_name = 'server_ID'
    elif item in ('total', 'connect', 'lookup'):
        father, son = db.web, db.web_status
        id_name = 'web_ID'
    elif item == 'temp':
        father, son = db.server, db.temperature
        id_name = 'server_ID'
    else:
        abort(404)

    t = int(t)
    num = int(num)

    all_list = son.find({id_name: ObjectId(oid)}).sort('datetime', -1)
    page_count = all_list.count() // num + 1
    status_list = all_list.skip((t - 1) * num).limit(num)
    status_list = [i for i in status_list]
    end, start = status_list[0]['datetime'], status_list[-1]['datetime']
    dates = [i['datetime'].strftime('%m-%d-%H:%M') for i in status_list]

    if item == 'cpu':
        data_list = [i['cpu_usage'] for i in status_list]
        name = 'cpu'
    elif item == 'mem':
        data_list = [
            i['mem_info']['mem_used'] / i['mem_info']['mem_total'] * 100
            for i in status_list
        ]
        name = '内存'
    elif item == 'load_1':
        data_list = [float(i['load_avg']['lavg_1']) for i in status_list]
        name = '最近一分钟负载'
    elif item == 'load_5':
        data_list = [float(i['load_avg']['lavg_5']) for i in status_list]
        name = '最近五分钟负载'
    elif item == 'load_15':
        data_list = [float(i['load_avg']['lavg_15']) for i in status_list]
        name = '最近十五分钟负载'
    elif item == 'total':
        data_list = [i['total_time'] for i in status_list]
        name = '总时间'
    elif item == 'connect':
        data_list = [i['connect_time'] for i in status_list]
        name = '连接时间'
    elif item == 'lookup':
        data_list = [i['name_look_up'] for i in status_list]
        name = '域名解析时间'
    elif item == 'temp':
        data_list = [t['temp'] for t in status_list]
        name = '温度'
    else:
        abort(404)
    return template("history", locals())
Exemplo n.º 8
0
def recognition_controller():
    """Photo Controller

    To query a photo, use GET:

        /recognize?swag_id=<swag_id>

    To add a photo, use POST:

        headers:

            Content-Type: application/json

        data:

            {
                'swag_id': <swag_id>
            }

    """

    if request.method == 'GET':

        # Get photo path
        swag_id = request.args.get('swag_id', None)

        # Check if necessary data is available
        if not swag_id:
            abort(400, "Error: required paramter swag_id")

        # Retrieve image data
        swag = db('swags').find_one({'_id': ObjectId(swag_id)})
        if not swag:
            abort(404, "Error: Swag not found")

        # Validate photo if it exists
        success, response = validate_photo(swag['image_path'])
        if not success:
            abort(400, response)

        # Execute the query and return the result
        result = json.loads(fm.query(swag['image_path'])).get('results')
        return jsonify({'result': result})

    elif request.method == 'POST':

        # Get photo path
        swag_id = request.json.get('swag_id', None)

        # Get swag
        swag = db('swags').find_one({'_id': ObjectId(swag_id)})

        # Validate photo
        success, response = validate_photo(swag['image_path'])
        if not success:
            abort(400, response)

        # Add photo to FlannManager, get flannd' data.
        fm.add_photo(swag['_id'], swag['image_path'])

        ## Index photo
        #fm.create_index()

        # Return response.
        return jsonify({'_id': str(swag['_id']), 'image_path': swag['image_path']})

    else:
        abort(405)
Exemplo n.º 9
0
def get_player_alias_to_id_map(scraper, dao):
    player_map = dao.get_player_id_map_from_player_aliases(
        scraper.get_players())

    for alias, id in player_map.iteritems():
        print ''

        if id is None:
            click.echo("%s does not exist in the current region %s." %
                       (alias, dao.region_id))

            db_player_list = dao.get_players_by_alias_from_all_regions(alias)

            # print out alias matches from other regions as suggestions list
            if db_player_list:
                for db_player in db_player_list:
                    click.echo(str(db_player))

            # prompt to add as new player or add alias to existing player
            add_new = click.confirm("Add this player as a new player?",
                                    default=True)
            if add_new:
                name = click.prompt("Enter name", default=alias)
                alias_set = set()
                alias_set.add(name.lower())
                alias_set.add(alias.lower())

                db_player = dao.get_player_by_alias(name)
                if db_player:
                    click.echo("%s already exists, adding %s as an alias." %
                               (name, player))
                    dao.add_alias_to_player(db_player, player)
                    continue

                regions = []
                include_in_region = click.confirm(
                    "Associate with current region %s?" % dao.region_id,
                    default=True)
                if include_in_region:
                    regions.append(dao.region_id)

                player_to_add = Player(name, list(alias_set), DEFAULT_RATING,
                                       regions)
                click.echo('Inserting player: %s' % player_to_add)
                new_player_id = dao.insert_player(player_to_add)
                player_map[alias] = new_player_id
            else:
                player_id_to_use = click.prompt("Enter this player's ID")

                db_player = dao.get_player_by_id(ObjectId(player_id_to_use))
                if db_player is None:
                    raise Exception('Player with id % not found!' %
                                    player_id_to_use)

                if not alias.lower() in db_player.aliases:
                    add_alias = click.confirm(
                        "Add %s as a new alias for player %s?" %
                        (alias, db_player.name),
                        default=True)
                    if add_alias:
                        dao.add_alias_to_player(db_player, alias)

                player_map[alias] = db_player.id

    return player_map
Exemplo n.º 10
0
def getLoadAtividades():
    eventos = ""
    usuarioAtivo = current_user.get_id()

    db = utilitariosDB.getDb()
    adm = db['usuarios'].find({"_id": usuarioAtivo, "administrador": "S"})
    if adm == None:
        return "usuários não autorizado"
    else:
        evento = db['evento'].find().sort([("dataCadastro", pymongo.DESCENDING)
                                           ])

    eventos += (
        '<div class="card shadow mb-4">'
        '<div class="card-header py-3">'
        '<h6 class="m-0 font-weight-bold text-primary">Administração de Usuários</h6>'
        '<a href="/cadadmatividades">'
        '<button type="button" class="btn btn-primary float-right" >Cadastrar</button>'
        '</a>'
        '</div>'
        '<div class="card-body">'
        '<div class="table-responsive">'
        '<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">'
        '<thead>'
        '<tr>'
        '<th>Titulo</th>'
        '<th>Categoria</th>'
        '<th>Execução</th>'
        '<th>Local</th>'
        '<th>Pontos</th>'
        '<th>Vagas</th>'
        '<th>Inscrições</th>'
        '<th>Publicado</th>'
        '<th>Concluído</th>'
        '<th>Cadastro</th>'
        '<th>Publicar</th>'
        '<th>Concluir</th>'
        '</tr>'
        '</thead>'
        '<tbody>')

    for reg in evento:
        eventos += (
            '<tr id="' + str(reg.get('_id')) + '">'
            '<td>' + reg.get('titulo', '') + '</td>'
            '<td>' + reg.get('categoria', '') + '</td>'
            '<td>' + reg.get('momentoExecucao', '').strftime("%d/%m/%y") +
            '</td>'
            '<td>' + reg.get('local', '') + '</td>'
            '<td>' + str(reg.get('pontos', '')) + '</td>'
            '<td>' + str(reg.get('vagas', '')) + '</td>'
            '<td>' + str(reg.get('inscricoes', '')) + '</td>'
            '<td>' + reg.get('publicado', '') + '</td>'
            '<td>' + reg.get('concluido', '') + '</td>'
            '<td>' + reg.get('momentoCadastro', '').strftime("%d/%m/%y") +
            '</td>'
            '<td> <button type="button" class="btn btn-primary" onclick="publicarEvento(this)">Publicar</button></td>'
            '<td><button type="button" class="btn btn-primary" onclick="concluirEvento(this)">Concluir</button></td>'
            '</tr>')

    eventos += ('</tbody>' '</table>' '</div>' '</div>' '</div>')

    sideBar = Markup(getSideBar())

    usuario = db['usuarios'].find_one({"_id": ObjectId(usuarioAtivo)})
    navbar = Markup(getNavBar(usuario))

    return render_template("admUsuario.html",
                           contentWS=Markup(eventos),
                           sideBarWS=sideBar,
                           navbarWS=navbar)
Exemplo n.º 11
0
def getAdmFeedBack():
    # trazer todos os eventos ativos com feedback removendo os que estão no feedback ok
    # ter a intereção de dar feedback ok ou não ok
    # caso não ok o usuário deve receber um novo item na agenda

    usuarioAtivo = current_user.get_id()
    db = utilitariosDB.getDb()
    sideBar = Markup(getSideBar())

    usuario = db['usuarios'].find_one({
        "_id": ObjectId(usuarioAtivo),
        "administrador": "S"
    })
    if usuario == None:
        return "usuários não autorizado"

    navbar = Markup(getNavBar(usuario))

    eventoFeedBack = db['eventoFeedBack'].find({"status": "novo"})

    evento = ''
    for reg in eventoFeedBack:
        eventoDados = reg.get('evento', '')
        usuarioDados = reg.get('usuario', '')

        evento += (
            '<div  class="col-xl-12 col-md-6 mb-4">'
            '<div class="card border-left-primary shadow h-100 py-2">'
            '<div class="card-body">'
            '<div class="row no-gutters align-items-center">'
            '<div class="col mr-2">'
            '<div class="text-xs font-weight-bold text-primary text-uppercase mb-0">'
            + eventoDados.get('categoria', '') + ' - ' +
            usuarioDados.get('nome', '') + '</div>'
            '<div class="h5 mb-0 font-weight-bold text-gray-800"> Execução da atividade: '
            + eventoDados.get('momentoExecucao',
                              '').strftime("%d/%m as %H horas") + '</div>'
            '</div>'
            '<div class="col-auto">'
            '<i class="fas fa-calendar fa-2x text-primary mr-1" data-toggle="modal" data-target="#eventoModal'
            + str(reg.get('_id', '')) + '"></i>'
            '<i class="fas fa-exclamation-circle fa-2x text-danger mr-1" id="'
            + str(reg.get('_id', '')) +
            '" onclick="reprovarFeedBack(this)"></i>'
            '<i class="fas fa-check fa-2x text-success" id="' +
            str(reg.get('_id', '')) + '" onclick="aprovarFeedBack(this)"></i>'
            '</div>'
            '</div>'
            '</div>'
            '</div>'
            '</div>')

        evento += ('<div class="modal fade" id="eventoModal' +
                   str(reg.get('_id', '')) + '" tabindex="-1" role="dialog"  >'
                   '<div class="modal-dialog" role="document">'
                   '<div class="modal-content">')

        evento += (
            '<div class="card shadow-lg mb-4">'
            '<div class="card-header py-3">'
            '<h6 class="m-0 font-weight-bold text-primary text-center">' +
            eventoDados.get('titulo', '') + '</h6>')

        evento += ('</div>' '<div class="card-body pb-2 mb-1">')

        if (reg.get('feedBackTipo', '') == 'TEXTO'):
            texto = reg.get('feedback', '').split('\n')
            evento += ('<div class="card py-3 border-bottom-primary">'
                       '<div class="card-body pb-0 pt-0">'
                       '<p class="mb-0 pb-0 mt-0">' + str(texto) + '</p>'
                       '</div>'
                       '</div>'
                       '</div>'
                       '<div class="card-footer pb-0 pt-3 mt-0 text-center">')

        evento += (
            '<div class="modal-footer">'
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>'
            '</div>'
            '</div>'
            '</div>'
            '</div>')

    return render_template("admFeedBack.html",
                           contentWS=Markup(evento),
                           sideBarWS=sideBar,
                           navbarWS=navbar)
Exemplo n.º 12
0
    def insert_one(self, document):

        common.validate_is_document_type("document", document)
        if not (isinstance(document, RawBSONDocument) or "_id" in document):
            document["_id"] = ObjectId()
def view_my_details_recipe(recipe_id):
       recipes_document_by_recipe = mongo.db.recipes.find_one({"_id": ObjectId(recipe_id)})
       return render_template("view_my_details_recipe.html",
                                recipes_document_by_recipe = recipes_document_by_recipe)
Exemplo n.º 14
0
def delete_user(id):
    mongo.db.users.delete_one({'_id': ObjectId(id)})
    response = jsonify({'message': 'User ' + id + ' was Deleted successfuly'})
    return response
Exemplo n.º 15
0
 def atualizar_statuspacote(id, statuspacote):
     result = mycolStatusPacote.update_one({'_id': ObjectId(id)}, {"$set": statuspacote.__dict__})
     if result.modified_count > 0:
         print(f'\nO status do pacote foi alterado com sucesso.')
Exemplo n.º 16
0
def main(version, date):
    # define the db and pyasn file
    client = MongoClient()
    db = client['conexdat-db']
    coll = db['traceroutes']
    edge = db['edges']
    asndb = pyasn.pyasn('ipasns/' + date + '-ipasn-v' + str(version) + '.dat')

    # create an empty DataFrame for the paths
    paths = pd.DataFrame()

    # run for every traceroute with of the campaign with the passed version
    for x in coll.find({'af': version, 'schedule_date': date},
                       {'from': 1, 'dst_addr': 1}):
        # get hop-data from collection
        query = coll.aggregate([{'$match': {'_id': ObjectId(x['_id'])}},
                                {'$unwind': '$result'},
                                {'$project': {'hop': '$result.hop',
                                              'result': '$result.result'}},
                                {'$unwind': '$result'},
                                {'$project': {'hop': '$hop',
                                              'ip': '$result.from'}}])
        # make sure every column exists in case the traceroute contains no data
        df = pd.DataFrame(columns=['_id', 'hop', 'ip'])
        # write data into the DataFrame
        list_results = [r for r in query]
        df = df.append(pd.DataFrame(list_results), sort=False)
        # drop hops without answer
        df = df.dropna(subset=['ip'])
        # reduce entry per traceroute - hop pair to one
        df = df.drop_duplicates(subset=['hop'])

        path = []
        # iterate over every hop in the measurement
        if len(df) > 0:
            _, last = next(df.iterrows())
        for i, row in df.iterrows():
            # get the AS number to the IP address of the hop
            row.ip = asndb.lookup(row.ip)[0]
            # check if the adjacent hops are different
            if(type(row.ip) == int and type(last.ip) == int and
               row.ip != last.ip):
                # add the AS to the path
                path.append(str(row.ip))
                # check if ASes are directly connected
                if last.hop == row.hop - 1:
                    # insert AS-Pair if it doesn't exist
                    # or add date to arrayif not in it yet
                    if(edge.count_documents(
                        {'asn1': {'$in': [last.ip, row.ip]},
                         'asn2': {'$in': [last.ip, row.ip]}}) == 0):
                        edge.insert_one({'asn1': last.ip, 'asn2': row.ip,
                                         'version': version,
                                         'schedule_date': [date]})
                    else:
                        edge.update_one({'asn1': {'$in': [last.ip, row.ip]},
                                         'asn2': {'$in': [last.ip, row.ip]},
                                         'schedule_date': {'$nin': [date]}},
                                        {'$push': {'schedule_date': date}})
                else:
                    path[-1] += '*'
            last = row
        if len(path) > 1:
            paths = paths.append(pd.DataFrame({'source': asndb.lookup(
                x['from'])[0], 'target': asndb.lookup(x['dst_addr'])[0],
                                               'path': [path]}))
    paths.to_csv('paths/' + date + '_paths_v' + str(version)
                 + '.csv', index=False)
Exemplo n.º 17
0
 def excluir_statuspacote(id):
     mycolStatusPacote.delete_one({'_id': ObjectId(id)})
     print("Status do pacote excluído com sucesso!")
def delete(car_id):
    mongo.db.cars.remove({'_id': ObjectId(car_id)})
    return redirect(url_for("home"))
Exemplo n.º 19
0
def detail_location(oid):
    loc = db.location.find_one({'_id': ObjectId(oid)})
    servers = db.server.find({'location_ID': oid})
    return template('detail_loc', locals())
Exemplo n.º 20
0
def get(post_id):
    # Convert from string to ObjectId:
    document = client.db.collection.find_one({'_id': ObjectId(post_id)})
 def get_vis(self, vis_id):
     doc = self.db["onto_vis"].find_one({"_id": ObjectId(vis_id)})
     return doc
Exemplo n.º 22
0
    def article_action(self, *args, **kwargs):
        method = self.get_body_argument("method", default="")
        id = self.get_body_argument("id", default=None)
        if method in ("star", "unstar"):
            star = True if method == "star" else False
            post = yield self.db.article.find_and_modify(
                {"_id": ObjectId(id)}, {"$set": {
                    "star": star
                }})
            content = u"你的文章《%s》被管理员" % post["title"] + (u"加精" if star else
                                                         u"取消精华") + u"了"
            yield self.message(fromuser=None,
                               touser=post["user"],
                               content=content,
                               jump="/post/%s" % id)
        elif method in ("open", "close"):
            open = True if method == "open" else False
            post = yield self.db.article.find_and_modify(
                {"_id": ObjectId(id)}, {"$set": {
                    "open": open
                }})
            yield self.message(fromuser=None,
                               touser=post["user"],
                               jump="/post/%s" % id,
                               content=u"你的文章《%s》被管理员%s了" %
                               (post["title"], u"公开" if open else u"取消公开"))
        elif method in ("top", "notop"):
            top = True if method == "top" else False
            post = yield self.db.article.find_and_modify(
                {"_id": ObjectId(id)}, {"$set": {
                    "top": top
                }})
            yield self.message(fromuser=None,
                               touser=post["user"],
                               jump="/post/%s" % id,
                               content=u"你的文章《%s》被管理员%s了" %
                               (post["title"], u"置顶" if top else u"取消置顶"))
        elif method == "del":
            post = yield self.db.article.find_and_modify({"_id": ObjectId(id)},
                                                         remove=True)
            if not post:
                self.custom_error("不存在这篇文章", jump="/")
            yield self.db.member.update({},
                                        {"$pull": {
                                            "bookmark": {
                                                "id": id
                                            }
                                        }},
                                        multi=True)
            yield self.message(fromuser=None,
                               touser=post["user"],
                               jump="/post/%s" % id,
                               content=u"你的文章《%s》被管理员删除了" % post["title"])
            self.redirect("/")
        elif method == "rank":
            rank = intval(self.get_body_argument("rank"))
            post = yield self.db.article.find_one({"_id": ObjectId(id)})
            if not post:
                self.custom_error("不存在这篇文章")
            if "rank" in post and post.get("rank") != 0:
                self.custom_error("已经评分过啦")
            if not (-10 <= rank <= 10):
                self.custom_error("评分超出范围拉")
            yield self.db.member.find_and_modify({"username": post["user"]},
                                                 {"$inc": {
                                                     "money": rank
                                                 }})
            yield self.db.article.find_and_modify({"_id": ObjectId(id)},
                                                  {"$set": {
                                                      "rank": rank
                                                  }})
            yield self.message(fromuser=None,
                               touser=post["user"],
                               content=u"你的文章《%s》被管理员" % post["title"] +
                               (u"奖励" if rank > 0 else u"扣除") +
                               u"%d金币" % abs(rank),
                               jump="/post/%s" % id)

        self.redirect("/post/%s" % id)
Exemplo n.º 23
0
def delete_task(task_id):
    mongo.db.tasks.remove({"_id": ObjectId(task_id)})
    flash("Task Successfuly Deleted")
    return redirect(url_for("get_tasks"))
Exemplo n.º 24
0
def update_like_counter(dream_id, action):  # action = 'like' or 'dislike'
    dreams = mongo.db.dreams
    if action == 'like':
        dreams.update({'_id': ObjectId(dream_id)}, {'$inc': {'number_of_likes': 1}})
    elif action == 'unlike':
        dreams.update({'_id': ObjectId(dream_id)}, {'$inc': {'number_of_likes': -1}})
Exemplo n.º 25
0
def ranchos_show(rancho_id):
    """Show a single Rancho."""
    current_user = None
    if 'user' in session:
        current_user = session['user']
    rancho = ranchos.find_one({'_id': ObjectId(rancho_id)})

    if rancho is None:
        error = {
            'error_message':
            "That Rancho was not found. It may have been released.",
            'error_link': '/',
            'back_message': 'Back to home?'
        }
        return render_template('error_message.html',
                               error=error,
                               current_user=current_user)

    # Update needs
    timediff = datetime.now() - rancho['needs']['last_cared']
    if timediff.days > 0:
        if timediff.days >= 4:
            # Been more than four days since last cared for
            new_needs = {
                'food': 0,
                'water': 0,
                'health': 0,
                'happiness': 0,
                'last_cared': rancho['needs']['last_cared'],
                'cared_by': rancho['needs']['cared_by'],
                'cared_by_id': rancho['needs']['cared_by_id']
            }

        elif timediff.days >= 3:
            # Been more than three days since last cared for

            new_needs = {
                'food': 25,
                'water': 0,
                'health': 50,
                'happiness': 0,
                'last_cared': rancho['needs']['last_cared'],
                'cared_by': rancho['needs']['cared_by'],
                'cared_by_id': rancho['needs']['cared_by_id']
            }

        elif timediff.days >= 2:
            # Been more than two days since last cared for
            new_needs = {
                'food': 50,
                'water': 0,
                'health': 100,
                'happiness': 50,
                'last_cared': rancho['needs']['last_cared'],
                'cared_by': rancho['needs']['cared_by'],
                'cared_by_id': rancho['needs']['cared_by_id']
            }

        elif timediff.days >= 1:
            # Been more than a day since last cared for
            new_needs = {
                'food': 75,
                'water': 50,
                'health': 100,
                'happiness': 75,
                'last_cared': rancho['needs']['last_cared'],
                'cared_by': rancho['needs']['cared_by'],
                'cared_by_id': rancho['needs']['cared_by_id']
            }
        ranchos.update_one({'_id': ObjectId(rancho_id)},
                           {'$set': {
                               'needs': new_needs
                           }})

    return render_template('ranchos/ranchos_show.html',
                           rancho=ranchos.find_one(
                               {'_id': ObjectId(rancho_id)}),
                           broods=broods.find({
                               '$or': [{
                                   'mother_id': ObjectId(rancho_id)
                               }, {
                                   'father_id': ObjectId(rancho_id)
                               }]
                           }),
                           current_user=current_user)
Exemplo n.º 26
0
def response_ipn_listener(responseId):
    from ..main import app, PROD

    ipn_body = app.current_request.raw_body.decode()
    VERIFY_URL_PROD = "https://www.paypal.com/cgi-bin/webscr"
    VERIFY_URL_TEST = "https://www.sandbox.paypal.com/cgi-bin/webscr"
    sandbox = not PROD
    VERIFY_URL = VERIFY_URL_PROD if PROD else VERIFY_URL_TEST

    paramDict = parse_ipn_body(ipn_body)

    responseIdFromIpn = paramDict.get("custom", "")
    response = Response.objects.get({"_id": ObjectId(responseId)})

    def raise_ipn_error(message):
        print(f"IPN error, message {message}, paramDict {paramDict}")
        response.payment_trail.append(
            PaymentTrailItem(
                value=paramDict,
                status="ERROR",
                date=datetime.datetime.now(),
                method="paypal_ipn",
                id=message,
            ))
        response.save()

    if responseId != responseIdFromIpn:
        raise_ipn_error(
            "Response ID {} does not match this endpoint: {}".format(
                responseIdFromIpn, responseId))
        return ""

    # Post back to PayPal for validation
    headers = {
        "content-type": "application/x-www-form-urlencoded",
        "host": "www.paypal.com",
    }
    r = requests.post(
        VERIFY_URL + "?cmd=_notify-validate",
        data=ipn_body,
        headers=headers,
        verify=True,
    )
    r.raise_for_status()

    # Check return message and take action as needed
    if r.text == "VERIFIED":
        # payment_status completed.
        form = Form.objects.only("formOptions").get({"_id": response.form.id})
        expected_receiver_email = form.formOptions.paymentMethods[
            "paypal_classic"]["business"]
        if paramDict.get("txn_type", "") in (
                "subscr_signup",
                "subscr_cancel",
                "subscr_eot",
                "subscr_modify",
                # "subscr_payment",
                "subscr_failed",
        ):
            # Don't handle subscription signups, cancels, expiries.
            # TODO: actually handle these.
            raise_ipn_error(
                "txn_type is not supported and must be manually handled.")
            return ""
        if paramDict["receiver_email"] != expected_receiver_email:
            raise_ipn_error("Emails do not match. {}, {}".format(
                paramDict["receiver_email"], expected_receiver_email))
            return ""
        txn_id = paramDict.get("txn_id", None)
        if not txn_id:
            raise_ipn_error("No IPN transaction ID.")
            return ""
        if any(item.status == "SUCCESS" and item.id == txn_id
               and item.method == "paypal_ipn"
               for item in response.payment_trail):
            raise_ipn_error(f"Duplicate IPN transaction ID: {txn_id}")
            return ""
        # TODO: add check for mc_currency
        if paramDict["payment_status"] == "Completed":
            mark_successful_payment(
                form=form,
                response=response,
                full_value=paramDict,
                method_name="paypal_ipn",
                amount=paramDict["mc_gross"],
                currency=paramDict["mc_currency"],
                id=txn_id,
            )
            response.save()
        elif paramDict["payment_status"] == "Refunded":
            mark_successful_payment(
                form=form,
                response=response,
                full_value=paramDict,
                method_name="paypal_ipn",
                amount=paramDict["mc_gross"],
                currency=paramDict["mc_currency"],
                id=txn_id,
            )
            response.save()
        else:
            raise_ipn_error(
                "Payment_status is not supported. Only Completed and Refunded payment statuses are supported."
            )
            return ""
        # Has user paid the amount owed? Checks the PENDING_UPDATE for the total amount owed, else the response itself (when not updating).
        # fullyPaid = response["IPN_TOTAL_AMOUNT"] >= response.get("PENDING_UPDATE", response)["paymentInfo"]["total"]

        # if fullyPaid and "PENDING_UPDATE" in response:
        #     # Updates value from saved pending update value and sends email.
        #     response_verify_update(response, self.TABLES.responses, form.formOptions.confirmationEmailInfo)
        # else:
        #     # update it as paid or not.
    elif r.text == "INVALID":
        raise_ipn_error("Rejected by PayPal: {}".format(VERIFY_URL))
        return ""
    else:
        raise_ipn_error("IPN was neither VERIFIED nor INVALID.")
        return ""

    return ""
Exemplo n.º 27
0
            "x": shape[1],
            "y": shape[0]
        },
        "resized_img_dimensions": {
            "x": RESIZE_DIMENSIONS[0],
            "y": RESIZE_DIMENSIONS[1]
        },
        "values": np.concatenate(features).ravel().tolist()
    }


if len(sys.argv) < 2:
    print("Article's ID from MongoDB must be provided!")
    sys.exit()

article_id = ObjectId(sys.argv[1])

print("ID of the article to process images: " + str(article_id))

client = MongoClient('mongodb://localhost:27017/')

db = client["news-scraper"]

articles_collection = db.articles

article = articles_collection.find_one({"_id": article_id})
images = article['images']

for image in images:
    try:
        url = image['url']
Exemplo n.º 28
0
def get_trip(trip_id):
    result = trips.find_one({'_id': ObjectId(trip_id)})
    return result
Exemplo n.º 29
0
def update_task(task_id):
    tasks = mongo.db.tasks
    tasks.update({"_id": ObjectId(task_id)}, request.form.to_dict())
    return redirect(url_for("get_tasks"))
Exemplo n.º 30
0
import os
from bson.objectid import ObjectId
from ml_forest.pipeline.pipe_init import PipeInit

home = os.path.expanduser("~")
bucket = "mltests3mongo"
home_path = home + "/Desktop/test_ml_forest/experiment/local_storage"
project = "housing_price"

db = {"host":bucket, "project":project}
filepaths = [{"home": home_path, "project":project}]


# TODO: the test actually depends on PipeInit, should take it into account as well.
pipe_id = ObjectId("5b54ef67b6492933d34f7ed8")
pipe_init = PipeInit(pipe_id=pipe_id, filepaths=filepaths)
core_docs = pipe_init.core
init_fnodes = pipe_init.init_fnodes
init_lnode = pipe_init.init_lnode


import unittest

key = 'LandContour'

from ml_forest.core.utils.connect_mongo import connect_collection

from ml_forest.pipeline.nodes.stacking_node import FNode, LNode
from ml_forest.pipeline.links.connector import FConnector
from ml_forest.pipeline.links.knitor import Knitor