def __init__(self, width, height): self.width = width self.height = height unit_w = self.width / 10 unit_h = self.height / 10 offset = self.width / 16 self.rabbits = [ Rabbit(unit_w - offset, unit_h * 6, unit_h * 6, unit_h * 4.5, width, height), Rabbit((unit_w * 2.8) - offset, unit_h * 7, unit_h * 7, unit_h * 5.5, width, height), Rabbit((unit_w * 5) - offset, unit_h * 6, unit_h * 6, unit_h * 4.5, width, height), Rabbit((unit_w * 6.8) - offset, unit_h * 7, unit_h * 7, unit_h * 5.5, width, height), Rabbit((unit_w * 8.5) - offset, unit_h * 6, unit_h * 6, unit_h * 4.5, width, height) ] self.score_objects = [] self.score = 0 self.timer = 0 self.GAME_LENGTH = 60 self.start_time = 0 self.penalise_error = True
def __init__(self, srn_sz: (float, float), clock: pygame.time.Clock, screen: pygame.Surface): """ Initializes the World Args: srn_sz ( (float, float) ): Screen size clock (pygame.time.Clock): pygame Clock screen (pygame.Surface): pygame Screen """ self.running = True self._clock = clock self.screen = screen self.runtime = 0 self.runtime_checkpoint = 0 self.size = srn_sz self.rabbits = [] self.wolves = [] self.food = [] for _ in range(20): self.rabbits.append(Rabbit(self, self._random_pos(), 2.5)) for _ in range(6): self.wolves.append(Wolf(self, self._random_pos(), 3.0)) for _ in range(80): self.food.append(Food(self, self._random_pos())) self._update_screen()
def update(self): self.ticks += 1 if self.ticks % 10 == 0: self.plants[Species.Carrot].append( Food(random.uniform(50, self.width - 50), random.uniform(50, self.height - 50))) for spec in self.animals.keys(): for animal in self.animals[spec]: animal.update(self) if animal.state == "dead": self.animals[spec].remove(animal) elif animal.state == "reproduced": if animal._species == Species.Rabbit: baby = Rabbit(animal.coord.x, animal.coord.y) baby.genes = Genes.combineGenes( animal.genes, animal.genes) self.animals[spec].append(baby) elif animal._species == Species.Fox: self.animals[spec].append( Fox(animal.coord.x, animal.coord.y)) for spec in self.plants.keys(): for plant in self.plants[spec]: if not plant.isAvailable(): self.plants[spec].remove(plant) self.recordPopulations()
def create_world(self): for i in range(self.num_hunters): x = randint(2, self.FIELD_LENGTH - 2) y = randint(2, self.FIELD_WIDTH - 2) hunter = Hunter(x, y, 5, self.field, 'h', 'r', 5) self.field.objects_array[x][y] = hunter self.field.array[x][y] = 'h' self.hunters.append(hunter) for i in range(self.num_rabbits): x = randint(2, self.FIELD_LENGTH - 2) y = randint(2, self.FIELD_WIDTH - 2) rabbit = Rabbit(x, y, 6, self.field, 'r', 'c', 5) self.field.objects_array[x][y] = rabbit self.field.array[x][y] = 'r' self.rabbits.append(rabbit) for i in range(self.num_carrots): x = randint(2, self.FIELD_LENGTH - 2) y = randint(2, self.FIELD_WIDTH - 2) carrot = Carrot(x, y, self.field) self.field.array[x][y] = 'c' self.field.objects_array[x][y] = carrot self.carrots.append(carrot) self.carrots_clone = self.carrots self.update()
def __init__(self, routing_key, host="localhost"): # routing_key - 'rpc_queue' self.routing_key = routing_key self.rabbit = Rabbit(host) # 队列名,随机 self.callback_queue_name = self.rabbit.declare_queue(exclusive=True) self.rabbit.register_consumer(queue_name=self.callback_queue_name, callback=self.on_response)
def create_rabbit(ai_settings, screen, rabbits, rabbit_number, row_number): """create a rabbit""" rabbit = Rabbit(ai_settings, screen) rabbit_width = rabbit.rect.width rabbit.x = rabbit_width + 2 * rabbit_width * rabbit_number rabbit.rect.x = rabbit.x rabbit.rect.y = rabbit.rect.height + 2 * rabbit.rect.height\ * row_number rabbits.add(rabbit)
def __init__(self, queue_name): self._queue_name = queue_name channel = Rabbit().create_channel() channel.queue_declare(queue=queue_name, durable=True) self.channel = channel self.lock = Lock() self._current_time = None self.count_per_minute = None self._init_count() print(f'{self.__class__} 被实例化了')
def create_fleet(ai_settings, screen, police, rabbits): """create a family of rabbits""" """create rabbit and compute the number of rabbits per line """ rabbit = Rabbit(ai_settings, screen) number_rabbits_x = get_number_rabbits_x(ai_settings, rabbit.rect.width) number_rows = get_number_rows(ai_settings, police.rect.height, rabbit.rect.height) # create a line of rabbits for row_number in range(number_rows): for rabbit_number in range(number_rabbits_x): create_rabbit(ai_settings, screen, rabbits, rabbit_number, row_number)
def __init__(self, srn_sz: (float, float), clock: pygame.time.Clock, screen: pygame.Surface, allCells): """ Initializes the World Args: srn_sz ( (float, float) ): Screen size clock (pygame.time.Clock): pygame Clock screen (pygame.Surface): pygame Screen """ self.running = True self._clock = clock self.screen = screen self.runtime = 0 self.runtime_checkpoint = 0 self.size = srn_sz self.rabbits = [] self.foxes = [] self.food = [] self.landcells = [] self.shorecells = [] self.watercells = [] self.cells = allCells self._classify_terrain() for _ in range(20): rand_pos = random.choice(self.landcells) self.rabbits.append( Rabbit(self, (rand_pos.x, rand_pos.y), self._random_speed())) #2.5 for _ in range(12): rand_pos = random.choice(self.landcells) self.foxes.append( Fox(self, (rand_pos.x, rand_pos.y), self._random_speed())) #3 self._random_pos() for _ in range(80): rand_pos = random.choice(self.landcells) self.food.append(Food( self, (rand_pos.x, rand_pos.y))) #self._random_pos() self._update_screen()
def worker(rabbit_cfg, function): f = FunctionWrapper( function['module_path'], function['module_name'], function['function_name'] ) r = Rabbit( function=f, exchange=function['exchange'], queue=function['queue'], routing_key=function.get('routing_key'), host=rabbit_cfg.get('host'), port=rabbit_cfg.get('port'), userid=rabbit_cfg.get('userid'), password=rabbit_cfg.get('password'), durable=rabbit_cfg.get('durable', True) ) r.connect() r.declare() r.consume()
def __init__(self, queue_name, consuming_function: Callable = None, threads_num=100, max_retry_times=3): """ :param queue_name: :param consuming_function: 处理消息的函数,函数有且只能有一个参数,参数表示消息。是为了简单,放弃策略和模板来强制参数。 :param threads_num: :param max_retry_times: """ self._queue_name = queue_name self.consuming_function = consuming_function self.threadpool = ThreadPoolExecutor(threads_num) self._max_retry_times = max_retry_times print(f'{self.__class__} 被实例化') self.rabbitmq_helper = Rabbit() channel = self.rabbitmq_helper.create_channel() channel.queue_declare(queue=self._queue_name, durable=True) channel.basic_qos(prefetch_count=threads_num) self.channel = channel
def __init__(self, animal_start, plant_start, height, width): self.population_log = {} for k in self.animals.keys(): self.population_log[k] = [] self.height = height self.width = width Animal.HEIGHT = height Animal.WIDTH = width self.animals_alive = 123 for i in range(animal_start): self.animals[Species.Rabbit].append( Rabbit(random.uniform(50, self.width - 50), random.uniform(50, self.height - 50))) for i in range(plant_start): self.plants[Species.Carrot].append( Carrot(random.uniform(50, self.width - 50), random.uniform(50, self.height - 50))) for i in range(2): self.animals[Species.Fox].append( Fox(random.uniform(50, self.width - 50), random.uniform(50, self.height - 50)))
def receive_msg(self): rabbit = Rabbit() rabbit.declare_queue("algorithm", durable=True) rabbit.register_consumer(queue_name="algorithm", callback=self.callback, no_ack=False) rabbit.start_consuming()
def test(self): rabbit = Rabbit() rabbit.sendMessage() things = rabbit.relayMessage() things = things.decode("unicode_escape") self.assertFalse(things != "Hello World!")
def new_rabbit(self, x, y): self.objects_array[x][y] = Rabbit(x,y, 7, self, 'r', 'c', 5) self.array[x][y] = 'r'
profile_list = data["data"] else: logger.error(str(data["status"]) + " " + data["message"]) exit(1) if not len(profile_list): return 0 name = profile_list[0]['name'] + "_" + profile_list[0]['type'] + "_" + str( jid) name = name.replace(" ", "") create_supervisord_config(ip, name, jid, thomson_host) get_supervisord(name) def callback2(ch, method, properties, body): print(" [x] Received %r" % body) print "-------------------------" if __name__ == "__main__": try: rb = Rabbit(SYSTEM["HOST"]) rb.connect() rb.channel.basic_consume(callback, queue=rb.routing_key, no_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') rb.channel.start_consuming() except Exception as e: logger.critical(str(e)) print e time.sleep(10)
help="User for accessing RabbitMQ") PARSER.add_argument("-p", "--password", required=False, default=None, type=str, help="Password for accessing RabbitMQ") PARSER.add_argument("-d", "--debug", action='store_true', help="Put Flask into debug mode") ARGS = PARSER.parse_args() APP = Flask(__name__, static_url_path='/static') RABBIT = Rabbit(host=ARGS.host, user=ARGS.user, password=ARGS.password) @APP.route('/') def index(): return render_template('index.html') @APP.route("/post", methods=["POST"]) def post(): exchange = "" if request.values.get('exchange') is not None: exchange = request.values.get('exchange').strip() topic = request.values.get('topic').strip() message = request.values.get('message').strip() return json.dumps(
parser.print_help() sys.exit(1) ip = get_ip(options.ip) if not ip: message = "Invalid ip source input: %s" % (options.ip) print message logger.error(message) sys.exit(1) host = options.host if not host: message = "Invalid host: %s" % (options.host) print message logger.error(message) sys.exit(1) jid = options.jid if not jid: message = "Invalid job id: %s" % (options.jid) print message logger.error(message) sys.exit(1) """ Process monitor source and return main """ time.sleep(300) """ clear supervisord job config """ rb = Rabbit(SYSTEM["LOG_QUEUE"]) rb.push("100")
def get_user_feed(): try: data = request.json chat_id, links, text = bot.get_feed(data) coupon = get_coupon_info(text) if text == '/start': user_response = 'Bienvenido a XBot, contacta con @RNogales para activar tu cuenta demo gratuitamente\nUsa /help para aprender como usar XBot' elif text == '/help': user_response = '/info Para otener información sobre Xbot\n/cupon CODIGO PRECIO URL\n/infocupon para informacion sobre /cupon' elif text == '/info': user_response = 'Xbot es una pareja de bots, @tg_xbot y @delivery_xbot. \nPuedes enviar links de Amazon o reenviar mensajes desde otros canales a @tg_xbot y @delivery_xbot te responderá.\nPero para activar tu cuenta necesitas enviar tu tag de amazon a @RNogales y añadir @delivery_xbot como administrador a un canal en el que quieras recibir las ofertas.\nXbot tambien puede buscar y enviarte ofertas automáticamente sin que tu hagas nada, incluso filtrar por categorias y extraer estadísticas de clicks de tus canales.' elif text == '/infocupon': user_response = 'Los centimos del precio deben separarse con punto (no vale coma) y el simbolo del € debe ir seguido sin espacios, tambien se puede usar el del $.\n\nSi el bot dice "cupon capturado" es que lo has hecho bien!' elif coupon is not None: code = coupon.get('code', None) final_price = coupon.get('final_price', None) links = coupon.get('urls', None) if (code is not None) and (final_price is not None) and (links is not None): for url in links: message = { 'origin': chat_id, 'url': url, 'coupon_code': code, 'coupon_price': final_price, 'time': datetime.now().strftime("%d/%m/%Y, %H:%M:%S") } Rabbit().log(body=message, routing_key='ManualFeed') user_response = f'Cupon Capturado:\nCODE: {code}\nPrecio: {final_price}\n {links[0]}' else: for url in links: message = { 'origin': chat_id, 'url': url, 'time': datetime.now().strftime("%d/%m/%Y, %H:%M:%S") } Rabbit().log(body=message, routing_key='ManualFeed') if len(links) == 0: user_response = 'No se ha capturado ningún link válido de Amazon, pruebe con otro mensaje' elif len(links) == 1: user_response = f'Link Capturado: {links[0]}' else: user_response = f'Links Capturados:\n{links}' json_data = { "chat_id": chat_id, "text": user_response, 'parse_mode': 'HTML' } message_url = BOT_URL + 'sendMessage' requests.post(message_url, json=json_data) # Notify admin user = xbotdb.get_user_by_chat_id(json_data['chat_id']) if user is not None: username = user.telegram_name else: username = chat_id json_data[ 'text'] = f"To: {username}\n{user_response}\nInput: {json.dumps(data)}" json_data['chat_id'] = 213337828 requests.post(message_url, json=json_data) except Exception as e: try: # Notify error to admin json_data = { "chat_id": 213337828, "text": f"ERROR: {str(e)}", 'parse_mode': 'HTML' } message_url = BOT_URL + 'sendMessage' requests.post(message_url, json=json_data) # Notify error to user data = request.json print(data) chat_id = data['chat']['id'] json_data['chat_id'] = chat_id requests.post(message_url, json=json_data) return Response(json.dumps({'Error': str(e)}), status=200, mimetype='application/json') except Exception as e: print( f'VERY IMPORTANT ERROR: {e}\nreturning 200 to avoid infinite loop' ) return Response(json.dumps({'Error': str(e)}), status=200, mimetype='application/json') return Response(json.dumps(json_data), status=200, mimetype='application/json')
def __init__(self): self.__rabbit = Rabbit(host="localhost")
from rabbit import Rabbit import json if __name__ == '__main__': rabbit = Rabbit() rabbit.declare_queue("queue_test", durable=True) test_data = { 'action': 'launch', 'owner': 'aiur_system', 'eval_info': { 'name': '【测试数据】视频-视频黑白边检测模型评测任务', 'model': '003', 'desc': 'today is friday', 'sample_pattern': '', 'num': '200', 'extra': { 'source': 'commercialization' } } } for i in range(10000): temp = json.dumps(test_data) rabbit.produce(f'{i}: {temp}', "queue_test") rabbit.close()
def test_rabbit(self): rabbit = Rabbit() rabbit.sendMessage() things = rabbit.relayMessage() self.failIf(things != "Hello World!")
profile = sa.update_data(ip) if not profile: raise ValueError('could not find %s' % (options.ip)) else: check = sa.check(profile) try: if options.jid != "None" and check == 1: try: jid = int(options.jid) message = { "host": options.thomson_host, "jid": jid, "source": get_ip_from_ip_multicast(options.ip), "status": check } running_backup_queue = Rabbit(SYSTEM["RUNNING_BACKUP_QUEUE"]) running_backup_queue.push(json.dumps(message)) logger.info("Jid: %s, check_status: %s --> send message: %s" % (str(options.jid), str(check), str(message))) except Exception as e: logger.error(str(e)) else: logger.info("Jid: %s, check_status: %s --> Not send message" % (str(options.jid), str(check))) """ clear supervisord job config """ rb = Rabbit(SYSTEM["HOST"]) rb.push("100") except Exception as e: print e
def initialize_forest(self): """Adds initial organisms to the map.""" directions = list(Direction) # Water map for pool_size in WATER_POOLS: rand_x = random.randint(0, self.width - 1) rand_y = random.randint(0, self.height - 1) while self.water_map[rand_x][rand_y]: rand_x = random.randint(0, self.width - 1) rand_y = random.randint(0, self.height - 1) water_pools_added = 0 positions = [(rand_x, rand_y)] WATER_POOLS_POSITIONS.append((rand_x, rand_y)) while water_pools_added < pool_size and positions: # Breadth first add water pools around x, y = positions.pop(0) if not self.water_map[x][y]: water = Water(self, x, y) self.water_map[x][y] = water water_pools_added += 1 # Insert all neighbors random.shuffle( directions) # shuffle for a bit random shapes for dir in directions: new_x = x + dir.value[0] new_y = y + dir.value[1] # Check if out of bounds if new_x < 0 or new_x >= self.width or new_y < 0 or new_y >= self.height: continue if self.water_map[new_x][new_y]: continue positions.append((new_x, new_y)) # Plant map for x in range(self.width): for y in range(self.height): # check if water if self.water_map[x][y]: continue if random.random() <= TREE_PERCENTAGE: tree = Tree(self, x, y) self.plant_map[x][y] = tree if random.random() <= HIVES_PER_TREE: hive = Hive(self, x, y) self.animal_map[x][y].append(hive) bee_amount = random.randint(HIVE_BEE_MIN_AMOUNT, HIVE_BEE_MAX_AMOUNT) bee = Bee(self, x, y, hive=hive, scout=True, age=random.randint(0, 24 * 150)) hive.bees.append(bee) self.animal_map[x][y].append(bee) for _ in range(bee_amount): bee = Bee(self, x, y, hive=hive, scout=False, age=random.randint(0, 24 * 150)) self.animal_map[x][y].append(bee) hive.bees.append(bee) elif random.random() <= GRASS_INIT_PERCENTAGE: grass = Grass(self, x, y, random.randint(-80, 100), None, self.get_initial_water_level(x, y)) self.plant_map[x][y] = grass else: earth = Earth(self, x, y, self.get_initial_water_level(x, y)) self.plant_map[x][y] = earth # Flower map from organisms import Type for x in range(self.width): for y in range(self.height): if self.water_map[x][y]: continue if random.random() <= FLOWER_PERCENTAGE: if self.plant_map[x][y] and self.plant_map[x][ y].type == Type.TREE: continue for _ in range(random.randint(1, 4)): flower = Flower(self, x, y, random.randint(-50, 100), nectar=random.randint(0, 100), has_seed=random.choice([True, False])) self.flower_map[x][y].append(flower) # Animal map import numpy as np # Rabbits for _ in range(BURROW_AMOUNT): x = random.randint(0, self.width - 1) y = random.randint(0, self.height - 1) while self.water_map[x][y]: x = random.randint(0, self.width - 1) y = random.randint(0, self.height - 1) burrow = Burrow(self, x, y) self.animal_map[x][y].append(burrow) rabbit_amount = random.randint(BURROW_RABBIT_MIN_AMOUNT, BURROW_RABBIT_MAX_AMOUNT) for _ in range(rabbit_amount): dx = random.randint(-3, 3) dy = random.randint(-3, 3) if x + dx < 0 or x + dx >= self.width or y + dy < 0 or y + dy >= self.height: continue if self.water_map[x + dx][y + dy]: continue rabbit = Rabbit(self, x + dx, y + dy, random.choice([True, False]), adult=True, burrow=burrow, age=random.randint(24 * 30, 24 * 30 * 3), reproduction_timer=random.randint(0, 24 * 6), genetics_factor=np.random.normal(1, 0.1)) self.animal_map[x + dx][y + dy].append(rabbit) # Foxes for _ in range(FOX_AMOUNT): x = random.randint(0, self.width - 1) y = random.randint(0, self.height - 1) while self.water_map[x][y]: x = random.randint(0, self.width - 1) y = random.randint(0, self.height - 1) fox = Fox(self, x, y, random.choice([True, False]), adult=True, age=random.randint(24 * 30 * 2, 24 * 30 * 6), genetics_factor=np.random.normal(1, 0.1)) self.animal_map[x][y].append(fox)
def consume_from_rmq(self): rabbit = Rabbit() rabbit.declare_queue("algorithm", durable=True) rabbit.register_consumer(queue_name="algorithm", callback=self.algorithmCallback, no_ack=False) rabbit.start_consuming()
stop = stop_job(jd) time.sleep(2) start = start_job(jd) logger.critical( "Tool just returned the main source by stop and start job: Job(%s)" % (str(data))) return 0 def callback(ch, method, properties, body): date_time = DateTime() print "------------->\n" + str(date_time.get_now_as_human_creadeble( )) + " recieved: " + body + "\n<-------------" logger.info("received " + body) if not body: logger.warning("received " + body + "empty!") return 1 t = threading.Thread(target=return_main, args=(body, )) t.start() if __name__ == "__main__": rb = Rabbit(SYSTEM["RUNNING_BACKUP_QUEUE"]) rb.connect() rb.channel.basic_consume(callback, queue=rb.routing_key, no_ack=True) print(' [*] Waiting for messages. To exit press CTRL+C') rb.channel.start_consuming() #data = """{"host":"172.17.5.110", "jid": 1100}""" #print return_main(data)