def test_nor(self): for i in range(0, NUM_TESTS): a = random.randint(MIN_TEST, MAX_TEST) b = random.randint(MIN_TEST, MAX_TEST) correct = opfunc.inv(opfunc.or_(a, b)) mips_machine.registers["T1"] = a mips_machine.registers["T2"] = b assemble("nor $t3, $t1, $t2", 'mips', mips_machine) self.assertEqual(mips_machine.registers["T3"], correct)
def _intertwining_basis(self, a): r""" Return a basis for the set of homomorphisms between this representation and the same representation conjugated by [a,0; 0,1], where a is a generator of `(Z/p^uZ)^\times`. These are the "candidates" for extending the rep to a `\mathrm{GL}_2`-rep. Depending on the example, the hom-space has dimension either `1` or `2`. EXAMPLES:: sage: from sage.modular.local_comp.type_space import example_type_space sage: example_type_space(2)._intertwining_basis(2) [ [ 1 -2 1 0] [ 1 -1 0 1] [ 1 0 -1 1] [ 0 1 -2 1] ] sage: example_type_space(3)._intertwining_basis(2) [ [ 1 0] [0 1] [-1 -1], [1 0] ] """ if self.conductor() % 2: f = self.prime() ** (self.u() + 1) else: f = self.prime() ** self.u() # f is smallest p-power such that rho is trivial modulo f ainv = (~Zmod(f)(a)).lift() gens = self._group_gens() gensconj = [[x[0], ainv*x[1], a*x[2], x[3]] for x in gens] rgens = [self._rho_s(x) for x in gens] rgensinv = [operator.inv(_) for _ in rgens] rgensconj = [self._rho_s(x) for x in gensconj] rows = [] MS = rgens[0].parent() for m in MS.basis(): rows.append([]) for i in range(len(gens)): rows[-1] += (m - rgensinv[i] * m * rgensconj[i]).list() S = matrix(rows).left_kernel() return [MS(u.list()) for u in S.gens()]
def test_invert(self): self.failUnless(operator.inv(4) == -5)
def n_inv(a): """safe inv""" return o.inv(intify(a))
def inv(a): return operator.inv(a)
def test_sys_drawing(self): from IronPythonTest import DaysInt, DaysShort, DaysLong, DaysSByte, DaysByte, DaysUShort, DaysUInt, DaysULong from System.Drawing import Point, Size, PointF, SizeF, Rectangle, RectangleF x = Point() self.assertTrue(x == Point(0,0)) x = Size() self.assertTrue(x == Size(0,0)) x = PointF() self.assertTrue(x == PointF(0,0)) x = SizeF() self.assertTrue(x == SizeF(0,0)) x = Rectangle() self.assertTrue(x == Rectangle(0,0,0,0)) x = RectangleF() self.assertTrue(x == RectangleF(0,0,0,0)) p = Point(3,4) s = Size(2,9) q = p + s self.assertTrue(q == Point(5,13)) self.assertTrue(q != Point(13,5)) q = p - s self.assertTrue(q == Point(1,-5)) self.assertTrue(q != Point(0,4)) q += s self.assertTrue(q == Point(3,4)) self.assertTrue(q != Point(2,4)) q -= Size(1,2) self.assertTrue(q == Point(2,2)) self.assertTrue(q != Point(1)) t = s self.assertTrue(t == s) self.assertTrue(t != s - Size(1,0)) t += Size(3,1) self.assertTrue(t == Size(5,10)) self.assertTrue(t != Size(5,0)) t -= Size(2,8) self.assertTrue(t == Size(3,2)) self.assertTrue(t != Size(0,2)) t = s + Size(-1,-2) self.assertTrue(t == Size(1,7)) self.assertTrue(t != Size(1,5)) t = s - Size(1,2) self.assertTrue(t == Size(1,7)) self.assertTrue(t != Size(1,3)) def weekdays(enum): return enum.Mon|enum.Tue|enum.Wed|enum.Thu|enum.Fri def weekend(enum): return enum.Sat|enum.Sun def enum_helper(enum): days = [enum.Mon,enum.Tue,enum.Wed,enum.Thu,enum.Fri,enum.Sat,enum.Sun] x = enum.Mon|enum.Tue|enum.Wed|enum.Thu|enum.Fri|enum.Sat|enum.Sun y = enum.Mon for day in days: y |= day self.assertTrue(x == y) self.assertFalse(x != y) if x == y: # EqualRetBool b = True else : b = False self.assertTrue(b) self.assertTrue(x == weekdays(enum)|weekend(enum)) self.assertTrue(x == (weekdays(enum)^weekend(enum))) self.assertTrue((weekdays(enum)&weekend(enum)) == enum["None"]) self.assertTrue(weekdays(enum) == enum.Weekdays) self.assertTrue(weekend(enum) == enum.Weekend) self.assertTrue(weekdays(enum) != enum.Weekend) self.assertTrue(weekdays(enum) != weekend(enum)) for e in [DaysInt, DaysShort, DaysLong, DaysSByte, DaysByte, DaysUShort, DaysUInt, DaysULong]: enum_helper(e) for e in [DaysInt, DaysShort, DaysLong, DaysSByte]: z = operator.inv(e.Mon) self.assertEqual(type(z), e) self.assertEqual(z.ToString(), "-2") for (e, v) in [ (DaysByte,254), (DaysUShort,65534), (DaysUInt,4294967294), (DaysULong,18446744073709551614) ]: z = operator.inv(e.Mon) self.assertEqual(type(z), e) self.assertEqual(z.ToString(), str(v)) self.assertRaises(ValueError, lambda: DaysInt.Mon & DaysShort.Mon) self.assertRaises(ValueError, lambda: DaysInt.Mon | DaysShort.Mon) self.assertRaises(ValueError, lambda: DaysInt.Mon ^ DaysShort.Mon) self.assertRaises(ValueError, lambda: DaysInt.Mon & 1) self.assertRaises(ValueError, lambda: DaysInt.Mon | 1) self.assertRaises(ValueError, lambda: DaysInt.Mon ^ 1) def f(): if DaysInt.Mon == DaysShort.Mon: return True return False self.assertEqual(f(), False) self.assertTrue(not DaysInt.Mon == None) self.assertTrue(DaysInt.Mon != None)
def test_invert(self): #operator = self.module self.assertRaises(TypeError, operator.invert) self.assertRaises(TypeError, operator.invert, None) self.assertEqual(operator.inv(4), -5)
def test_invert(self): self.failUnlessRaises(TypeError, operator.invert) self.failUnlessRaises(TypeError, operator.invert, None) self.failUnless(operator.inv(4) == -5)
from emmett import sdict from emmett.orm.objects import Expression, Query, Set as DBSet from functools import reduce from typing import Any, Callable, Dict, Optional, Set, Union from ..typing import ModelType from .errors import QueryError from .validation import op_validators _query_operators = { '$and': operator.and_, '$or': operator.or_, '$not': lambda field, value: operator.inv(value), '$eq': operator.eq, '$neq': operator.ne, '$lt': operator.lt, '$gt': operator.gt, '$lte': operator.le, '$gte': operator.ge, '$in': lambda field, value: operator.methodcaller('belongs', value)(field), '$exists':
class Z3Context(Context): def __init__(self, *args, **kw): Context.__init__(self, *args, **kw) self.solver = z3.Solver() def __getitem__(self, key): if not isinstance(key, Sort) and key in self.storage: return self.storage[key] elif isinstance(key, Sort): if key.name in self.storage: return self.storage[key.name] val = self.new_from_sort(key) self.storage[key.name] = val return val else: raise ValueError("%s not found! %s. %s." %(key, type(key), self.storage)) def new_from_sort(self, key): if isinstance(key, Bool): key = key.name val = z3.Bool(key) return val elif isinstance(key, Int): key = key.name val = z3.Int(key) return val elif isinstance(key, String): key = key.name val = z3.String(key) return val elif isinstance(key, BitVec): name = key.name size = key.size val = z3.BitVec(name, size) return val raise TypeError("%s not supported!" %type(key)) def s_assert(self, expr): self.solver.assert_exprs(expr.cval(self)) def s_check(self): res = self.solver.check() return res def s_model(self): try: m = self.solver.model() return self.process_model(m) except z3.Z3Exception: return {} def s_push(self): self.solver.push() def s_pop(self): self.solver.pop() def s_reset(self): self.solver.reset() def solve(self, AST): outputs = [] self.s_reset() for node in AST: if isinstance(node, Sort): self.s_assert(node) elif isinstance(node, Let): self.s_assert(node.term) elif isinstance(node, Command): if node.cname == "push": self.s_push() elif node.cname == "pop": self.s_pop() elif node.cname == "check-sat": logger.info("\n-------") outputs.append(self.s_check()) logger.info("Check: %s" % outputs[-1]) elif node.cname == "get-model": outputs.append(self.s_model()) logger.info("Model: %s" % outputs[-1]) else: raise ValueError("Command %s not supported!" %node) return outputs def process_model(self, z3_model): m = {} for v in z3_model: m[v.name()] = self.get_py_value(z3_model.get_interp(v)) return m def get_py_value(self, assignment): if z3.is_ast(assignment): if z3.is_int_value(assignment): return assignment.as_long() if z3.is_bool(assignment): return z3.is_true(assignment) if z3.is_string_value(assignment): try: val = assignment.as_string()[1:-1] # remove quotes val = val.replace("\\x00", "") return str(val) # Z3 throws encoding errors. It can't decode its own solution.. # TODO find a better fix. except UnicodeDecodeError: val = assignment.as_ast() return repr(val) raise ValueError("Unsupported Z3 type! %s" % type(assignment)) return assignment BoolVal = lambda self, x : z3.BoolVal(x) StringVal = lambda self, x : z3.StringVal(x) IntVal = lambda self, x : z3.IntVal(x) BitVecVal = lambda self, val, size : z3.BitVecVal(val, size) And = lambda self, *x : z3.And(x) Or = lambda self, *x : z3.Or(x) Xor = lambda self, *x : reduce(xor, x) Implies = lambda self, x, y : z3.Implies(x, y) Distinct = lambda self, x, y : z3.Distinct(x, y) def Eq(self, x, y): # x = z3.String("x") # x == "test" #throws an error. This is a workaround for now. x = z3.StringVal(x) if isinstance(x,str) else x y = z3.StringVal(y) if isinstance(y,str) else y return eq(x,y) Not = lambda self, x : z3.Not(x) If = lambda self, *x : z3.If(*x) add = lambda self, *x : reduce(add, x) sub = lambda self, *x : reduce(sub, x) if len(x) > 1 else -x[0] mul = lambda self, *x : reduce(mul, x) lt = lambda self, *x : reduce(lt, x) le = lambda self, *x : reduce(le, x) gt = lambda self, *x : reduce(gt, x) ge = lambda self, *x : reduce(ge, x) concat = lambda self, *x : reduce(add, x) length = lambda self, x : z3.Length(x) contains = lambda self, x, y : z3.Contains(x, y) indexof = lambda self, x, y, z=0 : z3.IndexOf(x, y, z) extract = lambda self, x, y, z : z3.Extract(x, y, z) bvadd = add bvsub = sub bvmul = mul bvxor = Xor bvneg = lambda self, x : neg(x) bvnot = lambda self, x : inv(x) bvconcat = lambda self, *x : z3.Concat(*x) bvlshr = lambda self, x, y : z3.LShR(x, y) bvlshl = lambda self, x, y : z3.LShL(x, y) bvuge = lambda self, x, y : z3.UGE(x, y) bvurem = lambda self, x, y : z3.URem(x, y) # TODO Need to define all these with stuff in computation folder FPAbs = lambda self, *x : None FPNeg = lambda self, *x : None FPAdd = lambda self, *x : None FPSub = lambda self, *x : None FPMul = lambda self, *x : None FPDiv = lambda self, *x : None FPFMA = lambda self, *x : None FPRem = lambda self, *x : None FPSqrt = lambda self, *x : None FPRoundToIntegral = lambda self, *x : None FPMin = lambda self, *x : None FPMax = lambda self, *x : None FPLEQ = lambda self, *x : None FPLT = lambda self, *x : None FPGEQ = lambda self, *x : None FPGT = lambda self, *x : None FPEQ = lambda self, *x : None FPIsNormal = lambda self, *x : None FPIsSubNormal = lambda self, *x : None FPIsZero = lambda self, *x : None FPIsInfinite = lambda self, *x : None FPIsNan = lambda self, *x : None FPIsNegative = lambda self, *x : None FPIsPositive = lambda self, *x : None
print operator.mod(9,4) #精确除法 print operator.truediv(9.04,4) #绝对值 print operator.abs(-10) #取反 相当于 -a print operator.neg(-10) #取反 相当于 ~a #~a = (-a)-1 #~10 = -11 #~(-10) = 9 print operator.inv(10) print operator.inv(-10) print operator.invert(10) print operator.invert(-10) #乘方 同a**b print operator.pow(2,3) #向左移位 同<< 相当于乘以2的相应次方 print operator.lshift(3,2) #向右移位 同>> 相当于除以2的相应次方 取整 print operator.rshift(3,2) #按位与 即 a&b print operator.and_(1,8)
import operator
def test_invert(self): self.failUnlessRaises(TypeError, operator.invert) self.failUnlessRaises(TypeError, operator.invert, None) self.assertEqual(operator.inv(4), -5)
a = 1 print id(a) b = 1 print operator.is_(a, b) b = 2 print operator.is_(a, b) a = -1 print id(a) print operator.index(1) print operator.inv(8) print operator.lshift(4, 1) print operator.or_(2,4) print operator.pos(30) print operator.pow(2,8)
def test_invert(self): self.assertRaises(TypeError, operator.invert) self.assertRaises(TypeError, operator.invert, None) self.assertTrue(operator.inv(4) == -5)
def __invert__(self): return Vector([operator.inv(c) for c in self]) def __neg__ (self): return Vector([operator.neg(c) for c in self])
# ===----------------------------------------------------------------------=== _inv, _shift, _rotate = map(Symbol, ' ~ shift rotate'.split()) from operator import inv builtinEnvironment[_inv] = Procedure( params = Tuple([ (1, FractionCompatible), ]), defaults = Tuple(), ellipsis = False, environment = builtinEnvironment, body = lambda eval_,env:inv(env[1]), ) # ===----------------------------------------------------------------------=== _abs, _add, _sub, _div, _mul, _divmod, _pow = map(Symbol, 'abs + - / * divmod pow'.split()) from operator import add, sub, mul, truediv builtinEnvironment[_add] = Procedure( params = Tuple([ (1, FractionCompatible), (2, FractionCompatible), ]), defaults = Tuple(),