def get_form(): """ @return: the body of a form """ # define the default tree string tree = NewickIO.parse(g_default_string, FelTree.NewickTree) formatted_tree_string = NewickIO.get_narrow_newick_string(tree, 60) # define the form objects form_objects = [ Form.MultiLine('tree', 'newick tree', formatted_tree_string), Form.RadioGroup('matrix', 'nodes used for the distance matrix', [ RadioItem('standard', 'tips only', True), RadioItem('augmented', 'all nodes'), RadioItem('named', 'all named nodes') ]), Form.CheckGroup('output_options', 'output options', [ CheckItem('show_split', 'exact criterion partition', True), CheckItem('show_value', 'exact criterion value', True), CheckItem('show_value_minus_trace', 'exact criterion value minus trace', True), CheckItem('show_fiedler_split', 'show the spectral sign partition', True), CheckItem('show_fiedler_eigenvector', 'show the eigenvector of interest', True), CheckItem('show_labels', 'ordered labels', True), CheckItem('show_distance_matrix', 'distance matrix', True), CheckItem('show_M_matrix', 'M matrix', True) ]) ] return form_objects
def get_presets(): presets = [ Form.Preset('a puzzle from the internet', {'sudoku': g_grid_hard}), Form.Preset('a 17 clue puzzle', {'sudoku': g_grid_min_1}), Form.Preset('tricky by Arto Inkala', {'sudoku': g_grid_arto_inkala}), ] return presets
def get_form(): """ @return: the body of a form """ # define the default newick tree tree_string = '((((a:.05, b:.05)L1:.15, c:.2)L2:.8, x:1)L3:.5, (((m:.05, n:.05)R1:.15, p:.2)R2:.8, y:1)R3:.5)root;' tree = Newick.parse(tree_string, Newick.NewickTree) formatted_tree_string = Newick.get_narrow_newick_string(tree, 60) # define the default rate matrix and its ordered states R = np.array([[-.3, .1, .1, .1], [.1, -.3, .1, .1], [.1, .1, -.3, .1], [.1, .1, .1, -.3]]) ordered_states = list('ACGT') # define the default leaf state assigments leaf_assignment_lines = [ 'a : A', 'b : A', 'c : A', 'x : A', 'm : C', 'n : C', 'p : C', 'y : C' ] # define the form objects form_objects = [ Form.MultiLine('tree', 'newick tree with branch lengths', formatted_tree_string), Form.Matrix('rate_matrix', 'rate matrix', R, MatrixUtil.assert_rate_matrix), Form.MultiLine('states', 'ordered states', '\n'.join(ordered_states)), Form.MultiLine('assignments', 'leaf states', '\n'.join(leaf_assignment_lines)) ] return form_objects
def main(): if len(sys.argv) < 2: raise UsageError('not enough args') script_name, module_name = sys.argv[:2] if not re.match(g_module_name_pattern, module_name): raise UsageError('expected the first arg to be a module name') usermod = __import__(module_name, globals(), locals(), [], -1) form_objects = usermod.get_form() if '--help' in sys.argv: print usermod.__doc__ print Form.get_help_string(form_objects) return else: d_in = argv_to_dict(sys.argv) d_out = {} for obj in form_objects: if not obj.web_only(): obj.process_cmdline_dict(d_in, d_out) args = dict_to_args(d_out) args.submit = 'download' if hasattr(usermod, 'get_response_content'): content = usermod.get_response_content(args) else: deprecated_header_pairs, content = usermod.get_response(args) output_filename_for_galaxy = get_output_filename_for_galaxy(sys.argv) if output_filename_for_galaxy: with open(output_filename_for_galaxy, 'w') as fout: fout.write(content) elif '--write_to_file_for_mobyle' in sys.argv: form_out = usermod.get_form_out() filename = form_out.get_filename(args) with open(filename, 'w') as fout: fout.write(content) else: sys.stdout.write(content)
def get_form(): """ @return: the body of a form """ # define some default data column_info_list = (ColumnData('TMEM195', 279, 'F', 'L'), ColumnData('SHANK3', 552, 'R', 'W'), ColumnData('ARHGAP6', 76, 'G', 'D'), ColumnData('GRPR', 261, 'R', 'L'), ColumnData('DRP2', 203, 'T', 'M'), ColumnData('PLXNB3', 981, 'R', 'H')) data_lines = [str(info) for info in column_info_list] # define the default wild and mutant amino acids wild_string = ''.join(info.wild for info in column_info_list) mutant_string = ''.join(info.mutant for info in column_info_list) # define the form objects form_objects = [ Form.MultiLine('mapp', 'MAPP output', g_mapp_output.strip()), Form.MultiLine('headers', 'alignment column headers', '\n'.join(data_lines)), Form.SingleLine('wild', 'wild type amino acids', wild_string), Form.SingleLine('mutant', 'mutant amino acids', mutant_string), Form.ImageFormat() ] return form_objects
def get_form(): """ @return: the body of a form """ # format the default tree string tree = Newick.parse(g_default_tree, Newick.NewickTree) formatted_tree_string = Newick.get_narrow_newick_string(tree, 60) # make a real distance matrix D_s = [line.split() for line in g_default_D_lines] D_default = np.array([[float(x) for x in row] for row in D_s]) # define the form objects form_objects = [ Form.MultiLine('test_tree', 'harmonic extension tree', formatted_tree_string), Form.Matrix('D', 'leaf distance matrix', D_default, MatrixUtil.assert_symmetric), Form.MultiLine('names', 'ordered leaf names', '\n'.join(g_default_leaf_names)), Form.Float('scale', 'scale the image of the tree by this factor', 200.0, low_exclusive=0.0), Form.ImageFormat() ] return form_objects
def get_presets(): return [ Form.Preset( 'a mutation probably happened', { 'ngenerations': '10', 'selection_param': '2.0', 'mutation_param': '0.0001', 'recombination_param': '0.001', 'initial_state': '1111\n0000\n', 'final_state': '0101\n0101\n' }), Form.Preset( 'a mutation must have happened', { 'ngenerations': '10', 'selection_param': '2.0', 'mutation_param': '0.0001', 'recombination_param': '0.001', 'initial_state': '1111\n0001\n', 'final_state': '1100\n0011\n' }), Form.Preset( 'identical endpoints', { 'ngenerations': '10', 'selection_param': '2.0', 'mutation_param': '0.0001', 'recombination_param': '0.001', 'initial_state': '1111\n1111\n', 'final_state': '1111\n1111\n' }), ]
def get_form(): """ @return: the body of a form """ form_objects = [ Form.Float('plot_width', 'plot width in tikz units', '4', low_exclusive=0, high_exclusive=20), Form.Float('plot_height', 'plot height in tikz units', '6', low_exclusive=0, high_exclusive=20), Form.Float('t_max', 'max time', '5', low_exclusive=0), Form.FloatInterval('p_low', 'p_high', 'proportion interval', '0.6', '0.8', low_exclusive=0.25, high_exclusive=1), Form.TikzFormat() ] return form_objects
def _render_content(self): txt = "<h1>General Settings</h1>" txt += "<h2>Networking</h2>" table = TableProps() self.AddPropEntry(table, 'Port', 'server!port', NOTE_PORT) self.AddPropEntry(table, 'Port TLS', 'server!port_tls', NOTE_PORT_TLS) self.AddPropCheck(table, 'IPv6', 'server!ipv6', True, NOTE_IPV6) self.AddPropEntry(table, 'Listen', 'server!listen', NOTE_LISTEN) txt += self.Indent(table) txt += "<h2>Basic Behavior</h2>" table = TableProps() self.AddPropEntry(table, 'Timeout (<i>secs</i>)', 'server!timeout', NOTE_TIMEOUT) self.AddPropOptions_Reload(table, 'Server Tokens', 'server!server_tokens', PRODUCT_TOKENS, NOTE_TOKENS) txt += self.Indent(table) txt += "<h2>Server Permissions</h2>" table = TableProps() self.AddPropEntry(table, 'User', 'server!user', NOTE_USER) self.AddPropEntry(table, 'Group', 'server!group', NOTE_GROUP) self.AddPropEntry(table, 'Chroot', 'server!chroot', NOTE_CHROOT) txt += self.Indent(table) form = Form("/%s" % (self._id), add_submit=False) return form.Render(txt, DEFAULT_SUBMIT_VALUE)
def get_form(): """ @return: the body of a form """ form_objects = [ Form.RadioGroup('leaf_options', 'number of leaves', [ RadioItem('six_leaves', '6', True), RadioItem('seven_leaves', '7')]), Form.CheckGroup('requirements', 'requirements', [ CheckItem('invalid_dendrogram', 'the topology of the naive dendrogram must be incorrect', True), CheckItem('informative_children', 'splits of the child trees must be informative', True), CheckItem('force_difference', 'full graph split must differ from Schur graph split', False), CheckItem('informative_full_split', 'full graph split must be informative', False)]), Form.CheckGroup('sampling_options', 'branch length sampling', [ CheckItem('allow_integers', 'allow single digit integer branch lengths', True), CheckItem('allow_reciprocals', 'allow reciprocal single digit integer branch lengths', False)])] return form_objects
def get_form(): """ @return: the body of a form """ # define the tree string tree = Newick.parse(g_tree_string, Newick.NewickTree) formatted_tree_string = Newick.get_narrow_newick_string(tree, 60) # define the default tip data lines default_tip_data_lines = [ 'a : A', 'b : A', 'c : C', 'd : T', 'e : T', 'f : T'] # define the default rate matrix lines R = np.array([ [-1, 1/3.0, 1/3.0, 1/3.0], [1/3.0, -1, 1/3.0, 1/3.0], [1/3.0, 1/3.0, -1, 1/3.0], [1/3.0, 1/3.0, 1/3.0, -1]]) # define the form objects form_objects = [ Form.MultiLine('tree', 'newick tree', formatted_tree_string), Form.MultiLine('column', 'tip data', '\n'.join(default_tip_data_lines)), Form.Matrix('matrix', 'rate matrix', R, MatrixUtil.assert_rate_matrix), Form.ImageFormat()] return form_objects
def get_form(): """ @return: the body of a form """ # define the default tree string tree_string = Newick.brown_example_tree tree = Newick.parse(tree_string, Newick.NewickTree) formatted_tree_string = Newick.get_narrow_newick_string(tree, 60) # define the default alignment string default_alignment_string = Fasta.brown_example_alignment.strip() # define the default nucleotide distribution weights default_nt_lines = ['A : 1', 'C : 1', 'G : 1', 'T : 1'] # define the form objects form_objects = [ Form.MultiLine('tree', 'newick tree', formatted_tree_string), Form.MultiLine('alignment', 'nucleotide alignment', default_alignment_string), Form.MultiLine('weights', 'nucleotide weights', '\n'.join(default_nt_lines)), Form.Float('kappa', 'transition transversion rate ratio', 2, low_inclusive=0) ] return form_objects
def get_form(): """ @return: the body of a form """ # define the default tree lines default_tree_lines = [ '(((a:0.05, b:0.05):0.15, c:0.2):0.8, x:1.0, (((m:0.05, n:0.05):0.15, p:0.2):0.8, y:1.0):1.0);', '(a:1.062, c:0.190, (d:1.080, b:2.30):2.112);', '((d:0.083, b:0.614):0.150, e:0.581, (c:1.290, a:0.359):1.070);', '((b:1.749, d:0.523):0.107, e:1.703, (a:0.746, c:0.070):4.025);' ] # define the list of form objects form_objects = [ Form.MultiLine('trees', 'newick trees (one tree per line)', '\n'.join(default_tree_lines)), Form.Float('epsilon', 'non-negligible eigenvalue', '1e-9'), Form.CheckGroup('options', 'show these tree sets', [ CheckItem('show_all', 'all reconstructed trees', True), CheckItem('show_incomplete', 'incompletely resolved reconstructed trees', True), CheckItem('show_conflicting', 'conflicting reconstructed trees', True), CheckItem('show_negligible', 'trees with potentially informative but small loadings', True) ]) ] return form_objects
def get_presets(): return [ Form.Preset( 'fig 1', { 'N_diploid' : '100', 'nmutants' : '20', 's_values' : ('0', '2.5', '5'), 'h_values' : ('-3', '0', '1', '2'), }), Form.Preset( 'fig 2', { 'N_diploid' : '100', 'nmutants' : '160', 's_values' : ('-1', '0', '1'), 'h_values' : ('2', '3', '5', '7'), }), Form.Preset( 'check confounding', { 'N_diploid' : '200', 'nmutants' : '1', 's_values' : ('1', '2', '4'), 'h_values' : ('0.5', '0.25'), }), ]
def main(): app = QApplication() app.setApplicationDisplayName("Function Plotter") app.setStyle("fusion") form = Form() form.show() sys.exit(app.exec_())
def get_form(): """ @return: the body of a form """ return [ Form.Float('blink_birth', 'tolerance birth rate', '0.01'), Form.Float('blink_death', 'tolerance death rate', '0.02'), ]
def get_form(): form_objects = [ Form.Integer('nstates', 'number of states', 4, low=2, high=10), Form.CheckGroup( 'partition_options', 'partition options', [Form.CheckItem('bipartitioned', 'bipartitioned', True)]), ] return form_objects
def get_form(): """ @return: a list of form objects """ # sample some points to use as the defaults M = np.array(list(SpiralSampler.gen_points(200, .01))) # define the form objects form_objects = [Form.Matrix('points', 'points', M), Form.ImageFormat()] return form_objects
def get_form(): """ @return: the body of a form """ form_objects = [ Form.MultiLine('table', 'table', '\n'.join(g_lines)), Form.ImageFormat() ] return form_objects
def _render_content(self): polling_methods = [] for name, desc in POLL_METHODS: if ((not name) or \ cherokee_has_polling_method (name)): polling_methods.append((name, desc)) txt = "<h1>Advanced configuration</h1>" txt += self.Dialog(WARNING, 'warning') txt += "<h2>Connections management</h2>" table = TableProps() self.AddPropCheck(table, 'Keep Alive', 'server!keepalive', True, NOTE_KEEPALIVE) self.AddPropEntry(table, 'Max keepalive reqs', 'server!keepalive_max_requests', NOTE_KEEPALIVE_RS) self.AddPropCheck(table, 'Chunked Encoding', 'server!chunked_encoding', True, NOTE_CHUNKED) txt += self.Indent(table) txt += "<h2>System tweaking</h2>" table = TableProps() self.AddPropEntry(table, 'Thread Number', 'server!thread_number', NOTE_THREAD_NUM) self.AddPropOptions_Reload(table, 'Thread Policy', 'server!thread_policy', THREAD_POLICY, NOTE_THREAD) self.AddPropEntry(table, 'File descriptors', 'server!fdlimit', NOTE_FD_NUM) txt += self.Indent(table) txt += "<h2>Server tweaking</h2>" table = TableProps() self.AddPropOptions_Reload(table, 'Polling Method', 'server!poll_method', polling_methods, NOTE_POLLING) self.AddPropEntry(table, 'Sendfile min size', 'server!sendfile_min', NOTE_SENDFILE_MIN) self.AddPropEntry(table, 'Sendfile max size', 'server!sendfile_max', NOTE_SENDFILE_MAX) self.AddPropEntry(table, 'Panic action', 'server!panic_action', NOTE_PANIC_ACTION) self.AddPropEntry(table, 'PID file', 'server!pid_file', NOTE_PID_FILE) txt += self.Indent(table) txt += "<h2>Server behavior</h2>" table = TableProps() self.AddPropEntry(table, 'Listening queue length', 'server!listen_queue', NOTE_LISTEN_Q) self.AddPropEntry(table, 'Reuse connections', 'server!max_connection_reuse', NOTE_REUSE_CONNS) self.AddPropEntry(table, 'Log flush time', 'server!log_flush_elapse', NOTE_FLUSH_TIME) txt += self.Indent(table) form = Form("/%s" % (self._id), add_submit=False) return form.Render(txt, DEFAULT_SUBMIT_VALUE)
def get_form(): """ @return: the body of a form """ form_objects = [ Form.Float('scaling_factor', 'scaling factor', 1.0, low_exclusive=0), Form.LatexFormat() ] return form_objects
def get_form(): """ @return: the body of a form """ form_objects = [ Form.MultiLine('table_a', 'first .hud table', '\n'.join(g_a_lines)), Form.MultiLine('table_b', 'second .hud table', '\n'.join(g_b_lines)) ] return form_objects
def __init__(self): Form.RadioGroup.__init__( self, 'kmeans_init', 'cluster center initialization', [ Form.RadioItem('init_choice', 'center on randomly chosen observed points', True), Form.RadioItem('init_cluster', 'use centroids of a random partition'), Form.RadioItem('init_range', 'choose centers uniformly in the observed range')])
def get_form(): """ @return: the body of a form """ return [ Form.RadioGroup('mattype', 'predefined rate matrix', [ Form.RadioItem('plain', 'plain 4x4 integer rate matrix', True), Form.RadioItem('rand', 'random rate matrix'), ]), ]
def get_form(): form_objects = [ Form.IntegerInterval( 'start_pos', 'stop_pos', 'alignment interval', 1, 4263, low=1, high=4263), Form.Integer('nsteps', 'MCMC steps', 8000, low=1), Form.SingleLine('alignment_id', 'alignment id', 'alignment'), Form.SingleLine('mcmc_id', 'mcmc id', 'mcmc'), ] return form_objects
def get_form(): """ @return: a list of form objects """ # define the form objects form_objects = [ Form.MultiLine('tree_string', 'newick tree', g_tree_string), Form.Integer('N', 'tip duplication factor', 10) ] return form_objects
def get_form(): """ @return: a list of form objects """ # define the form objects form_objects = [ Form.MultiLine('tree_string', 'newick tree', g_tree_string), Form.Float('strength', 'duplicate node pair connection strength', 100) ] return form_objects
def get_form(): """ @return: the body of a form """ return [ Form.Float('theta', 'mutation rate 4*N*mu', '1.0', low_inclusive=0.001), Form.Float('Nr', 'recombination rate N*r', '5.0', low_inclusive=0), Form.Float('Ns', 'selection N*s', '1.0', low_inclusive=0), ]
def get_form(): """ @return: the body of a form """ form_objects = [ Form.Float('ref_length', 'length of the reference branch', '0.1', low_inclusive=0.0), Form.Float('child_length', 'length of each child branch', '0.1', low_inclusive=0.0)] return form_objects
def get_form(): """ @return: the body of a form """ return [ Form.Integer('nB', 'number of B alleles', 1, low=0), Form.Integer('nb', 'number of b alleles', 400, low=0), Form.Float('s', 'positive when B is more fit', 0.01, low_exclusive=-1), ]
def process_module_name(module_name, bad_modules): """ @param module_name: name of the snippet module to try to run @param bad_modules: a collection of disallowed module names @return: module, success """ module = None try: requested_methods = [ '__doc__', 'get_form', 'get_response', 'get_response_content'] module = __import__(module_name, globals(), locals(), requested_methods) except Exception as e: raise SnippetTestError('error importing the snippet: ' + str(e)) if any(hasattr(module, x) for x in bad_modules): raise SnippetTestError( 'skipping because the snippet imports a disallowed module') try: response = module.get_form() form_body = Form.get_html_string(response) form_html = '<form>' + form_body + '</form>' except Exception as e: raise SnippetTestError('get form: ' + str(e)) # parse the default html parameters from the html string document = ht.fragment_fromstring(form_html) html_form = document.forms[0] html_inputs = html_form.inputs # create an object that looks like a FieldStorage object mock_field_storage = MockFieldStorage(html_inputs) # parse the field storage data according to the form data try: for form_item in response: form_item.process_fieldstorage(mock_field_storage) except Form.FormError as e: raise SnippetTestError('default error: ' + str(e)) # get the result of calling the function # using the default parameter values if hasattr(module, 'get_response_content'): try: response = module.get_response_content(mock_field_storage) if response is None: raise SnippetTestError('no response') except Exception as e: raise SnippetTestError('get response content: ' + str(e)) else: return module, True elif hasattr(module, 'get_response'): try: module.get_response(mock_field_storage) except Exception as e: raise SnippetTestError('get response: ' + str(e)) else: return module, True return module, False
def testmem(sa): import titlefield import textbox import slider import multiline while 1: F = Form(name="Testing") w = F.add_widget(titlefield.TitleText) str = "useable space = %s, %s; my height and width is: %s, %s" % (F.useable_space()[0], F.useable_space()[1], w.height, w.width) w.value = str w2 = F.add_widget(textbox.Textfield) str2 = "useable space = %s, %s; my height and width is: %s, %s" % (F.useable_space()[0], F.useable_space()[1], w2.height, w2.width) w2.value = str2 w3 = F.add_widget(slider.Slider) #w4 = F.add_widget(multiline.MultiLine, height=5) F.display()
def _get_cat_4_text(form_objects, presets): # this complicatedness helps to deal with integer and float intervals label_object_pairs = [] for obj in form_objects: obj_items = None try: obj_items = obj._get_temp_items() except AttributeError as e: pass if obj_items is None: obj_items = [obj] label_object_pairs.extend([(x.label, x) for x in obj_items]) label_to_form_object = dict(label_object_pairs) # write the javascript using horrific typechecking out = StringIO() print >> out, '<!-- these are hardcoded presets -->' print >> out, '<script type="text/javascript">' default_preset = Form.get_default_preset(form_objects) for i, preset in enumerate([default_preset] + presets): print >> out, 'function on_wsf_preset%d() {' % i for k, v in preset.d.items(): # check the form object corresponding to this item # FIXME this is horrible typechecking that is not pythonic form_object = label_to_form_object[k] if isinstance(form_object, Form.RadioGroup): print >> out, 'wsfSetRadio("%s", "%s");' % (k, v) elif isinstance(form_object, Form.CheckGroup): js_literal = _collection_to_javascript_literal(v) print >> out, 'wsfSetChecks("%s", %s);' % (k, js_literal) elif isinstance(form_object, Form.Sequence): print >> out, 'wsfSetInner("%s", "%s");' % (k, '\\n'.join(v)) elif isinstance(form_object, Form.MultiLine): contents = '\\n'.join(v.splitlines()) print >> out, 'wsfSetInner("%s", "%s");' % (k, contents) elif any([ isinstance(form_object, Form.Integer), isinstance(form_object, Form.Float), isinstance(form_object, Form.SingleLine)]): print >> out, 'wsfSetValue("%s", "%s");' % (k, v) else: # assume we want to set the inner html print >> out, 'wsfSetInner("%s", "%s");' % (k, v) print >> out, '}' print >> out, '</script>' return out.getvalue().rstrip()
def initialize( context ): import Document initializeProduct(context, this_module, globals(), document_module = Document, document_classes = document_classes, object_classes = object_classes, portal_tools = portal_tools, content_constructors = content_constructors, content_classes = content_classes) # Initialise ERP5Form Formulator FieldRegistry.registerField(ProxyField.ProxyField, 'www/StringField.gif') FieldRegistry.registerField(DurationField.DurationField, 'www/StringField.gif') FieldRegistry.registerField(EditorField.EditorField, 'www/TextAreaField.gif') FieldRegistry.registerField(FormBox.FormBox, 'www/StringField.gif') FieldRegistry.registerField(POSBox.POSBox, 'www/StringField.gif') FieldRegistry.registerField(ListBox.ListBox, 'www/StringField.gif') FieldRegistry.registerField(ReportBox.ReportBox, 'www/StringField.gif') FieldRegistry.registerField(PlanningBox.PlanningBox, 'www/StringField.gif') FieldRegistry.registerField(MatrixBox.MatrixBox, 'www/StringField.gif') FieldRegistry.registerField(RelationField.RelationStringField, 'www/StringField.gif') FieldRegistry.registerField(MultiRelationField.MultiRelationStringField, 'www/StringField.gif') FieldRegistry.registerField(ImageField.ImageField, 'www/StringField.gif') FieldRegistry.registerField(StandardFields.StringField, 'www/StringField.gif') FieldRegistry.registerField(StandardFields.CheckBoxField, 'www/CheckBoxField.gif') FieldRegistry.registerField(StandardFields.IntegerField, 'www/IntegerField.gif') FieldRegistry.registerField(StandardFields.TextAreaField, 'www/TextAreaField.gif') FieldRegistry.registerField(StandardFields.RawTextAreaField, 'www/TextAreaField.gif') FieldRegistry.registerField(StandardFields.LinesField, 'www/LinesField.gif') FieldRegistry.registerField(StandardFields.ListField, 'www/ListField.gif') FieldRegistry.registerField(StandardFields.MultiListField, 'www/MultiListField.gif') FieldRegistry.registerField(ParallelListField.ParallelListField, 'www/MultiListField.gif') FieldRegistry.registerField(StandardFields.RadioField, 'www/RadioField.gif') FieldRegistry.registerField(StandardFields.MultiCheckBoxField, 'www/MultiCheckBoxField.gif') FieldRegistry.registerField(StandardFields.PasswordField, 'www/PasswordField.gif') FieldRegistry.registerField(StandardFields.EmailField, 'www/EmailField.gif') FieldRegistry.registerField(StandardFields.PatternField, 'www/PatternField.gif') FieldRegistry.registerField(StandardFields.FloatField, 'www/FloatField.gif') FieldRegistry.registerField(StandardFields.DateTimeField, 'www/DateTimeField.gif') FieldRegistry.registerField(StandardFields.FileField, 'www/FileField.gif') FieldRegistry.registerField(StandardFields.LinkField, 'www/LinkField.gif') FieldRegistry.registerField(StandardFields.LabelField, 'www/LabelField.gif') FieldRegistry.registerField(MultiLinkField.MultiLinkField, 'www/LinkField.gif') FieldRegistry.registerField(InputButtonField.InputButtonField, 'www/StringField.gif') FieldRegistry.registerField(OOoChart.OOoChart, 'www/StringField.gif') FieldRegistry.registerField(CaptchaField.CaptchaField, 'www/StringField.gif') # some helper fields FieldRegistry.registerField(HelperFields.ListTextAreaField) FieldRegistry.registerField(HelperFields.MethodField) FieldRegistry.registerField(HelperFields.TALESField) import HyperLinkField FieldRegistry.registerField(HyperLinkField.HyperLinkField, 'www/LinkField.gif') import VideoField FieldRegistry.registerField(VideoField.VideoField, 'www/StringField.gif') import AudioField FieldRegistry.registerField(AudioField.AudioField, 'www/StringField.gif') # register help for the product context.registerHelp() # register field help for all fields FieldRegistry.registerFieldHelp(context) # make Dummy Fields into real fields FieldRegistry.initializeFields() # do initialization of Form class to make fields addable Form.initializeForm(FieldRegistry) Form.initializeForm(FieldRegistry, form_class=Report.ERP5Report) # Register FSPDFTemplate icon registerIcon(PDFTemplate.FSPDFTemplate, 'www/PDF.png', globals()) # Register ProxyField icon registerIcon(ProxyField.ProxyField, 'www/ProxyField.png', globals())
def handler(req): """ If no arguments were provided then display the directory of scripts. Otherwise if a valid myscript identifier was provided then dispatch the request to the script. Otherwise show an error message. """ import mod_python # redirect to the code page if no args were passed if not req.args: req.content_type = "text/html" print >> req, '<head>' print >> req, '<meta HTTP-EQUIV="REFRESH" content="0; url=/code">' print >> req, '</head>' print >> req, '<body></body>' return mod_python.apache.OK try: field_storage = mod_python.util.FieldStorage(req) scriptid = field_storage.getfirst('myscript') if not scriptid: raise DispatchError('no script snippet was specified') if not re.match(r'^\d{8}[a-zA-Z]$', scriptid): raise DispatchError('the specified script name did not meet the format requirements') try: module = __import__(scriptid, globals(), locals(), ['__doc__', 'handler', 'get_form', 'get_response']) except ImportError: raise DispatchError('the script could not be imported') # process the module differently depending on its type if hasattr(module, 'get_form') and hasattr(module, 'get_response'): # This is the more advanced dispatch method. # Get the form data. form_data = module.get_form() # Determine whether we are asking for a form or for a response. if len(field_storage.keys()) == 1: # the form from the module is either a string or a list of form objects if type(form_data) is str: form_html = form_data else: form_html = Form.get_html_string(form_data) req.content_type = str('text/html') print >> req, '<html>' title = SnippetUtil.docstring_to_title(module.__doc__) if title: print >> req, '<head>' print >> req, '<title>' print >> req, title print >> req, '</title>' print >> req, '</head>' print >> req, '<body>' print >> req, SnippetUtil.docstring_to_html(module.__doc__) print >> req, '<br/><br/>' print >> req, '<form method="post">' print >> req, '<input type="hidden" name="myscript" value="%s"/>' % scriptid print >> req, form_html print >> req, '<br/><br/>' print >> req, '<input type="submit" name="mysubmit" value="Submit"/><br/>' print >> req, '</form>' print >> req, '</body>' print >> req, '</html>' else: # possibly parse the field storage data according to the form data if type(form_data) is not str: for form_item in form_data: form_item.process_fieldstorage(field_storage) # get the response content_info, content_text = module.get_response(field_storage) for key, value in content_info: if key == 'Content-Type': req.content_type = value else: req.headers_out[key] = value req.write(content_text) else: raise DispatchError('no web interface was found for this script') except ImportError as e: req.content_type = "text/plain" print >> req, 'Uncaught ImportError:', e except DispatchError as e: req.content_type = "text/plain" print >> req, 'Error:', e except HandlingError as e: req.content_type = "text/plain" print >> req, 'Error:', e except Form.FormError as e: req.content_type = "text/plain" print >> req, 'Form validation error:', e # pretend everything is OK return mod_python.apache.OK
def index(self): out = StringIO() self._init_form() form_html = Form.get_html_string(self.form_objects) print >> out, '<html>' print >> out, '<head>' title = SnippetUtil.docstring_to_title(self.module.__doc__) if title: print >> out, '<title>' print >> out, title print >> out, '</title>' print >> out, FormHeaderJs.get_header_script_text( self.form_objects, self.form_presets) print >> out, '</head>' print >> out, '<body>' lines = smallutil.get_stripped_lines(StringIO(self.module.__doc__)) if lines: print >> out, lines[0] else: print >> out, gray_span('untitled') print >> out, '<br/>' print >> out, '<code>', if self.source_link: relative_link = '../' + self.source_link print >> out, '<a href="%s">source code</a>' % relative_link else: print >> out, gray_span('source code') print >> out, '</code>' print >> out, '<br/><br/>' print >> out if len(lines) > 1: print >> out, '<!-- long description -->' for line in lines[1:]: print >> out, line print >> out, '<br/><br/>' else: print >> out, '<!-- no long description available -->' print >> out print >> out, '<!-- main form -->' print >> out, '<div style="float: left;">' print >> out, '<form id="mainform" action="process" method="post">' if form_html: print >> out, form_html print >> out, '<br/><br/>' print >> out, '<input type="submit" name="submit" value="view"/>' print >> out, '<input type="submit" name="submit" value="download"/>' print >> out, '<br/>' print >> out, '</form>' print >> out, '</div>' print >> out if self.form_presets: print >> out, '<!-- preset configurations -->' print >> out, '<div style="float: left;">' print >> out, '<fieldset>' print >> out, '<legend>preset configurations</legend>' button_tags = [] default_preset = Form.get_default_preset(self.form_objects) for i, preset in enumerate([default_preset] + self.form_presets): tag = get_preset_button_tag(i, preset.description) button_tags.append(tag) print >> out, '<br/>\n'.join(button_tags) print >> out, '</fieldset>' print >> out, '</div>' print >> out print >> out, '</body>' print >> out, '</html>' return out.getvalue().rstrip()
def initialize(context): """Initialize the Formulator product. """ # register field classes FieldRegistry.registerField(StandardFields.StringField, 'www/StringField.gif') FieldRegistry.registerField(StandardFields.CheckBoxField, 'www/CheckBoxField.gif') FieldRegistry.registerField(StandardFields.IntegerField, 'www/IntegerField.gif') FieldRegistry.registerField(StandardFields.TextAreaField, 'www/TextAreaField.gif') FieldRegistry.registerField(StandardFields.RawTextAreaField, 'www/TextAreaField.gif') FieldRegistry.registerField(StandardFields.LinesField, 'www/LinesField.gif') FieldRegistry.registerField(StandardFields.ListField, 'www/ListField.gif') FieldRegistry.registerField(StandardFields.MultiListField, 'www/MultiListField.gif') FieldRegistry.registerField(StandardFields.RadioField, 'www/RadioField.gif') FieldRegistry.registerField(StandardFields.MultiCheckBoxField, 'www/MultiCheckBoxField.gif') FieldRegistry.registerField(StandardFields.PasswordField, 'www/PasswordField.gif') FieldRegistry.registerField(StandardFields.EmailField, 'www/EmailField.gif') FieldRegistry.registerField(StandardFields.PatternField, 'www/PatternField.gif') FieldRegistry.registerField(StandardFields.FloatField, 'www/FloatField.gif') FieldRegistry.registerField(StandardFields.DateTimeField, 'www/DateTimeField.gif') FieldRegistry.registerField(StandardFields.FileField, 'www/FileField.gif') FieldRegistry.registerField(StandardFields.LinkField, 'www/LinkField.gif') FieldRegistry.registerField(StandardFields.LabelField, 'www/LabelField.gif') # some helper fields FieldRegistry.registerField(HelperFields.ListTextAreaField) FieldRegistry.registerField(HelperFields.MethodField) FieldRegistry.registerField(HelperFields.TALESField) # obsolete field (same as helper; useable but not addable) FieldRegistry.registerField(StandardFields.RangedIntegerField, 'www/RangedIntegerField.gif') # register help for the product context.registerHelp() # register field help for all fields FieldRegistry.registerFieldHelp(context) # register the form itself context.registerClass( Form.ZMIForm, constructors = (Form.manage_addForm, Form.manage_add), icon = 'www/Form.gif') # make Dummy Fields into real fields FieldRegistry.initializeFields() # do initialization of Form class to make fields addable Form.initializeForm(FieldRegistry)
crawler = Crawler.Crawler(start,opener1) print "Scanning..." try: #for each url in queue while crawler.hasNext(): url = crawler.next() print url #display current url soup=crawler.process(root) if not soup: continue; # Process page's forms # i=0 for m in Form.getAllForms(soup): #take all forms wich have action attribute action = uri.buildAction(url,m['action']) if not action in actionDone and action!='': try: formResults=form.prepareFormInputs(m) #get inputs for form m r1 = request(url,action,formResults,opener1) #send request with user1 formResults=form.prepareFormInputs(m) #regenerate data r2 = request(url,action,formResults,opener2) #send same request with user 2 if(len(csrf)>0): if not re.search(csrf, r2): #We got a CSRF! try: print '=CSRF='+"\n\t"+'Name: '+m['name']+"\n\t"+'Action: '+m['action']+"\n\t"+'From: '+url+"\n" except KeyError: print '=CSRF='+"\n\t"+'Action: '+m['action']+"\n\t"+'From: '+url print "\t"+urllib.urlencode(formResults)