def check_validity(self, abs_scc): done = True tprint("Trying...{}".format(abs_scc)) for scc in abs_scc: if self.variables[scc[0]] == 0: pass elif self.variables[scc[0]] == operator.not_(scc[1]): # Opposites done = False break else: pass if not done: tprint("Trying opposite...") for scc in abs_scc: if self.variables[scc[0]] == 0: pass elif self.variables[scc[0]] == operator.not_( scc[1]): # Opposites idx = abs_scc.index(scc) scc[1] = operator.not_(scc[1]) abs_scc[idx] = scc else: done = False break if done: return abs_scc else: return False
def evaluate(parse_tree: BinaryTree): operates = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, 'and': operator.and_, 'or': operator.or_, 'not': operator.not_ } if parse_tree.left_child and parse_tree.right_child: print('LR:', parse_tree.left_child, parse_tree.right_child) fn = operates[parse_tree.key] if parse_tree.reverse: return operator.not_( fn(evaluate(parse_tree.left_child), evaluate(parse_tree.right_child))) return fn(evaluate(parse_tree.left_child), evaluate(parse_tree.right_child)) else: print(f'Returning {parse_tree.key}') if parse_tree.reverse: return operator.not_(parse_tree.key) return parse_tree.key
def random_graph(n, probability_threshold): graph = Graph(n) for v1 in range(0, n): for v2 in range(0, n): if v1 != v2 and random() < probability_threshold: if operator.not_(graph.vertex(v1).contains(v2)) and operator.not_(graph.vertex(v2).contains(v1)): graph.add_edge(v1, v2) return graph
def eval(self, env): if self.bin_op is None: if self.negated: return not_(self.left.eval(env)) return self.left.eval(env) else: evaluation = self.bin_op(self.left.eval(env), self.right.eval(env)) if self.negated: return not_(evaluation) return evaluation
def test_jbool_functions_fexprs(self): jl = JeevesLib x = jl.mkLabel('x') jl.restrict(x, lambda (a, _): a == 42) for lh in (True, False): for ll in (True, False): for rh in (True, False): for rl in (True, False): l = jl.mkSensitive(x, lh, ll) r = jl.mkSensitive(x, rh, rl) self.assertEquals(jl.concretize((42, 0), l and r), operator.and_(lh, rh)) self.assertEquals(jl.concretize((10, 0), l and r), operator.and_(ll, rl)) self.assertEquals(jl.concretize((42, 0), l or r), operator.or_(lh, rh)) self.assertEquals(jl.concretize((10, 0), l or r), operator.or_(ll, rl)) self.assertEquals(jl.concretize((42, 0), not l), operator.not_(lh)) self.assertEquals(jl.concretize((10, 0), not l), operator.not_(ll)) y = jl.mkLabel('y') jl.restrict(y, lambda (_, b): b == 42) for lh in (True, False): for ll in (True, False): for rh in (True, False): for rl in (True, False): l = jl.mkSensitive(x, lh, ll) r = jl.mkSensitive(y, rh, rl) self.assertEquals(jl.concretize((42, 0), l and r), operator.and_(lh, rl)) self.assertEquals(jl.concretize((10, 0), l and r), operator.and_(ll, rl)) self.assertEquals(jl.concretize((42, 42), l and r), operator.and_(lh, rh)) self.assertEquals(jl.concretize((10, 42), l and r), operator.and_(ll, rh)) self.assertEquals(jl.concretize((42, 0), l or r), operator.or_(lh, rl)) self.assertEquals(jl.concretize((10, 0), l or r), operator.or_(ll, rl)) self.assertEquals(jl.concretize((42, 42), l or r), operator.or_(lh, rh)) self.assertEquals(jl.concretize((10, 42), l or r), operator.or_(ll, rh))
def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True)
def mate_bin(parent1, parent2): for i in range(0,49): x=random.random(); if x>0.5: temp=parent1[i] parent1[i]=parent2[i] parent2[i]=temp m=random.random() if m<opt.mut_prob: #mut_prob is the probability of mutation to occur y=random.random(); if y>0.5: #to decide which parent to mutate parent1[i]=str(int(operator.not_(bool(parent1[i])))) else: parent2[i]=str(int(operator.not_(bool(parent2[i])))) return parent1, parent2
def evaluate(cond): # Method to evaluate the conditions if isinstance(cond,bool): return cond left, oper, right = cond if not model or not left in model.mgroup.fields: #check that the field exist return False oper = self.OPERAND_MAPPER.get(oper.lower(), oper) if oper == '=': res = operator.eq(model[left].get(model),right) elif oper == '!=': res = operator.ne(model[left].get(model),right) elif oper == '<': res = operator.lt(model[left].get(model),right) elif oper == '>': res = operator.gt(model[left].get(model),right) elif oper == '<=': res = operator.le(model[left].get(model),right) elif oper == '>=': res = operator.ge(model[left].get(model),right) elif oper == 'in': res = operator.contains(right, model[left].get(model)) elif oper == 'not in': res = operator.contains(right, model[left].get(model)) res = operator.not_(res) return res
def verify_arp_interface_exists(device, expected_interface, invert=False, max_time=60, check_interval=10): """Verify interface exists in arp table Args: device (obj): Device object expected_interface (str): Interface to check for invert (bool, optional): Inverts to ensure interface doesn't exist. Defaults to False. max_time (int, optional): Maximum timeout time. Defaults to 60. check_interval (int, optional): Check interval. Defaults to 10. """ op = operator.truth if invert: op = lambda val: operator.not_(operator.truth(val)) timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out = device.parse('show arp') except SchemaEmptyParserError as e: timeout.sleep() continue # "arp-table-information": { # "arp-entry-count": str, # "arp-table-entry": [ # { # "interface-name": str, if op(expected_interface in out.q.get_values('interface-name')): return True timeout.sleep() return False
def __depthfirstpathshelper(self, graph, vertex): self.visited[vertex] = True verticesTovisit = graph.vertexNeighbors(vertex) for vertexTovisit in verticesTovisit: if operator.not_(self.visited[vertexTovisit]): self.__depthfirstpathshelper(graph, vertexTovisit) self.edgeTo[vertexTovisit] = vertex
def main(): # Configs can be set in Configuration class directly or using helper utility config.load_kube_config() v1 = client.CoreV1Api() with open("run-my-nginx.yaml") as f: dep = yaml.safe_load(f) k8s_apps_v1 = client.AppsV1Api() resp = k8s_apps_v1.create_namespaced_deployment(body=dep, namespace="default") print("Deployment created. status='%s'" % resp.metadata.name) resting_time(10) print("Listing pods with their IPs:") # ret = v1.list_pod_for_all_namespaces(watch=False) ret = v1.list_namespaced_pod("default") for i in ret.items: print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name)) flag = True for x in range(10): print("****RUN***", x) scale_up_replicas(k8s_apps_v1, 30) resting_time(30) check_dup_ip(v1) scale_down_replicas(k8s_apps_v1, 1) resting_time(30) check_dup_ip(v1) restart_aws_node(k8s_apps_v1, flag) resting_time(30) flag = operator.not_(flag) restart_aws_node(k8s_apps_v1, flag) cleanup(k8s_apps_v1)
def range_fn(test): # test inside nrange? try: test = float(test) except: self.log.raiseException( "range_fn: can't convert test %s (type %s) to float" % (test, type(test))) start_res = True # default: -inf < test if start is not None: # start <= test start_res = operator.le(start, test) end_res = True # default: test < +inf if end is not None: # test <= end end_res = operator.le(test, end) tmp_res = operator.and_(start_res, end_res) if neg: tmp_res = operator.not_(tmp_res) self.log.debug( "range_fn: test %s start_res %s end_res %s result %s (neg %s)" % (test, start_res, end_res, tmp_res, neg)) return tmp_res
def evaluate(cond): # Method to evaluate the conditions if isinstance(cond, bool): return cond left, oper, right = cond if not model or not left in model.mgroup.fields: #check that the field exist return False oper = self.OPERAND_MAPPER.get(oper.lower(), oper) if oper == '=': res = operator.eq(model[left].get(model), right) elif oper == '!=': res = operator.ne(model[left].get(model), right) elif oper == '<': res = operator.lt(model[left].get(model), right) elif oper == '>': res = operator.gt(model[left].get(model), right) elif oper == '<=': res = operator.le(model[left].get(model), right) elif oper == '>=': res = operator.ge(model[left].get(model), right) elif oper == 'in': res = operator.contains(right, model[left].get(model)) elif oper == 'not in': res = operator.contains(right, model[left].get(model)) res = operator.not_(res) return res
def test_operator(): # stdlib import operator assert operator.truth(0) == SyFalse assert operator.truth(1) == SyTrue assert operator.not_(1) == SyFalse assert operator.not_(0) == SyTrue assert operator.contains([], 1) == SyFalse assert operator.contains([1], 1) == SyTrue assert operator.lt(0, 0) == SyFalse assert operator.lt(0, 1) == SyTrue assert operator.is_(SyTrue, SyTrue) == SyTrue assert operator.is_(SyTrue, SyFalse) == SyFalse assert operator.is_not(SyTrue, SyTrue) == SyFalse assert operator.is_not(SyTrue, SyFalse) == SyTrue
def noise_generator(self, bit): # model zakłóceń BSC # przypisz do new_bit negację bitu z prawdopodobieństwem self.noise # oraz właściwy bit z prawdopodobieństwem 1-self.noise new_bit = choices([not_(bit), bit], [self.noise, 1 - self.noise]) return int(new_bit[0])
def save(self, force_subindicator_update=False, *args, **kwargs): first_save = operator.not_(self.subindicators) if force_subindicator_update or first_save: logger.debug( f"Updating subindicators for indicator: {self.name} ({self.id})" ) self.subindicators = self.get_unique_subindicators() super().save(*args, **kwargs)
def visit_BoolOp(self, node): n = len(node.values) if n == 1: _internal_assert(isinstance(node.op, ast.Not), "Unary is supposed to be not!") return operator.not_(self.visit(node.values[0])) _internal_assert(isinstance(node.op, (ast.And, ast.Or)), "Binary is supposed to be and/or!") values = [self.visit(i) for i in node.values] return HybridParser._binop_maker[type(node.op)](*values)
def __ne__(self, other): inv = self.__eq__(other) try: result = operator.not_(inv) except ValueError: result = (1 - inv).astype(bool) pass return result
def verify_class_of_service_object_exists(device, interface, expected_object, invert=False, max_time=60, check_interval=10): """ Verifies class_of_service object exists Args: device (obj): Device object interface (str): Interface to check expected_object (str): Object name to check for invert (bool, optional): Whether to check if it doesn't exist or not. Defaults to False. max_time (int, optional): Maximum timeout time. Defaults to 60. check_interval (int, optional): Check interval. Defaults to 10. Returns: True/False """ op = operator.contains if invert: op = lambda lst, entry: operator.not_(operator.contains(lst, entry)) timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: out = device.parse( 'show class-of-service interface {interface}'.format( interface=interface)) except SchemaEmptyParserError: timeout.sleep() continue # Example dict # { # "cos-interface-information": { # "interface-map": { # "i-logical-map": { # "cos-objects": { # "cos-object-type": [ # str # ] # }, # }, # } # } # } object_types_ = out.q.get_values("cos-object-type") if not op(object_types_, expected_object): timeout.sleep() continue return True return False
def checkNoSolExist(no, obj, x=None, y=None, method=0): """ execute checking of non-existence region If interval-region does not have solution (No-solution), return True. If ruurn False, region has some solutions or unknown whether does. """ selectedMethod = selectMethod(obj, method) return op.not_(selectedMethod(no, obj, x, y))
def sibling(self): import operator return Stratify.objects.get( management_type=self.management_type, min_field=self.min_field, max_field=self.max_field, min_revenue=self.min_revenue, max_revenue=self.max_revenue, is_hire=operator.not_(self.is_hire), )
def visit_BoolOp(self, node): n = len(node.values) if n == 1: _internal_assert(isinstance(node.op, ast.Not), \ "Unary is supposed to be not!") return operator.not_(self.visit(node.values[0])) _internal_assert(isinstance(node.op, (ast.And, ast.Or)), \ "Binary is supposed to be and/or!") values = [self.visit(i) for i in node.values] return HybridParser._binop_maker[type(node.op)](*values)
def test_expected_not_result(self): with patch('sys.stdout', new_callable=StringIO) as stdout: test_value = 42 test_result = UnaryOperation("!", Number(test_value)).evaluate( self.scope) Print(test_result).evaluate(self.scope) if (not_(test_value)): self.assertNotEqual(int(stdout.getvalue()), 0) else: self.assertEqual(int(stdout.getvalue()), 0)
def train_VanillaAE(_run, _seed, _rnd, config: ConfigTopoAE, experiment_dir, experiment_root, device, num_threads, verbose): try: os.makedirs(experiment_dir) except: pass try: os.makedirs(experiment_root) except: pass if os.path.isfile(os.path.join(experiment_root, 'eval_metrics_all.csv')): pass else: df = pd.DataFrame(columns=COLS_DF_RESULT) df.to_csv(os.path.join(experiment_root, 'eval_metrics_all.csv')) # Sample data dataset = config.dataset X_train, y_train = dataset.sample(**config.sampling_kwargs, train=True) dataset_train = TensorDataset(torch.Tensor(X_train), torch.Tensor(y_train)) X_test, y_test = dataset.sample(**config.sampling_kwargs, train=False) dataset_test = TensorDataset(torch.Tensor(X_test), torch.Tensor(y_test)) torch.manual_seed(_seed) if device == 'cpu' and num_threads is not None: torch.set_num_threads(num_threads) # Initialize model model_class = config.model_class autoencoder = model_class(**config.model_kwargs) model = autoencoder model.to(device) # Train and evaluate model result = train(model=model, data_train=dataset_train, data_test=dataset_test, config=config, device=device, quiet=operator.not_(verbose), val_size=config.method_args['val_size'], _seed=_seed, _rnd=_rnd, _run=_run, rundir=experiment_dir) # Format experiment data df = pd.DataFrame.from_dict(result, orient='index').reset_index() df.columns = ['metric', 'value'] id_dict = config.create_id_dict() for key, value in id_dict.items(): df[key] = value df.set_index('uid') df = df[COLS_DF_RESULT] df.to_csv(os.path.join(experiment_root, 'eval_metrics_all.csv'), mode='a', header=False)
def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) self.assertIs(operator.isNumberType(None), False) self.assertIs(operator.isNumberType(0), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.isSequenceType(0), False) self.assertIs(operator.isSequenceType([]), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.isMappingType(1), False) self.assertIs(operator.isMappingType({}), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True)
def main(): a = -1 b = 5 print("a =", a) print("b =", b) print("not_(a) :", operator.not_(a)) print("truth(a) :", operator.truth(a)) print("is_(a, b) :", operator.is_(a, b)) print("is_not(a, b):", operator.is_not(a, b))
def operator_Boolean(): a = -1 b = 5 print('a = ', a) print('b = ', b) print() print('not_(a) :', operator.not_(a)) print('truth(a) :', operator.truth(a)) print('is_(a, b) :', operator.is_(a, b)) print('is_not(a, b) :', operator.is_not(a, b))
def collect(ast): if isinstance(ast[0], list): return ast.pop(0) negated = False while is_negation(ast[0]): ast.pop(0) negated = not_(negated) if is_variable(ast[0]): return Term(ast.pop(0), negated=negated) return negated
def check_make_tmp(cursor_in, cursor_out, t_name, func): sql_existance = f"SHOW TABLES LIKE '{t_name}'" cursor_out.execute(sql_existance) table_exists = op.truth(cursor_out.fetchall()) print(table_exists) if op.not_(table_exists): print(table_exists) try: func(cursor_in, cursor_out) except connector.Error as err: print(err)
def visit_BoolOp(self, node): n = len(node.values) if n == 1: _internal_assert(isinstance(node.op, ast.Not), \ "Unary is supposed to be not!") return operator.not_(self.visit(node.values[0])) elif n == 2: _internal_assert(isinstance(node.op, (ast.And, ast.Or)), \ "Binary is supposed to be and/or!") values = [self.visit(i) for i in node.values] return HybridParser._binop_maker[type(node.op)](*values) else: raise ValueError("This Bool Op is not supported yet!")
def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) self.assertIs(operator.isCallable(0), False) self.assertIs(operator.isCallable(len), True) self.assertIs(operator.isNumberType(None), False) self.assertIs(operator.isNumberType(0), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.isSequenceType(0), False) self.assertIs(operator.isSequenceType([]), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.isMappingType(1), False) self.assertIs(operator.isMappingType({}), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True)
def fn_not(function): """Reverts function return value. :rtype: function :Example: >>> not_all = fn_not(all) >>> not_all([True, False, True]) True """ return lambda x: not_(function(x))
def verify_log_exists(device, file_name, expected_log, max_time=60, check_interval=10, invert=False, match=None): """ Verify log exists Args: device('obj'): device to use file_name('str') : File name to check log expected_log ('str'): Expected log message max_time ('int'): Maximum time to keep checking check_interval ('int'): How often to check invert ('bool', 'optional'): Inverts to check if it doesn't exist Returns: Boolean Raises: N/A """ op = operator.truth if invert: op = lambda val: operator.not_(operator.truth(val)) timeout = Timeout(max_time, check_interval) # show commands: "show log {file_name}" while timeout.iterate(): try: if match: log_output = device.parse( 'show log {file_name} | match {match}'.format( file_name=file_name, match=match)) else: log_output = device.parse( 'show log {file_name}'.format(file_name=file_name)) except SchemaEmptyParserError: timeout.sleep() continue log_found = log_output.q.contains('.*{}.*'.format(expected_log), regex=True) if op(log_found): return True timeout.sleep() return False
def breathfirstsearch(self, graph, initvertex): # create a queue toVisit = deque() toVisit.append(initvertex) self.visited[initvertex] = True while toVisit: currentvertex = toVisit.popleft() adjcurrentvertex = graph.vertexNeighbors(currentvertex) for vertex in adjcurrentvertex: if operator.not_(self.visited[vertex]): # enqueue toVisit.append(vertex) self.visited[vertex] = True self.edgeTo[vertex] = currentvertex
def test_operator(self): import operator self.assertIs(operator.truth(0), False) self.assertIs(operator.truth(1), True) with test_support.check_py3k_warnings(): self.assertIs(operator.isCallable(0), False) self.assertIs(operator.isCallable(len), True) self.assertIs(operator.isNumberType(None), False) self.assertIs(operator.isNumberType(0), True) self.assertIs(operator.not_(1), False) self.assertIs(operator.not_(0), True) self.assertIs(operator.isSequenceType(0), False) self.assertIs(operator.isSequenceType([]), True) self.assertIs(operator.contains([], 1), False) self.assertIs(operator.contains([1], 1), True) self.assertIs(operator.isMappingType(1), False) self.assertIs(operator.isMappingType({}), True) self.assertIs(operator.lt(0, 0), False) self.assertIs(operator.lt(0, 1), True) self.assertIs(operator.is_(True, True), True) self.assertIs(operator.is_(True, False), False) self.assertIs(operator.is_not(True, True), False) self.assertIs(operator.is_not(True, False), True)
def test_jbool_functions_fexprs(self): jl = JeevesLib x = jl.mkLabel("x") jl.restrict(x, lambda (a, _): a == 42) for lh in (True, False): for ll in (True, False): for rh in (True, False): for rl in (True, False): l = jl.mkSensitive(x, lh, ll) r = jl.mkSensitive(x, rh, rl) self.assertEquals(jl.concretize((42, 0), l and r), operator.and_(lh, rh)) self.assertEquals(jl.concretize((10, 0), l and r), operator.and_(ll, rl)) self.assertEquals(jl.concretize((42, 0), l or r), operator.or_(lh, rh)) self.assertEquals(jl.concretize((10, 0), l or r), operator.or_(ll, rl)) self.assertEquals(jl.concretize((42, 0), not l), operator.not_(lh)) self.assertEquals(jl.concretize((10, 0), not l), operator.not_(ll)) y = jl.mkLabel("y") jl.restrict(y, lambda (_, b): b == 42) for lh in (True, False): for ll in (True, False): for rh in (True, False): for rl in (True, False): l = jl.mkSensitive(x, lh, ll) r = jl.mkSensitive(y, rh, rl) self.assertEquals(jl.concretize((42, 0), l and r), operator.and_(lh, rl)) self.assertEquals(jl.concretize((10, 0), l and r), operator.and_(ll, rl)) self.assertEquals(jl.concretize((42, 42), l and r), operator.and_(lh, rh)) self.assertEquals(jl.concretize((10, 42), l and r), operator.and_(ll, rh)) self.assertEquals(jl.concretize((42, 0), l or r), operator.or_(lh, rl)) self.assertEquals(jl.concretize((10, 0), l or r), operator.or_(ll, rl)) self.assertEquals(jl.concretize((42, 42), l or r), operator.or_(lh, rh)) self.assertEquals(jl.concretize((10, 42), l or r), operator.or_(ll, rh))
def unary_exp(tokens): assert len(tokens) if tokens[0] == "-": tokens.pop(0) value = value_exp(tokens) return lambda row, ctx: operator.neg(value(row, ctx)) elif tokens[0] == "not": tokens.pop(0) value = value_exp(tokens) return lambda row, ctx: operator.not_(value(row, ctx)) elif tokens[0] == "+": tokens.pop(0) return value_exp(tokens)
def keyboard(self, key): if self.jetson.userid == 0: swap_enable = self.jetson.swap.enable # Clear cache script if key == ord('c'): self.jetson.swap.clearCache() if key == ord('h'): # Change status swap self.jetson.swap.enable = operator.not_(swap_enable) # Enable nvpmodel control if not swap_enable: if key == ord('+'): self.jetson.swap.increase() elif key == ord('-'): self.jetson.swap.decrease()
def __init__(self): self.version = None self.options = None self.function_stack = [] # stack of functions called, from top-level to currently executing one # namespace includes variables and rules self.namespace = {} # Will be hash list of input files of whatever textual content self.namespace['report'] = OrderedDict() self.namespace['report']['title'] = "RCQC Quality Control Report" self.namespace['report']['tool_version'] = CODE_VERSION self.namespace['report']['job'] = {'status': 'ok'} self.namespace['report']['quality_control'] = {'status': 'ok'} self.namespace['sections'] = [] self.namespace['rule_index'] = {} # rule index based on location of store(_, location) field. 1 per. self.namespace['name_index'] = {} # index based on last (z) key of x.y.z namespace reference. self.namespace['files'] = [] self.namespace['file_names'] = {} self.namespace['iterator'] = {} # Provides the dictionary for each current iterator function evaluation (at call depth). self.namespace['report_html'] = '' self.input_file_paths = None self.ruleset_file_path = None self.output_json_file = None # Really core functions below require access to RCQC class variables. # Other functions can be added in rcqc_functions RCQCClassFnExtension and RCQCStaticFnExtension classes. self.functions = { '=': lambda location, value: self.storeNamespaceValue(value, location), 'store': self.storeNamespaceValue, 'store_array': self.storeNamespaceValueAsArray, 'if': self.fnIf, 'fail': self.fail, 'exit': self.exit, 'exists': lambda location: self.namespaceReadValue(location, True), '-': lambda x: operator.neg(x), 'not': lambda x: operator.not_(x), 'function': lambda x: self.applyRules(x) }
def range_fn(test): # test inside nrange? try: test = float(test) except ValueError: self.log.raiseException("range_fn: can't convert test %s (type %s) to float" % (test, type(test))) start_res = True # default: -inf < test if start is not None: # start <= test start_res = operator.le(start, test) end_res = True # default: test < +inf if end is not None: # test <= end end_res = operator.le(test, end) tmp_res = operator.and_(start_res, end_res) if neg: tmp_res = operator.not_(tmp_res) self.log.debug("range_fn: test %s start_res %s end_res %s result %s (neg %s)" % (test, start_res, end_res, tmp_res, neg)) return tmp_res
(2, IntegerCompatible), ]), defaults = Tuple(), ellipsis = False, environment = builtinEnvironment, body = lambda eval_,env:xor(env[1], env[2]), ) builtinEnvironment[_not] = Procedure( params = Tuple([ (1, FractionCompatible), ]), defaults = Tuple(), ellipsis = False, environment = builtinEnvironment, body = lambda eval_,env:not_(env[1]), ) # ===----------------------------------------------------------------------=== _inv, _shift, _rotate = map(Symbol, ' ~ shift rotate'.split()) from operator import inv builtinEnvironment[_inv] = Procedure( params = Tuple([ (1, FractionCompatible), ]), defaults = Tuple(), ellipsis = False,
def filter(self, *args, **kwargs): """ Instantiate a list of recordings from the 'replay that match the search terms given as `kwargs`. The replay uses an unusual, inflexible search mechanism, so this method marshals a sane filter set into a bizarro one. The queries are like a very simplified version of the Django QuerySet API. filtering against the following fields are supported: start=x :type(x) == datetime.datetime; match recordings commencing at `x` end=x :type(x) == datetime.datetime; match recordings ending at `x` uuid=x: type(x) == uuid.UUID; match recordings with the given UUID. id=x: type(x) == int; get the given integer id. room=x: type(x) == int; filter recordings of conferences in `room` (an entityID) tenant=x: type(x) == str; match recordinds made by the given tenant. displayname: type(x) == str; match the given username. resolution: type(x) == str; match the name of the resolution: 'CIF', 'HD' etc All fields above support less-than greater-than, in, not in, equality, inequality in any combination. e.g: >>> recordings = Replay('example.com', 'user', 'pass').filter( duration__lt=timedelta(hours=1), resolution__ni=['HD', 'QHD'], filesize__gte=1e9, start_time__gte=now() - timedelta(days=7), start_time__lte=now() - timedelta(days=2), tenant='mytenant' ) will filter for all standard-definition recordings made on 'mytenant' under a gigabyte in size, less than an hour in length made during a time-window five days long beginning last week. A single optional positional argument controls caching behaviour. e.g. >>> recordings = Replay('example.com', 'user', 'pass').filter( False, filesize__gte=1e9 ) ...results in the cache being disabled and will return fresh results for all recordings greater than a gigabyte in size. Bear in mind that the implementation does not handle short-circuit logic in the given arguments (this is impossible due the indeterminate order of keyword args - see PEP0468), which may adversely affect performance with a large number of filter predicates. """ # The replay can only search with queries against the username string # rather than a matching set of types and corresponding predicate # variables. This is totally broken behaviour so we get around this by # downloading a list of all recordings, and then filtering against the given # data client-side. cache = True if args: cache = args[0] all_records = self.all_records if cache else list(self._uncached_iter()) # At the moment we support the following search constraints filters = { 'start': _ReplayFilters.start, 'end': _ReplayFilters.end, 'uuid': _ReplayFilters.uuid, 'id': _ReplayFilters.id, 'room': _ReplayFilters.room, 'tenant': _ReplayFilters.tenant, 'display_name': _ReplayFilters.display_name, 'duration': _ReplayFilters.duration, 'resolution': _ReplayFilters.resolution, 'file_size': _ReplayFilters.file_size, 'framerate': _ReplayFilters.framerate, } operators = { 'lt': operator.lt, 'gt': operator.gt, 'ne': operator.ne, 'in': lambda x, y: operator.contains(y, x), 'ni': lambda x, y: operator.not_(operator.contains(y, x)), 'gte': operator.ge, 'lte': operator.le } # Encapsulate the lookup static method and the appropriate # value by matching kwargs with the correct function. Similar to zip() filters_with_args = [] matcher = re.compile('(%s)(%s)?$' % ( '|'.join(filters), '|'.join('__' + op for op in operators) )) for keyword in kwargs: match = matcher.match(keyword) if not match: raise ValueError("unsupported lookup %s" % keyword) field, op = match.groups() # As with django models, no double undescore suffix means the equality operator if op is None: op = operator.eq else: op = operators[op.lstrip('__')] logger.debug( "adding filter %r with operator %r and value %r", filters[field], op, kwargs[keyword] ) filters_with_args.append((filters[field], op, kwargs[keyword])) # This is our bunch of funcs which are dynamically generated so as to # emulate the ability for map() to pass multiple arguments to its callee # we have to use the extra layer if indirection via the # _closure_from_filterset() function because python references the variable # rather than captures the value of y at lambda # This must be a list, not a generator as we use it multiple times filter_funcs = [_closure_from_filterset(filterset) for filterset in filters_with_args] logger.debug("filter_funcs: %r", filter_funcs) # Now apply all the generated filters to each record in turn. # We're only interested in records that give True for all in {filter_funcs} return list(six.moves.filter( lambda record: all(_alt_map(record, filter_funcs)), all_records) )
def not_usecase(x): return operator.not_(x)
def manual_annotation(filelist, databasedir = None, annotationfile = 'annotation.yaml', newannotationfile = False, step = 1): ''' Manual slice classification from file list. >>> filelist = ['/home/mjirik/data/img1.dcm', './img2.png'] manual_anotation(filelist) ''' import dicom import os import operator import system # vytvoreni noveho souboru if newannotationfile | operator.not_(os.path.exists(annotationfile)): annotation = {} annotation ['data'] = {} else: #print 'Pridavam anotaci do souboru' annotation = system.obj_from_file(annotationfile) logger.info ('Adding annotation to file "' + annotationfile + '"') #print 'pocet souboru: ', len(filelist) # test jen na prvnim obrazku #filelist = [filelist[0]] # For step annotation #prev_retvalue = 'none' #prev_bodypartsind = 0 dm = None fileind = 0 while fileind < len(filelist): filepath = filelist[fileind] relfilepath = os.path.relpath(filepath, databasedir) #print '-------------------------------------------' # TODO je to děsně ukecaný dcmdata=dicom.read_file(filepath) #pdb.set_trace(); #logger.info('Modality: ' + dcmdata.Modality) #logger.info('PatientsName: ' + dcmdata.PatientsName) #logger.info('BodyPartExamined: '+ dcmdata.BodyPartExamined) #logger.info('SliceThickness: '+ str(dcmdata.SliceThickness)) #logger.info('PixelSpacing: '+ str(dcmdata.PixelSpacing)) # get data data = dcmdata.pixel_array if fileind % step == 0: dm = ButtonsInMatplotlib(data) logger.info( 'finished ('+str(fileind)+ '/'+ str(len(filelist))\ + ') ' + str(dm.retvalue)) #print 'finished ('+str(fileind)+ '/'+ str(len(filelist))\ # + ') ' + str(dm.retvalue) if dm.backrequest == 1: fileind = fileind -step dm.backcallback = 0 elif dm.exitrequest == 1: fileind = len(filelist) + step elif dm.skiprequest == 1: fileind = fileind + step else: fileind = fileind + step annotation['data'][relfilepath] = {'filepath':relfilepath, 'slicedescription': dm.retvalue, 'sliceclass':dm.bodypartsind} #pdb.set_trace(); #annotation={} #annotation['data'] = annotation_data annotation['info'] = {'classes': dm.bodyparts} system.obj_to_file(annotation, annotationfile)
print operator.eq("a","a") #判断值不等 同 != print operator.ne(1,"1") print operator.ne("a","a") #判断地址相等 同 is print operator.is_(1,"1") print operator.eq("a","a") #判断地址不相等 同 is not print operator.is_(1,"1") print operator.eq("a","a") #布尔值取反 同 not print operator.not_(True) print operator.not_(1==1) #判断是否为真 print operator.truth(True) print operator.truth(1==1) #大于等于 >= print operator.ge(5,5) print operator.ge(5,9) #大于 > print operator.gt(5,5) print operator.gt(5,0) #大于等于 <=
def not_(self): self.stack.append(int(not_(self.stack.pop_exceptionless())))
def execute_NOT(self): arg = self.stack.pop() self.stack.push(operator.not_(arg))
def not_(a): return operator.not_(a)
def _nin(field, value): return lambda obj: operator.not_(operator.contains(value, _x_f(obj, field)))
def op_not(x): return _op.not_(x) @cutype("(a, a) -> Bool")