예제 #1
0
    def storeEntries(self):
        """
        Store specification entries in filter dictionary
        Entries are always stored in dB (20 log10) !
        """
        idx = self.cmbUnitsA.currentIndex()  # read index of units combobox

        if idx == 0: # Entry is in dBs, same as in dictionary
            for i in range(len(self.qlineedit)):
                fb.fil[0].update(
                    {self.qlineedit[i].objectName():
                        simple_eval(self.qlineedit[i].text())})

        elif idx == 1:  # Entries are voltages, convert to dBs
            for i in range(len(self.qlineedit)):
                fb.fil[0].update(
                    {self.qlineedit[i].objectName():
                       - 20. * log10 (simple_eval(self.qlineedit[i].text()))})
        else:  # Entries are powers, convert to dBs
            for i in range(len(self.qlineedit)):
                fb.fil[0].update(
                    {self.qlineedit[i].objectName():
                       - 10. * log10 (simple_eval(self.qlineedit[i].text()))})
                       
        self.sigSpecsChanged.emit() # -> input_all
예제 #2
0
def reduced_fraction(num, den):
    """ Given a fraction num/den where num/den are strings, produces the LaTeX
        string for the reduced fraction. For example,
        reduced_fraction(3,9) = \frac{{1}}{{3}} while
        reduced_fraction(4,2) = 2
        <<INPUT>> 
        num, den (strings) for the numerator and denominator
    """
    template="{}\\frac{{ {} }}{{ {} }}"
    sign = ''
    try:
        numer = int(simple_eval(str(num)))
        denom = int(simple_eval(str(den)))

        if not denom:
            raise TypeError('Denominator cannot be zero or empty')

        gcd = fractions.gcd(numer, denom)
        (red_num, red_den) = (numer/gcd, denom/gcd)

        if red_den == 1:
            return str(int(red_num))
        else:
            if red_num*red_den < 0:
                sign = '-'
            return template.format(sign, int(abs(red_num)), int(abs(red_den)))

    except TypeError as e:
        raise e
예제 #3
0
파일: forms.py 프로젝트: ChillarAnand/calci
    def is_valid(self):

        valid = super(CalculationForm, self).is_valid()

        if not valid:
            return valid

        try:
            simple_eval(self.cleaned_data['expression'])
            return True
        except:
            self._errors['invalid_exp'] = 'Invalid expression'
            return False
예제 #4
0
 def update_value(self, button, calc):
    interest = float(simple_eval(str(self.interestEdit.text())))
    period = float(simple_eval(str(self.periodEdit.text())))
    
    self.factor = calculations.Factors(interest, period)
    calc = calc(self.factor)
    value = float(simple_eval(str(self.multiplierEdit.text()))) * calc
    
    button.setText(str(calc))
    self.finalValueEdit.setText(str(value))
    
    if is_number(str(self.sumEdit.text())):
       self.sum = float(self.sumEdit.text()) + value
    else:
       self.sum = value
    self.sumEdit.setText(str(self.sum))
    def check_row(self, cells):
        # Prepare names
        names = {}
        for cell in cells:
            if None not in [cell.get('header'), cell.get('value')]:
                try:
                    names[cell['header']] = float(cell['value'])
                except ValueError:
                    pass

        # Check constraint
        try:
            # This call should be considered as a safe expression evaluation
            # https://github.com/danthedeckie/simpleeval
            assert simple_eval(self.__constraint, names=names)
        except Exception:
            row_number = cells[0]['row-number']
            message = 'Custom constraint "{constraint}" fails for row {row_number}'
            message_substitutions = {
                'constraint': self.__constraint,
            }
            error = Error(
                'custom-constraint',
                row_number=row_number,
                message=message,
                message_substitutions=message_substitutions
            )
            return [error]
예제 #6
0
def coerce_retention_period(value):
    """
    Coerce a retention period to a Python value.

    :param value: A string containing the text 'always', a number or
                  an expression that can be evaluated to a number.
    :returns: A number or the string 'always'.
    :raises: :exc:`~exceptions.ValueError` when the string can't be coerced.
    """
    # Numbers pass through untouched.
    if not isinstance(value, numbers.Number):
        # Other values are expected to be strings.
        if not isinstance(value, string_types):
            msg = "Expected string, got %s instead!"
            raise ValueError(msg % type(value))
        # Check for the literal string `always'.
        value = value.strip()
        if value.lower() == 'always':
            value = 'always'
        else:
            # Evaluate other strings as expressions.
            value = simple_eval(value)
            if not isinstance(value, numbers.Number):
                msg = "Expected numeric result, got %s instead!"
                raise ValueError(msg % type(value))
    return value
예제 #7
0
def eval_():
    expr = request.args['expr']
    result = simple_eval(expr)
    return make_response("""
        <h1>eval page</h1>
        <pre>{} = {}</pre>
    """.format(expr, result))
예제 #8
0
    def saveCoeffs(self):
        """
        Read out coefficients table and save the values to filter 'coeffs'
        and 'zpk' dicts. Is called when clicking the <Save> button, triggers
        a recalculation and replot of all plot widgets.
        """
        if self.DEBUG:
            print("=====================\nInputCoeffs.saveCoeffs")
        coeffs = []
        num_rows, num_cols = self.tblCoeff.rowCount(), self.tblCoeff.columnCount()
        if self.DEBUG:
            print("Tbl rows /  cols:", num_rows, num_cols)
        #        if num_cols > 1: # IIR
        for col in range(num_cols):
            rows = []
            for row in range(num_rows):
                item = self.tblCoeff.item(row, col)
                if item:
                    if item.text() != "":
                        rows.append(simple_eval(item.text()))
                else:
                    rows.append(0.0)
            #                    rows.append(float(item.text()) if item else 0.)
            coeffs.append(rows)

        fb.fil[0]["N"] = num_rows - 1
        save_fil(fb.fil[0], coeffs, "ba", __name__)

        if self.DEBUG:
            print("Coeffs - ZPK:", fb.fil[0]["zpk"])
            print("Coeffs - b,a:", fb.fil[0]["ba"])
            print("Coeffs updated!")

        self.sigFilterDesigned.emit()  # -> input_all -> pyFDA -> pltAll.updateAll()
예제 #9
0
    def saveZPK(self):
        """
        Read out table and save the values to the filter PZ dict
        """
            
        if self.DEBUG:
            print("=====================\nInputPZ.saveZPK")
            
        zpk = [] 
        
        num_rows = self.tblPZ.rowCount()
        if self.DEBUG: print("nrows:",num_rows)

        #iterate over both columns
        for col in range(2):
            rows = []
            for row in range(num_rows):
                item = self.tblPZ.item(row, col)
                if item:
                    if item.text() != "":
                        rows.append(simple_eval(item.text()))
                else:
                    rows.append(0.)

            zpk.append(rows)

        zpk.append(simple_eval(self.ledGain.text())) # append k factor to zpk

        fb.fil[0]["N"] = num_rows
        save_fil(fb.fil[0], zpk, 'zpk', __name__) # save & convert to 'ba'
        
        if self.chkNorm.isChecked():
            # set gain factor k (zpk[2]) in such a way that the max. filter 
            # gain remains unchanged
            [w, H] = freqz(fb.fil[0]['ba'][0], fb.fil[0]['ba'][1]) # (bb, aa)
            zpk[2] = zpk[2] * self.Hmax_last / max(abs(H))
            save_fil(fb.fil[0], zpk, 'zpk', __name__) # save with new gain '

        if __name__ == '__main__':
            self.showZPK() # only needed for stand-alone test
            
        self.sigFilterDesigned.emit()

        if self.DEBUG:
            print("ZPK - coeffs:",  fb.fil[0]['ba'])
            print("ZPK - zpk:",  fb.fil[0]['zpk'])
            print("ZPK updated!")
예제 #10
0
 def storeEntries(self):
     """
     Store specification entries in filter dictionary
     Entries are normalized with sampling frequency self.f_S !
     The scale factor (khz, ...) is contained neither in f_S nor in the
     specs hence, it cancels out.
     """
     if self.DEBUG:
         print("input_freq_specs.storeEntries\n=================")
     for i in range(len(self.qlineedit)):
         fb.fil[0].update(
             {self.qlineedit[i].objectName():
                 simple_eval(self.qlineedit[i].text())/self.f_S})
         if self.DEBUG:
             print(self.qlineedit[i].objectName(),
                   simple_eval(self.qlineedit[i].text())/self.f_S,
                   float(fb.fil[0][self.qlineedit[i].objectName()]))
예제 #11
0
 def _sort_store_entries(self):
     """
     Sort visible spec entries with ascending frequency if "sort" button is
     pressed and write the sorted freq. specs back into the lineedit widgets
     and into the filter dict.
     """
     if fb.fil[0]['freq_specs_sort']:
         fSpecs = [simple_eval(self.qlineedit[i].text())
                                         for i in range(len(self.qlineedit))]
         fSpecs.sort()
 
         for i in range(len(self.qlineedit)):
             self.qlineedit[i].setText(str(fSpecs[i]))
             
     for i in range(len(self.qlineedit)):
         fb.fil[0].update(
             {self.qlineedit[i].objectName():round(
                 simple_eval(self.qlineedit[i].text())/fb.fil[0]['f_S'],11)})
예제 #12
0
 def storeEntries(self):
     """
     Store specification entries in filter dictionary
     """
     for i in range(len(self.qlabels)):
         fb.fil[0].update(
             {self.qlineedit[i].objectName():
                 simple_eval(self.qlineedit[i].text())})
                    
     self.sigSpecsChanged.emit() # -> input_widgets
예제 #13
0
def fitnessScore(chromosome):
  mathExpression = chromosomeToMathExpression(chromosome)
  try:
    chromosomeMathValue = simple_eval(mathExpression)
  except:
    return None
  try:
	  percentError =  abs(( numberWeAreLookingFor - chromosomeMathValue ) / numberWeAreLookingFor)
  except:
    	  return None
  return percentError
예제 #14
0
    def _is_condition_include(self, json_match):
        """ return true if a condition doesn't exists or if the condition is evaluation is true else false """
        if isinstance(json_match, dict) and "condition" in json_match:
            condition = json_match["condition"]
            if condition != None and isinstance(condition, str) and simple_eval != None:
                return simple_eval(condition)
            else:
                return True  
                # TODO property to manage

        return True  
예제 #15
0
 def _sort_entries(self):
     """
     Sort visible spec entries with ascending frequency if "sort" button is
     pressed and write the sorted freq. specs back into the lineedit widgets.
     """
     if self.butSort.isChecked():
         fSpecs = [simple_eval(self.qlineedit[i].text())
                                         for i in range(len(self.qlineedit))]
         fSpecs.sort()
 
         for i in range(len(self.qlineedit)):
             self.qlineedit[i].setText(str(fSpecs[i]))
예제 #16
0
    def get_line(self, values):
        'Return the tax line for the keyword values'
        pool = Pool()
        TaxLine = pool.get('account.tax.line')

        line = TaxLine()
        amount = simple_eval(decistmt(self.amount),
            functions={'Decimal': Decimal}, names=values)
        amount = self.line.move.company.currency.round(amount)
        line.amount = amount
        line.type = self.type
        line.tax = self.tax
        return line
예제 #17
0
 def setCoeffsZero(self):
     """
     Set all coefficients = 0 in table with a magnitude less than eps
     """
     eps = float(self.ledSetEps.text())
     num_rows, num_cols = self.tblCoeff.rowCount(), self.tblCoeff.columnCount()
     for col in range(num_cols):
         for row in range(num_rows):
             item = self.tblCoeff.item(row, col)
             if item:
                 if abs(simple_eval(item.text())) < eps:
                     item.setText(str(0.0))
             else:
                 self.tblCoeff.setItem(row, col, QtGui.QTableWidgetItem("0.0"))
예제 #18
0
def eval_datetime_formula(string):
    ''' evaluate a simple date/time formula, returning a unix datetime stamp '''

    replacements = [('WEEKS', '* 604800'),
                    ('WEEK', '* 604800'),
                    ('DAYS', '* 86400'),
                    ('DAY', '* 86400'),
                    ('MONTHS', '* 2592000'),  # 30 day month...
                    ('MONTH', '* 2592000'),
                   ]

    for rep_str, out_str in replacements:
        string = string.replace(rep_str, out_str)

    return simple_eval(string, names={'NOW': time()})
예제 #19
0
    def setZPKZero(self):
        """
        Set all PZs = 0 with a magnitude less than eps
        """
        eps = float(self.ledSetEps.text())
        num_rows= self.tblPZ.rowCount()

        for col in range(2):
            for row in range(num_rows):
                item = self.tblPZ.item(row, col)
                if item:
                    if abs(simple_eval(item.text())) < eps:
                        item.setText(str(0.))
                else:
                    self.tblPZ.setItem(row,col,QtGui.QTableWidgetItem("0.0"))
예제 #20
0
파일: eval.py 프로젝트: prologic/kdb
    def eval(self, source, target, args):
        """Evaluates the given expression and displays the result.

        Syntax: EVAL [<expr> ...]
        """

        if not args:
            return "No expression given."

        expression = args

        try:
            return str(simple_eval(expression))
        except Exception, error:
            return log("ERROR: {0:s}", error)
예제 #21
0
 def transform_resource(self, source, target):
     index = self.__position - 1 if self.__position else None
     if self.__incremental:
         target.data = source.to_petl().addrownumbers(field=self.__name)
     else:
         value = self.__value
         if isinstance(value, str) and value.startswith("<formula>"):
             formula = value.replace("<formula>", "")
             value = lambda row: simpleeval.simple_eval(formula, names=row)
         target.data = source.to_petl().addfield(self.__name,
                                                 value=value,
                                                 index=index)
     field = Field(name=self.__name, **self.__options)
     if index is None:
         target.schema.add_field(field)
     else:
         target.schema.fields.insert(index, field)
예제 #22
0
 def run(self):
     Quit = ['x', 'q', 'exit', 'quit']
     while True:
         time.sleep(Bot.wait)
         print(self._format(self.q))
         self.a = input()
         if self.a.lower() in Quit:
             break
         try:
             result = simple_eval(self.a)
         except ZeroDivisionError as err:  # useful
             print(f'Oops!There are something unexpected happened:{err}, please enter again')
         else:
             self.wait = self.calctime(result)
             time.sleep(self.wait)
             print(self._format(f'Done! Result is {result}'))
     print(self._format('Calculation Over, Thanks for using'))
예제 #23
0
    def get_line(self, origin, keywords, **context):
        pool = Pool()
        Line = pool.get('account.statement.line')
        context.setdefault('functions', {})['Decimal'] = Decimal
        context.setdefault('names', {}).update(keywords)

        currency = origin.statement.journal.currency
        amount = currency.round(simple_eval(decistmt(self.amount), **context))
        party = self._get_party(origin, keywords)
        invoice = self._get_invoice(origin, keywords)

        if invoice and party and invoice.party != party:
            return
        if invoice and not party:
            party = invoice.party

        account = self.account
        if not account:
            if invoice:
                account = invoice.account
            elif party:
                with Transaction().set_context(date=origin.date):
                    if amount > Decimal('0.0'):
                        account = party.account_receivable_used
                    else:
                        account = party.account_payable_used

        if not account:
            return
        if account.party_required and not party:
            return
        if not account.party_required:
            party = None

        line = Line()
        line.statement = origin.statement
        line.number = origin.number
        line.description = origin.description
        line.origin = origin
        line.amount = amount
        line.date = origin.date
        line.party = party
        line.account = account
        line.invoice = invoice
        return line
예제 #24
0
def df_simple_eval(command,
                   variables,
                   x,
                   command_function=None,
                   my_filter=False):
    """ Performs safe evals on dataframe

    Uses specified command with variable mapping onto x to generate numerical 
    (pd.DataFrame.dtypes number) values.

    Parameters
    ----------
    command :  arthematic expression structure e.g. "a + b"

    variables : dict, mapping for variables in command onto available columns

        columns are limited to pd.DataFrame.dtype = 'number'
        e.g. {"a": "_rxn_molarity_acid"...}

    x : row of dataframe which contains numerical data from columns used in variable

        (often specified as a lambda function from larger dataframe)

    Returns
    -------
    out_value : calculated value generated from applying 'command' to 
    the 'variables' in 'x'

    Notes
    -----
    See: https://github.com/danthedeckie/simpleeval for more information
        on supported evaluations
    """
    df_referenced_dict = {}
    if my_filter:
        for variable_name in variables.keys():
            df_referenced_dict[variable_name] = x.filter(
                regex=variables[variable_name])
    else:
        for variable_name in variables.keys():
            df_referenced_dict[variable_name] = x[variables[variable_name]]
    out_value = simple_eval(command,
                            names=df_referenced_dict,
                            functions=command_function)
    return out_value
예제 #25
0
 def run(self, env):
     if (env._goto):
         return None
     if (self.literal):
         val = expandvars(self.val, default='UNKNOWN_VARIABLE')
         env_print(env, '\n>>> EXPORT {0} = {1}'.format(self.var, val))
         set_utf8(self.var, val)
     else:
         val = expandvars(self.val, default='0')
         try:
             eval_val = simple_eval(val)
         except:
             eval_val = ''
         env_print(
             env,
             '\n>>> EVAL {0} = {1} = {2}'.format(self.var, val, eval_val))
         set_utf8(self.var, eval_val)
     return self.rc
예제 #26
0
파일: bot.py 프로젝트: CoolOlivie/bottombot
async def maths(ctx, *, args):
    global ttst
    global s
    try:
        if ctx.message.author.id == 763336086369861672:
            await ctx.send("no, f**k off")
        elif ctx.message.author.id == 456028176557015040:
            await ctx.send("no, f**k off") #same people banned as above
        else:
            await ctx.trigger_typing()
            response = simple_eval(args.replace("^", "**"), functions={"sqrt": lambda x: math.sqrt(x)})
            print(f"\u001b[33;1m{ctx.message.guild.name} | {ctx.message.author}: {args} -> {response}\u001b[31m")
            await ctx.send(response, tts=ttst)
            f = open(f"{filepath}/logs.txt", "a")
            f.write(f"{datetime.datetime.now()} - {ctx.message.guild.name} | {ctx.message.author} : !bb {args} -> {response}\n")
            f.close()
    except NumberTooHigh:
        await ctx.send("Result was too high")
예제 #27
0
    def storeEntries(self):
        """
        - Sort spec entries with ascending frequency if button is pressed
        - Store specification entries in filter dictionary:
          Entries are normalized with sampling frequency fb.fil[0]['f_S'] !
          The unit scale factor (khz, ...) is contained neither in f_S nor in 
          the specs, hence, it cancels out.
        - Emit sigFilterChanged signal
        """

        self._sort_store_entries() 
           
        for i in range(len(self.qlineedit)):
            fb.fil[0].update(
                {self.qlineedit[i].objectName():
                    simple_eval(self.qlineedit[i].text())/fb.fil[0]['f_S']})
                      
        self.sigSpecsChanged.emit()
예제 #28
0
파일: commands.py 프로젝트: Rettend/BuffBot
    async def math(self, ctx, *, params):
        try:
            result = simple_eval("{}".format(params),
                                 names={
                                     "e": math.e,
                                     "pi": math.pi
                                 },
                                 functions={
                                     "log": math.log,
                                     "sqrt": math.sqrt,
                                     "cos": math.cos,
                                     "sin": math.sin,
                                     "tan": math.tan
                                 })
        except Exception:
            result = "Read the f*****g manual"

        await self.respond(result, ctx.message.author.mention)
예제 #29
0
    def solve(self):
        """this function uses simple eval to attempt to evaluate the users expression """
        try:
            answer = float(
                simple_eval(
                    self.tk_value.get(),
                    names={
                        "math": math,
                        "pi": math.pi,
                        "e": math.e
                    },
                    functions=self.allowed_functions,
                ))

            self.answer.set("{:.10f}".format(answer))

        except Exception as error:
            # print(error)
            pass
def calculate():

	global no
	global send_str
	final_result = simple_eval(init_str)
	final_result=round(final_result,4)
	op_wind.insert(Tkinter.END,"Local Result: ")
	op_wind.insert(Tkinter.END,final_result)

	#Writing to persistent storage

	dat1 = datetime.datetime.utcnow()
	
	print dat1
	#https://www.guru99.com/reading-and-writing-files-in-python.html
	fin=open("cli"+str(no)+".txt","a+")
	fin.write(str(dat1)+" :"+send_str)

	fin.close()
예제 #31
0
def get_answer(question, choices):
    """ Evaluates the mathematical expression to compute the answer.
        <<INPUT>>
        question (MarkedQuestion) The object containing the question
        choices (String) String containing *concrete* choices
        <<OUTPUT>>
        (Integer)  The answer, to be saved

        Depends: simpleeval.simple_eval
    """
    answer = question.answer
    if choices is None:
        return answer
    if re.findall(r'{v\[\d+\]}', answer): # matches no variables
        answer = answer.format(v=choices.split(';'))
        answer = eval_sub_expression(answer)

    try:
        # Substitute the variables into the string and evaluate the functions dictionary
#        eval_string = answer.format(v=choices.split(';'))
        # Remove whitespace before evaluating
        eval_string = answer.replace(' ', '')
        functions = eval(question.functions)
        functions.update(settings.PREDEFINED_FUNCTIONS)

        return round(
            simple_eval(
                eval_string, 
                functions=functions, 
                names=settings.UNIVERSAL_CONSTANTS
            ),
        4)
    except (SyntaxError, NameNotDefined,) as e:
        # Enter this exception if the answer is not one that can be evaluated.
        # In that case, the answer is just the answer
#        if question.q_type == "MC":
#            return answer
#        else:
#            raise e
        return answer

    except Exception as e: 
        raise e
예제 #32
0
    def storeEntries(self):
        """
        - Sort spec entries with ascending frequency if button is pressed
        - Store specification entries in filter dictionary:
          Entries are normalized with sampling frequency fb.fil[0]['f_S'] !
          The unit scale factor (khz, ...) is contained neither in f_S nor in 
          the specs, hence, it cancels out.
        - Emit sigFilterChanged signal
        """

        self._sort_store_entries()

        for i in range(len(self.qlineedit)):
            fb.fil[0].update({
                self.qlineedit[i].objectName():
                simple_eval(self.qlineedit[i].text()) / fb.fil[0]['f_S']
            })

        self.sigSpecsChanged.emit()
예제 #33
0
    def solve(self):
        """this function uses simple eval to attempt to evaluate the users expression """
        
        #this function is ran in a loop to constantly update the output to be correct.
        #it works on the model that if something executes correctly, its a finished expression:
        #otherwise, its not fully typed or is wrong
        try:
            answer = float(
                simple_eval(
                        self.tk_value.get(),
                        names={"math": math, "pi": math.pi, "e": math.e}, #variables that may be accessed
                        functions=self.allowed_functions
                        )
            )

            self.answer.set("{:.10f}".format(answer))

        except Exception as error:
            pass
예제 #34
0
    def resolve_value(self, input_val):
        """ Return value of input_val.

        If input_val is either already not a string, in which case it will be returned.
        Alternatively, the input value could be a variable, as defined in the keys
        in the var_dict. In this case the value associated with this variable will be
        returned.
        :input: (str / float / bool etc) Variable value or variable string.
        """

        if type(input_val) is not str:
            return input_val
        else:
            try:
                return simple_eval(input_val, names=self.var_dict)
            except NameNotDefined:
                self.log.warn(
                    f"Could not resolve variable '{input_val}', treating as placeholder."
                )
                return self.default_placeholder_value(input_val)
예제 #35
0
    def perform_predicate_test(self, **context):
        from .docpath import Docpath

        predicate_type = type(ast.parse(self.predicate).body[0])
        if predicate_type == ast.Assign:
            raise SyntaxError(
                "invalid use of assignment operator in: '{}'".format(
                    self.predicate))

        result = simple_eval(self.predicate,
                             **self._get_evaluation_context(**context))

        if isinstance(result, Docpath):
            nodes = result.traverse(context['node'])
            matches = len(list(nodes))
            return matches > 0
        elif str(result).isdigit():
            return result == context.get('position', None)

        return bool(result)
예제 #36
0
    def transition_export(self):
        pool = Pool()
        Shop = pool.get('sale.shop')

        shop = self.start.shop
        from_date = self.start.from_date

        output = shop.esale_sale_export_csv(from_date)

        # Update date last import
        Shop.write([shop], {'esale_last_state_orders': from_date})

        self.result.csv_file = fields.Binary.cast(output.getvalue())
        if shop.esale_export_sale_filename:
            context = shop.get_export_csv_context_formula()
            filename = simple_eval(shop.esale_export_sale_filename, **context)
        else:
            filename = '%s-sales.csv' % (slugify(shop.name.replace('.', '-')))
        self.result.file_name = filename

        return 'result'
예제 #37
0
    def test_chaining_correct(self):
        """
            Contributed by Khalid Grandi (xaled).
        """
        class A(object):
            def __init__(self):
                self.a = "0"

            def add(self, b):
                self.a += "-add" + str(b)
                return self

            def sub(self, b):
                self.a += "-sub" + str(b)
                return self

            def tostring(self):
                return str(self.a)

        x = A()
        self.assertEqual(simple_eval("x.add(1).sub(2).sub(3).tostring()", names={"x": x}), "0-add1-sub2-sub3")
예제 #38
0
    def test_chaining_correct(self):
        """
            Contributed by Khalid Grandi (xaled).
        """
        class A(object):
            def __init__(self):
                self.a = "0"

            def add(self, b):
                self.a += "-add" + str(b)
                return self

            def sub(self, b):
                self.a += "-sub" + str(b)
                return self

            def tostring(self):
                return str(self.a)

        x = A()
        self.assertEqual(simple_eval("x.add(1).sub(2).sub(3).tostring()", names={"x": x}), "0-add1-sub2-sub3")
예제 #39
0
 def response_math(
         self,
         t,
         bot,
         clean=False):  #if not clean it outputs random error messages
     try:
         result = simpleeval.simple_eval(t.replace("^", "**"),
                                         functions=math_functions,
                                         names=math_constants)
         if type(result) == bool:
             if result: result = "waar"
             else: result = "niet waar"
         return "Dat is " + str(result)
     except (simpleeval.InvalidExpression, simpleeval.FunctionNotDefined,
             simpleeval.AttributeDoesNotExist, KeyError):
         if not clean: return bot.pick(bot.commands["math_error"])
         else: return "Sorry, dat snap ik niet :("
     except simpleeval.NumberTooHigh:
         return "Sorry, dat is te moeilijk voor me"
     except Exception:
         return "computer says no"
예제 #40
0
    def quantCoeffs(self):
        """
        Quantize all coefficients
        """
        qI = int(self.ledQuantI.text())
        qF = int(self.ledQuantF.text())
        qQuant = self.cmbQQuant.currentText()
        qOvfl = self.cmbQOvfl.currentText()
        q_obj = {"QI": qI, "QF": qF, "quant": qQuant, "ovfl": qOvfl}
        myQ = fix.Fixed(q_obj)  # instantiate fixed-point object
        num_rows, num_cols = self.tblCoeff.rowCount(), self.tblCoeff.columnCount()
        for col in range(num_cols):
            for row in range(num_rows):
                item = self.tblCoeff.item(row, col)
                if item:
                    item.setText(str(myQ.fix(simple_eval(item.text()))))
                else:
                    self.tblCoeff.setItem(row, col, QtGui.QTableWidgetItem("0.0"))

        self.tblCoeff.resizeColumnsToContents()
        self.tblCoeff.resizeRowsToContents()
예제 #41
0
 def transform_resource(self, resource):
     table = resource.to_petl()
     descriptor = self.to_dict()
     descriptor.pop("code", None)
     name = descriptor.pop("name", None)
     value = descriptor.pop("value", None)
     formula = descriptor.pop("formula", None)
     function = descriptor.pop("function", None)
     new_name = descriptor.pop("newName", None)
     if new_name:
         descriptor["name"] = new_name
     field = resource.schema.get_field(name)
     field.update(descriptor)
     if formula:
         function = lambda val, row: simpleeval.simple_eval(formula, names=row)
     if function:
         resource.data = table.convert(name, function)
     elif new_name:
         resource.data = table.rename({name: new_name})
     elif "value" in self:
         resource.data = table.update(name, value)
def run_simple_eval(dates, values, names, expression):
    """ param dates: a list of dates
        param values: a list of value triples, its a numerical expression so this will only work on the middle item of each triple: the number 
            The values take the form of triples allowing for an interfacw with different value types: string, number or concept.
            The numbers are cast as floats?
        param names: names corresponding to the values, referenced in the expression string
        
        min an max are supplied as predefined functions. This list may grow over time.
    """

    if len(values) != len(names):
        raise InputError(
            "different number of  values and names in run_simple_eval")

    i = 0
    variables = {}
    while i < len(values):
        if values[i][1] is None:
            return None
            # BAIL OUT!
        try:
            variables[names[i]] = float(values[i][1])
        except Exception as e:
            raise InputError("{} value could not be cast as float {}".format(
                i, values[i][1]))
        i = i + 1

    functions = {"min": lambda x, y: min(x, y), "max": lambda x, y: max(x, y)}

    try:
        value = simple_eval(expression, names=variables, functions=functions)
    except Exception as e:
        logger.error(
            "simple_eval errored. expr:%s, functions:%s  names_map:%s ",
            expression, functions, names)
        #(exc_type, exc_value, exc_traceback) = sys.exc_info()
        #traceback.print_tb(exc_traceback, limit=4, file=sys.stdout)
        raise e

    return (value)
예제 #43
0
 def evaluate_expression(self, expr, object_id, field):
     if expr:
         try:
             data = dict(EVAL_DEFAULT_NAMES)
             expr = self.replace_parameters(expr, data=data)
             return simple_eval(expr,
                                names=data,
                                functions=self.eval_functions)
         except NameNotDefined as ex:
             raise ReportBroError(
                 Error('errorMsgInvalidExpressionNameNotDefined',
                       object_id=object_id,
                       field=field,
                       info=ex.name,
                       context=expr))
         except FunctionNotDefined as ex:
             # avoid possible unresolved attribute reference warning by using getattr
             func_name = getattr(ex, 'func_name')
             raise ReportBroError(
                 Error('errorMsgInvalidExpressionFuncNotDefined',
                       object_id=object_id,
                       field=field,
                       info=func_name,
                       context=expr))
         except SyntaxError as ex:
             raise ReportBroError(
                 Error('errorMsgInvalidExpression',
                       object_id=object_id,
                       field=field,
                       info=ex.msg,
                       context=expr))
         except Exception as ex:
             info = ex.message if hasattr(ex, 'message') else str(ex)
             raise ReportBroError(
                 Error('errorMsgInvalidExpression',
                       object_id=object_id,
                       field=field,
                       info=info,
                       context=expr))
     return True
예제 #44
0
def stringtotime(timing):
    allowedsymbols = [
        "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "y", "d", "h", "m",
        "s"
    ]
    seconds = timing.lower()
    for character in list(seconds):
        if character not in allowedsymbols:
            return None
    if "y" in timing:
        timing = timing.replace("y", "*31536000+")
    if "d" in timing:
        timing = timing.replace("d", "*86400+")
    if "h" in timing:
        timing = timing.replace("h", "*3600+")
    if "m" in timing:
        timing = timing.replace("m", "*60+")
    if "s" in timing:
        timing = timing.replace("s", "*1+")
    timing += "0"
    timing = simple_eval(timing)
    return timing
예제 #45
0
 def transform_resource(self, resource):
     view = resource.to_petl()
     name = self.get("name")
     value = self.get("value")
     formula = self.get("formula")
     function = self.get("function")
     position = self.get("position")
     incremental = self.get("incremental")
     options = self.get("options")
     field = Field(name=name, **options)
     index = position - 1 if position else None
     if index is None:
         resource.schema.add_field(field)
     else:
         resource.schema.fields.insert(index, field)
     if incremental:
         resource.data = view.addrownumbers(field=name)
     else:
         if formula:
             function = lambda row: simpleeval.simple_eval(formula, names=row)
         value = value or function
         resource.data = view.addfield(name, value=value, index=index)
예제 #46
0
 def transform_resource(self, resource):
     table = resource.to_petl()
     descriptor = self.to_dict()
     descriptor.pop("code", None)
     name = descriptor.pop("name", None)
     value = descriptor.pop("value", None)
     formula = descriptor.pop("formula", None)
     function = descriptor.pop("function", None)
     position = descriptor.pop("position", None)
     incremental = descriptor.pop("incremental", None)
     field = Field(descriptor, name=name)
     index = position - 1 if position else None
     if index is None:
         resource.schema.add_field(field)
     else:
         resource.schema.fields.insert(index, field)
     if incremental:
         resource.data = table.addrownumbers(field=name)
     else:
         if formula:
             function = lambda row: simpleeval.simple_eval(formula, names=row)
         value = value or function
         resource.data = table.addfield(name, value=value, index=index)
예제 #47
0
    def get_line(self, values):
        'Return the move line for the keyword values'
        pool = Pool()
        Line = pool.get('account.move.line')
        Keyword = pool.get('account.move.template.keyword')

        line = Line()
        amount = simple_eval(decistmt(self.amount),
            functions={'Decimal': Decimal}, names=values)
        amount = self.move.company.currency.round(amount)
        if self.operation == 'debit':
            line.debit = amount
        else:
            line.credit = amount
        line.account = self.account
        if self.party:
            line.party = values.get(self.party)
        if self.description:
            line.description = self.description.format(
                **dict(Keyword.format_values(self.move, values)))
        line.tax_lines = [t.get_line(values) for t in self.taxes]

        return line
예제 #48
0
    def get_y(self, x):
        """Get the corresponding output of the evaluated equation string, given an input.

        Args:
            x (float): An input value.

        Returns:
            float: The corresponding output generated by the equation string.

        Raises:
            ValueError: If the equation string is invalid.

        """
        eq = self.equation
        for key, val in self.eq_kwargs.items():
            eq = eq.replace(key, str(val))
        if self.x_multi:
            x *= self.x_multi
        eq = eq.replace(self.x_key, str(x))
        try:
            return simpleeval.simple_eval(eq, functions=EVAL_FUNCS)
        except:
            raise ValueError('Error in the produced equation: {0}'.format(eq))
예제 #49
0
def preprocess_toml(text):
    evals = 0

    lines = []
    for line in text.splitlines():
        if '=' in line:
            parts = line.split('=')
            if len(parts) > 1:
                operation = parts[1].strip()
                # Don't eval if the line starts with < " > or < ' >
                if operation[0] not in ['"', "'"]:
                    try:
                        evals += 1
                        parts[1] = simple_eval(str(parts[1].strip()))
                        lines.append('='.join([str(p) for p in parts]))
                        continue
                    except NameNotDefined:
                        pass

        lines.append(line)

    # print('Simple evals:',evals)
    return '\n'.join(lines)
예제 #50
0
    def get_line(self, values):
        'Return the move line for the keyword values'
        pool = Pool()
        Line = pool.get('account.move.line')
        Keyword = pool.get('account.move.template.keyword')

        line = Line()
        amount = simple_eval(decistmt(self.amount),
            functions={'Decimal': Decimal}, names=values)
        amount = self.move.company.currency.round(amount)
        if self.operation == 'debit':
            line.debit = amount
        else:
            line.credit = amount
        line.account = self.account
        if self.party:
            line.party = values.get(self.party)
        if self.description:
            line.description = self.description.format(
                **dict(Keyword.format_values(self.move, values)))
        line.tax_lines = [t.get_line(values) for t in self.taxes]

        return line
예제 #51
0
def weig_user(x: float, text: str) -> float:
    """ 
    Takes in a string and evaluates it (safely) with the simpleeval
    model to allow users to define their own probability weighting functions
    """
    res = simple_eval(
        text,
        functions={
            # "print": print,
            "abs": abs,
            "sin": math.sin,
            "cos": math.cos,
            "tan": math.tan,
            "e": math.e,
            "exp": math.exp,
            "log": math.log,
            "log10": math.log10,
            "pi": math.pi,
            "sqrt": math.sqrt,
        },
        names={"x": x},
    )
    return res
예제 #52
0
    def calcStoreBagCell(self, model_id, row, col, storebag):
        # model rows and cols
        rs_formula = self.db.table('sm.sm_model_formula').query(
                columns = '$formula',
                where = '$sm_model__id = :model__id \
                    AND @sm_model_row__id.code = :row_code \
                    AND @sm_model_col__id.code = :col_code',
                model__id = model_id,
                row_code = row,
                col_code = col
                ).fetch()

        value = '#n/d'
        for record in rs_formula:
            f = record['formula']
            #print('formula: ', f)
            refs = self.parseFormulaCellReference(f)
            for c in refs:
                # references are in the form: [Rx.Cy]
                # need to strip the [ ]
                bagRef = c[1:-1]
                # get the cell value
                tmpval = storebag[bagRef]
                # substitute the value found
                f = f.replace(c, str(tmpval))
            #print('parsed formula:', f)
        
        try:
            value = simple_eval(f)
        except TypeError as error:
            #print('TypeError on value(f) for ', f)
            pass
        except Exception as exception:
            #print('General Error on value(f) for ', f)
            pass

        return value
예제 #53
0
def eval_expression(s: str, names: Dict = None) -> str:
    """
    Customizes the functions and names available in
    expression and evaluates an expression.
    """
    functions = DEFAULT_FUNCTIONS.copy()
    functions.update(unixtime=_unixtime,
                     datetime_format=_datetime_format,
                     starts_with=_starts_with,
                     ends_with=_ends_with,
                     start=_start,
                     end=_end,
                     timedelta_days=_timedelta_days,
                     timedelta_hours=_timedelta_hours,
                     timedelta_minutes=_timedelta_minutes,
                     timedelta_seconds=_timedelta_seconds)

    names_combined = DEFAULT_NAMES.copy()
    names_combined.update(now=datetime.datetime.now())

    if names:
        names_combined.update(names)

    return simple_eval(s, functions=functions, names=names_combined)
예제 #54
0
 def think(self,i):    
     # User input
     #i = entry.text
     #i = self.root.ids.entry.text 
         
     if i.lower() in ['break','end','quit']:
         exit()
     
     else:
             
         try:
             #case 0 : a Number entered
             try:
                 o = (w2n.word_to_num(i))
             except:
                 try:
                     #case 1 : Normal calculations (basic calculator)
                     '''Easy way was to use eval, but using eval has great risks as it could be used to potentially crack your system'''
                     o = simple_eval(i)
                     
                 except:
                     try:
                         # clean sentence
                         i = i.lower()
                         words = [k for k in word_tokenize(i) if k not in stop_words]
                         o = words
                         
                     except:
                         #raise Exception()
                         pass
         except: # if in case of errors
             o = 'x_Random error occured_x'
                 
         # Output
         self.ids.output.text = str(o)
         self.ids.entry.text = ''
예제 #55
0
 def test_default_functions(self):
     self.assertEqual(simple_eval('rand() < 1.0 and rand() > -0.01'), True)
     self.assertEqual(simple_eval('randint(200) < 200 and rand() > 0'), True)
	def convert(self, reading):
		return simple_eval(self.formula, names={"x": float(reading)})
예제 #57
0
 def test_basic_run(self):
     self.assertEqual(simple_eval('6*7'), 42)
예제 #58
0
 def __getExpressionValue__(self, dict, expression):
     expressionValue = simple_eval(expression, names=dict)
     return expressionValue
예제 #59
0
 def get_amount(self, **context):
     'Return amount (as Decimal)'
     context.setdefault('functions', {})['Decimal'] = Decimal
     return simple_eval(decistmt(self.formula), **context)
예제 #60
0
    def replaceElements( self, tree, visibilityCondition, profileVisibility, items, properties = {}, customitems = None ):
        if tree is None: return
        for elem in tree:
            # <tag skinshortcuts="visible" /> -> <tag condition="[condition]" />
            if "skinshortcuts" in elem.attrib:
                # Get index of the element
                index = list( tree ).index( elem )
                
                # Get existing attributes, text and tag
                attribs = []
                for singleAttrib in elem.attrib:
                    if singleAttrib == "skinshortcuts":
                        type = elem.attrib.get( "skinshortcuts" )
                    else:
                        attribs.append( ( singleAttrib, elem.attrib.get( singleAttrib ) ) )
                text = elem.text
                tag = elem.tag
                
                # Don't continue is type = visibility, and no visibilityCondition
                if type == "visibility" and visibilityCondition is None:
                    continue
                
                # Remove the existing element
                tree.remove( elem )
                
                # Make replacement element
                newElement = xmltree.Element( tag )
                if text is not None:
                    newElement.text = text
                for singleAttrib in attribs:
                    newElement.set( singleAttrib[ 0 ], singleAttrib[ 1 ] )
                    
                # Make replacements
                if type == "visibility" and visibilityCondition is not None:
                    newElement.set( "condition", visibilityCondition )
                    
                # Insert it
                tree.insert( index, newElement )
            
            # <tag>$skinshortcuts[var]</tag> -> <tag>[value]</tag>
            # <tag>$skinshortcuts[var]</tag> -> <tag><include>[includeName]</include></tag> (property = $INCLUDE[includeName])
            if elem.text is not None:
                while "$SKINSHORTCUTS[" in elem.text:
                    # Split the string into its composite parts
                    stringStart = elem.text.split( "$SKINSHORTCUTS[", 1 )
                    stringEnd = stringStart[ 1 ].split( "]", 1 )
                    # stringStart[ 0 ] = Any code before the $SKINSHORTCUTS property
                    # StringEnd[ 0 ] = The name of the $SKINSHORTCUTS property
                    # stringEnd[ 1 ] = Any code after the $SKINSHORTCUTS property

                    if stringEnd[ 0 ] in properties:
                        if properties[ stringEnd[ 0 ] ].startswith( "$INCLUDE[" ):
                            # Remove text property
                            elem.text = ""
                            # Add include element
                            includeElement = xmltree.SubElement( elem, "include" )
                            includeElement.text = properties[ stringEnd [ 0 ] ][ 9:-1 ]
                        else:
                            elem.text = stringStart[ 0 ] + properties[ stringEnd[ 0 ] ] + stringEnd[ 1 ]
                    else:
                        elem.text = stringStart[ 0 ] + stringEnd[ 1 ]
            
            # <tag attrib="$skinshortcuts[var]" /> -> <tag attrib="[value]" />
            for attrib in elem.attrib:
                value = elem.attrib.get( attrib )
                while "$SKINSHORTCUTS[" in elem.attrib.get( attrib ):
                    # Split the string into its composite parts
                    stringStart = elem.attrib.get( attrib ).split( "$SKINSHORTCUTS[", 1 )
                    stringEnd = stringStart[ 1 ].split( "]", 1 )

                    if stringEnd[ 0 ] in properties:
                        elem.set( attrib, stringStart[ 0 ] + properties[ stringEnd[ 0 ] ] + stringEnd[ 1 ] )
                    else:
                        elem.set( attrib, stringStart[ 0 ] + stringEnd[ 1 ] )

                if value.startswith( "$SKINSHORTCUTS[" ) and value[ 15:-1 ] in properties:
                    newValue = ""
                    if value[ 15:-1 ] in properties:
                        newValue = properties[ value[ 15:-1 ] ]
                    elem.set( attrib, newValue )

            # <tag>$PYTHON[var]</tag> -> <tag>[result]</tag>
            if elem.text is not None:
                while "$PYTHON[" in elem.text:
                    # Split the string into its composite parts
                    stringStart = elem.text.split( "$PYTHON[", 1 )
                    stringEnd = stringStart[ 1 ].split( "]", 1 )
                    # stringStart[ 0 ] = Any code before the $MATHS property
                    # StringEnd[ 0 ] = The maths to be performed
                    # stringEnd[ 1 ] = Any code after the $MATHS property

                    stringEnd[ 0 ] = simple_eval( "%s" %( stringEnd[ 0 ] ), names=properties )
                    
                    elem.text = stringStart[ 0 ] + str( stringEnd[ 0 ] ) + stringEnd[ 1 ]
            
            # <tag attrib="$PYTHON[var]" /> -> <tag attrib="[value]" />
            for attrib in elem.attrib:
                value = elem.attrib.get( attrib )
                while "$PYTHON[" in elem.attrib.get( attrib ):
                    # Split the string into its composite parts
                    stringStart = elem.attrib.get( attrib ).split( "$PYTHON[", 1 )
                    stringEnd = stringStart[ 1 ].split( "]", 1 )

                    stringEnd[ 0 ] = simple_eval( "%s" %( stringEnd[ 0 ] ), names=properties )

                    elem.set( attrib, stringStart[ 0 ] + str( stringEnd[ 0 ] ) + stringEnd[ 1 ] )
            
            # <skinshortcuts>visible</skinshortcuts> -> <visible>[condition]</visible>
            # <skinshortcuts>items</skinshortcuts> -> <item/><item/>...
            if elem.tag == "skinshortcuts":
                # Get index of the element
                index = list( tree ).index( elem )
                
                # Get the type of replacement
                type = elem.text
                
                # Don't continue is type = visibility, and no visibilityCondition
                if type == "visibility" and visibilityCondition is None:
                    continue
                
                # Remove the existing element
                tree.remove( elem )
                
                # Make replacements
                if type == "visibility" and visibilityCondition is not None:
                    # Create a new visible element
                    newelement = xmltree.Element( "visible" )
                    newelement.text = visibilityCondition
                    # Insert it
                    tree.insert( index, newelement )
                elif type == "items" and customitems is not None and elem.attrib.get( "insert" ):
                    for elem in self.buildSubmenuCustomItems( customitems, items.findall( "item" ), elem.attrib.get( "insert" ), properties ):
                        for child in elem:
                            tree.insert( index, child )
                elif type == "items":
                    # Firstly, go through and create an array of all items in reverse order, without
                    # their existing visible element, if it matches our visibilityCondition
                    newelements = []
                    if items == []:
                        break
                    for item in items.findall( "item" ):
                        newitem = self.copy_tree( item )

                        # Remove the existing visible elem from this
                        for visibility in newitem.findall( "visible" ):
                            if visibility.text != profileVisibility:
                                continue
                            newitem.remove( visibility )
                        
                        # Add a copy to the array
                        newelements.insert( 0, newitem )
                    if len( newelements ) != 0:
                        for elem in newelements:
                            # Insert them into the template
                            tree.insert( index, elem )

            else:
                # Iterate through tree
                self.replaceElements( elem, visibilityCondition, profileVisibility, items, properties, customitems = customitems )