Ejemplo n.º 1
0
    def test_case_title(self):
        f = "%s-%s"

        book_num = self.fake.pyint()
        register = None
        case = Case(
            book_num=book_num,
            register=register,
        )
        self.assertEqual(case.title(f), f % ('', book_num))

        book_num = self.fake.pyint()
        register = Register(
            fund=self.fake.pystr()[:5],
            register=self.fake.pyint(),
        )
        case = Case(
            book_num=book_num,
            register=register,
        )
        self.assertEqual(case.title(f), f % (register, book_num))

        book_num = None
        register = Register(
            fund=self.fake.pystr()[:5],
            register=self.fake.pyint(),
        )
        case = Case(
            book_num=book_num,
            register=register,
        )
        self.assertEqual(case.title(f), f % (register, 1))
Ejemplo n.º 2
0
def createNewCase(request):
    form = CaseForm(request.POST or None)

    if form.is_valid():
        docs_type   = request.POST.getlist('file-type')
        docs        = request.FILES.getlist('docs')

        newRealEstate = form.save()
        newCase = Case(realEstate = newRealEstate)
        newCase.save()
        
        newCase.casestatus_set.create(case = newCase, status = Status.objects.get( pk = 1 ), dataEntryUpdate=datetime.now() , InspectorUpdate=datetime.now())

        # newCase.status.add(Status.objects.get(pk=1))
        UserCase(user_id=request.user, case_id=newCase).save()        
        UserCase(user_id=form.cleaned_data['inspector'], case_id=newCase).save()  

        if docs and docs_type:
            for (doc, doc_type) in zip(docs, docs_type):
                newRealEstate.realestatedocument_set.create(document=doc, document_type=DOCUMENTS_TYPE[doc_type])


        messages.success(request, 'تمت إضافة المعاملة بنجاح وإرسالها للمعاين {}'.format(form.cleaned_data['inspector']))
        form = CaseForm()
        return HttpResponseRedirect(reverse('Coordinator:new_case'))
    
    context = {
        'form' : form,
    }
    return render(request, 'coordinator/createNewCase.html', context)
Ejemplo n.º 3
0
def import_custom_case(filename, field_name, case_name, **kwargs):
    lines_as_ordered_dicts = read_file(filename)

    field, was_created = get_or_create(db.session, Field, name=field_name)
    db.session.add(field)

    data_dicts = [
        line_dict for line_dict in lines_as_ordered_dicts
        if not _should_ignore(line_dict)
    ]

    case_name = case_name if case_name else lines_as_ordered_dicts[0]['model']
    metrics = _get_metrics_with_data(lines_as_ordered_dicts)
    case = Case(name=case_name,
                field=field,
                phases=['TOTAL'],
                metrics=metrics,
                **kwargs)
    db.session.flush()

    locations = _add_locations(data_dicts, case=case)
    db.session.flush()

    realizations = _add_realizations(data_dicts,
                                     locations=locations,
                                     case=case)
    db.session.add_all(realizations.values())
    db.session.flush()

    _add_volumetrics(data_dicts,
                     realizations=realizations,
                     locations=locations,
                     case=case)
Ejemplo n.º 4
0
def print_coverage_stats():
    total_count = Case.select().count()
    has_transcript_count = Case.select().where(
        Case.transcript.is_null(False)).count()
    coverage = float(has_transcript_count) / float(total_count)
    logging.info(
        "There are %s cases and %s cases with transcripts, for a coverage of %s%s."
        % (total_count, has_transcript_count, round(coverage * 100.0, 2), "%"))
    total_count = Transcript.select().count()
    has_case_count = len([
        transcript for transcript in Transcript.select()
        if transcript.cases.count() > 0
    ])
    coverage = float(has_case_count) / float(total_count)
    logging.info(
        "There are %s transcripts and %s transcripts with cases, for a coverage of %s%s."
        % (total_count, has_case_count, round(coverage * 100.0, 2), "%"))
Ejemplo n.º 5
0
 def add_cases(self, request: HttpRequest, _: QuerySet):
     print(request.POST['city'])
     number_cases = int(request.POST['number_cases'])
     city = City.objects.get(uuid=request.POST['city'])
     cases_to_create = [
         Case(additional_details=f'This case is created automatically by admin for {city.name}', in_quarantine=False,
              automatically_created=True, city=city)
         for _ in range(number_cases)
     ]
     Case.objects.bulk_create(cases_to_create)
Ejemplo n.º 6
0
def addCase(date_str, title_str, keywords_str, introduction_str,
            description_str, image_ids):
    c = Case(date_str, title_str, keywords_str, introduction_str,
             description_str)
    db.session.add(c)
    try:
        db.session.commit()
    except Exception, e:
        db.session.rollback()
        return -1
Ejemplo n.º 7
0
def fill():
    "Fill db with sample data"
    fake = Factory.create('ru_RU')

    registers = random.randint(10, 50)
    for register_id in range(registers):
        register = Register()
        register.randomize(fake)

        print("Record#%d of %d: %s" % (register_id, registers, register))
        db.session.add(register)
        db.session.commit()

        cases = random.randint(1, 100)
        for case_id in range(cases):
            case = Case()
            case.randomize(fake)
            case.register = register

            print("\tRecord#%d of %d: %s" % (register_id, registers, register))
            print("\tCase#%d of %d: %s" % (case_id, cases, case))
            db.session.add(case)
            db.session.commit()

            protocols = random.randint(1, 50)
            for protocol_id in range(protocols):
                protocol = Protocol()
                protocol.randomize(fake)
                protocol.case = case

                print("\t\tRecord#%d of %d: %s" %
                      (register_id, registers, register))
                print("\t\tCase#%d of %d: %s" % (case_id, cases, case))
                print("\t\tProtocol#%d of %d: %s" %
                      (protocol_id, protocols, protocol))
                db.session.add(protocol)
                db.session.commit()

                decisions = random.randint(1, 20)
                for decision_id in range(decisions):
                    decision = Decision()
                    decision.randomize(fake)
                    decision.protocol = protocol

                    print("\t\t\tRecord#%d of %d: %s" %
                          (register_id, registers, register))
                    print("\t\t\tCase#%d of %d: %s" % (case_id, cases, case))
                    print("\t\t\tProtocol#%d of %d: %s" %
                          (protocol_id, protocols, protocol))
                    print("\t\t\tDecision#%d of %d: %s" %
                          (decision_id, decisions, decision))
                    db.session.add(decision)
                    db.session.commit()
Ejemplo n.º 8
0
def add_case():
    session = session_maker()
    parser = reqparse.RequestParser()
    parser.add_argument('name', type=str)
    parser.add_argument('schema', type=str)
    parser.add_argument('keywords', type=str)
    parser.add_argument('response', type=str)
    parser.add_argument('total_count', type=int)
    parser.add_argument('comments', type=str)
    args = parser.parse_args()
    session.add(Case(**args))
    session.commit()
    return Response.success()
Ejemplo n.º 9
0
    def post(self):
        """
        Adds a new case.
        """
        data = api.payload
        name = data.get('name')

        if Case.query.filter_by(name=name).first() is not None:
            return {'message': "The case\'s name already exists!"}, 400

        case = Case(name=name)
        db.session.add(case)
        db.session.commit()
        return {'element': case.to_json()}, 201
Ejemplo n.º 10
0
    def put(self, id):
        """
        Updates a problem.
        """
        data = request.json

        topics = data['topics']
        test_cases = data.get('cases')
        data.pop('topics', None)
        data.pop('cases', None)

        # Update problem's common fields
        Problem.query.filter(Problem.id == id).update(data)

        # Update test cases
        if (test_cases is not None):
            Case.query.filter(Case.problem_id == id).delete()

            # Create test cases
            for i in range(len(test_cases)):
                new_case = Case(is_sample=test_cases[i]['is_sample'],
                                input=test_cases[i]['input'],
                                feedback=test_cases[i]['feedback'],
                                output=test_cases[i]['output'],
                                problem_id=id)
                db.session.add(new_case)

            update_test_cases_in_filesystem({
                'problem_id': id,
                'test_cases': test_cases
            })

        # Delete problem's topics
        ProblemTopic.query.filter(ProblemTopic.problem_id == id).delete()

        # Create new problem's topic
        new_problemtopic = ProblemTopic(problem_id=id, topic_id=topics)
        db.session.add(new_problemtopic)

        db.session.commit()

        return None, 204
Ejemplo n.º 11
0
def import_fmu_case(filename, field_name, case_name, **kwargs):
    lines_as_ordered_dicts = _read_fmu_file(filename)

    field, was_created = get_or_create(db.session, Field, name=field_name)
    db.session.add(field)

    case_name = case_name if case_name else lines_as_ordered_dicts[0]['case']
    metrics = _get_metrics_with_data(lines_as_ordered_dicts)
    phases = _get_phases_with_data(lines_as_ordered_dicts)
    case = Case(name=case_name, field=field, metrics=metrics, phases=phases, **kwargs)
    db.session.flush()

    locations = _add_locations(lines_as_ordered_dicts, case)
    db.session.flush()

    realizations = _add_realizations(lines_as_ordered_dicts, locations=locations)
    db.session.add_all(realizations.values())
    db.session.flush()

    _add_volumetrics(lines_as_ordered_dicts, realizations=realizations, locations=locations)
Ejemplo n.º 12
0
def reconciliate_cases_and_transcripts():
    case_dockets = {}
    transcript_dockets = {}
    for case in Case.select():
        try:
            case_dockets[preprocess_docket(case.docket)] = case
        except:
            continue

    for transcript in Transcript.select():
        try:
            transcript_dockets[preprocess_docket(
                transcript.docket)] = transcript
        except:
            continue

    for docket in case_dockets:
        if docket in transcript_dockets:
            case = case_dockets[docket]
            case.transcript = transcript_dockets[docket]
            case.save()
Ejemplo n.º 13
0
def step_impl(context):
    context.cases = {}
    for row in context.table:
        name = row['name']
        case_version = row['case_version']
        case_type = row['case_type']
        description = row['description']
        created_user = row['created_user']
        is_official = row['is_official'] == 'True'
        is_shared = row['is_shared'] == 'True'
        case = Case(
            name=name,
            case_version=case_version,
            case_type=case_type,
            description=description,
            created_user=created_user,
            is_official=is_official,
            is_shared=is_shared,
            field=context.fields[row['field']],
        )
        context.cases[name] = case
        db.session.add(case)
    db.session.commit()
Ejemplo n.º 14
0
    def post(self):
        """
        Creates a problem
        """
        data = request.json

        #############
        # Update DB #
        #############

        # Create problem
        problem_name = data.get('name')
        description_english = data.get('description_english')
        description_spanish = data.get('description_spanish')
        memory_limit = data.get('memory_limit')
        time_limit = data.get('time_limit')
        language = data.get('language')
        author_id = data.get('author_id')
        difficulty = data.get('difficulty')
        code = data.get('code')
        template = data.get('template')
        signature = data.get('signature')
        test_cases = data['test_cases']
        topic_id = data['topic_id']
        # Added for subproblems functionality
        is_subproblem = data.get('is_subproblem')
        belongs_to = data.get('belongs_to')

        new_problem = Problem(name=problem_name,
                              author_id=author_id,
                              difficulty=difficulty, active=True,
                              language=language, code=code, template=template, signature=signature,
                              description_english=description_english,
                              description_spanish=description_spanish,
                              time_limit=time_limit, memory_limit=memory_limit, is_subproblem=is_subproblem,
                              belongs_to=belongs_to)
        db.session.add(new_problem)
        db.session.commit()
        problem_id = new_problem.id

        new_stat = Statistic(total_submissions = 0, total_accepted_submissions = 0, problem_id = new_problem.id)
        db.session.add(new_stat)
        db.session.commit()

        # Create problem-topic entry
        if (not(is_subproblem)):
            new_problemtopic = ProblemTopic(problem_id=problem_id,
                                            topic_id=topic_id)
            db.session.add(new_problemtopic)
            db.session.commit()

        # Create test cases
        for i in range(len(test_cases)):
            new_case = Case(is_sample=test_cases[i]['is_sample'],
                            input=test_cases[i]['input'],
                            feedback=test_cases[i]['feedback'],
                            output=test_cases[i]['output'],
                            problem_id=problem_id)
            db.session.add(new_case)
            db.session.commit()

        # Add input and output files to filesystem
        json = {}
        json['test_cases'] = data['test_cases']
        json['problem_id'] = problem_id

        result = services.upload_problem(json)

        return result
Ejemplo n.º 15
0
        # return render_template('case/testcase.html',data=data)
        # for k,v in range(len(user)):
        #     print(k,':',v)
        return render_template('case/testcase.html', content=case)
    else:
        exceldata = request.form.get('exceldata')
        id_list = eval(exceldata)

        for index in id_list:
            # print (type (index))
            # print(eval(index))
            values = list(index.values())
            case1 = Case(own_project=values[1],
                         functional_module=values[2],
                         case_title=values[3],
                         priority=values[4],
                         front_term=values[5],
                         case_description=values[6],
                         expect_result=values[7],
                         remarks=values[11])
            # case.append(case)
            db.session.add(case1)
            db.session.commit()
            # print(index[0],values)
        data = {"status": "1", "msg": "导入成功"}

        # a = [1, 2, 3, 4, 5, 6]
        # b = [6, 7, 8, 9, 0, 1]
        #
        # # user = User (user_name=name, user_password=pwd)
        # # db.session.add (user)
        # # db.session.commit ()  # 提交
Ejemplo n.º 16
0
def new(request):
    case = Case(source="Hello World")
    case.save()
    return HttpResponseRedirect(case.get_absolute_url())
Ejemplo n.º 17
0
def cases():

    params = request.form
    form = dict((k, v) for k, v in params.items() if v)

    aaData = []
    start = int(str(form.get("iDisplayStart")))
    display_length = int(str(form.get("iDisplayLength")))
    end = start + display_length
    search_0 = form.get('sSearch_0')
    search_1 = form.get('sSearch_1')
    search_2 = form.get('sSearch_2')
    search_3 = form.get('sSearch_3')
    search_4 = form.get('sSearch_4')
    search_5 = form.get('sSearch_5')
    search_6 = form.get('sSearch_6')
    search_7 = form.get('sSearch_7')

    update_time = Case.update_time()

    ORDER_BY_FIELDS = {
        0: 'username',
        1: 'email',
        2: 'is_active',
        4: 'date_joined',
    }
    all_cases = db.session.query(Case).join(State).join(
        CountryProcedence).filter(Case.created_at == update_time)
    if search_0:
        all_cases = all_cases.filter(State.name.like("%%%s%%" % search_0))

    if search_1:
        all_cases = all_cases.filter(Case.sex.like("%%%s%%" % search_1))

    if search_2:
        all_cases = all_cases.filter(Case.age.like("%%%s%%" % search_2))

    if search_3:
        all_cases = all_cases.filter(
            Case.symptom_date.like("%%%s%%" % search_3))

    if search_4:
        all_cases = all_cases.filter(Case.status.like("%%%s%%" % search_4))

    if search_5:
        all_cases = all_cases.filter(
            Case.type_contagion.like("%%%s%%" % search_5))

    if search_6:
        all_cases = all_cases.filter(
            CountryProcedence.name.like("%%%s%%" % search_6))

    if search_7:
        all_cases = all_cases.filter(
            Case.arrival_to_mexico.like("%%%s%%" % search_7))

    all_cases.all()
    count = all_cases.count()
    """
    if sort:
        direction = '-' if request.POST.get('sSortDir_0') == 'desc' else '' # asc or desc?
        index_of_field = int(sort) # order by which field?
        order_statment = direction + ORDER_BY_FIELDS.get(index_of_field)
        users = users.order_by(order_statment)
    """

    aaData = [(case.to_dict()) for case in all_cases[start:end]]
Ejemplo n.º 18
0
def obc_form(request, citizen_id=None, aadhaar_number=None):
    if request.method == "POST":
        obc_form_response = OBCFormResponse()
        obc_form = OBCFormForm(request.POST, instance=obc_form_response)
        
        if obc_form.is_valid():
            case = Case()
            case.office = Office.first()
            case.sms_selected = False
            case.robo_call_selected = False
            case.follow_up_selected = False
            
            office_visit = OfficeVisit()

            if citizen_id != None:
                citizen = Citizen.objects.get(pk = citizen_id)
                case.citizen = citizen
                case.save()

                office_visit.citizen = citizen
                office_visit.case = case
                office_visit.save()
            else:
                user = Citizen()
                citizen = CitizenForm(request.POST, instance=user)
                if citizen.is_valid():
                    citizen = citizen.save()
                    case.citizen = citizen
                    case.save()

                    office_visit.citizen = citizen
                    office_visit.case = case

                    office_visit.save()

            obc_form = obc_form.save(commit=False)
            obc_form.citizen = citizen
            obc_form.office_visit = office_visit
            obc_form.save() 
        return HttpResponseRedirect(reverse('aadhaar_lookup'))


    if request.method == "GET":
        obc_form = OBCFormForm()
        citizen_form = CitizenForm(initial={'aadhaar_number': aadhaar_number})
        inputFilter = ["Caste Serial Number", "Name of Father", "Name of Mother", "Male Constitutional Posts",
            "Female Constitutional Posts","Male Start of Appointment", "Male End of Appointment","Female Start of Appointment", "Female End of Appointment"]
        if citizen_id != None:
            try:
                citizen = Citizen.objects.get(pk=citizen_id)
                context = {'obc_form': obc_form, 'citizen': citizen, 'citizen_form':citizen_form, 'inputFilter': inputFilter}
                return render(request, 'bribecaster/OBC_form.html', context)
            except Exception as e:
                pass
        citizen = None
        context = {'obc_form': obc_form, 'citizen': citizen, 'citizen_form':citizen_form, 'inputFilter': inputFilter}
        return render(request, 'bribecaster/OBC_form.html', context)
Ejemplo n.º 19
0
def upload_file():
    if request.method == 'POST':
        # get file from form
        f = request.files['file']
        # if form is not empty
        if f:
            # temporarily save uploaded archive in folder with same name as archive filename
            filename = secure_filename(f.filename)
            folder = (app.config['UPLOAD_FOLDER'] + filename).replace('.zip', '')
            os.makedirs(folder)
            f.save(os.path.join(folder, filename))

            # extract uploaded archive to folder and delete original archive
            with open(os.path.join(folder, filename), 'r') as f:
                z = zipfile.ZipFile(f)
                z.extractall(folder)
            if REMOVE_TEMP:
                os.remove(f.name)

            # get encrypted AES key (128-bit SHA-1 of plaintext password) from XML file and decrypt using RSA private key
            with open(os.path.join(folder, 'accountData.xml'), 'r') as f:
                g = f.read()

            root = ET.fromstring(g)
            username = root.find('user').text
            enc_aes_key = root.find('pass').text.replace('\n','')
            enc_aes_key = base64.b64decode(enc_aes_key)
            private_key = RSA.importKey(Key.query.first().private_key)
            aes_key = private_key.decrypt(enc_aes_key)

            # decrypt image archive using decrypted AES key
            with open(os.path.join(folder, 'cipherZipFile.zip'), 'r') as f:
                enc_img_zip = f.read()
                cipher = AES.new(aes_key, AES.MODE_ECB, 'dummy_parameter')
                msg = cipher.decrypt(enc_img_zip)

            # store decrypted image archive on disk
            with open(os.path.join(folder, 'decrypted.zip'), 'w') as f:
                f.write(msg)
            if REMOVE_TEMP:
                os.remove(os.path.join(folder, 'cipherZipFile.zip'))

            # extract decrypted image archive and store in database
            with open(os.path.join(folder, 'decrypted.zip'), 'r') as f:
                z = zipfile.ZipFile(f)
                z.extractall(folder)
            if REMOVE_TEMP:
                os.remove(f.name)

            # make case using XML data
            tree = ET.parse(os.path.join(folder, 'textData.xml'))
            root = tree.getroot()
            mapping = {}
            for child in root:
                mapping[child.tag] = child.text
            month, day, year = map(int, mapping['date-created'].split('/'))
            hours, minutes, seconds = map(int, mapping['time-created'].split(':'))
            latitude = float(mapping['latitude'])
            longitude = float(mapping['longitude'])
            species = mapping['species'].replace('Plasmodium ', '').capitalize()
            age = mapping['age']
            address = mapping['address']
            region = Region.query.filter(Region.name == mapping['region']).first()

            dt = datetime.datetime(year, month, day, hours, minutes, seconds)
            case = Case(date=dt,age=age,address=address,human_diagnosis=species,lat=latitude,lng=longitude)
            case.region = region

            user = User.query.filter(User.username == username).first()
            hex_aes_key = ''.join(x.encode('hex') for x in aes_key)
            if hex_aes_key == user.password[:32]:
                db.session.add(case)
                db.session.commit()

                # store images in database
                for img_file in glob.glob(os.path.join(folder, "*.jpg")):
                    img = Image()
                    img.create_image(img_file, case)
                    db.session.add(img)
                    db.session.commit()
                    
                    # make new training image
                    trainingImg = TrainingImage(img.id, 0, 'Unlabeled', 'Unlabeled', None)
                    db.session.add(trainingImg)
                    db.session.commit()

                return 'OK'
            else:
                # {'username': (tries, case, folder)
                upload_cache[username] = (0, case, folder)
                return 'RETYPE 0'


    return '''
Ejemplo n.º 20
0
def import_yml(input=None):
    "Import data from db"
    if input is None:
        print("No data to import")
        return
    else:
        with open(input, 'r') as infile:
            try:
                print("Load from \"%s\"" % (input))
                data = yaml.load(infile)
                version = data.get('version')
                if version == "1.0.0":
                    print(version)

                    registers = data.get('registers', [])
                    register_lookup = dict()
                    for r in registers:
                        fund = r.get('fund')
                        register = Register.query.filter_by(
                            fund=fund, register=r.get('register')).first()
                        if register is None:
                            register = Register(fund=fund)
                        register.import_yml(r)
                        print("%s:\t%s" % (r.get('fund'), r))
                        register_lookup[r.get('id')] = register
                        db.session.add(register)
                    db.session.commit()

                    cases = data.get('cases', [])
                    case_lookup = dict()
                    for c in cases:
                        register = register_lookup.get(int(c.get('register')))
                        case = Case(register=register)
                        case.import_yml(c)
                        print("%s:\t%s" % (register, c))
                        case_lookup[int(c.get('id'))] = case
                        db.session.add(case)
                    db.session.commit()

                    protocols = data.get('protocols', [])
                    protocol_lookup = dict()
                    for p in protocols:
                        case = case_lookup.get(p.get('case'))
                        protocol = Protocol(case=case)
                        protocol.import_yml(p)
                        print("%s:\t%s" % (case, p))
                        protocol_lookup[int(p.get('id'))] = protocol
                        db.session.add(protocol)
                    db.session.commit()

                    decisions = data.get('decisions', [])
                    decision_lookup = dict()
                    for d in decisions:
                        protocol = protocol_lookup.get(d.get('protocol'))
                        decision = Decision(protocol=protocol)
                        decision.import_yml(d)
                        print("%s:\t%s" % (protocol, d))
                        decision_lookup[int(d.get('id'))] = decision
                        db.session.add(decision)
                    db.session.commit()

                    resolutions = data.get('resolutions', [])
                    for r in resolutions:
                        case = case_lookup.get(r.get('case'))
                        decision = decision_lookup.get(r.get('decision'))
                        resolution = Resolution(case=case, decision=decision)
                        resolution.import_yml(r)
                        print("%s, %s:\t%s" % (case, decision, r))
                        db.session.add(resolution)
                    db.session.commit()

                    print(register_lookup)
                    print(case_lookup)
                    print(protocol_lookup)
                print("Loaded from \"%s\"" % (input))
            except yaml.YAMLError as exc:
                print(exc)
Ejemplo n.º 21
0
def upload_file():
    if request.method == 'POST':
        # get file from form
        f = request.files['file']
        # if form is not empty
        if f:
            # temporarily save uploaded archive in folder with same name as archive filename
            filename = secure_filename(f.filename)
            folder = (app.config['UPLOAD_FOLDER'] + filename).replace(
                '.zip', '')
            os.makedirs(folder)
            f.save(os.path.join(folder, filename))

            # extract uploaded archive to folder and delete original archive
            with open(os.path.join(folder, filename), 'r') as f:
                z = zipfile.ZipFile(f)
                z.extractall(folder)
            if REMOVE_TEMP:
                os.remove(f.name)

            # get encrypted AES key (128-bit SHA-1 of plaintext password) from XML file and decrypt using RSA private key
            with open(os.path.join(folder, 'accountData.xml'), 'r') as f:
                g = f.read()

            root = ET.fromstring(g)
            username = root.find('user').text
            enc_aes_key = root.find('pass').text.replace('\n', '')
            enc_aes_key = base64.b64decode(enc_aes_key)
            private_key = RSA.importKey(Key.query.first().private_key)
            aes_key = private_key.decrypt(enc_aes_key)

            # decrypt image archive using decrypted AES key
            with open(os.path.join(folder, 'cipherZipFile.zip'), 'r') as f:
                enc_img_zip = f.read()
                cipher = AES.new(aes_key, AES.MODE_ECB, 'dummy_parameter')
                msg = cipher.decrypt(enc_img_zip)

            # store decrypted image archive on disk
            with open(os.path.join(folder, 'decrypted.zip'), 'w') as f:
                f.write(msg)
            if REMOVE_TEMP:
                os.remove(os.path.join(folder, 'cipherZipFile.zip'))

            # extract decrypted image archive and store in database
            with open(os.path.join(folder, 'decrypted.zip'), 'r') as f:
                z = zipfile.ZipFile(f)
                z.extractall(folder)
            if REMOVE_TEMP:
                os.remove(f.name)

            # make case using XML data
            tree = ET.parse(os.path.join(folder, 'textData.xml'))
            root = tree.getroot()
            mapping = {}
            for child in root:
                mapping[child.tag] = child.text
            month, day, year = map(int, mapping['date-created'].split('/'))
            hours, minutes, seconds = map(int,
                                          mapping['time-created'].split(':'))
            latitude = float(mapping['latitude'])
            longitude = float(mapping['longitude'])
            species = mapping['species'].replace('Plasmodium ',
                                                 '').capitalize()
            age = mapping['age']
            address = mapping['address']
            region = Region.query.filter(
                Region.name == mapping['region']).first()

            dt = datetime.datetime(year, month, day, hours, minutes, seconds)
            case = Case(date=dt,
                        age=age,
                        address=address,
                        human_diagnosis=species,
                        lat=latitude,
                        lng=longitude)
            case.region = region

            user = User.query.filter(User.username == username).first()
            hex_aes_key = ''.join(x.encode('hex') for x in aes_key)
            if hex_aes_key == user.password[:32]:
                db.session.add(case)
                db.session.commit()

                # store images in database
                for img_file in glob.glob(os.path.join(folder, "*.jpg")):
                    img = Image()
                    img.create_image(img_file, case)
                    db.session.add(img)
                    db.session.commit()

                    # make new training image
                    trainingImg = TrainingImage(img.id, 0, 'Unlabeled',
                                                'Unlabeled', None)
                    db.session.add(trainingImg)
                    db.session.commit()

                return 'OK'
            else:
                # {'username': (tries, case, folder)
                upload_cache[username] = (0, case, folder)
                return 'RETYPE 0'

    return '''
Ejemplo n.º 22
0
def request_post():
    """
		Content-Type: application/json
	"""
    data = request.form

    print data

    if 'case_id' not in data:
        # A new case
        try:
            device_id = data['device_id']
            longitude = data['longitude']
            latitude = data['latitude']

        except KeyError as e:
            # TODO: Handle missing param
            print sys.exc_info()
            return jsonify({"status": 400})

        # Create a new case
        case = Case(resolved=0)
        case_id = None

        try:
            db.session.add(case)
            db.session.commit()
            # Save the case id
            case_id = case.case_id
        except:
            print sys.exc_info()

    else:
        # Add a new request to an existing case
        try:
            case_id = data['case_id']
            device_id = data['device_id']
            longitude = data['longitude']
            latitude = data['latitude']

        except KeyError as e:
            # TODO: Handle missing param
            print sys.exc_info()
            return jsonify({"status": 400})

    # Add request into db
    req = Req(case_id=case_id,
              device_id=device_id,
              longitude=longitude,
              latitude=latitude)
    db.session.add(req)
    db.session.commit()

    # Send useful information to the front end
    map_msg = {
        "case_id": r['case_id'],
        "latitude": r['latitude'],
        "longitude": r['longitude']
    }

    # Send message to client
    socketio.emit('map message', map_msg)

    return jsonify({'status': 'success'})
Ejemplo n.º 23
0
                 color=color)
    return _


# Create a repeatable backlog of cases that have binomially distributed sizes and normally distributed values
logging.info('Creating standard cases')
np.random.seed(RANDOM_SEED)

standard_cases = []
sizes = np.random.gamma(10, size=NUM_SOURCE_CASES).astype(np.int64)
values = (np.random.normal(0, 1, size=NUM_SOURCE_CASES)) * 10
for idx, size in enumerate(sizes):
    standard_cases.append(
        Case(size=max(size, 1),
             value=values[idx],
             name='%d' % idx,
             workflow=StandardWorkflowFactory.make_workflow(
                 dev_size=size)))  # value = size

# Do multiple executions of this model where behaviour of models varies
runs = []
releases = []
cases = []
current_release = None  # a global resource, can only be one release active at a time
sourcers = []
dispatchers = []
finisher = None

for run in tqdm(range(NUM_RUNS)):
    logging.debug('---- Run %s -----' % run)
    # Create environment and start processes