Python config.DEBUG Examples

The following are 23 code examples of config.DEBUG(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module config , or try the search function .
Example #1
Source File: nfp_log.py    From nightmare with GNU General Public License v2.0 5 votes vote down vote up
def debug(msg):
  if DEBUG:
    log(msg) 
Example #2
Source File: base.py    From backtrader-binance-bot with MIT License 5 votes vote down vote up
def log(self, txt, send_telegram=False, color=None):
        if not DEBUG:
            return

        value = datetime.now()
        if len(self) > 0:
            value = self.data0.datetime.datetime()

        if color:
            txt = colored(txt, color)

        print('[%s] %s' % (value.strftime("%d-%m-%y %H:%M"), txt))
        if send_telegram:
            send_telegram_message(txt) 
Example #3
Source File: web.py    From certitude with GNU General Public License v2.0 5 votes vote down vote up
def run_server():
    context = None

    if USE_SSL and os.path.isfile(SSL_KEY_FILE) and os.path.isfile(SSL_CERT_FILE):
        context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
        context.load_cert_chain(SSL_CERT_FILE, SSL_KEY_FILE)
        loggingserver.info('Using SSL, open interface in HTTPS')

    loggingserver.info('Web interface starting')
    app.run(
        host=LISTEN_ADDRESS,
        port=LISTEN_PORT,
        debug=DEBUG,
        ssl_context=context
    ) 
Example #4
Source File: gen.py    From web-traffic-generator with MIT License 5 votes vote down vote up
def debug_print(message, color=Colors.NONE):
    """ A method which prints if DEBUG is set """
    if config.DEBUG:
        print(color + message + Colors.NONE) 
Example #5
Source File: cn_log.py    From cosa-nostra with GNU General Public License v3.0 5 votes vote down vote up
def debug(msg):
  if DEBUG:
    log(msg) 
Example #6
Source File: self-serve.py    From danforth-east with MIT License 5 votes vote down vote up
def get(self):
        """Serve the form page.
        """
        logging.info('SelfComboPage.GET')
        logging.info('headers: %s' % self.request.headers.items())
        logging.info('params: %s' % self.request.params.items())
        logging.info('body: %s' % self.request.body)

        # Make sure (as best we can) that this is being requested from a site
        # that's allowed to embed our join form.
        # This is such a weak check that I'm not sure it's worth it.
        #if not config.DEBUG:
        #    if not self.request.referer or \
        #       urlparse(self.request.referer).hostname not in config.ALLOWED_EMBED_REFERERS:
        #        webapp2.abort(403, detail='bad referer')

        csrf_token = helpers.get_csrf_token(self.request)

        volunteer_interests = gapps.get_volunteer_interests()
        skills_categories = gapps.get_skills_categories()

        template_values = {
            'FIELDS': config.FIELDS,
            'csrf_token': csrf_token,
            'volunteer_interests': volunteer_interests,
            'skills_categories': skills_categories,
            'config': config,
        }
        template = JINJA_ENVIRONMENT.get_template('self-serve-combo.jinja')

        helpers.set_csrf_cookie(self.response, csrf_token)
        self.response.write(template.render(template_values)) 
Example #7
Source File: self-serve.py    From danforth-east with MIT License 5 votes vote down vote up
def post(self):
        """Create the new volunteer.
        """
        logging.info('SelfVolunteerPage.POST')
        logging.info('headers: %s' % self.request.headers.items())
        logging.info('params: %s' % self.request.params.items())
        logging.info('body: %s' % self.request.body)

        # Make sure (as best we can) that this is being requested from a site
        # that's allowed to embed our join form.
        # This is such a weak check that I'm not sure it's worth it.
        #if not config.DEBUG:
        #    if not self.request.referer or \
        #       urlparse(self.request.referer).hostname not in config.ALLOWED_EMBED_REFERERS:
        #        webapp2.abort(403, detail='bad referer')
        # TODO: Use new CSRF approach that doesn't need cookies.
        #helpers.check_csrf(self.request)

        # TODO: Don't hardcode key
        referrer = self.request.params.get('_referrer') or self.request.referer

        # Create a dict of the volunteer info.
        new_volunteer = gapps.volunteer_dict_from_request(self.request,
                                                          referrer)

        gapps.join_volunteer_from_dict(new_volunteer)

        self.response.write('success')

        # Queue the welcome email
        taskqueue.add(url='/tasks/new-volunteer-mail', params=new_volunteer) 
Example #8
Source File: self-serve.py    From danforth-east with MIT License 5 votes vote down vote up
def get(self):
        """Serve the form page.
        """
        logging.info('SelfVolunteerPage.GET')
        logging.info('headers: %s' % self.request.headers.items())
        logging.info('params: %s' % self.request.params.items())
        logging.info('body: %s' % self.request.body)

        # Make sure (as best we can) that this is being requested from a site
        # that's allowed to embed our join form.
        # This is such a weak check that I'm not sure it's worth it.
        #if not config.DEBUG:
        #    if not self.request.referer or \
        #       urlparse(self.request.referer).hostname not in config.ALLOWED_EMBED_REFERERS:
        #        webapp2.abort(403, detail='bad referer')

        csrf_token = helpers.get_csrf_token(self.request)

        volunteer_interests = gapps.get_volunteer_interests()
        skills_categories = gapps.get_skills_categories()

        template_values = {
            'FIELDS': config.FIELDS,
            'csrf_token': csrf_token,
            'volunteer_interests': volunteer_interests,
            'skills_categories': skills_categories,
            'config': config,
        }
        template = JINJA_ENVIRONMENT.get_template('self-serve-volunteer.jinja')

        helpers.set_csrf_cookie(self.response, csrf_token)
        self.response.write(template.render(template_values)) 
Example #9
Source File: self-serve.py    From danforth-east with MIT License 5 votes vote down vote up
def get(self):
        """Serve the form page.
        """
        logging.info('SelfJoinPage.GET')
        logging.info('headers: %s', self.request.headers.items())
        logging.info('params: %s', self.request.params.items())
        logging.info('body: %s', self.request.body)

        # Make sure (as best we can) that this is being requested from a site
        # that's allowed to embed our join form.
        # This is such a weak check that I'm not sure it's worth it.
        #if not config.DEBUG:
        #    if not self.request.referer or \
        #       urlparse(self.request.referer).hostname not in config.ALLOWED_EMBED_REFERERS:
        #        webapp2.abort(403, detail='bad referer')

        csrf_token = helpers.get_csrf_token(self.request)

        volunteer_interests = gapps.get_volunteer_interests()
        skills_categories = gapps.get_skills_categories()

        template_values = {
            'FIELDS': config.FIELDS,
            'csrf_token': csrf_token,
            'volunteer_interests': volunteer_interests,
            'skills_categories': skills_categories,
            'config': config,
        }
        template = JINJA_ENVIRONMENT.get_template('self-serve-join.jinja')

        helpers.set_csrf_cookie(self.response, csrf_token)
        self.response.write(template.render(template_values)) 
Example #10
Source File: morphoconllu.py    From Finnish-dep-parser with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, form, lemma, cpostag, postag, feats):
        self.form = form
        self.lemma = lemma
        self.cpostag = cpostag
        self.postag = postag
        self._feats = feats

        if DEBUG:
            self.validate()

        self._fmap = None 
Example #11
Source File: runserver.py    From apache-flask with MIT License 5 votes vote down vote up
def runserver():

	port = int(os.environ.get('PORT', DEFAULT_PORT))
	app.run(host=DEFAULT_HOST, port=port, debug=DEBUG)

#------------------------------ 
Example #12
Source File: manage.py    From CHN-Server with GNU Lesser General Public License v2.1 5 votes vote down vote up
def runlocal():
        serverurl = urlparse(config.SERVER_BASE_URL)
        mhn.run(debug=config.DEBUG, host='0.0.0.0',
                port=serverurl.port) 
Example #13
Source File: manage.py    From CHN-Server with GNU Lesser General Public License v2.1 5 votes vote down vote up
def run():
        # Takes run parameters from configuration.
        serverurl = urlparse(config.SERVER_BASE_URL)
        mhn.run(debug=config.DEBUG, host='0.0.0.0',
                port=serverurl.port) 
Example #14
Source File: preprocessing.py    From tf.fashionAI with Apache License 2.0 5 votes vote down vote up
def preprocess_for_test_raw_output(image, output_height, output_width, data_format='NCHW', scope=None):
  """Preprocesses the given image for evaluation.

  Args:
    image: A `Tensor` representing an image of arbitrary size.
    output_height: The height of the image after preprocessing.
    output_width: The width of the image after preprocessing.

  Returns:
    A preprocessed image.
  """
  with tf.name_scope(scope, 'vgg_test_image_raw_output', [image, output_height, output_width]):
    # Crop the central region of the image with an area containing 87.5% of
    # the original image.
    image = tf.image.resize_bilinear(image, [output_height, output_width], align_corners=False)
    image = tf.squeeze(image, [0])
    image.set_shape([output_height, output_width, 3])

    if config.DEBUG:
      save_image_op = tf.py_func(_save_image,
                                  [image],
                                  tf.int64, stateful=True)
      image = tf.Print(image, [save_image_op])

    image = tf.to_float(image)
    normarlized_image = _mean_image_subtraction(image, [_R_MEAN, _G_MEAN, _B_MEAN])
    if data_format == 'NCHW':
      normarlized_image = tf.transpose(normarlized_image, perm=(2, 0, 1))
    return tf.expand_dims(normarlized_image/255., 0) 
Example #15
Source File: utility.py    From PeachOrchard with MIT License 5 votes vote down vote up
def msg(string, level=INFO):
    """ Handle messages; this takes care of logging and
    debug checking, as well as output colors
    """

    string = "[%s] %s" % (timestamp(), string)
    color_string = None
    if 'linux' in platform.platform().lower():
        if level is INFO:
            color_string = '%s%s%s' % ('\033[32m', string, '\033[0m')
        elif level is DEBUG:
            color_string = '%s%s%s' % ('\033[34m', string, '\033[0m')
        elif level is ERROR:
            color_string = '%s%s%s' % ('\033[31m', string, '\033[0m')
        else:
            color_string = string

    if not color_string:
        color_string = string

    if level is DEBUG and not config.DEBUG:
        return

    if not level is LOG:
        print color_string

    log(string) 
Example #16
Source File: w.py    From goodbye-mihome with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def make_app():
    static_path = os.path.join(os.path.dirname(__file__), "static")
    settings = {
        'static_path': static_path,
        'debug': config.DEBUG
    }
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/updates", UpdatesHandler),
        (r"/static/(.*)", tornado.web.StaticFileHandler, {'path': static_path}),
    ], **settings) 
Example #17
Source File: self-serve.py    From danforth-east with MIT License 4 votes vote down vote up
def post(self):
        """Create the new member.
        """
        logging.info('SelfJoinPage.POST')
        logging.info('headers: %s', self.request.headers.items())
        logging.info('params: %s', self.request.params.items())
        logging.info('cookies: %s', self.request.cookies.items())
        logging.info('body: %s', self.request.body)

        # Make sure (as best we can) that this is being requested from a site
        # that's allowed to embed our join form.
        # This is such a weak check that I'm not sure it's worth it.
        #if not config.DEBUG:
        #    if not self.request.referer or \
        #       urlparse(self.request.referer).hostname not in config.ALLOWED_EMBED_REFERERS:
        #        webapp2.abort(403, detail='bad referer')

        # HACK: Safari doesn't allow cookie setting in an iframe without
        # direct user interaction. So this fails every time on desktop and
        # mobile Safari.
        # TODO: Use new CSRF approach that doesn't need cookies.
        #helpers.check_csrf(self.request)

        # TODO: Don't hardcode key
        referrer = self.request.params.get('_referrer') or self.request.referer

        # Create a dict of the member info.
        new_member = gapps.member_dict_from_request(self.request,
                                                    referrer,
                                                    'join')

        # "Paid" field shouldn't be set by form in self-serve.
        new_member[config.MEMBER_FIELDS.paid.name] = 'N'
        if self.request.params.get('payment_method') == 'paypal':
            new_member[config.MEMBER_FIELDS.paid.name] = 'paypal'

        # Write the member info to the member candidate store.
        member_candidate = MemberCandidate(
            member_json=webapp2_extras.json.encode(new_member),
            created=datetime.datetime.now(),
            expire=datetime.datetime.now()+datetime.timedelta(days=1))
        member_candidate_key = member_candidate.put()

        invoice_id = member_candidate_key.urlsafe()

        # If the payment method is "cheque" create the new member directly,
        # otherwise start the PayPal process.
        # TODO: Don't hardcode field name
        if self.request.params.get('payment_method') == 'cheque':
            params = {'invoice': invoice_id}
            taskqueue.add(url='/self-serve/process-member-worker',
                          params=params)
            self.response.write('success')
        else:
            # We put the key value into the URL so we can retrieve this member
            # after payment.
            paypal_url = config.PAYPAL_PAYMENT_URL % (invoice_id,)

            self.response.write(paypal_url) 
Example #18
Source File: network.py    From Learning-to-See-Moving-Objects-in-the-Dark with MIT License 4 votes vote down vote up
def network(input, depth=3, channel=32, prefix=''):
    depth = min(max(depth, 2), 4)

    conv1 = slim.conv3d(input, channel, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv1_1')
    conv1 = slim.conv3d(conv1, channel, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv1_2')
    pool1 = tf.expand_dims(slim.max_pool2d(conv1[0], [2, 2], padding='SAME'), axis=0)

    conv2 = slim.conv3d(pool1, channel * 2, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv2_1')
    conv2 = slim.conv3d(conv2, channel * 2, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv2_2')
    pool2 = tf.expand_dims(slim.max_pool2d(conv2[0], [2, 2], padding='SAME'), axis=0)

    conv3 = slim.conv3d(pool2, channel * 4, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv3_1')
    conv3 = slim.conv3d(conv3, channel * 4, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv3_2')
    if depth == 2:
        up8 = upsample_and_concat(conv3, conv2, channel * 2, channel * 4)
    else:
        pool3 = tf.expand_dims(slim.max_pool2d(conv3[0], [2, 2], padding='SAME'), axis=0)

        conv4 = slim.conv3d(pool3, channel * 8, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv4_1')
        conv4 = slim.conv3d(conv4, channel * 8, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv4_2')
        if depth == 3:
            up7 = upsample_and_concat(conv4, conv3, channel * 4, channel * 8)
        else:
            pool4 = tf.expand_dims(slim.max_pool2d(conv4[0], [2, 2], padding='SAME'), axis=0)

            conv5 = slim.conv3d(pool4, channel * 16, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv5_1')
            conv5 = slim.conv3d(conv5, channel * 16, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv5_2')

            up6 = upsample_and_concat(conv5, conv4, channel * 8, channel * 16)
            conv6 = slim.conv3d(up6, channel * 8, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv6_1')
            conv6 = slim.conv3d(conv6, channel * 8, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv6_2')

            up7 = upsample_and_concat(conv6, conv3, channel * 4, channel * 8)
        conv7 = slim.conv3d(up7, channel * 4, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv7_1')
        conv7 = slim.conv3d(conv7, channel * 4, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv7_2')

        up8 = upsample_and_concat(conv7, conv2, channel * 2, channel * 4)
    conv8 = slim.conv3d(up8, channel * 2, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv8_1')
    conv8 = slim.conv3d(conv8, channel * 2, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv8_2')

    up9 = upsample_and_concat(conv8, conv1, channel, channel * 2)
    conv9 = slim.conv3d(up9, channel, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv9_1')
    conv9 = slim.conv3d(conv9, channel, [3, 3, 3], rate=1, activation_fn=lrelu, scope=prefix + 'g_conv9_2')

    conv10 = slim.conv3d(conv9, 12, [1, 1, 1], rate=1, activation_fn=None, scope=prefix + 'g_conv10')

    out = tf.concat([tf.expand_dims(tf.depth_to_space(conv10[:, i, :, :, :], 2), axis=1) for i in range(conv10.shape[1])], axis=1)
    if DEBUG:
        print '[DEBUG] (network.py) conv10.shape, out.shape:', conv10.shape, out.shape

    return out


# test function for network 
Example #19
Source File: main.py    From w12scan-client with MIT License 4 votes vote down vote up
def main():
    PATHS.ROOT_PATH = module_path()
    PATHS.PLUGIN_PATH = os.path.join(PATHS.ROOT_PATH, "pocs")
    PATHS.OUTPUT_PATH = os.path.join(PATHS.ROOT_PATH, "output")
    PATHS.DATA_PATH = os.path.join(PATHS.ROOT_PATH, "data")

    patch_all()
    logger.info("Hello W12SCAN !")

    # domain域名整理(统一格式:无论是域名还是二级目录,右边没有 /),ip cidr模式识别,ip整理

    # 访问redis获取目标
    def redis_get():
        list_name = "w12scan_scanned"
        while 1:
            target = redis_con.blpop(list_name)[1]
            scheduler.put_target(target)

        # redis_get()

    def debug_get():
        target = "http://stun.tuniu.com"
        scheduler.put_target(target)

    def node_register():
        first_blood = True
        while 1:
            if first_blood:
                dd = {
                    "last_time": time.time(),
                    "tasks": 0,
                    "running": 0,
                    "finished": 0
                }
                redis_con.hmset(NODE_NAME, dd)
                first_blood = False
            else:
                redis_con.hset(NODE_NAME, "last_time", time.time())
            time.sleep(50 * 5)

    scheduler = Schedular(threadnum=THREAD_NUM)
    scheduler.start()
    # 启动任务分发调度器
    if DEBUG:
        func_target = debug_get
    else:
        func_target = redis_get

    # 与WEB的通信线程
    node = threading.Thread(target=node_register)
    node.start()

    # 队列下发线程
    t = threading.Thread(target=func_target, name='LoopThread')
    t.start()

    try:
        scheduler.run()
    except KeyboardInterrupt:
        logger.info("User exit") 
Example #20
Source File: collector.py    From w12scan-client with MIT License 4 votes vote down vote up
def submit(self):
        '''
        传递信息给web restful接口
        :return:
        '''
        # domain
        while not self.cache_queue.empty():
            data = self.cache_queue.get()
            # self.collect_lock.acquire()
            # with open("domain.result.txt", "a+") as f:
            #     f.write(json.dumps(data) + ",")
            # self.collect_lock.release()
            if DEBUG:
                print("[submit] " + repr(data))
                continue
            _api = urljoin(WEB_INTERFACE, "./api/v1/domain")
            headers = {
                "W12SCAN": WEB_INTERFACE_KEY
            }
            try:
                r = requests.post(_api, json=data, headers=headers)
            except Exception as e:
                print("api request faild: {0} ".format(str(e)))
                continue

            if r.status_code == 200:
                status = json.loads(r.text)
                if status["status"] != 200:
                    print("api request faild(status!=200) " + status["msg"])

        # ips
        while not self.cache_ips.empty():
            data = self.cache_ips.get()
            # self.collect_lock.acquire()
            # with open("ips.result.txt", "a+") as f:
            #     f.write(json.dumps(data) + ",")
            # self.collect_lock.release()
            if DEBUG:
                print("[submit] " + repr(data))
                continue
            _api = urljoin(WEB_INTERFACE, "./api/v1/ip")
            headers = {
                "w12scan": WEB_INTERFACE_KEY
            }
            try:
                r = requests.post(_api, json=data, headers=headers)
            except Exception as e:
                print("api request faild: {0} ".format(str(e)))
                continue
            if r.status_code == 200:
                status = json.loads(r.text)
                if status["status"] != 200:
                    print("api request faild(status!=200) " + status["msg"]) 
Example #21
Source File: preprocessing.py    From tf.fashionAI with Apache License 2.0 4 votes vote down vote up
def preprocess_for_test(image, file_name, shape, output_height, output_width, data_format='NCHW', bbox_border=25., heatmap_sigma=1., heatmap_size=64, pred_df=None, scope=None):
  """Preprocesses the given image for evaluation.

  Args:
    image: A `Tensor` representing an image of arbitrary size.
    output_height: The height of the image after preprocessing.
    output_width: The width of the image after preprocessing.

  Returns:
    A preprocessed image.
  """
  with tf.name_scope(scope, 'vgg_test_image', [image, output_height, output_width]):
    # Crop the central region of the image with an area containing 87.5% of
    # the original image.

    if pred_df is not None:
      xmin, ymin, xmax, ymax  = [table_.lookup(file_name) for table_ in pred_df]
      #xmin, ymin, xmax, ymax = [tf.to_float(b) for b in bbox_cord]
      #xmin = tf.Print(xmin, [file_name, xmin, ymin, xmax, ymax], summarize=500)
      height, width, channals = tf.unstack(shape, axis=0)
      xmin, ymin, xmax, ymax = xmin - 100, ymin - 80, xmax + 100, ymax + 80

      xmin, ymin, xmax, ymax = tf.clip_by_value(xmin, 0, width[0]-1), tf.clip_by_value(ymin, 0, height[0]-1), \
                              tf.clip_by_value(xmax, 0, width[0]-1), tf.clip_by_value(ymax, 0, height[0]-1)

      bbox_h = ymax - ymin
      bbox_w = xmax - xmin
      areas = bbox_h * bbox_w

      offsets=tf.stack([xmin, ymin], axis=0)
      crop_shape = tf.stack([bbox_h, bbox_w, channals[0]], axis=0)

      ymin, xmin, bbox_h, bbox_w = tf.cast(ymin, tf.int32), tf.cast(xmin, tf.int32), tf.cast(bbox_h, tf.int32), tf.cast(bbox_w, tf.int32)
      crop_image = tf.image.crop_to_bounding_box(image, ymin, xmin, bbox_h, bbox_w)

      image, shape, offsets = tf.cond(areas > 0, lambda : (crop_image, crop_shape, offsets),
                                      lambda : (image, shape, tf.constant([0, 0], tf.int64)))
      offsets.set_shape([2])
      shape.set_shape([3])
    else:
      offsets = tf.constant([0, 0], tf.int64)

    image = tf.expand_dims(image, 0)
    image = tf.image.resize_bilinear(image, [output_height, output_width], align_corners=False)
    image = tf.squeeze(image, [0])
    image.set_shape([output_height, output_width, 3])

    if config.DEBUG:
      save_image_op = tf.py_func(_save_image,
                                  [image],
                                  tf.int64, stateful=True)
      image = tf.Print(image, [save_image_op])

    image = tf.to_float(image)
    normarlized_image = _mean_image_subtraction(image, [_R_MEAN, _G_MEAN, _B_MEAN])
    if data_format == 'NCHW':
      normarlized_image = tf.transpose(normarlized_image, perm=(2, 0, 1))
    return normarlized_image/255., shape, offsets 
Example #22
Source File: preprocessing.py    From tf.fashionAI with Apache License 2.0 4 votes vote down vote up
def preprocess_for_eval(image, classid, shape, output_height, output_width, key_x, key_y, key_v, norm_table, data_format, category, bbox_border, heatmap_sigma, heatmap_size, resize_side, scope=None):
  """Preprocesses the given image for evaluation.

  Args:
    image: A `Tensor` representing an image of arbitrary size.
    output_height: The height of the image after preprocessing.
    output_width: The width of the image after preprocessing.
    resize_side: The smallest side of the image for aspect-preserving resizing.

  Returns:
    A preprocessed image.
  """
  with tf.name_scope(scope, 'vgg_eval_image', [image, output_height, output_width]):
    # Crop the central region of the image with an area containing 87.5% of
    # the original image.
    fkey_x, fkey_y = tf.cast(key_x, tf.float32)/tf.cast(shape[1], tf.float32), tf.cast(key_y, tf.float32)/tf.cast(shape[0], tf.float32)
    image = tf.expand_dims(image, 0)
    image = tf.image.resize_bilinear(image, [output_height, output_width], align_corners=False)
    image = tf.squeeze(image, [0])
    image.set_shape([output_height, output_width, 3])
    image = tf.to_float(image)

    ikey_x = tf.cast(tf.round(fkey_x * heatmap_size), tf.int64)
    ikey_y = tf.cast(tf.round(fkey_y * heatmap_size), tf.int64)

    targets, isvalid = draw_labelmap(ikey_x, ikey_y, heatmap_sigma, heatmap_size)

    norm_gather_ind = tf.stack([norm_table[0].lookup(classid), norm_table[1].lookup(classid)], axis=-1)

    key_x = tf.cast(tf.round(fkey_x * output_width), tf.int64)
    key_y = tf.cast(tf.round(fkey_y * output_height), tf.int64)

    norm_x, norm_y = tf.cast(tf.gather(key_x, norm_gather_ind), tf.float32), tf.cast(tf.gather(key_y, norm_gather_ind), tf.float32)
    norm_x, norm_y = tf.squeeze(norm_x), tf.squeeze(norm_y)
    norm_value = tf.pow(tf.pow(norm_x[0] - norm_x[1], 2.) + tf.pow(norm_y[0] - norm_y[1], 2.), .5)

    if config.DEBUG:
      save_image_op = tf.py_func(save_image_with_heatmap,
                                  [image, targets,
                                  config.left_right_group_map[category][0],
                                  config.left_right_group_map[category][1],
                                  config.left_right_group_map[category][2],
                                  [output_height, output_width],
                                  heatmap_size],
                                  tf.int64, stateful=True)
      with tf.control_dependencies([save_image_op]):
        normarlized_image = _mean_image_subtraction(image, [_R_MEAN, _G_MEAN, _B_MEAN])
    else:
      normarlized_image = _mean_image_subtraction(image, [_R_MEAN, _G_MEAN, _B_MEAN])

    if data_format == 'NCHW':
      normarlized_image = tf.transpose(normarlized_image, perm=(2, 0, 1))
    return normarlized_image/255., targets, key_v, isvalid, norm_value 
Example #23
Source File: log.py    From certitude with GNU General Public License v2.0 4 votes vote down vote up
def init():
    try:
        chemin = path.dirname(path.abspath(__file__))
    except:
        chemin = "" # relatif


    logging.basicConfig(filename=path.join(chemin, '..', LOG_DIRECTORY, 'certitude-core.log'), format=FORMAT_LOGS, filemode='a')
    formatter = logging.Formatter(FORMAT_LOGS)

    if DEBUG:
        logging.getLogger('').setLevel(logging.DEBUG)
    else:
        logging.getLogger('').setLevel(logging.INFO)

    # Database
    loggingdb = logging.getLogger('sqlalchemy.engine')
    loggingdb.setLevel(logging.WARNING)
    handler_logdb = logging.FileHandler(path.join(chemin, '..', LOG_DIRECTORY, 'db.log'))
    handler_logdb.setFormatter(formatter)
    loggingdb.addHandler(handler_logdb)

    # API Server
    loggingserver = logging.getLogger('api')
    handler_logapi = logging.FileHandler(path.join(chemin, '..', LOG_DIRECTORY, 'api.log'))
    handler_logapi.setFormatter(formatter)
    loggingserver.addHandler(handler_logapi)

    # IOCScanners
    loggingiocscan = logging.getLogger('iocscanner')
    handler_logiocscan = logging.FileHandler(path.join(chemin, '..', LOG_DIRECTORY, 'iocscanners.log'))
    handler_logiocscan.setFormatter(formatter)
    loggingiocscan.addHandler(handler_logiocscan)
    
     # Hashscanners
    logginghashscan = logging.getLogger('hashscanner')
    handler_loghashscan = logging.FileHandler(path.join(chemin, '..', LOG_DIRECTORY, 'hashscanners.log'))
    handler_loghashscan.setFormatter(formatter)
    logginghashscan.addHandler(handler_loghashscan)
    
    # Console output
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler()
    console.setLevel(CONSOLE_DEBUG_LEVEL)
    # set a format which is simpler for console use
    formatter = logging.Formatter('%(name)-20s : %(levelname)-8s %(message)s')
    # tell the handler to use this format
    console.setFormatter(formatter)
    # add the handler to the root logger
    logging.getLogger('').addHandler(console)