def activity_stream_item(self, activity_type, revision, user_id): import ckan.model import ckan.logic assert activity_type in ("new", "changed"), (str(activity_type)) # Handle 'deleted' objects. # When the user marks a package as deleted this comes through here as # a 'changed' package activity. We detect this and change it to a # 'deleted' activity. if activity_type == 'changed' and self.state == u'deleted': if meta.Session.query(activity.Activity).filter_by( object_id=self.id, activity_type='deleted').all(): # A 'deleted' activity for this object has already been emitted # FIXME: What if the object was deleted and then activated # again? return None else: # Emit a 'deleted' activity for this object. activity_type = 'deleted' try: d = { 'package': dictization.table_dictize(self, context={'model': ckan.model}) } return activity.Activity(user_id, self.id, revision.id, "%s package" % activity_type, d) except ckan.logic.NotFound: # This happens if this package is being purged and therefore has no # current revision. # TODO: Purge all related activity stream items when a model object # is purged. return None
def apply(self, eutopia, time): if time == self.time: a = activity.Activity( self.name, aggregate_measures=eutopia.activities.aggregates, **self.activity) eutopia.activities.activities.append(a)
def post(self, *args, **kwargs): # incoming POST request print("\n[{}] Received POST Request from client...".format(datetime.now())) # (1) Decode the POST data -> a dictionary: json_data = self.request.body.decode('utf-8') # obtain POST body from request, decode from bytes -> Str post_body = json.loads(json_data) # convert JSON data -> dict # (2) Authenticate incoming message & generate a response header: auth_header = self.request.headers.get('Authorization', None) service_url = post_body.get("serviceUrl", None) channel_id = post_body.get("channelId", None) psid = post_body['from'].get('id', None) if 'from' in post_body else None if psid is not None: # turn on the sender action self.turnOnSenderAction(channel_id, psid) status = authenticator.authenticateIncomingMessage(auth_header, service_url, channel_id) # authenticate req while status == 000: # immature token time.sleep(0.05) # brief delay before attempting to decode token again status = authenticator.authenticateIncomingMessage(auth_header, service_url, channel_id) self.set_header("Content-type", "application/json") if status != 200: # authentication was UNSUCCESSFUL - terminate function print("Authorization failed") self.set_status(status, "Access Denied") # return status code return # terminate function here! # (3) If the request was successfully authenticated, init an <Activity> object & provide flow control: conversation = post_body['conversation']['id'] # cache the conversationID (identifies each UNIQUE user) print("\nConversation ID = {}".format(conversation)) position = db_handler.getPositionInFlow(conversation) # check current position in flow print("Current position in conversation = [{}]".format(position)) user = db_handler.getUsername(conversation) # get user to pass -> Activity current_activity = activity.Activity(db_handler, authenticator, post_body, position, user) # init activity db_handler.updateConversation(conversation, activity.UPDATED_POSITION, current_activity.getUserName())
def new_activity(): logging.info("Starting to add activities n' stuff") # activities.append(a) stop_input = "y" invalid_data = 'true' b = activity.Activity() while stop_input.lower().strip()[0] == 'y': a = activity.Activity() # while invalid_data == 'true': # invalid_data = 'false' # if not a.project: # invalid_data = 'true' a.project = raw_input("Project number?[{}]: ".format( b.project)) or b.project # if not a.category: # invalid_data = 'true' if not validate_project(a.project): raise InvalidProjectException( "%s is not a valid project, please enter one of the following\n: %s" % (a.project, backend.execute("projects"))) a.category = raw_input("Category number?[{}]: ".format( b.category)) or b.category # if not a.hours: # invalid_data = 'true' if not validate_category(a.category): raise InvalidCategoryException( "%s is not a valid category, please enter one of the following\n: %s" % (a.category, backend.execute("categories"))) a.hours = raw_input("Number of hours?[{}]: ".format( b.hours)) or b.hours # if not a.comment: # invalid_data = 'true' a.comment = raw_input("Comment?[{}]: ".format(b.comment)) or b.comment b = a print backend.execute(a.toString()) # Adding to file store = raw_input("Want to save activity to file? [y/N]") if store == "y".lower().strip()[0]: save_activity(a) # Loop stop_input = raw_input("Want to add another? [Y/n]: ") or "y" logging.info("add another? %s", stop_input)
def activity_stream_item(self, activity_type, revision, user_id): import ckan.model import ckan.logic assert activity_type in ("new", "changed"), (str(activity_type)) # Handle 'deleted' objects. # When the user marks a package as deleted this comes through here as # a 'changed' package activity. We detect this and change it to a # 'deleted' activity. if activity_type == 'changed' and self.state == u'deleted': if meta.Session.query(activity.Activity).filter_by( object_id=self.id, activity_type='deleted').all(): # A 'deleted' activity for this object has already been emitted # FIXME: What if the object was deleted and then activated # again? return None else: # Emit a 'deleted' activity for this object. activity_type = 'deleted' try: # We save the entire rendered package dict so we can support # viewing the past packages from the activity feed. dictized_package = ckan.logic.get_action('package_show')( { 'model': ckan.model, 'session': ckan.model.Session, 'for_view': False, # avoid ckanext-multilingual translating it 'ignore_auth': True }, { 'id': self.id, 'include_tracking': False }) except ckan.logic.NotFound: # This happens if this package is being purged and therefore has no # current revision. # TODO: Purge all related activity stream items when a model object # is purged. return None actor = meta.Session.query(ckan.model.User).get(user_id) return activity.Activity( user_id, self.id, revision.id, "%s package" % activity_type, { 'package': dictized_package, # We keep the acting user name around so that actions can be # properly displayed even if the user is deleted in the future. 'actor': actor.name if actor else None })
def __init__(self): self.pi = pigpio.pi() self.active = False # Heartbeat of main thread self.hearttime = 0 self.starttime = time.time() # Create Activity object which watches table status with vibration sensor self.activity = activity.Activity(self.pi, gpio=17, onVacant=self.vacant, onOccupied=self.occupied) # Create Goaldetect object which watches for goals using the laser sensors self.goaldetect = goaldetect.GoalDetect(self.pi, power=9, detect1=10, detect2=11, onGoal=self.goal) # Create dictionary to hold team info: scoreboards, buttons and current score self.team = {1: Bunch(), 2: Bunch()} # Create Team 1 scoreboard + 2 buttons self.team[1].scoreboard = teamscore.TeamScore(self.pi, clock=22, data=27, load=23) self.team[1].up = button.Button(pi=self.pi, gpio=25, callback=self.scoreCorrect, args=[1, 1]) self.team[1].down = button.Button(pi=self.pi, gpio=18, callback=self.scoreCorrect, args=[1, -1]) self.team[1].score = 0 self.team[2].scoreboard = teamscore.TeamScore(self.pi, clock=22, data=27, load=24) self.team[2].up = button.Button(pi=self.pi, gpio=7, callback=self.scoreCorrect, args=[2, 1]) self.team[2].down = button.Button(pi=self.pi, gpio=8, callback=self.scoreCorrect, args=[2, -1]) self.team[2].score = 0 # Make sure scoreboards use the same lock, since they share clock and data gpio pins self.team[2].scoreboard.setLock(self.team[1].scoreboard.getLock()) # Create Menu object # TO DO # Create external fileupdater object self.external = external.External(cbSetScore=self.setFromExternal) # Listen and catch signals to end program self.signalbreak = 0 signal.signal(signal.SIGTERM, self.sigterm) signal.signal(signal.SIGINT, self.sigterm)
def add_from_file(): file_act = read_from_file() if file_act.keys() > 0: logging.info("Pack de actividades encontrado papu") for i in file_act.keys(): a = activity.Activity() dic = file_act[i] for v in dic: for k in v: setattr(a, k, v[k]) print backend.execute(a.toString())
def _gen_activity_list(self, activity_dict): activities = [] if not activity_dict: for i in range(self.nactivity): act = activity.Activity(self.settings, self.time_ranges[i], self.user, self.app, 'unsupported') activities.append(act) self.n_packet += len(act.packet_list) return activities " The first activity should be 'user_login' " act = HttpSess.deep_dive_apps[self.app.name](self.settings, self.httpsess_id, self.time_ranges[0], self.user, self.app, 'user_login', activity_dict['user_login']) activities.append(act) self.n_packet += len(act.packet_list) new_activity_dict = {} for (k, v) in activity_dict.items(): if k == 'user_login': continue new_activity_dict[k] = v activity_key_list = random.sample(new_activity_dict.keys() * (self.nactivity - 1), self.nactivity - 1) for activity_key in activity_key_list: act = HttpSess.deep_dive_apps[self.app.name](self.settings, self.httpsess_id, self.time_ranges[activity_key_list.index(activity_key)], self.user, self.app, activity_key, activity_dict[activity_key]) activities.append(act) self.n_packet += len(act.packet_list) return activities
__author__ = 'chance' from bs4 import BeautifulSoup from selenium import webdriver import time import activity inst = activity.Activity()
def post(self, *args, **kwargs): # incoming POST request print("\n[{}] Received POST Request from client...".format( datetime.now())) # (1) Decode the POST data -> a dictionary: json_data = self.request.body.decode( 'utf-8') # obtain POST body from request, decode from bytes -> Str post_body = json.loads(json_data) # convert JSON data -> dict # (2) Authenticate incoming message & generate a response header: auth_header = self.request.headers.get('Authorization', None) service_url = post_body.get("serviceUrl", None) channel_id = post_body.get("channelId", None) psid = post_body['from'].get('id', None) if 'from' in post_body else None if psid is not None: # turn on the sender action self.turnOnSenderAction(channel_id, psid) status = authenticator.authenticateIncomingMessage( auth_header, service_url, channel_id) # authenticate req while status == 000: # immature token time.sleep( 0.05) # brief delay before attempting to decode token again status = authenticator.authenticateIncomingMessage( auth_header, service_url, channel_id) self.set_header("Content-type", "application/json") if status != 200: # authentication was UNSUCCESSFUL - terminate function print("Authorization failed") self.set_status(status, "Access Denied") # return status code return # terminate function here! # (3) If the request was successfully authenticated, init an <Activity> object & provide flow control: conversation = post_body['conversation'][ 'id'] # cache the conversationID (identifies each UNIQUE user) print("\nConversation ID = {}".format(conversation)) global CONVERSATIONS # call global dict to keep track of position/patient for each user if conversation not in CONVERSATIONS: # check if conversation has been initialized print("NEW conversation - initializing in CONVERSATIONS cache...") CONVERSATIONS[conversation] = { "position": 0, "patient": None } # initialize cache position = CONVERSATIONS[conversation].get( "position") # check current position in flow print("Current position in conversation = [{}]".format(position)) patient = CONVERSATIONS[conversation].get( "patient", None) # get patient object to pass -> Activity user = CONVERSATIONS[conversation].get( "user", None) # get user to pass -> Activity if (patient) and (post_body.get( "text", None) is not None): # patient exists AND incoming msg is TEXT print("Blocker Set? {}".format(patient.isBlocked(conversation))) if not patient.isBlocked( conversation ): # blocker is NOT set - pass activity through patient.setBlock( conversation ) # set blocker BEFORE initializing the new activity current_activity = activity.Activity(authenticator, post_body, position, user, patient) # init self.updateConversationsDictionary( conversation, activity.UPDATED_POSITION, current_activity.getPatient(), current_activity.getUserName()) else: # initialization flow current_activity = activity.Activity(authenticator, post_body, position, user, patient) # init Activity self.updateConversationsDictionary(conversation, activity.UPDATED_POSITION, current_activity.getPatient(), current_activity.getUserName())