def main(args=None): hosts, ports, latex, verbose = getArgs(args) allResults = AllResults() with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor: # add all port checking to the thread pool futures = [] for host in hosts: pResults = [] for port in ports: futures.append(executor.submit(checkPort, host, port, verbose)) # add our result once the thread has finished i = 0 if verbose: bar = progressbar.ProgressBar(max_value=len(futures)) for future in concurrent.futures.as_completed(futures): result = future.result() if verbose: bar.update(i) allResults.addPortResult(result) i += 1 if verbose: bar.finish() # output the results if latex is None: Formatter(allResults).print() else: Formatter(allResults).latex(latex)
def __fetch_summary(omit: bool) -> str: pulls = __fetch_pulls(omit) milestone = __fetch_next_milestone() if milestone is None: return Formatter(pulls).format() issues = __fetch_next_issues(milestone) return Formatter(pulls, milestone, issues).format()
def build_dashboard(self, input_data={}, aligment={}, params={}, title="Stock Closing Prices", ylabel='Price', ylabel_right={}, show=True, column='adj_close', height=[], **kwargs_to_bokeh): plots = [] _data, x_range, _names = Formatter().format_input_data( input_data, column) _params = Formatter().format_params(_data, params, _names) _aligment = Formatter().format_aligment(aligment, _names) _y_label_right = Formatter().format_y_label_right( ylabel_right, ylabel, _names) kwargs_to_bokeh['y_axis_label'] = ylabel if 'x_range' not in kwargs_to_bokeh: kwargs_to_bokeh['x_range'] = Range1d(x_range[0], x_range[-1]) if not height: height = [(1. / len(_data))] * len(_data) else: assert len(height) == len(_data), ( "Number of heights should be equal to the number of plots. " + "expected: %s, " % len(_data) + "found: %s, len(height)= %s. " % (height, len(height))) assert sum(height) == 1, ("All heights should sum up to 1, " + "found: %s, sum(height)=%s" % (height, sum(height))) for i, (plot_title, data) in enumerate(_data.items()): plots.append( self._plot_stock(data=data, names=_names[plot_title], title=plot_title, params=_params[plot_title], aligment=_aligment[plot_title], ylabel_right=_y_label_right[plot_title], height=height[i], **kwargs_to_bokeh)) layout = gridplot(plots, plot_width=self.width, ncols=self.ncols) self.layout = layout if show: curdoc().add_root(layout) curdoc().title = title return curdoc
async def process(ctx): file_path = Formatter(ctx.channel.id).getInputFilePath( int(open("counter.txt", 'r').readline())) input_text = ''.join(open(file_path, 'r').readlines()) output = await Summarizer().summarize(ctx, input_text) Summarizer().save_summaries(output, int(open("counter.txt", 'r').readline()))
def main(): """ Get all questions, for each question get all the answers. :return: """ print '|Getting questions from Stackoverflow. Please wait...|' items = list() questions = get_questions() print '|Total questions: {} |'.format(len(questions)) if questions: for question in questions: formatter = Formatter() question.body = get_question_body(question.id) question.body_clean = formatter.beautify(question.body) question.answers = get_answers(question.id) # Iterate over each question and get all answers print '|Display information' for question in questions: item = Item() if question.title and question.body_clean: item.text = question.title + ' ' + question.body_clean if question.answers: for answer in question.answers: item.text += ' ' + answer.body_clean item.text.rstrip('\r\n') items.append(item) print '<<' print item.text
def formatProperties(namespace): formatter = Formatter(METHOD_INDENTATION) for property in namespace['properties']: formatter.add(generatePropertyJSDoc(property)) formatter.addLine(convertKey(property['name']), ':null,') formatter.newLine() return formatter.getResult()
def __init__(self, conf): self.proxy_address = conf.proxy_address self.proxy_port = conf.proxy_port self.interface = None # Defined later in self.run self.formatter = Formatter(self) # Makes sure files exist #TODO: Reference documentation on how to generate these files. if not os.path.exists(conf.cert_file): raise RuntimeError('cert_file "%s" not found!' % conf.cert_file) if conf.key_file and not os.path.exists(conf.key_file): raise RuntimeError('key_file "%s" not found!' % conf.key_file) if not os.path.exists(conf.accepted_certs_file): raise RuntimeError('accepted_certs_file "%s" not found!' % conf.accepted_certs_file) #TODO: proxy and port need to be parsed more robustly with urlparse self.proxy = xmlrpclib.ServerProxy( "%s:%s/" % (self.proxy_address, self.proxy_port), transport=securexmlrpc.HTTPSTransport( certfile=conf.cert_file, keyfile=conf.key_file, ca_certs=conf.accepted_certs_file, )) # Start event subprocess self.event_pipe, child_conn = Pipe() self.event_process = Process(target=event_loop, args=( self.proxy, child_conn, )) self.event_process.start()
def format_text(self, text, document, formatting): par_len = 150 applicator = Applicator() cleaner = Cleaner() formatter = Formatter() new_text = self.get_string(text) cleaner.create_sentc_list(new_text) sentc_list = cleaner.get_sentc_list() formatter.set_sentlist(sentc_list) if formatting == "list": formatter.frmt_textlist() elif formatting == "block": formatter.frmt_textblock(par_len=par_len) elif formatting == "string": formatter.frmt_textstring() else: print("format not supported") raise SystemExit format_text = formatter.get_text() applicator.apply_text(format_text, document=document)
def _generate_img(self): crop_box = None if self.crop_left: crop_box = (self.crop_left, self.crop_top, \ self.crop_left + self.crop_width, self.crop_top + self.crop_height) important_box = None if self.photo.important_top is not None: p = self.photo important_box = (p.important_left, p.important_top, p.important_right, p.important_bottom) image = None if crop_box is None and self.format.master_id: try: fp = FormatedPhoto.objects.get(format=self.format.master_id, photo=self.photo) image = Image.open(fp.image) except FormatedPhoto.DoesNotExist: pass if image is None: image = self.photo._get_image() formatter = Formatter(image, self.format, crop_box=crop_box, important_box=important_box) return formatter.format()
def start_vm(template_id, tag, count, node): from management_api import ManagementApi from management_api import NotFoundException mgmt_api = ManagementApi(host) new_ids = None try: new_ids = mgmt_api.start_vm(template_id, count, tag=tag, node=node) except NotFoundException: template_id_from_list = mgmt_api.search_template_by_name(template_id) if template_id_from_list: new_ids = mgmt_api.start_vm(template_id_from_list, count, tag=tag, node=node) else: click.echo("Template not found") exit(-1) if new_ids: click.echo("\nvms created") vms_created = [] for new_id in new_ids: vm_info = mgmt_api.show_vm(new_id) info_to_show = { 'id': new_id, 'state': vm_info.get('instance_state') } vms_created.append(info_to_show) from formatter import Formatter formatter = Formatter() click.echo(formatter.format_list_of_dicts(vms_created)) else: click.echo("\ncreate failed")
def formatNamespace(namespace): namespaceName = convertIds(namespace[0]) namespaceContent = namespace[1] formatter = Formatter() formatter.add(generateNamespaceJSDoc(namespaceContent)) if namespaceName.find('.') < 0: if namespaceName == 'Global': # ie. Global.alert -> alert() formatter.add(formatGlobal(namespaceContent)) return formatter.getResult() formatter.add('var ') if namespaceName == 'Titanium': namespaceName = 'Ti' elif namespaceName.startswith( 'Global.'): # ie. Global.String prototype extension formatter.add(extendGlobal(namespaceName[7:], namespaceContent)) return formatter.getResult() if 'subtype' in namespaceContent and namespaceContent['subtype'] == 'proxy': formatter.addLine(namespaceName, ' = function() {').addLine('};') formatter.addLine(namespaceName, '.prototype = {').newLine() else: formatter.addLine(namespaceName, ' = {').newLine() formatter.addLine(formatProperties(namespaceContent)) formatter.addLine(formatMethods(namespaceContent)) formatter.addLine('};').newLine() return formatter.getResult()
def show_template(vm_id): from management_api import ManagementApi from management_api import NotFoundException mgmt_api = ManagementApi(host) vm = {} try: vm = mgmt_api.show_registry(vm_id) except NotFoundException: template_id_from_list = mgmt_api.search_template_by_name(vm_id) if template_id_from_list: vm = mgmt_api.show_registry(template_id_from_list) else: click.echo('Template not found') exit(-1) versions = vm.pop('versions', []) vm_dict = OrderedDict([('id', vm.get('id')), ('name', vm.get('name'))]) formatted_versions = [] for version_dict in versions: number = version_dict.get('number') tag = version_dict.get('tag', '-') formatted_versions.append( OrderedDict([('number', number), ('tag', tag)])) vm_dict['versions'] = formatted_versions from formatter import Formatter formatter = Formatter() click.echo(formatter.format_dict(vm_dict))
def main(): if len(sys.argv) == 1: # READ IN FROM STANDARD INPUT lines = [line.rstrip() for line in sys.stdin] f = Formatter(inputlines = lines) else: # READ IN FROM TEXT FILE inputfile = open(sys.argv[1]) lines = [line.rstrip() for line in inputfile] f = Formatter(inputlines = lines) lines = f.get_lines() for l in lines: print (l)
def list_templates(): from management_api import ManagementApi mgmt_api = ManagementApi(host) result = mgmt_api.list_registry() from formatter import Formatter formatter = Formatter() click.echo(formatter.format_list_of_dicts(result))
def __init__(self): """inicializa propiedades del problema""" self.solution = Solution() # solucion del problema self.formatter = Formatter() # representaciones internas self.operations = [] # lista de operaciones self.jobs = [] # lista de tareas self.machines = [] # lista de maquinas self.no_machines = 0 # cantidad de maquinas self.no_jobs = 0 # cantidad de tareas
def run(simulation_name, file_name): runner = ParallelRunner(simulation_name, 400, 1000, 4) output = runner.run() formatter = Formatter(output) for_out = formatter.format() saver = Saver(for_out, file_name) saver.save()
def do_projection(): factor = get_float("Enter factor to scale by: ") min_amt = get_float(MIN_AMT_PR, required=False) max_amt = get_float(MAX_AMT_PR, required=False) new_donors = donors.challenge(factor, min_amt=min_amt, max_amt=max_amt) new_fmt = Formatter(new_donors) display("<<<BEGIN CUSTOM PROJECTION>>>") display_report(new_fmt) display("<<< END CUSTOM PROJECTION >>>")
def list_vms(): from management_api import ManagementApi mgmt_api = ManagementApi(host) list_of_vms = mgmt_api.list() click.echo("\nvms:\n") from formatter import Formatter formatter = Formatter() click.echo(formatter.format_list_of_dicts(list_of_vms)) click.echo("\n")
def test_run_hama(self): runner = SerialRunner("HamadryasSim", 50, 2) output = runner.run() formatter = Formatter(output) for_out = formatter.format() self.assertTrue(for_out) self.assertEqual(len(output) + 1, len(for_out))
def test_run_sav(self): runner = SerialRunner("SavannahSim", 50, 2) output = runner.run() formatter = Formatter(output) for_out = formatter.format() self.assertTrue(for_out) self.assertEqual(len(output) + 1, len(for_out))
def formatGlobal(namespace): formatter = Formatter(METHOD_INDENTATION) for method in namespace['methods']: formatter.add(generateMethodJSDoc(method)) formatter.addLine('function ', convertKey(method['name']), '(', formatParams(method['parameters']), ") {") formatter.addLine('}') formatter.newLine() return formatter.getResult()
def formatMethods(namespace): formatter = Formatter(METHOD_INDENTATION) key = 'methods' if 'methods' in namespace else 'method' for method in namespace[key]: formatter.add(generateMethodJSDoc(method)) formatter.addLine(convertKey(method['name']), ':function(', formatParams(method['parameters']), ") {") formatter.addLine('},') formatter.newLine() return formatter.getResult()
def test_formatter(self): file_path: str = "/app/data/dist_matrix/sample_trip.json" with open(file_path, "r") as f: trip: Dict = json.load(f) formatter: Formatter = Formatter(trip) addr_map: Dict = formatter.get_addr_map() trip_route: Dict = formatter.get_trip_route([0, 3, 1, 2, 0]) print(addr_map) print(trip_route)
def main(): """ Starts the Two Bedrooms Scraper """ scraper = Scraper(ASCENT_URL) results = scraper.get_available_floor_plans() formatter = Formatter(results) message = formatter.create_slack_message() slack = Slack(WEBHOOK_URL) slack.send(message)
def main(args): rospy.init_node('nnet_ai', anonymous=False) form = Formatter(n_input, 'data') # imgs and labels in '${PWD}/data' with tf.Session() as sess: net = ConvNet(sess, n_input, n_classes) # TRAIN ... train(form, net) # NOW OUTPUT CMDs based on input camera img... ic = img2cmd(net) rospy.spin()
def __init__(self): self.formatter = Formatter() try: from cStringIO import StringIO except ImportError: from io import StringIO self.log_stream = StringIO() logging.basicConfig(stream=self.log_stream, level=logging.DEBUG, format='%(message)s')
def __init__(self, width, height): self.width = 480 self.height = 360 self.cx = self.width / 2 self.cy = self.height / 2 self.buttons = {} self.textBoxes = {} self.checkBoxes = {} self.path = "" self.formatter = Formatter() self.running = False
def base(): Format = Formatter(filename=project_setup) if request.method == 'GET': return render_template("index.html", F=Format) else: create_requirements(Format, request.form) return send_file('features/project_setup.feature', mimetype='text/csv', attachment_filename=f'project_setup.feature', as_attachment=True)
def __init__(self, **kwargs): Globals.CONFIG = App.get_running_app().config Globals.TESTING = Globals.CONFIG.get('Development', 'test_mode') self.playlist_width = int( Globals.CONFIG.get('Playlist', 'playlist_width')) Globals.API = GoogleMusicApi() self.login_failed_popup = None self.google_music_api_login() self.formatter = Formatter() self.player = Player() self.player.set_streaming_quality( Globals.CONFIG.get('Google Play Music', 'quality').split(':')[0]) self.playlist = Playlist() self.librarymanager = LibraryManager() # self.librarymanager.load_library() self.history = History() self.playlist.queue = self.history.playlist_history self.updating_progress = False self.playlist_hidden = False super().__init__(**kwargs) self.player.bind(playing=self.update_play_button_state) self.player.bind(progress_percent=self.update_progress_slider) # Add search result views # Songs self.songlist = SongViewer() # Stations # self.stationlist = StationViewer() self.stationscroll = ScrollView(size_hint=(1, 1)) self.stationscroll.do_scroll_x = False self.stationlist = StackLayout(size_hint_y=None, spacing=10) self.stationlist.bind(minimum_height=self.stationlist.setter('height')) self.stationscroll.add_widget(self.stationlist) # Albums self.albumlist = AlbumViewer() # Create and init screen manager self.sm = ScreenManager() self.init_screens() # Listen for Keyboard events self._keyboard = Window.request_keyboard(None, self, 'text') self._keyboard.bind(on_key_down=self._pressed_key) self.searchbar.focus = True
def extendGlobal(name, namespace): formatter = Formatter(METHOD_INDENTATION) for method in namespace['methods']: formatter.add(generateMethodJSDoc(method)) formatter.addLine(name, '.prototype.', convertKey(method['name']), ' = function(', formatParams(method['parameters']), ") {") formatter.addLine('};') formatter.newLine() return formatter.getResult()