def run(self, client_info): if Tasks.has_error(client_info): logger.debug('client data not valid') return if not Tasks.is_mobile(client_info): logger.debug('client is not on mobile') return address = Tasks.get_address(client_info) if not address: logger.debug('client does not have a public IP') return whatsapp_contact = Tasks.get_whatsapp_contact(client_info) if not whatsapp_contact: logger.debug('client does not have a whatsapp contact') return return ping_and_scan(remote_address = address['address'], warmup = self.warmup, npings = self.npings, whatsapp_contact = whatsapp_contact, pattern_duration = self.pattern_duration, pattern_interval = self.pattern_interval, zmap_binary = self.zmap_binary, subnets = self.subnets, nrounds = self.nrounds, cooldown = self.cooldown)
def getMessageByIDCheckingForDuplicates(randomIndex): randomMessageQuery = MessagesByIndexQuery(randomIndex) messageCount = randomMessageQuery.count(limit=5) if messageCount > 1: logging.info("Starting duplicate insert counter task") Tasks.startFixMultipleInsertIndexTask(randomIndex) return randomMessageQuery
def run(self, client_info): if Tasks.has_error(client_info): logger.debug('client data not valid') return if not Tasks.is_mobile(client_info): logger.debug('client is not on mobile') return address = Tasks.get_address(client_info) if not address: logger.debug('client does not have a public IP') return whatsapp_contact = Tasks.get_whatsapp_contact(client_info) if not whatsapp_contact: logger.debug('client does not have a whatsapp contact') return subnets = ['%s/%s' % (address['address'], address['mask_len'])] generator = Whatsapp_generator.Generator(whatsapp_contact, self.pattern_duration, self.pattern_interval) return identify(zmap_binary = self.zmap_binary, subnets = subnets, nrounds = self.nrounds, cooldown = self.cooldown, pattern_generator = generator)
def __register_to_redis(self): try: rgtr = Register(self.myIP) task = Tasks(self.myIP) except Exception as e: self.__error_handle( { "error":{ "title": "__register_to_redis", "message": e } } ) self.__stop(internal=True) else: startTime = datetime.today().strftime("%Y-%m-%d %H-%M-%S") resp = rgtr.register(self.myIP, startTime) if "error" in resp: self.__error_handle(resp) self.__stop(internal=True) else: self.logger.info("Redis registered") resp = task.set_change() if "error" in resp: self.__error_handle(resp)
def startNextTask(): if not os.path.exists(cfg.dataPath): os.makedirs(cfg.dataPath) try: query = {'command': 'check'} r = requests.post(cfg.jobUrl, json=query, timeout=5) except requests.exceptions.ConnectionError: return False if not r.status_code == 200: raise Exception(r.status_code) # If no new jobs to process, return false and sleep if not r.json(): return False try: query = {'command': 'nextTask'} r = requests.post(cfg.jobUrl, json=query) except requests.exceptions.ConnectionError: return False if not r.status_code == 200: raise Exception(r.status_code) task = r.json() query = { 'command': 'update', 'args': { 'id': task['id'], 'task': { 'taskId': task['taskId'], 'status': 'Queued' } } } try: r = requests.post(cfg.jobUrl, json=query) except requests.exceptions.ConnectionError: return False if not r.status_code == 200: raise Exception(r.status_code) queuedTask = r.json() if queuedTask['sameStatusUpdate']: print('task already queued', queuedTask) return False if cfg.useSlurm: createSlurmTask(queuedTask) else: tasks.runTask(queuedTask['id'], queuedTask['taskId']) return True
def __init__(self, host, port): """ Constructs an instance of DeadlineCon. Params: host name of the web service (string) port number the web service is listening on (integer) """ #Builds the ConnectionProperty object used for sending requests address = host + ":" + str(port) self.connectionProperties = ConnectionProperty(address) #The different request groups use the ConnectionProperty object to send their requests self.Jobs = Jobs.Jobs(self.connectionProperties) self.SlavesRenderingJob = SlavesRenderingJob.SlavesRenderingJob( self.connectionProperties) self.Tasks = Tasks.Tasks(self.connectionProperties) self.TaskReports = TaskReports.TaskReports(self.connectionProperties) self.JobReports = JobReports.JobReports(self.connectionProperties) self.LimitGroups = Limits.LimitGroups(self.connectionProperties) self.Pulse = Pulse.Pulse(self.connectionProperties) self.Repository = Repository.Repository(self.connectionProperties) self.MappedPaths = MappedPaths.MappedPaths(self.connectionProperties) self.MaximumPriority = MaximumPriority.MaximumPriority( self.connectionProperties) self.Pools = Pools.Pools(self.connectionProperties) self.Groups = Groups.Groups(self.connectionProperties) self.Plugins = Plugins.Plugins(self.connectionProperties) self.Slaves = Slaves.Slaves(self.connectionProperties) self.Users = Users.Users(self.connectionProperties) self.Balancer = Balancer.Balancer(self.connectionProperties)
def action_sell_trailing(params, data): trade = data['trade'] # symbol = params[0].strip().upper() margin = string_to_relative(params[1]) prev_order_id = string_to_int(params[2]) if len(params) > 2 else None order_term = 'GOOD_UNTIL_CANCEL' if margin is None: return '-> error: margin' if margin >= 0: print('-> error: margin must be negative') return False # # quantity # quantity = check_positions_quantity(symbol, data) if quantity <= 0: print('Cannot sell an equity that I do not own') return False # # previous orders # open_orders = trade.find_open_orders(symbol, 'SELL') if len(open_orders) > 1: print( 'Multiple sell orders have been placed on this security, please cancel them before continue.' ) return False if len(open_orders) == 1: if prev_order_id is not None: print('A sell order has already been placed [' + str(open_orders[0][0]) + '] on this security and it is not ' + str(prev_order_id)) return False prev_order_id = open_orders[0][0] # # TODO not tested # job_server = data['job_server'] new_id = job_server.next_valid_task_id() new_task = Tasks.SellTrailing(new_id, None) new_task.set_order_data(symbol=symbol, qty=quantity, margin=margin, prev_order_id=prev_order_id, order_term=order_term, update_freq=10) job_server.add(new_task) job_server.list_done_tasks() print('job created') return False
def getRandomMessage(): if not dataStoreHasMessages(): Tasks.startMessageGetTask() logging.info("Tasks are empty") return None continueWithLoop = True; while continueWithLoop: maxIndex = getMaxIndex() randomIndex = random.randint(0, maxIndex) randomMessageQuery = getMessageByIDCheckingForDuplicates(randomIndex) randomMessages = randomMessageQuery.get() if randomMessages != None: break; else: logging.warning("Could not get message for insert value " + str(randomIndex)) return randomMessages
def __deregister_to_redis(self): try: rgtr = Register(self.myIP) task = Tasks(self.myIP) except Exception as e: self.__error_handle( { "error":{ "title": "__deregister_to_redis", "message": e } } ) else: resp = rgtr.deregister(self.myIP) if "error" in resp: self.__error_handle(resp) else: self.logger.info("Redis deregistered") resp = task.set_change() if "error" in resp: self.__error_handle(resp) self.__clear_crontab()
def __init__(self, spec): Chain.__init__(self) assert (spec["Type"] == "MultiLevel") self.ChainSpec = spec["Chain"] self.Licenses = spec["Licenses"] for lic in self.Licenses: lic["Count"] = lic["MaxCount"] self.Tasks = {} for i, taskSpec in enumerate(spec["Tasks"]): if self.FindTaskInChain(taskSpec["Name"]) == None: print "MultiLevelChain: Task %s not referenced in the chain, skipping it" % taskSpec[ "Name"] continue task = Tasks.Create(self, taskSpec) task.ID = i + 1 self.Tasks[task.Name] = task Chain.Initialize(self)
def __treading(self): try: task = Tasks(self.myIP) mem = Members(self.myIP) algor = Algorithm() rgtr = Register(self.myIP) rsync = RSYNC(self.myIP) except Exception as e: self.__error_handle( { "error":{ "title": "__threading", "message": e } } ) else: self.__members_handler(mem, rgtr, task) self.__task_allocation(task, algor) self.__task_announcement(task)
def get_by_board(board_id, sprint_id = None): ''' Get the stories for a board. arg: board_id - the id of the board to get stories for arg: sprint_id - the id of the sprint the stories belong to. Passing in 'all' gets all the stories, and passing in 'backlog' gets backlogged stories ''' board_id = UUID(board_id) #set up the query dynamically based on the sprint_id passed in sql_str = ''' SELECT `id`, `name`, `description`, `estimate`, `board_id`, `sprint_id` FROM `stories` WHERE `board_id`=%s ''' sql_tuple = (board_id.bytes) if sprint_id != 'all': if sprint_id == 'backlog': sql_str += ' AND `sprint_id` is NULL' else: sql_str += ' AND `sprint_id`=%s' sql_tuple = (board_id.bytes, UUID(sprint_id).bytes) cursor.execute(sql_str, sql_tuple) rows = cursor.fetchall() stories = [] for row in rows: stories.append(Story( binascii.b2a_hex(row[0]), row[1], row[2], float(row[3]), binascii.b2a_hex(row[4]), binascii.b2a_hex(row[5]) if row[5] is not None else row[5], Tasks.get_by_story(binascii.b2a_hex(row[0])) ) ) return stories
def update_user(hsh): try: _json = request.args _title = _json['title'] _description = _json['description'] _due = _json['due'] # validate the received values if _title and _description and _due and request.method == 'POST': task = Tasks.Task(_title, _description, _due) new_hash = db.update_task(task, hsh) resp = jsonify({ 'message': 'User updated successfully!', 'hash': new_hash, }) resp.status_code = 200 return resp else: return not_found() except Exception as e: print(e)
from flask import Flask, jsonify, flash, request import Tasks app = Flask(__name__) key = "1h8J9DHD8ZPgKU6g5uUZcOcVnkwtUUTBRDBrPkDFiv14" credsfile = 'Goodenbour-4447ab141b22.json' db = Tasks.Worksheet(key) db.initialise(credsfile) def not_found(error=None): message = { 'status': 404, 'message': 'Not Found: ' + request.url, } resp = jsonify(message) resp.status_code = 404 return resp @app.route('/tasks/') def tasks(): try: tasks = db.get_all_tasks() resp = jsonify([task.__dict__ for task in tasks]) resp.status_code = 200 return resp except Exception as e:
def test_fizzbuzz_buzz(self): assert Tasks.fizzbuzz(5) == 'Buzz'
def test_profit(self): assert Tasks.profit({ "cost_price": 32.67, "sell_price": 45.00, "quantity": 1200 }) == 14796
def action_sell(params, data): trade = data['trade'] console = data['console'] # symbol = params[0].strip().upper() limit_price = string_to_price_relative( params[1], symbol, trade, condition='') if len(params) > 1 else 'MEAN_PRICE' session____ = string_to_session( params[2]) if len(params) > 2 else 'REGULAR' prev_order_id = string_to_int(params[3]) if len(params) > 3 else None order_term = 'GOOD_UNTIL_CANCEL' if limit_price is None: return '-> error: limit_price' if session____ is None: return '-> error: session' # # quantity # quantity = check_positions_quantity(symbol, data) if quantity <= 0: print('Cannot sell an equity that I do not own') return False # # previous orders # open_orders = trade.find_open_orders(symbol, 'SELL') if len(open_orders) > 1: print( 'Multiple sell orders have been placed on this security, please cancel them before continue.' ) return False if len(open_orders) == 1: if prev_order_id is not None: print('A sell order has already been placed [' + str(open_orders[0][0]) + '] on this security and it is not ' + str(prev_order_id)) return False prev_order_id = open_orders[0][0] # # market and immediate_order # limit_price, immediate_order = decide_market_limit_price( session____, limit_price, None) # # confirm # print( format_order_action('SELL', symbol, quantity, limit_price, session____, order_term, prev_order_id, immediate_order)) yn = console.prompt_selection('confirm [y/n]? ', Console.str_from(['y', 'n']), default='n') if yn == 'n': return False # # order # if immediate_order: try: order_no, msg = trade.place_limit_order( action='SELL', symbol=symbol, quantity=quantity, limit_price=limit_price, session=session____, order_term=order_term, prev_order_id=prev_order_id) except ValueError as e: print(str(e)) return False print(msg) print('order_no = ' + str(order_no)) else: # # TODO not tested # job_server = data['job_server'] new_id = job_server.next_valid_task_id() new_task = Tasks.OrderWhenOpen(new_id, None) new_task.order_data['action'] = 'SELL' new_task.order_data['symbol'] = symbol new_task.order_data['quantity'] = quantity new_task.order_data['limit_price'] = limit_price new_task.order_data['order_term'] = order_term new_task.order_data['prev_order_id'] = prev_order_id job_server.add(new_task) job_server.list_done_tasks() print('job created') return False
var_console = bili_console.Biliconsole(loop) list_raffle_connection = [connect.RaffleConnect(i) for i in range(1, 5)] list_raffle_connection_task = [i.run() for i in list_raffle_connection] yjconnection = connect.YjConnection() danmu_connection = connect.connect() bili_timer = BiliTimer(loop) console_thread = threading.Thread(target=var_console.cmdloop) console_thread.start() Tasks.init() tasks = [ OnlineHeart.run(), Silver.run(), danmu_connection.run(), rafflehandler.run(), yjconnection.run() ] try: loop.run_until_complete(asyncio.wait(tasks + list_raffle_connection_task)) except KeyboardInterrupt: # print(sys.exc_info()[0], sys.exc_info()[1]) if ConfigLoader().dic_user['other_control']['keep-login']: pass else: response = login.logout()
def action_buy(params, data): trade = data['trade'] console = data['console'] # symbol = params[0].strip().upper() value______ = string_to_value( params[1]) if params[1] != '_' else read_preferences( symbol, data['preferences'])[0] limit_price = string_to_price_relative( params[2], symbol, trade, condition='') if len(params) > 2 else 'MEAN_PRICE' session____ = string_to_session( params[3]) if len(params) > 3 else 'REGULAR' prev_order_id = string_to_int(params[4]) if len(params) > 4 else None order_term = 'GOOD_UNTIL_CANCEL' if value______ is None: return '-> error: value' if limit_price is None: return '-> error: limit_price' if session____ is None: return '-> error: session' # # previous orders # prev_order_id = select_from_open_orders(prev_order_id, symbol, 'BUY', trade, console) if prev_order_id == 'abort': return False # # amount, price, quantity # try: if isinstance(limit_price, float): price = limit_price else: price = trade.get_current_price(symbol) price = round(price, 2) quantity = int(math.floor(value______ / price)) except ValueError as e: print(e) return False # # TODO check if I have money to make the purchase # # # market and immediate_order # limit_price, immediate_order = decide_market_limit_price( session____, limit_price, price) # # confirm # print( format_order_action('BUY', symbol, quantity, limit_price, session____, order_term, prev_order_id, immediate_order)) yn = console.prompt_selection('confirm [y/n]? ', Console.str_from(['y', 'n']), default='n') if yn == 'n': return False # # order # if immediate_order: try: order_no, msg = trade.place_limit_order( action='BUY', symbol=symbol, quantity=quantity, limit_price=limit_price, session=session____, order_term=order_term, prev_order_id=prev_order_id) except ValueError as e: print(str(e)) return False print(msg) print('order_no = ' + str(order_no)) else: # # TODO not tested # job_server = data['job_server'] new_id = job_server.next_valid_task_id() new_task = Tasks.OrderWhenOpen(new_id, None) new_task.order_data['action'] = 'BUY' new_task.order_data['symbol'] = symbol new_task.order_data['quantity'] = quantity new_task.order_data['limit_price'] = limit_price new_task.order_data['order_term'] = order_term new_task.order_data['prev_order_id'] = prev_order_id job_server.add(new_task) job_server.list_done_tasks() print('job created') return False
def test_square_equation(self): assert Tasks.square_equation(1, 0, -1) == 2
def __new__(cls, loop=None): if not cls.instance: cls.instance = super(BiliTimer, cls).__new__(cls) cls.instance.loop = loop Tasks.init() return cls.instance
""" Основной модуль, вызывающий все другие """ if __name__ == '__main__': from utils import console import __connection__ import Tasks import daemon.parse TASKS = Tasks.get_old_data()
import Login import Game import User import Tasks import time # Login to those credidentals login = Login.Login("Username", "password") # Get user object to pass it to game object constructor user = login.GetUser() # Create game object and log on server "Permafrost" game = Game.Game(user, "Permafrost") # Get SocketClient object from game object to pass it on to the Tasks object sock = game.Sock # Create tasks object tasks = Tasks.Tasks(sock, user) # Join room ID 100 (Town) tasks.JoinRoom(100) while True: # Keep sending emote ID 1 (:D) every 4 seconds tasks.SendEmote(1) time.sleep(4)
def test_fizz(self): assert Tasks.fizzbuzz(3) == 'Fizz'
# Test driver import numpy as np from Tasks import * q = Tasks(full_dataset_filename='./dataset/Training_Data.csv', judge_filename='dataset/Training_Data_9col.csv') one_hot_dataset = q.Q_02(q.judge_dataset) q.EDA(one_hot_dataset) # np.set_printoptions(threshold=np.inf) # y_pred = q.Q_17(q.judge_dataset) # print("y pred: \n", y_pred) # --- KEV MAIN --- # print("\n\nQuestion 1") # print(q.Q_01()) # # # print("\n\nQuestion 2") # one_hot_dataset = q.Q_02(q.full_dataset) # print(one_hot_dataset) # # # print("\n\nQuestion 3") # missing_count, revised_full_dataset = q.Q_03(one_hot_dataset) # print(missing_count)
tasks.delete_completed_tasks(1) if __name__ == "__main__": # init logging logging.basicConfig(filename=LOG_FILE_PATH, level=logging.DEBUG) logging.info("Start Screen Program") # init date and time dt = DateAndTime.DateAndTime() # init weather weather_obj = Weather.Weather() # init tasks tasks = Tasks.Tasks() # init the fonts font18 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 18) font24 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 24) font35 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 35) font68 = ImageFont.truetype(os.path.join(fontdir, 'Font.ttc'), 68) schedule.every(1).minutes.do(update_screen, dt=dt, weather=weather_obj.weather_dict, tasks=tasks) schedule.every(1).minutes.do(update_weather, weather_obj=weather_obj) schedule.every(1).minutes.do(update_tasks, tasks=tasks) schedule.every(5).minutes.do(check_log_file) schedule.every(12).hours.do(delete_completed_tasks, tasks=tasks)
def action_sell_stop(params, data): trade = data['trade'] console = data['console'] # symbol = params[0].strip().upper() margin = string_to_relative(params[1]) session____ = string_to_session( params[2]) if len(params) > 2 else 'REGULAR' prev_order_id = string_to_int(params[3]) if len(params) > 3 else None order_term = 'GOOD_UNTIL_CANCEL' if margin is None: return '-> error: margin' if margin >= 0: print('-> error: margin must be negative') return False if session____ is None: return '-> error: session' # # quantity # quantity = check_positions_quantity(symbol, data) if quantity <= 0: print('Cannot sell an equity that I do not own') return False # # previous orders # old_stopPrice = None open_orders = trade.find_open_orders(symbol, 'SELL') if len(open_orders) > 1: print( 'Multiple sell orders have been placed on this security, please cancel them before continue.' ) return False if len(open_orders) == 1: # save old price if open_orders[0][1]['priceType'] == 'STOP': if int(open_orders[0][1]['orderedQuantity']) == quantity: old_stopPrice = float(open_orders[0][1]['stopPrice']) # check used prev_order_id if prev_order_id is not None: print('A sell order has already been placed [' + str(open_orders[0][0]) + '] on this security and it is not ' + str(prev_order_id)) return False prev_order_id = open_orders[0][0] # # price # try: current_price = trade.get_current_price(symbol) stop_price = round(current_price * (1.0 + margin), 2) except ValueError as e: print(str(e)) return False # # market and immediate_order # _, immediate_order = decide_market_limit_price(session____, None, None) # # confirm # if (old_stopPrice is not None) and (old_stopPrice > stop_price): current_set_margin = round( ((old_stopPrice / current_price) - 1.0) * 100.0, 2) print('protection already set to ' + str(current_set_margin) + '% (' + str(old_stopPrice) + ').') return False print( format_order_action('SELL_STOP', symbol, quantity, stop_price, session____, order_term, prev_order_id, immediate_order)) yn = console.prompt_selection('confirm [y/n]? ', Console.str_from(['y', 'n']), default='n') if yn == 'n': return False # # order # if immediate_order: try: order_no, msg = trade.place_stop_order(action='SELL', symbol=symbol, quantity=quantity, stop_price=stop_price, session=session____, order_term=order_term, prev_order_id=prev_order_id) except ValueError as e: print(str(e)) return False print(msg) print('order_no = ' + str(order_no)) else: # # TODO not tested # job_server = data['job_server'] new_id = job_server.next_valid_task_id() new_task = Tasks.OrderWhenOpen(new_id, None) new_task.order_data['action'] = 'SELL_STOP' new_task.order_data['symbol'] = symbol new_task.order_data['quantity'] = quantity new_task.order_data['stop_price'] = stop_price new_task.order_data['order_term'] = order_term new_task.order_data['prev_order_id'] = prev_order_id job_server.add(new_task) job_server.list_done_tasks() print('job created') return False
import Authenticate import Tasks auth = Authenticate.Authentication() db = Authenticate.Database() task = Tasks.Task() class AskingUser: email = "" password = "" personal_details = { "Name": "", "Age": "", "Gender": "", "Date_of_birth" "Something_about_yourself": "", } def __init__(self): print("Hello user ..!") def user_choice(self): choice = input("What would you like to do ? \n 1.Login ? \n 2.Register \n") if int(choice) == 1: self.ask_user() self.login() self.add_task_details() elif int(choice) == 2: self.ask_user()
async def run(self): Tasks.init() while True: i = await self.jobs.get() asyncio.ensure_future(i[0](*i[1]))
import PrintMode import Events import Tasks import subprocess import PrinterConnector if __name__ == "__main__": putter = PrintMode.ImgCreator() events = Events.EventGetter() printer = PrinterConnector.PrinterConnector() url_auth = 'https://accounts.google.com/ServiceLoginAuth' url_login = '******' task_session = Tasks.SessionGoogle(url_login, url_auth, 'YOUR_EMAIL', 'YOURPASSWORD') task_session.get('http://keep.google.com/#reminders') task_session.get_page_text() task_session.parse_json() reminders = task_session.get_reminders() text = events.get_next_events() events_text = [[k, v] for k, v in text.items()] events_text = sorted(events_text, key=lambda x: x[0]) events_text = [events_text] + [reminders] + [''] putter.put_all_boxes() putter.put_all_text(events_text) putter.save_img('printbuffer.png') printer.print_file('PRINTER', 'printbuffer.png')
def test_fizzbuzz_fizzbuzz(self): assert Tasks.fizzbuzz(15) == 'FizzBuzz'