Exemple #1
0
def get_pros_information(users):
    ret = []
    for user in users:
        d = {}
        company = Company.query.filter_by(user_id=user.id).first()
        project = Project.query.filter_by(company_id=company.id).order_by(
            Project.created_at.desc()).all()
        image = Image.query.filter_by(id=company.image_id).first()
        image_path = utils.get_image_path(image.image_path)
        status_name = Status.query.filter_by(
            id=user.status_id).first().status_name
        if len(project) == 0:
            d['last_project_created'] = user.created_at
        else:
            d['last_project_created'] = project[0].created_at
            image = Image.query.filter_by(id=project[0].image_id).first()
            image_path = utils.get_image_path(image.image_path)
        d['user'] = user
        d['over_introduction'] = False
        if len(company.company_introduction) > 250:
            company.company_introduction = company.company_introduction[:250]
            d['over_introduction'] = True
        d['company'] = company
        d['image_path'] = image_path
        d['status_name'] = status_name
        ret.append(d)
    return ret
Exemple #2
0
    def __init__(self):
        test_noisy_image = utils.imread(utils.get_image_path(False, 64, 4003))
        test_noisy_image = utils.scale_image(test_noisy_image,
                                             2.0)  # Image size 128x128
        test_noisy_image /= 255.0
        test_noisy_image = test_noisy_image.reshape(128, 128, 1)
        self.noisy_img1 = test_noisy_image

        test_noisy_image = utils.imread(utils.get_image_path(False, 64, 19983))
        test_noisy_image = utils.scale_image(test_noisy_image,
                                             2.0)  # Image size 128x128
        test_noisy_image /= 255.0
        test_noisy_image = test_noisy_image.reshape(128, 128, 1)
        self.noisy_img2 = test_noisy_image
Exemple #3
0
    def do_GET(self):
        p = self.path[1:]  #strip leading /

        splitted = p.split("/")

        key = ""
        command = "update"
        arg = ""

        if len(splitted) >= 1:
            key = splitted[0]

        if len(splitted) == 0 or key != self.server.get_key():
            self.wfile.write("PenguinTV Unauthorized")
            return

        if len(splitted) >= 2:
            command = splitted[1]
        if len(splitted) >= 3:
            arg = splitted[2]

        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

        if command == "update":
            if self.server.update_count() == 0:
                self.wfile.write("".encode('utf-8'))
            else:
                update = self.server.peek_update()
                self.wfile.write(update.encode('utf-8'))
        elif command == "icon":
            theme = gtk.icon_theme_get_default()
            iconinfo = theme.lookup_icon(arg, 16, gtk.ICON_LOOKUP_NO_SVG)
            if iconinfo is not None:
                image_data = self._image_cache.get_image_from_file(
                    iconinfo.get_filename())
                self.wfile.write(image_data)
            else:
                logging.error("no icon found for: %s" % (arg, ))
                self.wfile.write("")
        elif command == "pixmaps":
            image_data = self._image_cache.get_image_from_file(
                utils.get_image_path(arg))
            self.wfile.write(image_data)
        elif command == "cache":
            #strip out possible ../../../ crap.  I think this is all I need?
            securitize = [s for s in splitted if s not in ("/", ".", "..")]
            filename = os.path.join(self._server.store_location,
                                    *securitize[2:])
            if utils.RUNNING_HILDON:
                #not enough ram to cache it
                f = open(filename, "rb")
                image_data = f.read()
                f.close()
            else:
                image_data = self._image_cache.get_image_from_file(filename)
            self.wfile.write(image_data)

        self.wfile.flush()
Exemple #4
0
def get_shop_information(t_products):
    products = []
    for t_product in t_products:
        product_has_image = Product_has_image.query.filter_by(
            product_id=t_product.id).first()
        image_id = product_has_image.image_id
        image = Image.query.filter_by(id=image_id).first()
        image_path = utils.get_image_path(image.image_path)
        user = User.query.filter_by(id=t_product.user_id).first()
        category_name = Shop_category.query.filter_by(
            id=t_product.shop_category_id).first().category_name
        status_name = Status.query.filter_by(
            id=t_product.status_id).first().status_name
        d = {
            'product':
            t_product,
            'product_real_price':
            utils.convert_price_to_won(t_product.product_price),
            'user':
            user,
            'image_path':
            image_path,
            'category_name':
            category_name,
            'status_name':
            status_name
        }
        products.append(d)
    return products
Exemple #5
0
 def plot_layers(self):
     net = self.net
     metrics = ['data', 'params', 'gradients']
     data_funcs = {
         'data':      lambda layer: net.blobs[layer].data[0],
         'params':    lambda layer: net.params[layer][0].data,
         'gradients': lambda layer: net.blobs[layer].diff[0]
     }
     num_layers = len(LAYER_NAMES)
     num_metrics = len(metrics)
     f, axarr = plt.subplots(
         num_layers * num_metrics,
         2  # Values and histogram
     )
     i = 0
     for layer_name in LAYER_NAMES:
         for metric in metrics:
             feat = data_funcs[metric](layer_name).flat
             axarr[i, 0].plot(feat)
             axarr[i, 0].set_title(layer_name + ' ' + metric)
             # noinspection PyBroadException
             try:
                 axarr[i, 1].hist(feat[feat > 0], bins=100)
             except:
                 print 'problem with histogram', layer_name, metric
             else:
                 axarr[i, 1].set_title(layer_name + ' ' + metric + ' histogram')
             i += 1
     f.subplots_adjust(hspace=1.3)
     plt.savefig(get_image_path('layers', self.start_timestamp))
     f.clf()
     plt.close()
     gc.collect()
Exemple #6
0
def run_images():
    parser = argparse.ArgumentParser()
    parser.add_argument('--dir_path', default="./test_images", type=str)
    parser.add_argument('--out_path', default='./out_images', type=str)
    parser.add_argument('--model_file',
                        default="./model/yolov2-tiny-voc.h5",
                        type=str)
    args = parser.parse_args()

    paths = utils.get_image_path(args.dir_path)
    images = []
    print('reading image from %s' % args.dir_path)
    for path in paths:
        image = cv2.imread(path)
        resized = cv2.resize(image, (416, 416))
        images.append(resized)

    image_processed = []
    for image in images:
        image_processed.append(utils.preprocess_image(image))

    print('loading model from %s' % args.model_file)
    model = load_model(args.model_file)
    predictions = model.predict(np.array(image_processed))

    if not os.path.exists(args.out_path):
        os.mkdir(args.out_path)
    print('writing image to %s' % args.out_path)
    for i in range(predictions.shape[0]):
        boxes = utils.process_predictions(predictions[i],
                                          probs_threshold=0.3,
                                          iou_threshold=0.2)
        out_image = utils.draw_boxes(images[i], boxes)
        cv2.imwrite('%s/out%s.jpg' % (args.out_path, i), out_image)
Exemple #7
0
def fetch_spacex(args) -> None:
    mission = args.spacex_mission
    try:
        mission_name, images_urls = get_mission_name_and_images_urls(mission)
    except Exception as e:
        logger.error(
            'An error is occurred, SpaceX images data cannot be retrieved: %s',
            str(e))
        return

    if not images_urls:
        logger.warning(
            'Images data on the SpaceX site is empty. Try another mission.')
        return

    logger.info('Start downloading SpaceX.')
    logger.info('%i SpaceX images found.', len(images_urls))
    for i, image_url in enumerate(images_urls):
        image_path = utils.get_image_path(mission_name, image_url, i)
        logger.info(f'Downloading image %s.', image_url)
        try:
            is_downloaded = utils.download_image(image_url, image_path)
        except Exception as e:
            logger.error('Image %s cannot be retrieved: %s', image_path,
                         str(e))
            continue
        if is_downloaded:
            logger.info('%s is fetched.', image_url)
        else:
            logger.warning('Skip %s.', image_url)
    logger.info('SpaceX downloading is finished.')
Exemple #8
0
	def do_GET(self):
		p = self.path[1:] #strip leading /
		
		splitted = p.split("/")
		
		key = ""
		command = "update"
		arg = ""
		
		if len(splitted) >= 1:
			key = splitted[0]
		
		if len(splitted) == 0 or key != self.server.get_key():
			self.wfile.write("PenguinTV Unauthorized")
			return
			
		if len(splitted) >= 2:
			command = splitted[1]
		if len(splitted) >= 3:
			arg = splitted[2]
			
		self.send_response(200)
		self.send_header('Content-type', 'text/html')
		self.end_headers()

		if command == "update":
			if self.server.update_count()==0:
				self.wfile.write("".encode('utf-8'))
			else:
				update = self.server.peek_update()
				self.wfile.write(update.encode('utf-8'))
		elif command == "icon":
			theme = gtk.icon_theme_get_default()
			iconinfo = theme.lookup_icon(arg, 16, gtk.ICON_LOOKUP_NO_SVG)
			if iconinfo is not None:
				image_data = self._image_cache.get_image_from_file(iconinfo.get_filename())
				self.wfile.write(image_data)
			else:
				logging.error("no icon found for: %s" % (arg,))
				self.wfile.write("")
		elif command == "pixmaps":
			image_data = self._image_cache.get_image_from_file(utils.get_image_path(arg))
			self.wfile.write(image_data)
		elif command == "cache":
			#strip out possible ../../../ crap.  I think this is all I need?
			securitize = [s for s in splitted if s not in ("/",".","..")]
			filename = os.path.join(self._server.store_location, *securitize[2:])
			if utils.RUNNING_HILDON:
				#not enough ram to cache it
				f = open(filename, "rb")
				image_data = f.read()
				f.close()
			else:
				image_data = self._image_cache.get_image_from_file(filename)
			self.wfile.write(image_data)
		
		self.wfile.flush()
Exemple #9
0
def get_image_url_and_path_by_id(image_id: int) -> (str, str):
    hubble_single_image_api_url = f'{settings.HUBBLE_API_URL}image/{image_id}'
    response = requests.get(hubble_single_image_api_url)
    response.raise_for_status()

    response_dict = response.json()
    image_url = get_max_fit_hubble_image(response_dict['image_files'])
    image_path = utils.get_image_path(response_dict['name'], image_url,
                                      image_id)

    return image_url, image_path
Exemple #10
0
    def test(self):
        self.load_best_model()
        saved_dir = os.path.join(os.getcwd(), "xray_images")
        saved_dir = os.path.join(saved_dir, "test_images_128x128")
        if not os.path.exists(saved_dir):
            os.mkdir(saved_dir)
        for i in range(1, 4000):
            if os.path.exists(utils.get_image_path(True, 64, i)):
                test_noisy_128 = utils.imread(utils.get_image_path(
                    True, 64, i))
                test_noisy_128 = utils.scale_image(test_noisy_128,
                                                   2.0)  # Image size 128x128
                test_noisy_128 /= 255.0
                test_noisy_128 = test_noisy_128.reshape(128, 128, 1)

                prediction = self.model.predict(np.array([test_noisy_128]))[0]
                prediction = prediction * 255
                prediction = prediction.astype('uint8').reshape((128, 128))
                predicted_img = Image.fromarray(prediction)
                clean_image_path = utils.get_image_path(True, 128, i)
                predicted_img.save(clean_image_path)
def remove_below_specified_resolution(raw_img_dir: str,
                                      resolution: tuple) -> None:
    """
  remove the image which is smaller than specified resolution.
  :param raw_img_dir:
  :return:
  """
    img_paths = utils.get_image_path(raw_img_dir)
    for path in img_paths:
        size = Image.open(path).size
        if size[0] < resolution[0] or size[0] < resolution[1]:
            os.remove(path)
            print('{} doesn\'t satisfied. deleted.'.format(path))
    def test_commit(self):
        print "Creating VM image"
        base_file = utils.get_image_path('BASE', False, False)
        utils.build_vm('BASE', touch_script, '10G')
        s1_file = utils.create_image('S1', 'BASE', size='10G')

        # Monitor the image sizes
        stats = {'BASE': [], 'S1': []}
        stopEvent = threading.Event()
        base_watcher = ImageWatcher(base_file, stats['BASE'], stopEvent)
        base_watcher.start()
        s1_watcher = ImageWatcher(s1_file, stats['S1'], stopEvent)
        s1_watcher.start()

        # Run the test
        print "Starting VM"
        dom = utils.create_vm('livemerge-test', 'S1')
        # TODO: Start a livemerge

        try:
            dom.blockCommit(s1_file, base_file, s1_file, 0, 0)
            flags = libvirt.VIR_DOMAIN_BLOCK_JOB_TYPE_COMMIT
            self.assertTrue(utils.wait_block_job(dom, s1_file, flags))
        finally:
            dom.destroy()


        ## Wait until image has grown enough
        #print "Sampling"
        #while True:
            #end = utils.get_image_end_offset(s1_file) / 1024 / 1024
            #print "S1 is using %i MB" % end
            #if end >= 5 * 1024:
                #break
            #time.sleep(5)

        # Stop the test
        print "Cleaning up"
        stopEvent.set()
        base_watcher.join()
        s1_watcher.join()

        # Print results
        self._print_results(stats)
Exemple #13
0
def show_product(update, context):
    try:
        product = db.get_product(
            update.message.text, context.user_data['category'])
        context.user_data.update(
            product=product
            )
        desc = f'*{product.title}*\n\n'\
               f'{product.composition}\n\n'\
               f'Цена: {product.price} {config.text["currency"]}\n\n'\
               f'*Выберите* или *введите* количество:'
        update.message.reply_photo(
            photo=open(utils.get_image_path(product.img_path), 'rb'),
            caption=desc,
            parse_mode=ParseMode.MARKDOWN,
            reply_markup=utils.get_quontity_kb()
        )
        return TYPING_QUONTITY
    except Exception as ex:
        print(f'{ex}')
Exemple #14
0
def get_feed_information(feeds):
    ret = []
    for feed in feeds:
        d = {}
        image = Image.query.filter_by(id=feed.image_id).first()
        image_path = utils.get_image_path(image.image_path)
        user = User.query.filter_by(id=feed.user_id).first()
        all_comments = Comment.query.filter_by(feed_id=feed.id).order_by(
            Comment.created_at.asc()).all()
        status_name = Status.query.filter_by(
            id=feed.status_id).first().status_name

        comments_dict_list = []
        for all_comment in all_comments:
            comment_user = User.query.filter_by(id=all_comment.user_id).first()
            cur = {'comment': all_comment, 'user': comment_user}
            comments_dict_list.append(cur)

        all_likes = User_like_feed.query.filter_by(feed_id=feed.id).all()
        is_user_like = False
        if 'user_id' in session:
            if User_like_feed.query.filter_by(
                    user_id=session['user_id']).filter_by(
                        feed_id=feed.id).first():
                is_user_like = True

        d['image_path'] = image_path
        d['user'] = user
        d['feed'] = feed
        d['number_of_comment'] = len(all_comments)
        d['all_comments'] = comments_dict_list
        d['number_of_like'] = len(all_likes)
        d['is_user_like'] = is_user_like
        d['status_name'] = status_name
        ret.append(d)
    return ret
Exemple #15
0
def ajax_get_image_path():
    image_code = request.args.get('image_code', '')  # 以中文逗号隔开
    # print 'image_code::',image_code
    results = get_image_path(image_code)
    return json.dumps(results)
Exemple #16
0
	h, w = image.shape[0:2]
	rotation = numpy.random.uniform(-rotation_range, rotation_range)
	scale = numpy.random.uniform(1 - zoom_range, 1 + zoom_range)
	tx = numpy.random.uniform(-shift_range, shift_range) * w
	ty = numpy.random.uniform(-shift_range, shift_range) * h
	mat = cv2.getRotationMatrix2D((w // 2, h // 2), rotation, scale)
	mat[:, 2] += (tx, ty)
	result = cv2.warpAffine(image, mat, (w, h), borderMode=cv2.BORDER_REPLICATE)
	if numpy.random.random() < random_flip:
		result = result[:, ::-1]
	return result


if __name__ == '__main__':

	paths = get_image_path(image_path)
	test = load_images_r(paths)
	test[0] = cv2.cvtColor(test[0], cv2.COLOR_BGR2RGB)
	plt.figure()
	plt.imshow(test[0])
	plt.pause(0.001)
	new = random_transform(test[0], 100, 0.5, 0, 0.5)
	plt.figure()
	plt.imshow(new)
	plt.pause(0.001)

	pass



Exemple #17
0
 def htmlify_media(self, medium):
     ret = []
     ret.append('<div class="media">')
     if medium['download_status'] == D_NOT_DOWNLOADED:
         ret.append(
             '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>'''
         )
         if medium['file'] is None:
             filename = medium['url'][medium['url'].rfind("/") + 1:]
         else:
             filename = medium['file'][medium['file'].rfind("/") + 1:]
         ret.append(
             self._html_command('download://', medium['media_id']) +
             "</td><td>")
         ret.append(
             self._html_command('downloadqueue://', medium['media_id']) +
             "</td><td>")
         ret.append('</tr><tr><td colspan="3">(%s: %s)</td></tr></table>' %
                    (filename, utils.format_size(medium['size'])))
     elif medium['download_status'] == D_DOWNLOADING:
         if self._basic_progress:
             if self._ajax_url is None:
                 ret.append('<img src="file://' +
                            utils.get_image_path("throbber.gif") + '"/>')
             else:
                 ret.append('<img src="' + self._ajax_url +
                            '/pixmaps/throbber.gif"/>')
             ret.append('<i>' + _('Downloading %s...') %
                        utils.format_size(medium['size']) + '</i> ' +
                        self._html_command('pause://', medium['media_id']) +
                        ' ' +
                        self._html_command('stop://', medium['media_id']))
         elif medium.has_key('progress_message'
                             ):  #downloading and we have a custom message
             if self._ajax_url is None:
                 ret.append('<img src="file://' +
                            utils.get_image_path("throbber.gif") + '"/>')
             else:
                 ret.append('<img src="' + self._ajax_url +
                            '/pixmaps/throbber.gif"/>')
             ret.append('<p><i>' + medium['progress_message'] + '</i></p>')
             ret.append(
                 '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>'''
             )
             ret.append(
                 self._html_command('pause://', medium['media_id']) +
                 "</td><td>")
             ret.append(
                 self._html_command('stop://', medium['media_id']) +
                 "</td></tr></table>")
         elif self._mm.has_downloader(
                 medium['media_id']):  #we have a downloader object
             downloader = self._mm.get_downloader(medium['media_id'])
             if downloader.status == Downloader.DOWNLOADING:
                 d = {
                     'progress': downloader.progress,
                     'size': utils.format_size(medium['size'])
                 }
                 #ret.append('<p><i>'+_("Downloaded %(progress)d%% of %(size)s") % d +'</i> '+
                 ret.append(
                     '''<table border="0" cellpadding="0" cellspacing="12pt">'''
                 )
                 ret.append('''<tr><td rowspan="2">''')
                 if self._ajax_url is None:
                     ret.append('<img src="file://' +
                                utils.get_image_path("throbber.gif") +
                                '"/>')
                 else:
                     ret.append('<img src="' + self._ajax_url +
                                '/pixmaps/throbber.gif"/>')
                 ret.append("</td><td>")
                 ret.append(
                     self._html_progress_bar(d['progress'], d['size']) +
                     "</td><td>")
                 ret.append(
                     self._html_command('pause://', medium['media_id']) +
                     "</td><td>")
                 ret.append(
                     self._html_command('stop://', medium['media_id']) +
                     "</td></tr></table>")
             elif downloader.status == Downloader.QUEUED:
                 ret.append('<p><i>' + _("Download queued") + '</i></p>')
                 ret.append(
                     '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>'''
                 )
                 ret.append(
                     self._html_command('pause://', medium['media_id']) +
                     "</td><td>")
                 ret.append(
                     self._html_command('stop://', medium['media_id']) +
                     "</td></tr></table>")
         elif medium.has_key(
                 'progress'
         ):  #no custom message, but we have a progress value
             d = {
                 'progress': medium['progress'],
                 'size': utils.format_size(medium['size'])
             }
             #ret.append('<p><i>'+_("Downloaded %(progress)d%% of %(size)s") % d +'</i> '+
             ret.append(
                 '''<table border="0" cellpadding="0" cellspacing="12pt">'''
             )
             ret.append('''<tr><td rowspan="2">''')
             if self._ajax_url is None:
                 ret.append('<img src="file://' +
                            utils.get_image_path("throbber.gif") + '"/>')
             else:
                 ret.append('<img src="' + self._ajax_url +
                            '/pixmaps/throbber.gif"/>')
             ret.append("</td><td>")
             ret.append(
                 self._html_progress_bar(d['progress'], d['size']) +
                 "</td><td>")
             ret.append(
                 self._html_command('pause://', medium['media_id']) +
                 "</td><td>")
             ret.append(
                 self._html_command('stop://', medium['media_id']) +
                 "</td></tr></table>")
         else:  # we have nothing to go on
             ret.append('<p><i>' + _('Downloading %s...') %
                        utils.format_size(medium['size']) + '</i></p>')
             ret.append(
                 '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>'''
             )
             ret.append(
                 self._html_command('pause://', medium['media_id']) +
                 "</td><td>")
             ret.append(
                 self._html_command('stop://', medium['media_id']) +
                 "</td></tr></table>")
     elif medium['download_status'] == D_DOWNLOADED:
         if self._mm.has_downloader(medium['media_id']):
             downloader = self._mm.get_downloader(medium['media_id'])
             ret.append('<p>' + str(downloader.message) + '</p>')
         filename = medium['file'][medium['file'].rfind("/") + 1:]
         if utils.is_known_media(medium['file']):  #we have a handler
             if os.path.isdir(medium['file']) and medium['file'][-1] != '/':
                 medium['file'] = medium['file'] + '/'
             ret.append(
                 '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>'''
             )
             ret.append(
                 self._html_command('play://', medium['media_id']) +
                 "</td><td>")
             ret.append(
                 self._html_command('redownload', medium['media_id']) +
                 "</td><td>")
             ret.append(
                 self._html_command('delete://', medium['media_id']) +
                 "</td></tr>")
             ret.append(
                 '<tr><td colspan="3">(<a href="reveal://%s">%s</a>: %s)</td></tr></table>'
                 % (medium['file'], filename,
                    utils.format_size(medium['size'])))
         elif os.path.isdir(medium['file']):  #it's a folder
             ret.append(
                 '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>'''
             )
             ret.append(
                 self._html_command('file://', medium['file']) +
                 "</td><td>")
             ret.append(
                 self._html_command('redownload', medium['media_id']) +
                 "</td><td>")
             ret.append(
                 self._html_command('delete://', medium['media_id']) +
                 "</td></tr></table>")
         else:  #we have no idea what this is
             ret.append(
                 '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>'''
             )
             ret.append(
                 self._html_command('file://', medium['file']) +
                 "</td><td>")
             ret.append(
                 self._html_command('redownload', medium['media_id']) +
                 "</td><td>")
             ret.append(
                 self._html_command('delete://', medium['media_id']) +
                 "</td></tr>")
             ret.append(
                 '<tr><td colspan="3">(<a href="reveal://%s">%s</a>: %s)</td></tr></table>'
                 % (medium['file'], filename,
                    utils.format_size(medium['size'])))
     elif medium['download_status'] == D_RESUMABLE:
         ret.append(
             '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>'''
         )
         ret.append(
             self._html_command('resume://', medium['media_id']) +
             "</td><td>")
         ret.append(
             self._html_command('redownload', medium['media_id']) +
             "</td><td>")
         ret.append(
             self._html_command('delete://', medium['media_id']) +
             "</td></tr><tr><td>")
         ret.append('(%s)</td></tr></table>' %
                    (utils.format_size(medium['size']), ))
     elif medium['download_status'] == D_ERROR:
         if len(medium['errormsg']) > 0:
             error_msg = medium['errormsg']
         else:
             error_msg = _("There was an error downloading the file.")
         ret.append(
             '''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>'''
         )
         ret.append(medium['url'][medium['url'].rfind('/') + 1:] + ': ' +
                    str(error_msg) + "</td><td>")
         ret.append(
             self._html_command('retry', medium['media_id']) + "</td><td>")
         ret.append(
             self._html_command('tryresume://', medium['media_id']) +
             "</td><td>")
         ret.append(
             self._html_command('cancel://', medium['media_id']) +
             "</td></tr><tr><td>")
         ret.append('(%s)</td></tr></table>' %
                    (utils.format_size(medium['size']), ))
     ret.append('</div>')
     return ret
Exemple #18
0
def get_course_photo_path(*args):
    return get_image_path(*args, dir_name=settings.CONTENT_PHOTOS_DIR_NAME)
Exemple #19
0
	testMineral = testMinerals[mineral]
	mineralNames.append(mineral)
	for vector in testMineral["elements"]:
		calibratedVector = { "name" : mineral, "index" : mineralIndex}
		for element in calibration:
			if element in vector.keys():
				calibratedVector[element] = calibration[element] * vector[element]
			else:
				calibratedVector[element] = 0
		calibratedVectors.append(calibratedVector)

# for each element name in calibration:
# load image of form targetname/targetname_32bt_elementname.tif
element_scans = {}
for element in calibration:
	img = imread(utils.get_image_path(targetObject, element))
	element_scans[element] = img

# load targetname/targetname_mask.tif
targetMask = imread(utils.get_target_mask(targetObject))

# create output image same size as mask, initialized to zero, formatted as uint8
tWidth = len(targetMask[0])
tHeight = len(targetMask)
outputImage = np.zeros((tHeight, tWidth), dtype = np.uint8)

mineral_dists = np.full((tHeight, tWidth), constants.infInt_32bt, dtype = np.int32)

#for each pixel in mask:
##if mask pixel is not zero:
###closestDist=maxval
Exemple #20
0
	def htmlify_media(self, medium):
		ret = []
		ret.append('<div class="media">')
		if medium['download_status']==D_NOT_DOWNLOADED:  
			ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''')
			if medium['file'] is None:
				filename = medium['url'][medium['url'].rfind("/")+1:]
			else:
				filename = medium['file'][medium['file'].rfind("/")+1:]
			ret.append(self._html_command('download://',medium['media_id']) + "</td><td>")
			ret.append(self._html_command('downloadqueue://',medium['media_id']) + "</td><td>")
			ret.append('</tr><tr><td colspan="3">(%s: %s)</td></tr></table>' % (filename, utils.format_size(medium['size'])))
		elif medium['download_status'] == D_DOWNLOADING: 
			if self._basic_progress:
				if self._ajax_url is None:
					ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>')
				else:
					ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>')
				ret.append('<i>'+_('Downloading %s...') % utils.format_size(medium['size'])+'</i> '+self._html_command('pause://',medium['media_id'])+' '+self._html_command('stop://',medium['media_id']))
			elif medium.has_key('progress_message'): #downloading and we have a custom message
				if self._ajax_url is None:
					ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>')
				else:
					ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>')
				ret.append('<p><i>'+medium['progress_message']+'</i></p>')
				ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''')
				ret.append(self._html_command('pause://',medium['media_id']) + "</td><td>")
				ret.append(self._html_command('stop://',medium['media_id'])+"</td></tr></table>")
			elif self._mm.has_downloader(medium['media_id']): #we have a downloader object
				downloader = self._mm.get_downloader(medium['media_id'])
				if downloader.status == Downloader.DOWNLOADING:
					d = {'progress':downloader.progress,
						 'size':utils.format_size(medium['size'])}
					#ret.append('<p><i>'+_("Downloaded %(progress)d%% of %(size)s") % d +'</i> '+
					ret.append('''<table border="0" cellpadding="0" cellspacing="12pt">''')
					ret.append('''<tr><td rowspan="2">''')
					if self._ajax_url is None:
						ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>')
					else:
						ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>')
					ret.append("</td><td>")
					ret.append(self._html_progress_bar(d['progress'], d['size']) + "</td><td>")
					ret.append(self._html_command('pause://',medium['media_id']) + "</td><td>")
					ret.append(self._html_command('stop://',medium['media_id'])+"</td></tr></table>")
				elif downloader.status == Downloader.QUEUED:
					ret.append('<p><i>'+_("Download queued") +'</i></p>')
					ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''')
					ret.append(self._html_command('pause://',medium['media_id']) + "</td><td>")
					ret.append(self._html_command('stop://',medium['media_id'])+"</td></tr></table>")
			elif medium.has_key('progress'):       #no custom message, but we have a progress value
				d = {'progress':medium['progress'],
					 'size':utils.format_size(medium['size'])}
				#ret.append('<p><i>'+_("Downloaded %(progress)d%% of %(size)s") % d +'</i> '+
				ret.append('''<table border="0" cellpadding="0" cellspacing="12pt">''')
				ret.append('''<tr><td rowspan="2">''')
				if self._ajax_url is None:
					ret.append('<img src="file://' + utils.get_image_path("throbber.gif") + '"/>')
				else:
					ret.append('<img src="' + self._ajax_url + '/pixmaps/throbber.gif"/>')
				ret.append("</td><td>")
				ret.append(self._html_progress_bar(d['progress'], d['size']) + "</td><td>")
				ret.append(self._html_command('pause://',medium['media_id']) + "</td><td>")
				ret.append(self._html_command('stop://',medium['media_id'])+"</td></tr></table>")
			else:       # we have nothing to go on
				ret.append('<p><i>'+_('Downloading %s...') % utils.format_size(medium['size'])+'</i></p>')
				ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''')
				ret.append(self._html_command('pause://',medium['media_id']) + "</td><td>")
				ret.append(self._html_command('stop://',medium['media_id'])+"</td></tr></table>")
		elif medium['download_status'] == D_DOWNLOADED:
			if self._mm.has_downloader(medium['media_id']):	
				downloader = self._mm.get_downloader(medium['media_id'])
				ret.append('<p>'+ str(downloader.message)+'</p>')
			filename = medium['file'][medium['file'].rfind("/")+1:]
			if utils.is_known_media(medium['file']): #we have a handler
				if os.path.isdir(medium['file']) and medium['file'][-1]!='/':
					medium['file']=medium['file']+'/'
				ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''')
				ret.append(self._html_command('play://',medium['media_id']) + "</td><td>")
				ret.append(self._html_command('redownload',medium['media_id']) + "</td><td>")
				ret.append(self._html_command('delete://',medium['media_id'])+"</td></tr>")
				ret.append('<tr><td colspan="3">(<a href="reveal://%s">%s</a>: %s)</td></tr></table>' % (medium['file'], filename, utils.format_size(medium['size'])))
			elif os.path.isdir(medium['file']): #it's a folder
				ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''')
				ret.append(self._html_command('file://',medium['file']) + "</td><td>")
				ret.append(self._html_command('redownload',medium['media_id']) + "</td><td>")
				ret.append(self._html_command('delete://',medium['media_id'])+"</td></tr></table>")
			else:                               #we have no idea what this is
				ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''')
				ret.append(self._html_command('file://',medium['file']) + "</td><td>")
				ret.append(self._html_command('redownload',medium['media_id']) + "</td><td>")
				ret.append(self._html_command('delete://',medium['media_id'])+"</td></tr>")
				ret.append('<tr><td colspan="3">(<a href="reveal://%s">%s</a>: %s)</td></tr></table>' % (medium['file'], filename, utils.format_size(medium['size'])))
		elif medium['download_status'] == D_RESUMABLE:
			ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''')
			ret.append(self._html_command('resume://',medium['media_id']) + "</td><td>")
			ret.append(self._html_command('redownload',medium['media_id']) + "</td><td>")
			ret.append(self._html_command('delete://',medium['media_id'])+"</td></tr><tr><td>")
			ret.append('(%s)</td></tr></table>' % (utils.format_size(medium['size']),))	
		elif medium['download_status'] == D_ERROR:
			if len(medium['errormsg']) > 0:
				error_msg = medium['errormsg']
			else:
				error_msg = _("There was an error downloading the file.")
			ret.append('''<table border="0" cellpadding="0" cellspacing="12pt"><tr><td>''')
			ret.append(medium['url'][medium['url'].rfind('/')+1:]+': '+str(error_msg) + "</td><td>")
			ret.append(self._html_command('retry',medium['media_id']) + "</td><td>")
			ret.append(self._html_command('tryresume://',medium['media_id']) + "</td><td>")
			ret.append(self._html_command('cancel://',medium['media_id'])+"</td></tr><tr><td>")
			ret.append('(%s)</td></tr></table>' % (utils.format_size(medium['size']),))
		ret.append('</div>')
		return ret
Exemple #21
0
def get_user_photo_path(*args):
    return get_image_path(*args, dir_name=settings.USER_PHOTOS_DIR_NAME)
Exemple #22
0
def get_theme_photo_path(*args):
    return get_image_path(*args, dir_name=settings.THEME_PHOTOS_DIR_NAME)
Exemple #23
0
def get_city_photo_path(*args):
    return get_image_path(*args, dir_name=settings.CITY_PHOTOS_DIR_NAME)
Exemple #24
0
def get_partner_logo_path(*args):
    return get_image_path(*args, dir_name=settings.PARTNER_LOGOS_DIR_NAME)