def json_obj_updated(self): """ Tranforma o jason em uma lista de ticketss """ if type(self.tickets) is list: objects = [ Ticket(item["TicketID"], item["CategoryID"], item["CustomerID"], item["CustomerName"], item["CustomerEmail"], item["DateCreate"], item["DateUpdate"], item["Interactions"], item["Priority"], item["Rating"]) for item in self.tickets ] return objects else: objects = [ Ticket(self.tickets["TicketID"], self.tickets["CategoryID"], self.tickets["CustomerID"], self.tickets["CustomerName"], self.tickets["CustomerEmail"], self.tickets["DateCreate"], self.tickets["DateUpdate"], self.tickets["Interactions"], self.tickets["Priority"], self.tickets["Rating"]) ] return objects
def generate_ticket(id): """ generate a ticket object form a API results by calling Object factory. Args: id: Integer, ID of the selected ticket. Returns: ticket: Ticket object, which contains ticket data if error: returns a default ticket with Error message assigned. """ # get query generated by zendesk_api.py methods url = ApiQuery().get_selected_ticket(id) query = ApiQuery().get_full_query(url) response = ApiCall().get_result(query) if response.is_success: result_data = response.result ticket_data = result_data['ticket'] factory = ObjectFactory() ticket = factory.create_ticket_object(ticket_data) else: ticket = Ticket() ticket.error_message = response.error_message return ticket
def main(): print("\nWelcome to the ticketing service.") user = User() request = None while True: while True: checkIn = False isCreated = False print("\n<> 1. Sing In\n<> 2. Create Account\n<> 3. Turn off the system") request = input(">> ") if request == "3": user = User() print("\nGoodbye. We'll be waiting for you!") break # sing in elif request == "1": login = input("Your login:\n>> ") password = input("Your password:\n>> ") if user.checkUser(login, password): checkIn = True # registration elif request == "2": login = input("Your login:\n>> ") password = input("Your password:\n>> ") name = input("What is your name:\n>> ") if not user.createUser(login, password, name): isCreated = True if checkIn: break elif isCreated: print("\n!!! Choose another login. This already exists") else: print("\n!!! Wrong login or password. Try again\n") if request == "3": break isLogout = False while True: print("\n<> 1. Buy ticket\n<> 2. My ticket\n<> 3. Log out") request = input(">> ") if request == "3": user = User() isLogout = True break elif request == "1": buy = buyTicket(user) if not buy[0]: continue cinema = buy[1] ticket = Ticket() ticket.setTicket(cinema) print("\nYour ticket:\n{}".format(ticket)) user.setTicket(ticket) elif request == "2": print() for item in range(0, len(user.myTickets())): print(user.myTickets()[item]) if item != len(user.myTickets())-1: print("-----------------------------") if isLogout: continue
def test_ticket_ms14_068(): try: cc1 = CCache() cc1.set_raw_data(ccache_ms14_068.decode('hex')) raw_ticket = cc1.get_ticket('krbtgt/%s@%s' % (DOMAIN, DOMAIN)) if not raw_ticket: logging.error('No ticket found!') return False tktobj = Ticket(raw_ticket) enc_tgt = tktobj.get_encrypted_data() enc_tgt_type = tktobj.get_encryption_type() tgtobj = CCacheTGT() tgtobj.set_ciphertext(enc_tgt) tgtobj.set_key([enc_tgt_type, KRBTGT_NTLM.decode('hex')]) tgtobj.set_mode(MODE_TGT) clear_tgt = tgtobj.decrypt() if USER in clear_tgt: return True else: return False except Exception as e: logging.error(e) return False
class Client(Cmd): def __init__(self): Cmd.__init__(self) self.prompt = '12306>' self.intro = ''' Welcome to 12306 Cmd Client Author : 9527 Time : %s Input help for more information ''' % time.strftime('%X', time.localtime()) self.tic = Ticket() def do_help(self, arg): print u''' query : query tickets price : look the price of the ticket which you query just now order : query tickets and order you want before: show all query exit : we say goodbye That's All ! Have a try! ''' def do_query(self, arg): try: self.tic.query() except (QueryError, KeyError): print u'what the f**k u input!' except Exception, e: print e print u'no result'
def __init__(self): self.client = MongoClient(os.getenv('DB_HOST'), 27017) self.db = self.client['db_freshdesk'] self.tickets = self.db.tickets self.contacts = self.db.contacts self._ticket = Ticket() self._contact = Contact()
def testTicket_1(self): """ Input: zero integer and floating point value. Expected Output: raise ValueError """ with self.assertRaises(ValueError): Ticket(0) Ticket(0.00)
def makeTicket(ticket_id): t = Ticket() while t.complete == False: t.on_event(getRandomTransition(str(t.state))) activities = t.activity for a in activities: a['ticket_id'] = ticket_id return (activities)
def owner_finder(hosts): ticket = Ticket() hosts_ticket = {} with open('owner.json') as f: owners = json.load(f) for host in hosts: ticketno = ticket.unknown_host(host) hosts_ticket.update({host.strip('\n'): ticketno}) return hosts_ticket, owners
def __init__(self): Cmd.__init__(self) self.prompt = '12306>' self.intro = ''' Welcome to 12306 Cmd Client Author : 9527 Time : %s Input help for more information ''' % time.strftime('%X', time.localtime()) self.tic = Ticket()
def generateData(self): for block in self.data: if not "ticket" in block: self.rules = [Rule(x) for x in block.split("\n") if x] if "nearby" in block: self.nearbyTickets = [ Ticket(x) for x in block.split("\n") if x and ":" not in x ] if "your" in block: self.myTicket = [ Ticket(x) for x in block.split("\n") if x and ":" not in x ][0]
def test_ticket(): print("- Ticket initialisation") ticket = Ticket() articles = [('a', 2, 2.5, -2, 'Parce que vous le valez bien!'), ('b', 3, 1.5, 0, '')] print("- Appending articles") for a in articles: ticket.ajout(a[0], a[1], a[2], a[3], a[4]) print("- Printing ticket") print(ticket)
def checkNewReplies(self): replied_tickets = Datebase().getRepliesTicketsIdList() if (len(activeRepTickets) != 0): try: closedTickets = { k: activeRepTickets[k] for k in activeRepTickets.keys() ^ set(replied_tickets) } for rTicket in closedTickets: self.CheckHandlerLog.info("[Ответ][%s] закрыт." % rTicket) self.openbot.sendMessageGroup("[Ответ][%s] закрыт." % rTicket) except KeyError: pass diff_ticket = { k: activeRepTickets[k] for k in activeRepTickets.keys() & set(replied_tickets) } activeRepTickets.clear() for i in diff_ticket: activeRepTickets[i] = diff_ticket[i] save_obj(activeRepTickets, 'activeRepTickets') for rTicket in replied_tickets: if rTicket not in activeRepTickets: time.sleep(0.5) for row in Datebase().getLastRepliesByTicketId(rTicket): ticket = Ticket(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10]) ticket.message = self.cleanUpMessage(ticket.message) activeRepTickets[ticket.ticket_id] = ticket save_obj(activeRepTickets, 'activeRepTickets') self.CheckHandlerLog.info( "[Reply][%s] Новый ответ.\n %s \n %s \n %s" % (ticket.ticket_id, ticket.email, ticket.subject, ticket.message)) self.openbot.sendMessageGroup( "[Reply][%s] Новый ответ.\n %s \n %s \n %s" % (ticket.ticket_id, ticket.email, ticket.subject, ticket.message), 'HTML', False)
def auto_cc_plan(self): status = self.CS.status ticket = Ticket(self.cur_name,self.cur_tf) if not self.CS.has_cc(): return cmd = 1 if status['CC']['ZPOINT'] == 'MW_down' else 0 factor = -1 if cmd == 1 else 1 entry = float(status['CC']['CC1P']) stoploss = float(status['CC']['CC1P']) + 0.10 * factor takeprofit= status['CC']['OBJPROP_PRICE1'] ticket.new(ordertype = 'ordersend', orderbody = {'cmd':cmd,'vol':0.01,'price':entry,'stoploss':stoploss,'takeprofit':takeprofit}) return
def clone_subtask_to_existing_parent(subtask_id, parent_id, project, inject, position=None, prod=False, dry_run=False, custom_substitutions=None): """Clone single subtask to existing parent task. Args: subtask_id: String JIRA id of a subtask parent_id: String JIRA id of an existing task project: String project key in JIRA in which new tickets are created inject: Dictionary with values for injecting formatted for JIRA API position: Position of a subtask to be moved to as int, default None prod: Choose if production JIRA is used, default False dry_run: If True action is not performed, just logged, default False custom_substitutions: dict with {"VAR": "substitution",} """ cloner = Cloner( [], project, inject=inject, prod=prod, dry_run=dry_run, custom_substitutions=custom_substitutions, ) cloner.clone_subtask_to_existing_parent(Ticket( prod=prod, ticket_id=subtask_id, custom_substitutions=custom_substitutions), parent_id, position=position) cloner.link_tickets()
def init_synthethic_dataset(self): self.database = {} passengers = [Passenger(name) for name in ["john green", \ "louie anderson", \ "liza koshy"]] bookings = [Booking(*booking) for booking in [("AMS", "ZRH", "10-Dec-2018"), \ ("LHR", "AMS", "01-Jan-2019"), \ ("BER", "ARN", "02-Mar-2019")]] flights = [Flight(*flight) for flight in \ [("KLM", "AMS", "BSL", "10-Dec-2018", 200), \ ("SWISS", "BSL", "ZRH", "10-Dec-2018", 100), \ ("KLM", "LHR", "AMS", "01-Jan-2019", 300), \ ("Eurowings", "BER", "ARN", "02-Mar-2019", 300)]] tickets = [Ticket(*ticket) for ticket in \ [(passengers[0], flights[0], "economy"), (passengers[0], flights[1], "economy"), (passengers[1], flights[2], "business"), \ (passengers[2], flights[3], "economy")]] bookings[0].add_ticket(tickets[0]) bookings[0].add_ticket(tickets[1]) bookings[1].add_ticket(tickets[2]) bookings[2].add_ticket(tickets[3]) self.database["passengers"] = passengers self.database["bookings"] = bookings self.database["flights"] = flights self.database["tickets"] = tickets self.database["name_to_tickets"] = { passenger.name: [] for passenger in passengers } for ticket in tickets: self.database["name_to_tickets"][ticket.client.name] += [ticket]
def generate_ticket(ticket_id: int, flight_id: int, airplane_id: int, flight_date): return Ticket(ticket_id, generate_price(), generate_birth_date(), flight_date, generate_purchase_date(flight_date), generate_document_id(), ticket_id, flight_id, airplane_id, generate_name(), generate_surname(), generate_document_type(), generate_sex())
def new_ticket(): if is_authenticated(request) and not is_staff(request): form = NewTicketForm() if request.method == "GET": return render_template("pages/customer_pages/ticket_create.html", staff=is_staff(request), user=get_user(request), form=form) elif request.method == "POST" and form.validate_on_submit(): user = get_user(request) ticket_dat = dat_loader.load_data("Tickets") messages = [] ticket_id = ticket_dat["id"] ticket_list = ticket_dat["data"] files = form.files.data uploaded_files = [] if files[0].filename != "": for x in files: try: uploaded_files.append(upload(x, False, user)) except ValueError: return abort(400) m_obj = Message(user, uploaded_files, form.description.data) messages.append(m_obj) t_obj = Ticket(ticket_id, user, form.subject.data, messages) ticket_list.append(t_obj) dat_loader.write_data("Tickets", ticket_list) return redirect("/dashboard/support/") elif is_authenticated(request) and is_staff(request): return abort(403) else: return redirect("/login/")
def test_pac(vec): ccache_file = vec[1] domain = vec[2] username = vec[3] passwd = vec[4] try: cc1 = CCache() cc1.set_raw_data(ccache_file.decode('hex')) raw_ticket = cc1.get_ticket('krbtgt/%s@%s' % (domain, domain)) if not raw_ticket: return False tgtobj = CCacheTGT() enc_tgt = Ticket(raw_ticket).get_encrypted_data() tgtobj.set_ciphertext(enc_tgt) tgtobj.set_key(passwd) tgtobj.set_mode(MODE_TGT) clear_tgt = tgtobj.decrypt() if username.upper() in clear_tgt.upper() or domain.upper( ) in clear_tgt.upper(): return True else: return False except Exception as e: logging.error(e) return False
def clone_tickets(ticket_ids, project, inject, prod=False, dry_run=False, custom_substitutions=None): """Perform cloning of tickets with all their links, parents and subtasks. Args: ticket_ids: List of ticket IDs to be cloned project: String project key in JIRA in which new tickets are created inject: Dictionary with values for injecting formatted for JIRA API prod: Choose if production JIRA is used, default False dry_run: If True action is not performed, just logged, default False custom_substitutions: dict with {"VAR": "substitution",} """ tickets = [] for id in ticket_ids: tickets.append( Ticket( prod=prod, ticket_id=id, custom_substitutions=custom_substitutions, )) cloner = Cloner(tickets, project, inject=inject, custom_substitutions=custom_substitutions, prod=prod, dry_run=dry_run) cloner.clone_tickets() cloner.link_tickets()
def insert_ticket(ticket_list): city = LottoController.select_city() bet_type = LottoController.select_bet_type() amount_of_numbers = LottoController.select_amount_of_numbers(bet_type) a_ticket = Ticket(city=city, bet_type=bet_type, amount_of_numbers=amount_of_numbers) ticket_list.append(a_ticket)
def ticket(branch, ticket, jira_username, jira_token, jenkins_username, jenkins_token, github_username, github_token): "Tells you if a ticket has passed smoke test and has been promoted into a build" default_branch = releases['default'][branch] issue = Ticket(ticket, branch, jira_username, jira_token, github_username, github_token) log.debug('Ticket ID: {}'.format(issue.id)) if issue.is_merged: server = Jenkins(jenkins_username, jenkins_token) build_numbers = server.smoke_tests(default_branch) promotion_build_numbers = server.promotions(default_branch) shas = filter(lambda x: x, map(parse_build_description, build_numbers)) enterprise_dist = EnterpriseDist(branch) vanagon = PeModulesVanagon(branch) vanagon_shas = [ enterprise_dist.get_vanagon_commit_sha(sha) for sha in shas ] data = {} for pr in issue.pull_requests: log.debug('Repo: {}, Pull Request: {}'.format( pr.repo.name, int(pr.number))) repo_shas = [ vanagon.get_repo_commit_sha(vanagon_ref, pr.repo.name) for vanagon_ref in vanagon_shas ] for commit in pr.commits: log.debug('PR Commit: {}'.format(commit)) if commit and commit in repo_shas: i = repo_shas.index(commit) log.debug('Build Number: {}'.format(build_numbers[i])) log.debug('Repository {} has commit {}'.format( pr.repo.name, commit)) log.debug('Ticket {} passed smoke test in build {}'.format( ticket, build_numbers[i])) data[build_numbers[i]] = {'smoke': pr.repo.name} if build_numbers[i] in promotion_build_numbers: log.debug('Ticket {} was promoted in build {}'.format( ticket, build_numbers[i])) data[build_numbers[i]]['promoted'] = pr.repo.name if data: build = sorted(data.keys(), reverse=True)[0] click.echo('Ticket {} passed smoke test in build {}'.format( ticket, build)) if 'promoted' in data[build]: click.echo('Ticket {} was promoted in build {}'.format( ticket, build)) else: click.echo('Unable to find this {} in a build.'.format(ticket)) else: click.echo("Not all PR's for this ticket have been merged")
def append_pav_to_tickets(pav, pav_append, prod=False, dry_run=False): """Find tickets with given PAV and append new PAV to them. Args: pav: Existing PAV to search with pav_append: New PAV that will be added to tickets prod: Choose if production JIRA is used, default False dry_run: If True action is not performed, just logged, default False """ ticket_ids = get_ticket_IDs(prod=prod, pav=pav) if not ticket_ids: logging.error('No tickets match provided PAV') return for ticket_id in ticket_ids: logging.debug('Appending PAV to ticket {0}'.format(ticket_id)) if not dry_run: ticket = Ticket(prod=prod, ticket_id=ticket_id) ticket.add_pav(pav_append)
def create_dictionary_of_parameters(df, plan): df = clean_dataframe(df, list(plan.keys())) list_tickets = [] for index, row in df.iterrows(): single_ticket = Ticket() for key in plan: plan.get(key)(single_ticket, row[key]) list_tickets.append(single_ticket) return list_tickets
def generate_ticket_list(): """ generate a ticket list form a API results by calling Object factory. Returns: tickets: list of Ticket objects, which contains ticket data if error: returns a default ticket with Error message assigned. """ # get query generated by zendesk_api.py methods url = ApiQuery().get_all() query = ApiQuery().get_full_query(url) response = ApiCall().get_result(query) tickets = [] # loop while result do not have more pages # happens when json result have more than 100 tickets while True: if response.is_success: result_data = response.result ticket_data = result_data['tickets'] for current_ticket in ticket_data: factory = ObjectFactory() ticket = factory.create_ticket_object(current_ticket) tickets.append(ticket) if result_data['next_page']: query = result_data['next_page'] response = ApiCall().get_result(query) else: break else: tickets.clear() ticket = Ticket() ticket.error_message = response.error_message tickets.append(ticket) break return tickets
def test_Ticket_findValidFields(self): ticket = Ticket("3,9,18") rules = [Rule("class: 0-1 or 4-19"), Rule("row: 0-5 or 8-19"), Rule("seat: 0-13 or 16-19")] result = ticket.findValidFields(rules) self.assertEqual(3, len(result)) self.assertEqual(0, result["row"][0]) ticket = Ticket("15,1,5") result2 = ticket.findValidFields(rules) self.assertEqual(3, len(result2)) #self.assertEqual(0, result2["row"][0]) ticket = Ticket("5,14,9") result3 = ticket.findValidFields(rules) self.assertEqual(3, len(result3))
def create_ticket(content): """ Given a body we add 'creation_date', 'limit_date' and 'status' fields and store them in the db. """ content['creation_date'] = datetime.now() content['limit_date'] = timedelta(days=PRIORITY_AND_DAYS_TO_COMPLETE[int( content['priority'])]) + content['creation_date'] content['status'] = 'abierto' ticket = Ticket(**content) db.save_ticket(vars(ticket))
def link_tickets(self): """Create links between tickets in self._links.""" if self.dry_run: return for link in self._links: ticket_id_1, ticket_id_2, link_type, direction = link clone_id_1 = self._cloned.get(ticket_id_1) clone_id_2 = self._cloned.get(ticket_id_2) if not clone_id_1 or not clone_id_2: continue if ([clone_id_2, clone_id_1] in self._linked or [clone_id_1, clone_id_2] in self._linked): continue self.log.debug('Linking {0} to {1}'.format(clone_id_1, clone_id_2)) t = Ticket(prod=self.prod, project=self.project, ticket_id=clone_id_1) t.create_link((clone_id_2, link_type, direction)) self._linked.append([clone_id_1, clone_id_2])
def set_ticket_price(self): """ A generator function that randomly assigns ticket price to the event. Ticket prices are sampled from a range of 1 - 100. These values are added to an instance of class ticket """ while self.numTickets > 0: price = round(random.uniform(1, 99), 2) ticket = Ticket(price) self.tickets.append(ticket) self.numTickets -= 1
def myTickets(self): arr = [] db = DB() for item in db.select("Tickets", '*', 'user_id=' + str(self.id)): ticket = Ticket() ticket.cinemaName = item[2] ticket.kino = item[3] ticket.time = item[4] ticket.place = item[5] ticket.price = item[6] ticket.totalPrice = item[7] arr.append(ticket) return arr
def handle_new_ticket(pieces): purchase_date = parse_datetime(pieces[:2]) txhash = pieces[-1] txinfo = execute_dcrwallet_command(['gettransaction', txhash]) price = abs(txinfo['details'][0]['amount']) fee = txinfo['details'][0]['fee'] ticket = Ticket(txhash, purchase_date, price, fee, TicketStatus.MEMPOOL) mempool_tickets.add(ticket) tickets[txhash] = ticket
def create_ticket(self): try: messages = self.params['messages'] except Exception as e: return {"error": "Invalid payload received: {0}".format(e)} if not messages or len(messages) < 0: return {'error': 'messages is not iterable'} for message in messages: try: message_data = message['data'] incident_id = Ticket.get_incident_number(message_data) if incident_id in self.incident_ids: continue self.incident_ids.append(incident_id) if PagerDuty.is_triggered_alert(message_data) and not Ticket.exists(message_data, self.env_vars): ticket = Ticket(message_data, self.env_vars) ticket.create() # TODO update_pager_duty_with_ticket_info() except Exception as e: logging.info('{0}'.format(e)) return {"error": "Ticket could not be created: {0}".format(e)} return True
def __init__(self, ip, time): Ticket.__init__(self, ip, time)
def print_ticket(self): self.executor.handle_bar(Ticket.new_bar(datetime.now()), emit=False, to_printer=True)
def get_ticket(self, bar): return Ticket.create(self.query('select * from ticket where bar = "%s"' % (bar,)))
set_text(5, 66, " CL.") for b in tlay.blocks: line = int(b.line) column = int(b.column) length = int(b.length) for part in b.text.split("\n"): set_text(line, column, part) line += 1 return "\n".join(result) t = Ticket.from_file(sys.argv[1]) print("Header: {}".format(t.header)) print("Version: {}".format(t.version)) print("Issuer: {}".format(t.issuer)) print("Key Nr: {}".format(t.key_id)) print("Signature: {}".format(t.signature.hex())) print("Payload size: {}".format(t.payload_size)) print("---") for section in t.payload.section: print(section.name) print("---") if hasattr(section.data, 'head'): print("RICS: {}".format(section.data.head.rics)) print("Order: {}".format(section.data.head.ticket_id))
from ticket import Ticket c = Ticket('type', 'price_range', 'customer', 'location') print c.create_circle('name1', 'desc1')