Example #1
0
def callback(request, auth_name):
    if auth_name == 'dropbox':
        post_dict = parser.parse(request.POST.urlencode())
        code = str(post_dict['code'])
        userid = str(post_dict['userid'])
        json_response = dbauth.handleCallback(userid, code, request)
        return HttpResponse(json_response)

    if auth_name == 'google':
        post_dict = parser.parse(request.POST.urlencode())
        code = str(post_dict['code'])
        json_response = gauth.handleCallback(code, request)
        return HttpResponse(json_response)

    return HttpResponse('Invalid URL')
def trainamodel(request):
    data = {}
    try:
        post_dict = parser.parse(request.POST.urlencode())

        socketid = post_dict['socketid']
        log_to_terminal('Beginning training a new model', post_dict['socketid'])

        old_save_dir = conf.PIC_DIR
        folder_name = str(socketid)
        save_dir = os.path.join(conf.PIC_DIR, folder_name)
        train_dir = os.path.join(save_dir, 'train')
        test_dir = os.path.join(save_dir, 'test')
        util_dir = os.path.join(save_dir, 'util')

        if not os.path.exists(os.path.join(old_save_dir, folder_name)):
            raise Exception('No training images has been provided for this job.')

        trainModel(save_dir, post_dict['socketid'])

        data['info'] = 'completed'
        response = JSONResponse(data, {}, response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        log_to_terminal('Finished training your model with the new categories. Now, upload some test images to test this model. ', socketid)
        return response
    except Exception as e:
        data['error'] = str(traceback.format_exc())
        log_to_terminal(str(traceback.format_exc()), socketid)
        response = JSONResponse(data, {}, response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response
Example #3
0
def delete_equipment(request):
    if request.method == 'POST':
        post = parser.parse(request.POST.urlencode())
        e = Equipment.objects.get(pk=int(post['equip']))
        print 'vai deletar aqui'
        #e.delete()
    return HttpResponse("ok", mimetype='application/json')
Example #4
0
	def get(self, request, **kwargs):
		arguments = parser.parse(request.GET.urlencode())

		take = arguments.get('take', 10)
		skip = arguments.get('skip', 0)
		total = skip+take
		filter_arg = dict()
		sort_arg = list()
		filter_logic = 'and'

		if(arguments.has_key('filter') and arguments['filter'].has_key('filters')):
			filter_arg = self._build_filters(arguments['filter']['filters'], filter_arg)
			filter_logic = arguments['filter']['logic'].upper()

		if(arguments.has_key('group')):
			sort_arg = self._build_sorts(arguments['group'], sort_arg)

		if(arguments.has_key('sort')):
			sort_arg = self._build_sorts(arguments['sort'], sort_arg)

		output = dict()

		try:
			filters = Q(**filter_arg)
			filters.connector = filter_logic
			items = self.model.objects.filter(filters).order_by(*sort_arg)
			if(self.distinct):
				items = items.distinct()
			self.queryset = items[skip:total]
			output = {'result':1, 'count':items.count(), 'payload':self.get_queryset()}
		except FieldError:
			output = {'result':0, 'error':'Invalid request. Tried to filter or sort using invalid field.'}

		return response_json(request, output)
Example #5
0
    def parse(self, stream, media_type=None, parser_context=None):
        import urllib
        from querystring_parser import parser
        from django.conf import settings

        encoding = parser_context.get("encoding", settings.DEFAULT_CHARSET)
        return parser.parse(stream.read(), unquote=True, encoding=encoding)
Example #6
0
def geocoder(request):
    
    parsed_dict = parser.parse(request.POST.urlencode())
                    
    r = Geocode(parsed_dict['addresses'])
        
    return HttpResponse(r, mimetype='application/json')
Example #7
0
def page_report(request, report, fmt='csv', conf=None):
    get_dict = parser.parse(request.GET.urlencode())
    objs = get_queryset(request, report, get_dict)[:100]
    if objs.count()==0:
        return HttpResponse('No Data')

#    if(isinstance(objs, list)):
#        conn = DictListConnector(objs, expand_obs=True)
#    else:
#        conn = DjangoQuerySetConnector(objs)

#    if report in REPORTS:
#        cls = REPORTS[report]
#        if cls.Meta.fields:
#            conn.header = cls.Meta.fields
#        elif cls.Meta.exclude:
#            conn.header = Set(conn.header) - Set(cls.Meta.exclude)
#        elif cls.Meta.sequence:
#            conn.header = Set(cls.Meta.sequence) | Set(conn.header)

    tf = tempfile.NamedTemporaryFile()
    fn = tf.name
    fp = open(fn, "w+")
    DataProvider.WriteData(objs, fmt, fn)
    fp.close()
    response = StreamingHttpResponse(open(fn), content_type='text/csv') 
    response['Content-Disposition'] = 'attachment; filename=' + report  + '.csv'
    return response
def set_led_values(device_name):
    check_device(device_name)
    dev = devices[device_name]
    args = parser.parse(request.get_data())
    for led, value in args['led'].items():
        dev.set_pwm(int(led), int(value))
    return create_response({'result': 'ok'})
Example #9
0
def decaf_train(request):
    post_dict = parser.parse(request.POST.urlencode())
    try:
        if 'urls' not in post_dict:
            data = {'error': 'NoFileSelected'}
        else:
            data = {'info': 'ProcessingImages'}

            # Download these images. Run Feature Extraction. Post results.
            uuid, image_path = downloadAndSaveImages(post_dict['urls'], post_dict['socketid'])

            output_path = os.path.join(image_path, 'results')
            if not os.path.exists(output_path):
                os.makedirs(output_path)
            decaf_wrapper_local(image_path, output_path, post_dict['socketid'], os.path.join(conf.PIC_URL, uuid))
            log_to_terminal('Processing Images Now', post_dict['socketid'])

        response = JSONResponse(data, {}, response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response
    except:
        data = {'result': str(traceback.format_exc())}
        response = JSONResponse(data, {}, response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response
Example #10
0
def show_deploy(request, cluster_id):


    #get_dict = parser.parse( unicode(request.GET.urlencode()).encode("utf-8") )
    #return uncache_response(HttpResponse(json.dumps(get_dict, indent=2), content_type="text/plain"))
    #return uncache_response(HttpResponse( get_dict['password'] , content_type="text/plain"))

    context = {}
    password = None

    try:
        cluster = ClusterDefinition.objects.get( id=cluster_id )

        if cluster.encryption_checksum != '':
            try:
                get_dict = parser.parse( unicode(request.GET.urlencode()).encode("utf-8") )
                password = get_dict['password']
                cluster.decrypt(password)
            except Exception as e:
                #messages.error(request, "The password provided is wrong: %s" % e)
                messages.error(request, "The password provided is wrong")
                return render(request, "cluster/deploy.html", {})

    except ClusterDefinition.DoesNotExist, Http404:
        messages.error(request, 'Cluster does not exist')
        return render(request, "cluster/deploy.html", {})
    def get(self):
        args = parser.parse(request.query_string)
        options = {
            "start": args.get("start", 0),
            "limit": args.get("length", 10),
            "search": args.get("search", {}).get("value"),
        }

        columns = []
        for i in range(len(args["columns"])):
            columns.append(args["columns"][i])

        order = []
        for i in range(len(args["order"])):
            column_id = args["order"][i]["column"]
            order.append({"column": columns[column_id]["data"], "dir": args["order"][i]["dir"]})
        options["order"] = order

        rows, total = self.get_queryset(**options)
        data = []
        for row in rows:
            row_data = {}
            for column in columns:
                callback = getattr(self, "process_%s" % column["data"], lambda row, val: val)
                val = getattr(row, column["data"], None)
                row_data[column["data"]] = callback(row, val)
            data.append(row_data)

        return jsonify(recordsTotal=total, recordsFiltered=total, data=data)
Example #12
0
    def parse(self, stream, media_type=None, parser_context=None):
        from querystring_parser import parser
        from django.conf import settings

        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
        encoded_data = stream.read().decode(encoding)
        return parser.parse(encoded_data)
Example #13
0
def get_bookmarks(request):
    #sync the client-side bookmarks with the server side bookmarks
    #update the server-side bookmarks and return the new list
    try:        
        bookmark_dict = parser.parse(request.POST.urlencode())['bookmarks']
    except:
        bookmark_dict = {}
    try:
        #loop through the list from the client
        #if user, bm_name, and bm_state match then skip 
        #otherwise, add to the db
        for key,bookmark in bookmark_dict.items():
            try:
                Bookmark.objects.get(user=request.user, name=bookmark['name'], url_hash=bookmark['hash'])
            except:
                new_bookmark = Bookmark(user=request.user, name=bookmark['name'], url_hash=bookmark['hash'])
                new_bookmark.save()
    
        #grab all bookmarks belonging to this user 
        #serialize bookmarks into 'name', 'hash' objects and return simplejson dump 
        content = []
        bookmark_list = Bookmark.objects.filter(user=request.user)
        for bookmark in bookmark_list:
            content.append({'name': bookmark.name, 'hash': bookmark.url_hash})
        return HttpResponse(simplejson.dumps(content), mimetype="application/json", status=200)
    except:
        return HttpResponse(status=304)
Example #14
0
def _validate_for_save(request):
    """
    Validates the HttpRequest. It uses the forms defined in forms.py to
    check all the fields and runs some additional checks. It returns
    an HttpResponse instance if request is invalid and the dictionary of clean
    date otherwise.
    """
    data = parser.parse(request.POST.urlencode())
    clean_data = {}

    # Cluster section
    cluster_f = ClusterForm(data.get("cluster", {}))
    if not cluster_f.is_valid():
        for label, msg in cluster_f.errors_list:
            messages.error(request, "Cluster %s: %s" % (label, msg))
        return _show_cluster_def(request, data)
    clean_data["cluster"] = cluster_f.clean()

    # Check that contexts belong to user or is public
    for context_field_code in ["master_context_id", "worker_context_id"]:
        c = ContextDefinition.objects.get(
            id=clean_data["cluster"][context_field_code]
        )
        if not c.public and c.owner != request.user:
            messages.error(
                request,
                "Context with id '%s' is not public and does not belong to\
 you" % (c.id)
            )
            return _show_cluster_def(request, data)
        #if c.is_encrypted:
        #    messages.error(request, "Context '%s' is encrypted!" % (c.name))
        #    return _show_cluster_def(request, data)

    # elastiq section
    elastiq_f = ElastiqForm(data.get("elastiq", {}))
    if not elastiq_f.is_valid():
        for label, msg in elastiq_f.errors_list:
            messages.error(request, "elastiq %s: %s" % (label, msg))
        return _show_cluster_def(request, data)
    clean_data["elastiq"] = elastiq_f.clean()

    # EC2 section
    ec2_f = EC2Form(data.get("ec2", {}))
    if not ec2_f.is_valid():
        for label, msg in ec2_f.errors_list:
            messages.error(request, "EC2 %s: %s" % (label, msg))
        return _show_cluster_def(request, data)
    clean_data["ec2"] = ec2_f.clean()

    # Quota section
    quota_f = QuotaForm(data.get("quota", {}))
    if not quota_f.is_valid():
        for label, msg in quota_f.errors_list:
            messages.error(request, "Quota %s: %s" % (label, msg))
        return _show_cluster_def(request, data)
    clean_data["quota"] = quota_f.clean()

    return clean_data
Example #15
0
 def update_cart(self):
     """
     Cart update form action: update quantities, remove marked for removal items
     """
     post_dict = parser.parse(self.request.POST.urlencode())
     self.request.cart.update_quantities(post_dict["item_quantity"])
     if "remove_item" in post_dict:
         self.request.cart.remove_items(list(post_dict["remove_item"]))
Example #16
0
def decafDemo(request):
    post_dict = parser.parse(request.POST.urlencode())
    log_to_terminal('Processing Demo Images Now', post_dict['socketid'])
    if 'src' in post_dict and post_dict['src']!='':
        file_name = basename(urlparse(post_dict['src']).path)
        redis_obj.publish(decaf_channel_name, json.dumps({'dir': DEMO_IMAGE_PATH, 'flag': '2', 'socketid': post_dict['socketid'], 'demo':'True', 'filename': file_name}))
    else:
        redis_obj.publish(decaf_channel_name, json.dumps({'dir': DEMO_IMAGE_PATH, 'flag': '2', 'socketid': post_dict['socketid']}))
Example #17
0
def user_availability_create(request):
	#try:
	data = parser.parse(request.POST.urlencode())
	user = get_current_user(request)
	if data.get('availability'):
		availability_raw = data['availability']['']
	else:
		availability_raw = []
	availability = []
	if not isinstance(availability_raw, list):
		availability_raw = [availability_raw]
	for available_raw_item in availability_raw:
		avail_data = string.split(available_raw_item, '_')
		if avail_data[1] == 'morning':
			time_array = [16, 18, 20, 22]
		elif avail_data[1] == 'afternoon':
			time_array = [24, 26, 28, 30]
		elif avail_data[1] == 'night':
			time_array = [32, 34, 36, 38]
		elif avail_data[1] == 'late-night':
			time_array = [40, 42, 44]
		elif avail_data[1] == 'night-owl':
			time_array = [46, 48, 50]
		for time in time_array:
			availability.append({
				'day': int(avail_data[0]),
				'start_time': int(time),
				'end_time': int(time) + 2
			})

	availability_array = []
	for available_slot in availability:
		newSlot = available_slot
		newSlot['start_time'] -= user.timezone * 2
		newSlot['end_time'] -= user.timezone * 2
		if newSlot['start_time'] < 0:
			newSlot['day'] = newSlot['day'] - 1
			newSlot['start_time'] = 48 + newSlot['start_time']
		if newSlot['end_time'] < 0:
			newSlot['end_time'] = 48 + newSlot['end_time']
		if newSlot['start_time'] > 47:
			newSlot['start_time'] = newSlot['start_time'] - 48
			newSlot['day'] = newSlot['day'] + 1
		if newSlot['end_time'] > 47:
			newSlot['end_time'] = newSlot['end_time'] - 48
		if newSlot['day'] < 0:
			newSlot['day'] = 7 + newSlot['day']
		if newSlot['day'] > 6:
			newSlot['day'] = newSlot['day'] - 7
		avail_document = UserAvailability(
			day = newSlot['day'],
			start_time = newSlot['start_time'],
			end_time = newSlot['end_time']
		)
		availability_array.append(avail_document)
	user.availability = availability_array
	user.save()
	return HttpResponse(model_encode(user.availability_tz()), mimetype="application/json")
Example #18
0
def course_list_ajax_handler(request):
    request_dict = querystring_parser.parse(request.GET.urlencode())
    draw = int(request_dict['draw'])
    start = request_dict['start']
    length = request_dict['length']
    search = request_dict.get('search', None)

    objects = Course.objects.all()

    if search and search['value']:
        objects = objects.filter(Q(name__icontains=search['value']) |
                                 Q(school__name__icontains=search['value']) |
                                 Q(department__school__name__icontains=search['value']))

    order_fields = []
    for order_index in request_dict['order']:
        order_field = None
        order = request_dict['order'][order_index]
        if order['column'] == 1:
            order_field = 'updated_at'
        elif order['column'] == 2:
            order_field = 'file_count'
        elif order['column'] == 3:
            order_field = 'thank_count'

        if order['dir'] == 'desc':
            order_field = '-' + order_field

        if order_field:
            order_fields.append(order_field)

    objects = objects.order_by(*order_fields)

    displayRecords = objects.count()

    if start > 0:
        objects = objects[start:]

    objects = objects[:length]

    row_data = [
        [
            course_json(course),
            calendar.timegm(course.updated_at.timetuple()),
            course.file_count,
            course.thank_count,
            course.school.name if course.school else course.department.school.name,
        ] for course in objects
    ]

    response_dict = {
        'draw': draw,
        'recordsTotal': Course.objects.count(),
        'recordsFiltered': displayRecords,
        'data': row_data
    }

    return HttpResponse(json.dumps(response_dict), mimetype='application/json')
Example #19
0
def route_calculator(request):
    
    parsed_dict = parser.parse(request.POST.urlencode())
    
    p = parsed_dict['points']
    t = parsed_dict['tolerance']
    
    r = Routecalc(p,t)
    
    return HttpResponse(r, mimetype='application/json')
Example #20
0
def demoVqa(request):
    post_dict = parser.parse(request.POST.urlencode())
    try:
        socketid = post_dict['socketid']

        if 'src' not in post_dict:
            data = {'error': 'NoImageSelected'}
        else:
            data = {'info': 'Processing'}
            result_prefix_url = post_dict['src']
            imgname = basename(urlparse(result_prefix_url).path)

            image_path = os.path.join(conf.LOCAL_DEMO_VQA_PIC_DIR, imgname)

            # folder_name = str(shortuuid.uuid())
            # For now lets use socket id
            folder_name = socketid
            save_dir = os.path.join(conf.PIC_DIR, folder_name)
            feat_folder = os.path.join(save_dir, 'results')

            # Make the new directory based on time
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
                os.makedirs(feat_folder)

            feat_path = os.path.join(feat_folder, imgname)

            print image_path
            print result_prefix_url
            log_to_terminal('Processing image...', socketid)

            # This is for running it locally ie on Godel
            vqa_wrapper_feat(image_path, socketid, result_prefix_url, feat_path)

            # This is for posting it on Redis - ie to Rosenblatt
            # classify_wrapper_redis(image_path, post_dict['socketid'], result_path)

            data = {'info': 'Completed'}

        try:
            request.META['REMOTE_ADDR']

        except:
            print str(traceback.format_exc())
            log_to_terminal(str(traceback.format_exc()), socketid)
            response = JSONResponse(data, {}, response_mimetype(request))
            response['Content-Disposition'] = 'inline; filename=files.json'
            return response

    except:
        data = {'result': str(traceback.format_exc())}
        response = JSONResponse(data, {}, response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
    log_to_terminal(str(traceback.format_exc()), socketid)
    return response
Example #21
0
def handleQuestion(request):
    post_dict = parser.parse(request.POST.urlencode())
    try:
        """
        try:
            if post_dict['pass'] != 'Passphrase#123!':
                response = JSONResponse({'passworderror': 'Error'}, {}, response_mimetype(request))
                response['Content-Disposition'] = 'inline; filename=files.json'
                return response
        except Exception as e:
            return 'Error'
        """
        socketid = post_dict['socketid']
        imageid = post_dict['imageid']

        result_url = post_dict['src']
        question = post_dict['qn']

        data = {'info': 'Processing'}

        # data_row = VQA_Question.create(socketid = socketid, questionText = question, imageName = imageid, imagePath = '/home/ubuntu/cloudcv/cloudcv17/cloudcv17/media/pictures/cloudcv')

        imgname = basename(urlparse(result_url).path)

        # folder_name = str(shortuuid.uuid())
        # For now lets use socket id

        feat_folder = os.path.join(conf.PIC_DIR, socketid, 'results')
        feat_path = os.path.join(feat_folder, imgname)

        # Throw exception here if file does not exist
        # if not os.path.exists(feat_path):

        log_to_terminal(feat_path, socketid)
        log_to_terminal(result_url, socketid)
        log_to_terminal('Processing image...', socketid)

        # This is for running it locally ie on Godel
        vqa_wrapper_answer(feat_path, question, socketid, imageid)

        # This is for posting it on Redis - ie to Rosenblatt
        # classify_wrapper_redis(image_path, post_dict['socketid'], result_path)

        data = {'info': 'Completed', 'questionid': "1"}

        response = JSONResponse(data, {}, response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response

    except Exception as e:
        data = {'result': str(traceback.format_exc(e))}
        response = JSONResponse(data, {}, response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response
Example #22
0
def get_bookmarks(request):
    # sync the client-side bookmarks with the server side bookmarks
    # update the server-side bookmarks and return the new list
    try:
        bookmark_dict = parser.parse(request.POST.urlencode())["bookmarks"]
    except:
        bookmark_dict = {}
    try:
        # loop through the list from the client
        # if user, bm_name, and bm_state match then skip
        # otherwise, add to the db
        for key, bookmark in bookmark_dict.items():
            try:
                Bookmark.objects.get(user=request.user, name=bookmark["name"], url_hash=bookmark["hash"])
            except Bookmark.DoesNotExist:
                new_bookmark = Bookmark(user=request.user, name=bookmark["name"], url_hash=bookmark["hash"])
                new_bookmark.save()
            except:
                continue

        # grab all bookmarks belonging to this user
        # serialize bookmarks into 'name', 'hash' objects and return simplejson dump
        content = []
        bookmark_list = Bookmark.objects.filter(user=request.user)
        for bookmark in bookmark_list:
            sharing_groups = [group.name for group in bookmark.sharing_groups.all()]
            content.append(
                {
                    "uid": bookmark.uid,
                    "name": bookmark.name,
                    "hash": bookmark.url_hash,
                    "sharing_groups": sharing_groups,
                }
            )

        shared_bookmarks = Bookmark.objects.shared_with_user(request.user)
        for bookmark in shared_bookmarks:
            if bookmark not in bookmark_list:
                username = bookmark.user.username
                actual_name = bookmark.user.first_name + " " + bookmark.user.last_name
                content.append(
                    {
                        "uid": bookmark.uid,
                        "name": bookmark.name,
                        "hash": bookmark.url_hash,
                        "shared": True,
                        "shared_by_username": username,
                        "shared_by_name": actual_name,
                    }
                )
        return HttpResponse(simplejson.dumps(content), mimetype="application/json", status=200)
    except:
        return HttpResponse(status=304)
Example #23
0
def embedded_template_requesting(request):
    try:
        hsclient = HSClient(api_key=API_KEY)
    except NoAuthMethod:
        return render(request, 'hellosign/embedded_template_requesting.html', {
            'error_message': "Please update your settings to include a " +
            "value for API_KEY.",
        })
    if request.method == 'POST':
        try:
            signers = []
            post_dict = parser.parse(request.POST.urlencode())
            template_id = post_dict["template"]
            for key, value in post_dict["signerRole"].iteritems():
                if value:
                    value['role_name'] = key
                    signers.append(value)
            ccs = []
            for key, value in post_dict["ccRole"].iteritems():
                # if value:
                ccs.append({'role_name': key, 'email_address': value})
            custom_fields = []
            for key, value in post_dict["cf"].iteritems():
                if value:
                    custom_fields.append({key: value})
            sr = hsclient.send_signature_request_embedded_with_rf(test_mode = "1",
                client_id = CLIENT_ID, reusable_form_id = template_id, title = "NDA with Acme Co.",
                subject = "The NDA we talked about", message = "Please sign this NDA and then we" +
                " can discuss more. Let me know if you have any questions.",
                signing_redirect_url = "", signers = signers, ccs = ccs, custom_fields = custom_fields)
            embedded = hsclient.get_embeded_object(sr.signatures[0]["signature_id"])
        # TODO: need some more validations here
        # except KeyError:
        #     return render(request, 'hellosign/embedded_template_requesting.html', {
        #         'error_message': "Please enter both your name and email.",
        #     })
        except NoAuthMethod:
            pass
        else:
            return render(request, 'hellosign/embedded_template_requesting.html', {
                    'client_id': CLIENT_ID,
                    'sign_url': str(embedded.sign_url)
                    })
    else:
        rf_list = hsclient.get_reusable_form_list()
        templates = "[";
        for rf in rf_list:
            # print json.dumps(rf.json_data)
            templates = templates + json.dumps(rf.json_data) + ", "
        templates = templates + "]"
        return render(request, 'hellosign/embedded_template_requesting.html', {
                    'templates': templates
                    })
Example #24
0
def handleQuestion(request):
    post_dict = parser.parse(request.POST.urlencode())
    try:
        socketid = post_dict['socketid']
        imageid = post_dict['imageid']

        result_url = post_dict['src']
        question = post_dict['qn']

        data = {'info': 'Processing'}

        imgname = basename(urlparse(result_url).path)

        # folder_name = str(shortuuid.uuid())
        # For now lets use socket id

        feat_folder = os.path.join(conf.PIC_DIR, socketid, 'results')
        feat_path = os.path.join(feat_folder, imgname)

        # Throw exception here if file does not exist
        # if not os.path.exists(feat_path):

        log_to_terminal(feat_path, socketid)
        log_to_terminal(result_url, socketid)
        log_to_terminal('Processing image...', socketid)

        # This is for running it locally ie on Godel
        vqa_wrapper_answer(feat_path, question, socketid, imageid)

        # This is for posting it on Redis - ie to Rosenblatt
        #classify_wrapper_redis(image_path, post_dict['socketid'], result_path)

        data = {'info': 'Completed'}

        # try:
        #     client_address = request.META['REMOTE_ADDR']
        #     log_file.write('Demo classify request from IP:'+client_address)
        #     log_file.close()
        #
        # except Exception as e:
        #     log_file.write('Exception when finding client ip:'+str(traceback.format_exc())+'\n');
        #     log_file.close()

        response = JSONResponse(data, {}, response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response

    except Exception as e:
        data = {'result': str(traceback.format_exc())}
        response = JSONResponse(data, {}, response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response
        def request_callback(request):
            payload = querystring_parser.parse(request.body)

            if validate_zeropush_payload(payload):
                response_body = {
                    "sent_count": len(payload["device_tokens"][""]),
                    "inactive_tokens": [],
                    "unregistered_tokens": [],
                }
                headers = {"Content-Type": "application/json"}
                return (200, headers, json.dumps(response_body))
            else:
                return (400, {}, {})
def parse_params(params):
    def listify(params):
        if isinstance(params, dict):
            if params.keys() == range(len(params)):
                params = params.values()
            else:
                for k, v in params.iteritems():
                    params[k] = listify(v)
        if isinstance(params, list):
            return [listify(param) for param in params]
        return params

    return listify(querystring_parser.parse('&'.join(params)))
Example #27
0
def login_view(request):
    try:
        user = User.objects.get(fb_id=request.POST['id'])
        if user.check_access_token(request.POST['access_token']):
            user.backend = 'mongoengine.django.auth.MongoEngineBackend'
            login(request, user)
            request.session.set_expiry(60 * 60 * 24 * 30) # 1 month timeout
            return HttpResponse(model_encode(user), mimetype="application/json")
        else:
            return HttpResponse('login failed')
    except DoesNotExist:
		data = parser.parse(request.POST.urlencode())
		if not data.get('email'):
			data['email'] = str(data['id']) + '@facebook.com'
		if not data.get('username'):
			data['username'] = data['email']
		if not data.get('bio'):
			data['bio'] = ''
		user = User(
			username = data['email'],
			name = data['name'],
			first_name = data['first_name'],
			last_name = data['last_name'],
			fb_id = data['id'],
			fb_access_token = data['access_token'],
			fb_link = data['link'],
			fb_username = data['username'],
			bio = data['bio'],
			email = data['email'],
			timezone = data['timezone'],
			locale = data['locale'],
			gender = data['gender']
		)
		imgdata = urllib2.urlopen('https://graph.facebook.com/'+str(data['id'])+'/picture?type=large')
		image_type,width,height = getImageInfo(imgdata)
		user.picture_width = width
		user.picture_height = height
		user.save()
		if data.get('hometown'):
			user.add_property('location', data['hometown'], 650)
		if data.get('location'):
			user.add_property('location', data['location'], 750)
		for i in range(len(data['work'])):
			work_score = 200 * 3/(min(i,4)+1)
			user.add_property('work', data['work'][i], work_score)
		for i in range(len(data['education'])):
			user.add_property('school', data['education'][i], 680*(4+i)/4)
		for i in range(len(data['inspirational_people'])):
			user.add_property('inspirational_person', data['inspirational_people'][i], 200)
		user.set_default_featured_properties()
		return HttpResponse(model_encode(user), mimetype="application/json")
Example #28
0
def show_new(request, cluster_id=None):

    if cluster_id is None:
        # New context
        return _show_cluster_def(request, {})
    else:

        #
        # Cloning existing context
        #

        # Try to fetch context from the database. Don't filter on current user.
        try:

            cluster = ClusterDefinition.objects.get( id=cluster_id )

            # Unmarshal data
            try:

                if cluster.is_encrypted:
                    post_dict = parser.parse( unicode(request.POST.urlencode()).encode("utf-8") )
                    try:
                        cluster.decrypt( post_dict['password'] )
                    except ClusterDefinition.CryptographyError:
                        messages.error(request, 'Wrong password')
                        return _show_cluster_def(request, {})

                cluster_data_dict = json.loads( cluster.data )

            except ValueError:
                messages.error(request, 'Corrupted cluster data: creating a new cluster.')
                return _show_cluster_def(request, {})

            # Mangle the dictionary to suit form structure
            cluster_data_dict['cluster'] = {
                'master_context_id': cluster.master_context_id,
                'worker_context_id': cluster.worker_context_id,
                'id': cluster.id,
                'name': cluster.name,
                'description': cluster.description
            }
            if 'passphrase' in cluster_data_dict:
                cluster_data_dict['cluster']['passphrase'] = cluster_data_dict['passphrase']
                del cluster_data_dict['passphrase']

            #return uncache_response(HttpResponse(json.dumps(cluster_data_dict, indent=2), content_type="text/plain"))
            return _show_cluster_def(request, cluster_data_dict)

        except ClusterDefinition.DoesNotExist, Http404:
            messages.error(request, 'The specified cluster does not exist: creating a new cluster instead.')
            return _show_cluster_def(request, {})
Example #29
0
def pass1(request):
    try:
        data = {'success': 'false'}
        if request.method == 'POST':
            post_dict = parser.parse(request.POST.urlencode())
            print post_dict
            if post_dict['pass'] == 'Passphrase#123!':
                data = {'success': 'true'}
        response = JSONResponse(data, {}, response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response
    except:
        # print str(traceback.format_exc())
        data['error'] = 'Error'
        response = JSONResponse(data, {}, response_mimetype(request))
        return response
Example #30
0
def view_cart(request):

  # Get cart
  cart = cart_from_request(request)
  error = None

  # If is a submit, pre validate the data
  if request.method == 'POST' and isinstance(cart, list) and len(cart) > 0:

    # Get cart options
    post = parser.parse(request.POST.urlencode())

    coupon_code = post.get('coupon_code')
    coupon = Coupon.objects.get_valid_coupon(coupon_code)

    page_datetime = datetime.fromtimestamp(post.get('datetime'))
    allow_sub_detail = post.get('allow_sub_detail')
    allow_sub_detail = {} if allow_sub_detail is None else allow_sub_detail

    # Validate delivery choices
    delivery_choices = post.get('delivery_choices')
    delivery_options = validate_delivery_choices(delivery_choices)

    if delivery_options == False:
      error = 'The delivery option you select is no longer valid'
    elif len(coupon_code) > 0 and coupon == False:
      error = 'The coupon you have entered is no longer valid'
    else:
      request.session['checkout_package'] = {
        'cart': cart,
        'delivery_choices': delivery_choices,
        'allow_sub_detail': allow_sub_detail,
        'coupon_code': coupon_code,
        'page_datetime': page_datetime,
      }
      response = HttpResponseRedirect(reverse('order:checkout'))
      return response

  store_items = cart_to_store_items(cart)
  template = loader.get_template('order/cart.html')
  context = RequestContext(request, {
    'store_items': store_items,
    'datetime': datetime.now(),
    'error': error,
  })
  return HttpResponse(template.render(context))