示例#1
0
	def load_config(self):
		lines=[]
		lines=inp_load_file(self.config_file_path)
		if lines!=False:
			self.file_names=[inp_get_token_value_from_list(lines,"#import_file_path")]
			if os.path.isfile(self.file_names[0])==False:
				return False

			self.disable_callbacks=True
			self.x_combo.setCurrentIndex(int(inp_get_token_value_from_list(lines,"#import_x_combo_pos")))
			self.data_combo.setCurrentIndex(int(inp_get_token_value_from_list(lines,"#import_data_combo_pos")))
			
			self.title_entry.setText(inp_get_token_value_from_list(lines,"#import_title"))
			self.xlabel_entry.setText(inp_get_token_value_from_list(lines,"#import_xlabel"))
			self.data_label_entry.setText(inp_get_token_value_from_list(lines,"#import_data_label"))
			self.area_entry.setText(inp_get_token_value_from_list(lines,"#import_area"))

			self.x_spin.setValue(int(inp_get_token_value_from_list(lines,"#import_x_spin")))
			self.data_spin.setValue(int(inp_get_token_value_from_list(lines,"#import_data_spin")))

			self.x_invert.setChecked(str2bool(inp_get_token_value_from_list(lines,"#import_x_invert")))
			self.data_invert.setChecked(str2bool(inp_get_token_value_from_list(lines,"#import_data_invert")))
			self.disable_callbacks=False
			self.update()

			return True
		else:
			return False
示例#2
0
def api_register():
    email = request.args.get('email')
    password = request.args.get('password')
    super_admin = None
    client_admin = None
    agency_user = None
    client_id = None
    if request.args.get('super_admin'):
        super_admin = str2bool(request.args.get('super_admin'))
    if request.args.get('client_admin'):
        client_admin = str2bool(request.args.get('client_admin'))
    if request.args.get('agency_user'):
        agency_user = str2bool(request.args.get('agency_user'))
    if request.args.get('client_id'):
        client_id = request.args.get('client_id')

    auth_info = {
        'email': email,
        'password': password,
        'super_admin': super_admin,
        'client_admin': client_admin,
        'agency_user': agency_user,
        'client_id': client_id
    }
    return jsonify(database.select_register(auth_info=auth_info))
示例#3
0
文件: dat_file.py 项目: Ly0n/gpvdm
    def decode_gobj_lines(self, lines):
        nobj = 0
        for line in lines:
            o = gl_base_object()
            l = line.split(";;")

            #print(l)
            if len(l) > 1:
                o.type = l[0]
                o.id = ["obj" + str(nobj)]
                o.xyz.x = float(l[1])
                o.xyz.y = float(l[2])
                o.xyz.z = float(l[3])

                o.dxyz.x = float(l[4])
                o.dxyz.y = float(l[5])
                o.dxyz.z = float(l[6])

                o.r = float(l[7])
                o.g = float(l[8])
                o.b = float(l[9])

                o.alpha = float(l[10])

                o.selected = str2bool(l[11])
                o.selectable = str2bool(l[12])
                o.moveable = str2bool(l[13])
                o.allow_cut_view = str2bool(l[14])

                o.text = l[15]
                o.origonal_object = str2bool(l[16])

                self.data.append(o)
                nobj = nobj + 1
示例#4
0
def api_user_edit():
    email = request.args.get('email')
    password = request.args.get('password')
    user_id = request.args.get('user_id')
    client_admin = None
    agency_user = None
    client_id = None
    if request.args.get('client_admin'):
        client_admin = str2bool(request.args.get('client_admin'))
    if request.args.get('agency_user'):
        agency_user = str2bool(request.args.get('agency_user'))
    if request.args.get('client_id'):
        if request.args.get('client_id') == 'null':
            client_id = str2bool(request.args.get('client_id'))
        else:
            client_id = request.args.get('client_id')

    auth_info = {
        'email': email,
        'password': password,
        'user_id': user_id,
        'client_admin': client_admin,
        'agency_user': agency_user,
        'client_id': client_id
    }
    return jsonify(database.select_user_edit(auth_info=auth_info))
示例#5
0
def code_ctrl_load():
    lines = []
    global store_enable_webupdates
    global store_enable_webbrowser
    global store_enable_cluster
    global store_enable_betafeatures
    lines = inp_load_file(os.path.join(get_inp_file_path(), "ver.inp"),
                          archive="base.gpvdm")
    if lines != False:
        store_enable_webupdates = str2bool(
            inp_search_token_value(lines, "#enable_webupdates"))
        store_enable_webbrowser = str2bool(
            inp_search_token_value(lines, "#enable_webbrowser"))
        store_enable_cluster = str2bool(
            inp_search_token_value(lines, "#enable_cluster"))
        beta = inp_search_token_value(lines, "#enable_betafeatures")
        store_enable_betafeatures = str2bool(beta)
        if os.path.isdir(os.path.join(get_inp_file_path(),
                                      "enablebeta")) == True:
            store_enable_betafeatures = True
    else:
        print("Can not load ver.inp file")
        store_enable_webupdates = False
        store_enable_webbrowser = False
        store_enable_cluster = False
        store_enable_betafeatures = False
示例#6
0
    def load_image(self):
        if os.path.isfile(self.image_in) == False:
            self.im = None
            return

        img = Image.open(self.image_in)
        if img.mode != "RGB":
            img = img.convert('RGB')

        f = inp()
        f.load(os.path.join(self.path, "shape_import.inp"))
        self.gaussian_blur = int(f.get_token("#shape_import_blur"))
        self.y_norm = str2bool(f.get_token("#shape_import_y_norm"))
        self.z_norm = str2bool(f.get_token("#shape_import_z_norm"))
        self.blur_enable = str2bool(f.get_token("#shape_import_blur_enabled"))
        self.y_norm_percent = int(f.get_token("#shape_import_y_norm_percent"))
        self.rotate = int(f.get_token("#shape_import_rotate"))

        if self.blur_enable == True:
            img = img.filter(
                ImageFilter.GaussianBlur(radius=self.gaussian_blur))

        if self.rotate != 0:
            img = img.rotate(360 - self.rotate)

        if self.z_norm == True:
            img2 = img.resize((1, 1))
            color = img2.getpixel((0, 0))
            avg_pixel = (color[0] + color[1] + color[2]) / 3
            width, height = img.size
            for z in range(0, height):
                x_avg = 0
                for x in range(0, width):
                    color = img.getpixel((x, z))
                    c = (color[0] + color[1] + color[2]) / 3
                    x_avg = x_avg + c
                x_avg = x_avg / width
                delta = avg_pixel - x_avg
                for x in range(0, width):
                    color = img.getpixel((x, z))
                    c = (color[0] + color[1] + color[2]) / 3
                    img.putpixel(
                        (x, z),
                        (int(c + delta), int(c + delta), int(c + delta)))

                #print(x_avg)

            #print("avg color>>",c)

        if self.y_norm == True:
            print(self.y_norm_percent, img.mode)
            img = ImageOps.autocontrast(img,
                                        cutoff=self.y_norm_percent,
                                        ignore=None)

        self.im = img.convert('RGB')
        self.im.save(self.image_out)

        self.build_mesh()
示例#7
0
	def callback_model_select(self):
		epi=get_epi()
		for i in range(0,self.tab.rowCount()):
			epi.layers[i].solve_optical_problem=str2bool(self.tab.get_value(i, 8))
			epi.layers[i].solve_thermal_problem=str2bool(self.tab.get_value(i, 9))
			#print(epi.layers[i].solve_optical_probelm,epi.layers[i].solve_thermal_probelm)
		#self.emit_structure_changed()

		self.save_model()
示例#8
0
class DevelopmentConfig(Config):
    DEBUG = True

    APP_ENABLE_SENTRY = str2bool(os.environ.get('APP_ENABLE_SENTRY')) or False
    APP_ENABLE_PROXY_FIX = str2bool(
        os.environ.get('APP_ENABLE_PROXY_FIX')) or False

    LOGGING_LEVEL = logging.INFO

    PREFERRED_URL_SCHEME = os.getenv('PREFERRED_URL_SCHEME') or 'http'
示例#9
0
 def render_POST(self, request):
     data = ast.literal_eval(request.payload)
     res = BedroomResources()
     res.location_query = request.uri_query
     if (data["object"] == "light1"):
         res.payload = useLight1(str2bool(data["state"]))
     elif (data["object"] == "light2"):
         res.payload = useLight2(str2bool(data["state"]))
     else:
         res.payload = False
     return res
示例#10
0
 def render_POST(self, request):
     data = ast.literal_eval(request.payload)
     res = UtilityRoomResources()
     res.location_query = request.uri_query
     if (data["object"] == "light"):
         res.payload = useLight(str2bool(data["state"]))
     elif (data["object"] == "machine"):
         res.payload = useMachine(str2bool(data["state"]))
     else:
         res.payload = False
     return res
示例#11
0
    def __init__(self):
        load_dotenv()

        self.APP_ENABLE_FILE_LOGGING = str2bool(
            os.environ.get('APP_ENABLE_FILE_LOGGING')) or False
        self.APP_ENABLE_SENTRY = str2bool(
            os.environ.get('APP_ENABLE_SENTRY')) or True

        self.LOG_FORMAT = '[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s'
        self.LOG_FILE_PATH = Path(
            os.environ.get('LOG_FILE_PATH') or '/var/log/app/app.log')
示例#12
0
def api_google_remove():
    current_id = request.args.get('current_id')
    if current_id and current_id == 'null':
        current_id = str2bool(current_id)

    users_id = request.args.get('user_id')
    if users_id and users_id == 'null':
        users_id = str2bool(users_id)
    dict_data = {'users_id': users_id, 'current_id': current_id}
    data = database.select_google_list_remove(dict_data)
    return jsonify(data)
示例#13
0
 def render_POST(self, request):
     print("request asked:  ",request.payload)
     data = ast.literal_eval(request.payload)
     print("data:,", data)
     res = BathroomResources()
     res.location_query = request.uri_query
     if(data["object"] == "light" ):
         res.payload = useLight(str2bool(data["state"]))
     elif (data["object"] == "shower"):
         res.payload = useShower(str2bool(data["state"]))
     else:
         res.payload = False    
     return res
示例#14
0
文件: shape.py 项目: Ly0n/gpvdm
	def do_load(self):
		f=inp()
		#print(self.file_name+".inp")
		if f.load(self.file_name+".inp")==False:
			print("shape file not found: ",self.file_name)
			return

		self.shape_enabled=str2bool(f.get_token("#shape_enabled"))

		self.type=f.get_token("#shape_type")


		self.dx=float(f.get_token("#shape_dx"))
		self.dy=float(f.get_token("#shape_dy"))
		self.dz=float(f.get_token("#shape_dz"))

		self.load_triangles()

		try:		
			self.dx_padding=float(f.get_token("#shape_padding_dx"))
			self.dy_padding=float(f.get_token("#shape_padding_dy"))
			self.dz_padding=float(f.get_token("#shape_padding_dz"))

			rgb=f.get_array("#red_green_blue")
			self.r=float(rgb[0])
			self.g=float(rgb[1])
			self.b=float(rgb[2])


			self.shape_nx=int(f.get_token("#shape_nx"))
			self.shape_ny=int(f.get_token("#shape_ny"))
			self.shape_nz=int(f.get_token("#shape_nz"))
			self.name=f.get_token("#shape_name")
			self.shape_dos=f.get_token("#shape_dos")
			self.shape_electrical=f.get_token("#shape_electrical")
			self.x0=float(f.get_token("#shape_x0"))
			self.y0=float(f.get_token("#shape_y0"))
			self.z0=float(f.get_token("#shape_z0"))

			self.shape_flip_y=str2bool(f.get_token("#shape_flip_y"))
			self.shape_flip_x=str2bool(f.get_token("#shape_flip_x"))

			self.optical_material=f.get_token("#shape_optical_material")
			self.optical_material.replace("\\", "/")

			#self.y0=0.0

			self.shape_remove_layer=str2bool(f.get_token("#shape_remove_layer"))
		except:
			pass
class DevelopmentConfig(Config):
    DEBUG = True

    APP_ENABLE_SENTRY = str2bool(os.environ.get('APP_ENABLE_SENTRY')) or False
    APP_ENABLE_PROXY_FIX = str2bool(
        os.environ.get('APP_ENABLE_PROXY_FIX')) or False

    LOGGING_LEVEL = logging.INFO

    SQLALCHEMY_DATABASE_URI = os.getenv(
        'SQLALCHEMY_DATABASE_URI') or 'postgresql://*****:*****@app-db/app'

    SERVER_NAME = os.getenv('SERVER_NAME') or 'localhost:9000'
    PREFERRED_URL_SCHEME = os.getenv('PREFERRED_URL_SCHEME') or 'http'
示例#16
0
 def render_POST(self, request):
     data = ast.literal_eval(request.payload)
     res = KitchenResources()
     res.location_query = request.uri_query
     if (data["object"] == "light"):
         res.payload = useLight(str2bool(data["state"]))
     elif (data["object"] == "hood"):
         res.payload = useHood(str2bool(data["state"]))
     elif (data["object"] == "cooker"):
         res.payload = useCooker(str2bool(data["state"]))
     elif (data["object"] == "sink"):
         res.payload = useSink(str2bool(data["state"]))
     else:
         res.payload = False
     return res
示例#17
0
def get_case_by_id(context, expected_value):
    case_id = context.case_created_events[0]['payload']['collectionCase']['id']
    response = requests.get(f'{Config.CASE_API_CASE_URL}{case_id}')
    test_helper.assertEqual(response.status_code, 200, 'Case not found')
    case_details = response.json()

    assert case_details['secureEstablishment'] == str2bool(expected_value), "Unexpected secureEstablishment value"
示例#18
0
    def update_ui(self, update_help):
        self.blockSignals(True)
        f = inp()
        f.load(os.path.join(get_sim_path(), "thermal.inp"))
        v = f.get_token("#thermal")
        self.thermal = str2bool(v)
        #print(self.thermal)

        if self.thermal == True:
            self.setIcon(icon_get("thermal-on"))
            self.setText(_("Thermal model\nenabled"))
            if update_help == True:
                help_window().help_set_help([
                    "thermal-on.png",
                    _("<big><b>Thermal solver switched on</b></big><br>The heat equation will be solved across the device"
                      )
                ])

        if self.thermal == False:
            self.setIcon(icon_get("thermal-off"))
            self.setText(_("Iso-thermal\nmodel"))
            if update_help == True:
                help_window().help_set_help([
                    "thermal-off.png",
                    _("<big><b>Isothermal mode</b></big><br>A single temperature will be assumed across the entire device."
                      )
                ])
        self.blockSignals(False)
示例#19
0
def fwmt_message_received_with_ce1_complete(context, expected_value):
    if expected_value == "none":
        converted_expected_value = None
    else:
        converted_expected_value = str2bool(expected_value)

    _check_emitted_action_instructions(context, converted_expected_value)
示例#20
0
    def __get_stop_loss(self, current_price, current_low, open_price):
        """
        Check if we have reached stop loss
        return True/False
        """
        direction = config.main.trade_direction
        stop_perc = float(config.main.stop_loss_perc)
        immediate = str2bool(config.main.immediate_stop)

        if not open_price:
            return False
        if direction == 'long' and self.test_data and immediate:
            check = current_low
        elif direction == 'short' and self.test_data and immediate:
            check = current_low
        else:
            check = current_price

        if direction == 'long':
            result = float(check) < sub_perc(float(stop_perc), float(open_price))
        elif direction == 'short':
            result = float(check) > add_perc(float(stop_perc), float(open_price))

        if result:
            self.logger.info("StopLoss reached current_low: %s current_price: %s "
                             "open_price: %s" % (current_low, current_price, open_price))
        return result
示例#21
0
def _load_state_data_by_file(path, dtype='', pandas=False):
    # Check to see when file was last modified. Prompt the user to continue
    # if file is old.
    today = datetime.now().date()
    file_last_modified = datetime.utcfromtimestamp(os.path.getmtime(path)).date()
    if today > file_last_modified:
        user_input = input('{} file was last modified on {}'.format(
            dtype, file_last_modified) + ' Do you want to continue working with' + \
            ' this data? (y/n)\n>>>>>>\t')
        if str2bool(user_input) == False:
            sys.exit('Program exited.')
    supported_extensions = ['csv', 'xlsx', 'pkl']
    # Load relevant xlsx workbook or csv file with inventory levels.    
    extension = os.path.basename(path).split('.')[-1]
    if extension.lower() == 'csv':
        data = pd.read_csv(path)
        if data.shape[1] <= 1:
            # Try another separator
            data = pd.read_csv(path, sep=';')
    elif extension.lower() == 'xlsx':
        data = pd.read_excel(path, dtype=str)
    elif extension.lower() == 'pkl':
        data = pickle.load(open(path, 'rb'))
    else:
        raise ValueError('Extension {} not supported.'.format(extension) + \
            ' Ensure file is in one of the following formats: {}'.format(
                supported_extensions))
    if type(data) == pd.core.frame.DataFrame:
        try:
            data = data.drop('Unnamed: 0', axis=1)
        except KeyError:
            pass
        if pandas == False:
            data = data.values
    return data
示例#22
0
def send_gmail_alert(action, pair, price):
    """
    Send email alert using gmail
    """
    if not str2bool(config.email.email_active):
        return
    email_to = config.email.email_to
    email_from = config.email.email_from
    email_password = config.email.email_password

    fromaddr = email_from
    toaddr = email_to
    msg = MIMEMultipart()
    msg['From'] = email_from
    msg['To'] = email_to
    message = "{0} alert generated for {1} at {2}".format(action, pair, price)
    msg['Subject'] = message

    body = message
    msg.attach(MIMEText(body, 'plain'))

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(email_from, email_password)
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()
示例#23
0
def checkvalid_boolean(var_str):
    # Helper function to verify that the parameter that should be a boolean
    # can indeed be converted from a string (read from the file) to a boolean.
    #
    # The function str2bool converts common strings (like 'True', 'true', 't',
    # 'False', etc) to boolean. If the input string is not valid (for list of all
    # valid inputs see https://github.com/symonsoft/str2bool) the function
    # returns nothing and does not throw an exception.
    if var_str:
        var_str = str(var_str)
        try:
            var = str2bool(var_str.lower())
            # Because str2bool returns nothing if there is invalid input
            #    we have to check if var is a boolean
            assert isinstance(var, bool), ([
                '"' + str(var_str) + '"' +
                ' parameter can not be converted to' +
                ' a boolean: Verify parameter file'
            ])
            return var
        except Exception as e:
            param_logger.exception(e)

    else:
        return None
示例#24
0
    def load(self, epi):
        self.epi = epi
        self.file = inp()
        file_name = os.path.join(get_sim_path(),
                                 "mesh_" + self.direction + ".inp")

        self.clear()

        if self.check_curcuit_sim(epi) == True:
            self.update()
            return True

        if self.file.load(file_name) != False:

            remesh = str2bool(self.file.get_next_val())

            self.remesh = remesh

            mesh_layers = int(self.file.get_next_val())

            for i in range(0, mesh_layers):
                #thick
                thick = float(self.file.get_next_val())  #length

                points = float(self.file.get_next_val())  #points

                mul = float(self.file.get_next_val())  #mul

                left_right = self.file.get_next_val()  #left_right

                self.add_layer(thick, points, mul, left_right)

        self.update()
        return True
示例#25
0
    def check_pairs(self, items_list):
        """
        Check we can trade which each of given trading pairs
        Return filtered list
        """
        dbase = Mysql(test=self.test_data, interval=self.interval)
        current_trades = dbase.get_trades()
        drain = str2bool(config.main.drain)
        avail_slots = self.max_trades - len(current_trades)
        self.logger.info("%s buy slots available" % avail_slots)
        if avail_slots <= 0:
            self.logger.warning("Too many trades, skipping")
            return []
        elif drain and not self.test_data:
            self.logger.warning("%s is in drain, skipping..." % self.interval)
            return []

        final_list = []
        for item in items_list:
            if current_trades and item[0] in current_trades[0]:
                self.logger.warning(
                    "We already have a trade of %s, skipping..." % item)
            elif item[0] not in config.main.pairs and not self.test_data:
                self.logger.warning("Pair %s not in main_pairs, skipping..." %
                                    item[0])
            else:
                final_list.append(item)
        return final_list
示例#26
0
    def _atualizar_produto(self, id, nome, descricao, ingredientes,
                           modo_de_preparo, preco, estabelecimento_id,
                           categoria_id, inativo):

        produto = self._buscar_produto(id)

        if produto == None:
            raise Exception("Nenhum produto encontrado!")

        if Produto.query.filter(
                Produto.nome == nome, Produto.estabelecimento_id
                == estabelecimento_id, Produto.id != id).count() > 0:
            raise Exception("Já existe um produto com o nome informado!")

        estabelecimento = Estabelecimento.query.filter_by(
            id=estabelecimento_id).first()
        categoria = Categoria.query.filter_by(id=categoria_id).first()
        produto.nome = nome
        produto.descricao = descricao
        produto.ingredientes = ingredientes
        produto.modo_de_preparo = modo_de_preparo
        produto.preco = preco
        produto.estabelecimento = estabelecimento
        produto.inativo = str2bool(str(inativo).lower())
        produto.categoria = categoria

        db.session.add(produto)
        db.session.commit()
        return produto
示例#27
0
	def insert_row(self,i,enabled,src_file,src_token,src_path,dest_file,dest_token,dest_path):
		self.tab.blockSignals(True)
		self.tab.insertRow(i)

		item = gtkswitch()
		item.set_value(str2bool(enabled))
		item.changed.connect(self.tab_changed)
		self.tab.setCellWidget(i,0,item)

		item = QTableWidgetItem(src_file)
		self.tab.setItem(i,1,item)

		item = QTableWidgetItem(src_token)
		self.tab.setItem(i,2,item)

		self.item = gpvdm_select()
		self.item.setText(src_path)
		self.item.button.clicked.connect(self.callback_show_list_src)
		self.tab.setCellWidget(i,3,self.item)

		item = QTableWidgetItem(dest_file)
		self.tab.setItem(i,4,item)

		item = QTableWidgetItem(dest_token)
		self.tab.setItem(i,5,item)

		self.item = gpvdm_select()
		self.item.setText(dest_path)
		self.item.button.clicked.connect(self.callback_show_list_dest)
		self.tab.setCellWidget(i,6,self.item)
		
		self.tab.blockSignals(False)
示例#28
0
def get_user_settings_dir():
    global use_gpvdm_local
    if use_gpvdm_local == None:
        use_gpvdm_local = True
        file_path = os.path.join(os.getcwd(), "config.inp")

        if os.path.isfile(file_path):
            f = open(file_path, mode='r')
            read_lines = f.read().split()
            f.close()
            for i in range(0, len(read_lines)):
                read_lines[i] = read_lines[i].rstrip()
            for i in range(0, len(read_lines)):
                if read_lines[i] == "#use_gpvdm_local":
                    use_gpvdm_local = str2bool(read_lines[i + 1])
                    break

    if use_gpvdm_local == True:
        ret = os.path.join(get_home_path(), "gpvdm_local")

        if os.path.isdir(ret) == False:
            os.makedirs(ret)
    else:
        return os.getcwd()
    return ret
示例#29
0
    def load_config(self):
        self.cache_config_file = os.path.join(get_user_settings_dir(),
                                              "cache.inp")
        self.max_size = 1000
        self.enabled = True
        if os.path.isfile(self.cache_config_file) == False:
            speed = disk_test(get_user_settings_dir())
            lines = []
            lines.append("#cache_size")
            lines.append(str(self.max_size))
            lines.append("#cache_disk_speed")
            lines.append(str(speed))
            if (speed < 200):
                self.enabled = False
            lines.append("#cache_enabled")
            lines.append(str(self.enabled))
            lines.append("#ver")
            lines.append("1.0")
            lines.append("#end")

            inp_save_lines_to_file(self.cache_config_file, lines)

        else:
            lines = inp_load_file(
                os.path.join(get_user_settings_dir(), "cache.inp"))
            self.max_size = int(inp_search_token_value(lines, "#cache_size"))
            self.enabled = str2bool(
                inp_search_token_value(lines, "#cache_enabled"))
示例#30
0
    def __get_take_profit(self, current_price, current_high, open_price):
        """
        Check if we have reached take profit
        return True/False
        """
        profit_perc = float(config.main.take_profit_perc)

        if profit_perc <= 0:
            return False
        direction = config.main.trade_direction
        immediate = str2bool(config.main.immediate_take_profit)

        if not open_price:
            return False

        if direction == 'long' and self.test_data and immediate:
            check = current_high
        elif direction == 'short' and self.test_data and immediate:
            check = current_high
        else:
            check = current_price

        if direction == 'long':
            result = float(check) > add_perc(float(profit_perc), float(open_price))
        elif direction == 'short':
            result = float(check) < sub_perc(float(profit_perc), float(open_price))

        if result:
            self.logger.info("TakeProfit reached current_high: %s current_price: %s "
                             "open_price: %s" % (current_high, current_price, open_price))
        return result