Beispiel #1
0
def deploy_app():
    request_json = request.get_json()
    repository = request_json['repository']
    git_url = repository['url']
    topic = getTopic(git_url)
    publisher.publish(topic)
    return "sent-update"
Beispiel #2
0
    def test_publish_happy(self):
        """
        should be able to publish message with all params passed
        """
        expected_payload = {
            'Payload': 'eyJib2R5IjogeyJoZWxsbyI6ICJ3b3JsZCJ9fQ==',
            'Topic': 'test'
        }
        publisher.SWITCH_BASE_URL = 'http://test.com'
        responses.add(responses.POST,
                      f'{publisher.SWITCH_BASE_URL}/publish',
                      json={'sucess': 'thank you'},
                      status=200)

        publish(topic='test',
                author='test_author',
                options={'body': {
                    'hello': 'world'
                }})

        self.assertEqual(len(responses.calls), 1)
        self.assertEqual(json.loads(responses.calls[0].request.body),
                         expected_payload)
        decoded = jwt.decode(
            responses.calls[0].request.headers['Authorization'].split(
                'bearer ')[1],
            SWITCH_JWT_SECRET,
            algorithms='HS256')
Beispiel #3
0
def trystep(config):
  (n, vs, I, O) = config
  v = findn(vs, n)
  (n, c) = v.params
  if c.operator == END:
    return (TERMINATED, None)
  elif I == [] and (c.operator in (DOUNTIL, IFELSE)):
    return (WAITING, None)
  elif c.operator == DOONCE:
    (a, n2) = c.params
    doaction(a)
    return (STEP, (n2, vs, I, [a] + O))
  elif c.operator == DOUNTIL:
    (a, cnd, n2) = c.params
    b = checkcond(cnd)
    doaction(a)
    if b:
      return (STEP, (n2, vs, I, [a] + O))
    else:
      return (STEP, (n, vs, I, [a] + O))
  elif c.operator == IFELSE:
    (cnd, n2, n3) = c.params
    b = checkcond(cnd)
    if b:
      return (STEP, (n2, vs, I, O))
    else:
      return (STEP, (n3, vs, I, O))
  elif c.operator == GOTO:
    (n2,) = c.params
    return (STEP, (n2, vs, I, O))
  else:
    publisher.publish("Runtime Error: Unknown Content Operator?");
    raise Exception("Runtime Error: Unknown Content Operator?")
Beispiel #4
0
def trystep(config):
    (n, vs, I, O) = config
    v = findn(vs, n)
    (n, c) = v.params
    if c.operator == END:
        return (TERMINATED, None)
    elif I == [] and (c.operator in (DOUNTIL, IFELSE)):
        return (WAITING, None)
    elif c.operator == DOONCE:
        (a, n2) = c.params
        doaction(a)
        return (STEP, (n2, vs, I, [a] + O))
    elif c.operator == DOUNTIL:
        (a, cnd, n2) = c.params
        b = checkcond(cnd)
        doaction(a)
        if b:
            return (STEP, (n2, vs, I, [a] + O))
        else:
            return (STEP, (n, vs, I, [a] + O))
    elif c.operator == IFELSE:
        (cnd, n2, n3) = c.params
        b = checkcond(cnd)
        if b:
            return (STEP, (n2, vs, I, O))
        else:
            return (STEP, (n3, vs, I, O))
    elif c.operator == GOTO:
        (n2, ) = c.params
        return (STEP, (n2, vs, I, O))
    else:
        publisher.publish("Runtime Error: Unknown Content Operator?")
        raise Exception("Runtime Error: Unknown Content Operator?")
Beispiel #5
0
	def delay(self):
		args = []
		args.extend(self.args)
		kwargs = self.kwargs.copy()

		module = module_by_name(self.__module__)
		method = function_by_name(module, self.__name__)
		publish(message=pickle.dumps(Stone(method, *args, **kwargs)))
def post_to_service(metrics):
    for url, stats in metrics.items():
        data = {
            'storageGroupName': 'ping',
            'name': url + '-avg-resp-ms',
            'data': stats[0]
        }

        Producer.publish(data)
Beispiel #7
0
def compile_and_publish_requests(time_after):
    all_subscriptions = subscriptions.get_all()
    feed_space_map = compile_feed_space_map(all_subscriptions)
    for feed, space_list in feed_space_map.items():
        message = {
            'feed': feed,
            'spaces': space_list,
            'onlyFetchAfter': time_after,
        }
        message_bytes = str.encode(json.dumps(message))
        publisher.publish(message_bytes)
Beispiel #8
0
def doaction(action):
  # we currently only support moving and saying in this simulation
  if action.operator == MOVE:
    (distance, angular, speed, delta_y, rotation) = action.params
    print "Moving for distance %s at rotation %s with a speed of %s %s %s" \
	%(distance, angular, speed, delta_y, rotation)
    publisher.publish("Moving for distance %s at rotation %s with a speed of %s %s %s" \
	%(distance, angular, speed, delta_y, rotation))
    turtlebot.move(distance, angular, speed, delta_y, rotation)
  elif action.operator == SAY:
    (s,) = action.params
    turtlebot.say(s)
  elif action.operator == LOCATE:
    (x,y) = action.params
    publisher.publish ("Locating inital pose of robot to (%s, %s)" %(x,y))
    turtlebot.locate(x,y)
  elif action.operator == MOVETO:
    (x,y) = action.params
    publisher.publish ("Moving to pose of (%s, %s)" %(x,y))
    turtlebot.moveTo (x,y)
  elif action.operator == MOVEABS:
    (x,y,v) = action.params # x,y coordinates and linear velocity.
    print "Using move absolute!"
  elif action.operator == MOVEREL:
    (x,y,v) = action.params # x,y distance from current pos and linear velocity.
    print "Using move relative!"
  elif action.operator == TURNABS:
    (d,r) = action.params # direction and rotational velocity. D = South, North, East, West
    print "Using turn absolute!"
  elif action.operator == TURNREL:
    (d,r) = action.params # Degree from current orientation and rotational velocity.
    print "Using turn relative!"
  else:
    publisher.publish("Runtime Error: Unsupported action!");
    raise Exception("Runtime Error: Unsupported action!")
Beispiel #9
0
def doaction(action):
    # we currently only support moving and saying in this simulation
    if action.operator == MOVE:
        (distance, angular, speed, delta_y, rotation) = action.params
        print "Moving for distance %s at rotation %s with a speed of %s %s %s" \
     %(distance, angular, speed, delta_y, rotation)
        publisher.publish("Moving for distance %s at rotation %s with a speed of %s %s %s" \
     %(distance, angular, speed, delta_y, rotation))
        turtlebot.move(distance, angular, speed, delta_y, rotation)
    elif action.operator == SAY:
        (s, ) = action.params
        turtlebot.say(s)
    else:
        publisher.publish("Runtime Error: Unsupported action!")
        raise Exception("Runtime Error: Unsupported action!")
    def __init__(self, rss_url=None):
        self.cache_file_downloaded = False
        self.rss_url = rss_url
        self.key = safe_filename(self.rss_url)
        self.rss_folder = os.path.join(STORAGE_DIR, self.key)
        self.ipns_file = os.path.join(STORAGE_DIR, "%s.pns" % self.key)
        self.replacements = []
        self.cache_file = construct_cache_file_name(self.rss_url,
                                                    subdir="%s.orig" %
                                                    self.key)

        self.text = ''
        self.load_text()

        self.feed = None
        self.parent_hash = ""
        self.ipns_hash = ""

        if os.path.exists(self.ipns_file):
            self.ipns_hash = open(self.ipns_file, 'r').read()
        # self.cache_file = download(self.rss_url, subdir="%s.orig" % self.key)

        if not os.path.exists(self.rss_folder):
            os.makedirs(self.rss_folder)
        dirname = os.path.dirname(self.cache_file)
        basename = os.path.basename(self.cache_file)
        final_filename = "%s.final.xml" % basename
        self.final_file = os.path.join(self.rss_folder, final_filename)
        self.pub_key, self.test_pub_key = publish(self.cache_file)
        log.debug("Initialized rss_url:%s" % rss_url)
 def process_image(self):
     try:
         log.debug("feed.feed.image:%s" % self.feed.feed.image)
         self.image = self.feed.feed.image
         subdir = safe_filename(self.rss_url)
         self.image_cache_file = download(self.image.href,
                                          TTL=(60 * 60 * 24),
                                          subdir=subdir)
         if not self.image_cache_file:
             return
         dirname = os.path.dirname(self.image_cache_file)
         basename = os.path.basename(self.image_cache_file)
         folder_basename = os.path.basename(dirname)
         pub_key, test_pub_key = publish(self.image_cache_file)
         hashes = self.full_publish_folder(dirname)
         parent_hash = ""
         for name, h in hashes:
             if name == folder_basename:
                 log.debug("--------------")
             log.debug("hash:%s" % h)
             log.debug("name:%s" % name)
             if name == folder_basename:
                 parent_hash = deepcopy(h)
                 log.debug("--------------")
         enclosure_replacement = os.path.join(parent_hash, basename)
         log.debug("parent_hash:%s" % parent_hash)
         log.debug("basename:%s" % basename)
         log.debug("image enclosure_replacement:%s" % enclosure_replacement)
         self.replacements.append(
             (enclosure.href, enclosure_replacement, pub_key, test_pub_key))
     except:
         pass
Beispiel #12
0
def eval(ast):
    (v, vs) = ast.params
    (n, c) = v.params
    config = (n, [v] + vs, [True], [])
    while True:
        (status, config2) = trystep(config)
        if status == WAITING:
            print "Robot is waiting for input! But this shouldn't happen in this simulation! What's going on?"
            break
        elif status == TERMINATED:
            print "Finished!"
            publisher.publish("Finished!")
            break
        else:
            config = config2
    (_, _, _, O) = config
    print "End output: ",
    print O
    return
Beispiel #13
0
def eval(ast):
  (v, vs) = ast.params
  (n, c) = v.params
  config = (n, [v]+vs, [True], [])
  while True:
    (status, config2) = trystep(config)
    if status == WAITING:
      print "Robot is waiting for input! But this shouldn't happen in this simulation! What's going on?"
      break
    elif status == TERMINATED:
      print "Finished!"
      publisher.publish("Finished!");
      break
    else:
      config = config2
  (_, _, _, O) = config
  print "End output: ",
  print O
  return
Beispiel #14
0
	def consume(self, message):
		message_loaded = pickle.loads(message)
		stone = message_loaded
		if stone.eta <= now():
			publish(message, queue=self.worker_queue)
			self.logger.info("scheduled %s task execution" % stone.name)
			stone.move_next()
			#print "next execution: %s" % stone.eta
			publish(pickle.dumps(stone), queue=self.internal_queue)
		else:
			#print "%s eta %s" % (stone.name, stone.eta)
			publish(message, queue=self.internal_queue)
		time.sleep(SLEEP)
Beispiel #15
0
def doaction(action):
    # we currently only support moving and saying in this simulation
    if action.operator == MOVE:
        (distance, angular, speed, delta_y, rotation) = action.params
        print "Moving for distance %s at rotation %s with a speed of %s %s %s" \
     %(distance, angular, speed, delta_y, rotation)
        publisher.publish("Moving for distance %s at rotation %s with a speed of %s %s %s" \
     %(distance, angular, speed, delta_y, rotation))
        turtlebot.move(distance, angular, speed, delta_y, rotation)
    elif action.operator == SAY:
        (s, ) = action.params
        turtlebot.say(s)
    elif action.operator == LOCATE:
        (x, y) = action.params
        publisher.publish("Locating inital pose of robot to (%s, %s)" % (x, y))
        turtlebot.locate(x, y)
    elif action.operator == MOVETO:
        (x, y) = action.params
        publisher.publish("Moving to pose of (%s, %s)" % (x, y))
        turtlebot.moveTo(x, y)
    elif action.operator == MOVEABS:
        (x, y, v) = action.params  # x,y coordinates and linear velocity.
        print "Using move absolute!"
    elif action.operator == MOVEREL:
        (
            x, y, v
        ) = action.params  # x,y distance from current pos and linear velocity.
        print "Using move relative!"
    elif action.operator == TURNABS:
        (
            d, r
        ) = action.params  # direction and rotational velocity. D = South, North, East, West
        print "Using turn absolute!"
    elif action.operator == TURNREL:
        (
            d, r
        ) = action.params  # Degree from current orientation and rotational velocity.
        print "Using turn relative!"
    else:
        publisher.publish("Runtime Error: Unsupported action!")
        raise Exception("Runtime Error: Unsupported action!")
    def process_enclosures(self):
        for entry in self.feed['entries']:
            log.debug("entry:%s" % pformat(entry))
            subdir = safe_filename(self.rss_url)
            published_parsed = entry.get("published_parsed")
            if published_parsed:
                # 'published_parsed': time.struct_time(tm_year=2009, tm_mon=7, tm_mday=30, tm_hour=10, tm_min=52, tm_sec=31, tm_wday=3, tm_yday=211, tm_isdst=0),
                pub_subdir = time.strftime("%Y/%m-%b/%Y-%m-%d %a",
                                           published_parsed)
                subdir = os.path.join(subdir, pub_subdir)

            for enclosure in entry['enclosures']:
                log.debug("enclosure:%s" % enclosure)
                enclosure_cache_file = download(enclosure.href,
                                                False,
                                                subdir=subdir)
                if not enclosure_cache_file:
                    continue
                log.debug("enclosure_cache_file:%s" % enclosure_cache_file)
                pub_key, test_pub_key = publish(enclosure_cache_file)
                if not pub_key or not test_pub_key:
                    continue
                dirname = os.path.dirname(enclosure_cache_file)
                basename = os.path.basename(enclosure_cache_file)
                folder_basename = os.path.basename(dirname)
                hashes = self.full_publish_folder(dirname)
                parent_hash = ""
                for name, h in hashes:
                    if name == folder_basename:
                        log.debug("--------------")
                    log.debug("hash:%s" % h)
                    log.debug("name:%s" % name)
                    if name == folder_basename:
                        parent_hash = deepcopy(h)
                        log.debug("--------------")
                enclosure_replacement = os.path.join(parent_hash, basename)
                log.debug("parent_hash:%s" % parent_hash)
                log.debug("basename:%s" % basename)
                log.debug("enclosure_replacement:%s" % enclosure_replacement)

                self.replacements.append(
                    (enclosure.href, enclosure_replacement, pub_key,
                     test_pub_key))
Beispiel #17
0
	def delay(self):
		module = module_by_name(self.__module__)
		method = function_by_name(module, self.__name__)
		publish(message=pickle.dumps(PeriodicStone(method, self.every)), queue=SISYPHUS_SCHEDULER_QUEUE_NAME)
Beispiel #18
0
    #gesture detection


    #upward lift
    #Upwards definition is orientation (roll= 0,pitch= 0,yaw=Any value) within a certain threshold, and then Z acceleration change by a certain amt.
    #Note Gyro Has drift

    if ACCz > threshold_accel_z:
        if upwards_cycle_count <= 5:
            upwards_cycle_count = upwards_cycle_count + 1
            va1 = val1 + ACCz/1000
        else:
            upwards_cycle_count = 0
            notification_count = notification_count + 1
            publisher.publish(client, "Sudden Flip Detected!!")
            #print("Upwards Lift Detected: " +str(ACCz/1000))
        if notification_count % 8 ==0:
            notification_count = 1
            notification.notify("NightLight Detect: Danger", "Sudden Flip Detected!")
    else:
        upwards_cycle_count = 0

    #if ACCy < threshold_accel_y :
   #     if forwards_cycle_count <= forwards_cycle_cap:
     #       forwards_cycle_count = forwards_cycle_count + 1
     #   else:
     #       forwards_cycle_count = 0
            #publisher.publish(client,"Forwards Lift Detected: " +str(ACCz/1000)
            #print("Forward Push Detected: " +str(ACCx/1000))
  #  else:
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 13 10:17:50 2015

@author: jmmauricio
"""

import sys, os

sys.path.append(os.path.join('..', 'pypstools'))

import publisher

pub = publisher.publish()

#figures,h_tests = pub.publisher('/home/jmmauricio/Documents/public/jmmauricio6/RESEARCH/benches/ieee_12_generic/doc/source/pvsync/ieee12g_pvsync_30/bus_fault/pub_ieee12g_30_bus_fault.yaml')
#figures,h_tests = pub.publisher('/home/jmmauricio/Documents/public/jmmauricio6/RESEARCH/benches/ieee_12_generic/doc/source/pvsync/ieee12g_pvsync_50/bus_fault/pub_ieee12g_50_bus_fault.yaml')

#figures,h_tests = pub.publisher('/home/jmmauricio/Documents/public/jmmauricio6/RESEARCH/benches/ieee_12_generic/doc/source/pvsync/ieee12g_pvsync_10/gen_trip/pub_ieee12g_10_gen_trip.yaml')
#figures,h_tests = pub.publisher('/home/jmmauricio/Documents/public/jmmauricio6/RESEARCH/benches/ieee_12_generic/doc/source/pvsync/ieee12g_pvsync_30/gen_trip/pub_ieee12g_30_gen_trip.yaml')
#figures,h_tests = pub.publisher('/home/jmmauricio/Documents/public/jmmauricio6/RESEARCH/benches/ieee_12_generic/doc/source/pvsync/ieee12g_pvsync_50/gen_trip/pub_ieee12g_50_gen_trip.yaml')

#figures,h_tests = pub.publisher('/home/jmmauricio/Documents/public/jmmauricio6/RESEARCH/benches/ieee_12_generic/doc/source/pvsync/ieee12g_pvsync_10/load_trip/pub_ieee12g_10_load_trip.yaml')

# plots ok
#figures,h_tests = pub.publisher('/home/jmmauricio/Documents/public/jmmauricio6/RESEARCH/benches/ieee_12_generic/doc/source/pvsync/ieee12g_pvsync_10/load_trip/pub_ieee12g_10_load_trip.yaml')
#figures,h_tests = pub.publisher('/home/jmmauricio/Documents/public/jmmauricio6/RESEARCH/benches/ieee_12_generic/doc/source/pvsync/ieee12g_pvsync_10/gen_trip/pub_ieee12g_10_gen_trip.yaml')
#figures,h_tests = pub.publisher('/home/jmmauricio/Documents/public/jmmauricio6/RESEARCH/benches/ieee_12_generic/doc/source/pvsync/ieee12g_pvsync_10/bus_fault/pub_ieee12g_10_bus_fault.yaml')
figures, h_tests = pub.publisher(
    '/home/jmmauricio/Documents/public/jmmauricio6/RESEARCH/benches/ieee_12_generic/doc/source/pvsync/ieee12g_pvsync_10/line_trip/pub_ieee12g_10_line_trip.yaml'
)
Beispiel #20
0
def publishLog(logData: LogModel):
    publisher.publish(logData.json())
    return {'message': 'log data sent'}
Beispiel #21
0
import dynamics
import publisher

import sys

lexer = lex.lex(module=lexerIG)
parser = yacc.yacc(module=parserIG)

if __name__ == "__main__":
  if len(sys.argv) != 2:
    print "Use: main.py <IG program>"
    exit(1)
  # Initializes node if not already initialized.
  publisher.initialize()
  # Publishes started message.
  publisher.publish("Starting")
  try:
    igfile = open(sys.argv[1], "r")
    igcode = igfile.read()
  except Exception as e:
    print e
    print "Could not open file for reading!"
    publisher.publish("Could not open file for reading!")
    exit(1)
  
  publisher.publish("Parsing and validating instructions")
  ast = parser.parse(igcode)
  assert(statics.valid(ast))
  publisher.publish("Running the instruction graph")
  dynamics.eval(ast)
  igfile.close()
Beispiel #22
0
def p_error(t):
  print t
  print "Found syntax error in input!"
  publisher.publish("Found syntax error in input!")
  raise Exception("Parser Error")
Beispiel #23
0
	def publish(self):
		import publisher 
		publisher.publish(job)
Beispiel #24
0
    values = {}
    co2_seen = 0
    temperature_seen = 0

    while True:
        data = list(ord(e) for e in fp.read(8))
        decrypted = decrypt(key, data)
        if decrypted[4] != 0x0d or (sum(decrypted[:3]) & 0xff) != decrypted[3]:
            print(hd(data), " => ", hd(decrypted),  "Checksum error")
        else:
            op = decrypted[0]
            val = decrypted[1] << 8 | decrypted[2]
            values[op] = val

            if (0x50 in values) and (0x42 in values):
                co2 = values[0x50]
                temperature = round(values[0x42]/16.0-273.15, 1)

                if (co2 > 5000 or co2 < 0 or (co2_seen == co2 and temperature_seen == temperature)):
                    continue

                co2_seen = co2
                temperature_seen = temperature
                time = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')

                try:
                    status_code = publisher.publish(time, temperature, co2, publish_server_url)
                    print("[%s] %ippm, %3.1fc, /%s" % (time, co2, temperature, status_code))
                except Exception as e:
                    print("[%s] %ippm, %3.1fc, /%s" % (time, co2, temperature, str(e)))
                    
Beispiel #25
0
def publish_well(uwi):
    topic = request.get_json()['topic']
    return publisher.publish(uwi, topic)
Beispiel #26
0
from reader import read
from calculate import calculate_scores, calculate_total_score
from publisher import publish
from pprint import pprint

if __name__ == "__main__":
    results = dict()
    for month in range(1, 2): # months from 1 to 12 (jan-dec)
        players = read(month)
        results[month] = calculate_scores(players)
        import ipdb; ipdb.set_trace()

    total_results = calculate_total_score(results)
    publish(total_results, results)
def p_error(t):
    print t
    print "Found syntax error in input!"
    publisher.publish("Found syntax error in input!")
    raise Exception("Parser Error")
Beispiel #28
0
import dynamics
import publisher

import sys

lexer = lex.lex(module=lexerIG)
parser = yacc.yacc(module=parserIG)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Use: main.py <IG program>"
        exit(1)
    # Initializes node if not already initialized.
    publisher.initialize()
    # Publishes started message.
    publisher.publish("Starting")
    try:
        igfile = open(sys.argv[1], "r")
        igcode = igfile.read()
    except Exception as e:
        print e
        print "Could not open file for reading!"
        publisher.publish("Could not open file for reading!")
        exit(1)

    publisher.publish("Parsing and validating instructions")
    ast = parser.parse(igcode)
    assert (statics.valid(ast))
    publisher.publish("Running the instruction graph")
    dynamics.eval(ast)
    igfile.close()