示例#1
0
 def test1(self):
     widget1 = Widget()
     assert widget1.func1() == "qwerty"
示例#2
0
 def runTest(self):
     '''
         PyUnit测试框架在运行一个测试用例时,TestCase子类定义的setUp()、runTest()和tearDown()方法被依次执行,最简单的测试用例只需覆盖runTest()方法来执行特定的测试代码就可以了
     '''
     widget = Widget()
     self.assertEqual(widget.getSize(), (40, 40))
示例#3
0
    style.add_part(AttributeFilter('pressed', True), button_style)

    painter = Painter(SdlPainterEngine())
    screen = Screen(painter, style=style)

    vbox = VBox(screen)
    title = Label(vbox, "hello")
    # title.request_size((5,1) * 32)
    button = Button(vbox)

    def on_click(widget):
        print "click"
        main_loop.quit()

    button.connect('clicked', on_click)

    widget = Widget(vbox)
    widget.request_size((480, 128))
    scroll = Scrollable(widget)

    vbox2 = VBox(scroll)

    for i in range(10):
        b = Button(vbox2)
        # Label(b, str(i))

    tasklet = SdlTasklet(screen)
    tasklet.start()
    print 'tasklet started'
    main_loop.run()
示例#4
0
 def setUp(self):
     self.widget = Widget('The widget')
     print('run setUp before each of test cases')
示例#5
0
 def setUp(self):
     self.widget = Widget()
示例#6
0
 def runTest(self):
     widget = Widget()
     self.assertEqual(widget.getSize(), (40, 40))
示例#7
0
t = randint(1, 3) + choice([0, 0.5])

r = randint(1, 15) / 100

a = round(p * (1 + r / n) ** (n * t), 2)

plural_end = "s" if t != 1 else ""

problem_instruction = "Find the amount that results from the following investment:"

problem_text = rf"$\${p}$ invested at ${int(r*100)}\%$ compounded {compounding_choices[n]} after a period of ${ffrac(t)}$ year{plural_end}"

solution_text = rf"$\${a}$"

content = [
    Widget(TextWidgetOptions(problem_instruction)),
    Widget(TextWidgetOptions(problem_text)),
]

solution = Widget(TextWidgetOptions(solution_text))

problem = Problem(content, [solution])

render_testbed_problem(problem)
#%%


def compound_interest_find_p():
    from math import e

    a = 50 * randint(1, 21)
示例#8
0
def showProgress(progressText, progressIterator, cancel=False):
    """Show the progress for a long-running synchronous operation.
    progressIterator should be a generator-like object that can return
    either None, for an indeterminate indicator,
    A float value between 0.0 and 1.0 for a determinate indicator,
    A string, to update the progress info label
    or a tuple of (float value, string) to set the progress and update the label"""
    class ProgressWidget(Dialog):
        progressFraction = 0.0
        firstDraw = False
        root = None

        def draw(self, surface):
            if self.root is None:
                self.root = self.get_root()
            Widget.draw(self, surface)
            frameStart = datetime.now()
            frameInterval = timedelta(0, 1, 0) / 2
            amount = None

            try:
                while datetime.now() < frameStart + frameInterval:
                    amount = progressIterator.next()
                    if self.firstDraw is False:
                        self.firstDraw = True
                        break

            except StopIteration:
                self.dismiss()

            infoText = ""
            if amount is not None:

                if isinstance(amount, tuple):
                    if len(amount) > 2:
                        infoText = ": " + amount[2]

                    amount, max = amount[:2]

                else:
                    max = amount
                maxwidth = (self.width - self.margin * 2)
                if amount is None:
                    self.progressBar.width = maxwidth
                    self.progressBar.bg_color = (255, 255, 25, 255)
                elif isinstance(amount, basestring):
                    self.statusText = amount
                else:
                    self.progressAmount = amount
                    if isinstance(amount, (int, float)):
                        self.progressFraction = float(amount) / (float(max)
                                                                 or 1)
                        self.progressBar.width = maxwidth * self.progressFraction
                        self.statusText = str("{0} / {1}".format(amount, max))
                    else:
                        self.statusText = str(amount)

                if infoText:
                    self.statusText += infoText

        @property
        def estimateText(self):
            delta = (datetime.now() - self.startTime)
            progressPercent = (int(self.progressFraction * 10000))
            left = delta * (10000 - progressPercent) / (progressPercent or 1)
            return _("Time left: {0}").format(left)

        def cancel(self):
            if cancel:
                self.dismiss(False)

        def idleevent(self, evt):
            self.invalidate()

        def key_down(self, event):
            pass

        def key_up(self, event):
            pass

        def mouse_up(self, event):
            try:
                if "SelectionTool" in str(self.root.editor.currentTool):
                    if self.root.get_nudge_block().count > 0:
                        self.root.get_nudge_block().mouse_up(event)
            except:
                pass

    widget = ProgressWidget()
    widget.progressText = _(progressText)
    widget.statusText = ""
    widget.progressAmount = 0.0

    progressLabel = ValueDisplay(ref=AttrRef(widget, 'progressText'),
                                 width=550)
    statusLabel = ValueDisplay(ref=AttrRef(widget, 'statusText'), width=550)
    estimateLabel = ValueDisplay(ref=AttrRef(widget, 'estimateText'),
                                 width=550)

    progressBar = Widget(size=(550, 20), bg_color=(150, 150, 150, 255))
    widget.progressBar = progressBar
    col = (progressLabel, statusLabel, estimateLabel, progressBar)
    if cancel:
        cancelButton = Button("Cancel",
                              action=widget.cancel,
                              fg_color=(255, 0, 0, 255))
        col += (Column((cancelButton, ), align="r"), )

    widget.add(Column(col))
    widget.shrink_wrap()
    widget.startTime = datetime.now()
    if widget.present():
        return widget.progressAmount
    else:
        return "Canceled"
示例#9
0
    def _get_display(self):

        # set up the security object
        from pyasm.security import Security, Sudo
        from pyasm.biz import Project
        from pyasm.web import WebContainer
        web = WebContainer.get_web()

        # guest mode
        #
        allow_guest = Config.get_value("security", "allow_guest")
        if allow_guest == 'true':
            allow_guest = True
        else:
            allow_guest = False

        site_obj = Site.get()
        site_allow_guest = site_obj.allow_guest()
        if site_allow_guest != None:
            allow_guest = site_allow_guest

        security = Security()
        try:
            security = self.handle_security(security)
            is_logged_in = security.is_logged_in()
        except Exception as e:
            print("AppServer Exception: ", e)
            return self.handle_not_logged_in()

        guest_mode = Config.get_value("security", "guest_mode")
        if not guest_mode:
            guest_mode = 'restricted'

        # Test
        #allow_guest = True
        #guest_mode = "full"

        # if not logged in, then log in as guest
        if not is_logged_in:
            if not allow_guest:
                return self.handle_not_logged_in()
            else:
                # login as guest
                security = Security()
                self.handle_guest_security(security)

        # for here on, the user is logged in
        login_name = Environment.get_user_name()

        is_upload = '/UploadServer' in web.get_request_url().to_string()

        # check if the user has permission to see this project
        project = web.get_context_name()
        if project == 'default':
            override_default = Project.get_default_project()
            if override_default:
                project = override_default
        if is_upload:
            print("IS UPLOAD")
            access = True

        elif project != 'default':

            # make sure the security check is done on the appropriate site
            path_info = site_obj.get_request_path_info()
            if path_info:
                site = path_info.get("site")
                Site.set_site(site)
                s = Environment.get_security()
                has_site = True
            else:
                s = security
                has_site = False

            try:
                security_version = get_security_version()
                if security_version == 1:
                    default = "view"
                    access = s.check_access("project",
                                            project,
                                            "view",
                                            default="view")
                else:
                    default = "deny"
                    key = {"code": project}
                    key2 = {"code": "*"}
                    keys = [key, key2]
                    access = s.check_access("project",
                                            keys,
                                            "allow",
                                            default=default)
            finally:
                if has_site:
                    Site.pop_site()

        else:
            # you always have access to the default project
            access = True

        if not access:
            if login_name == "guest":
                from pyasm.widget import WebLoginWdg

                msg = web.get_form_value(WebLoginWdg.LOGIN_MSG)
                if not msg:
                    msg = "User [%s] is not allowed to see this project [%s]" % (
                        login_name, project)
                    web.set_form_value(WebLoginWdg.LOGIN_MSG, msg)
                return self.handle_not_logged_in(allow_change_admin=False)

            else:
                from pyasm.widget import BottomWdg, Error403Wdg
                widget = Widget()
                top = self.get_top_wdg()
                widget.add(top)
                widget.add(Error403Wdg())
                widget.add(BottomWdg())
                widget.get_display()
                if is_upload:
                    print(
                        "WARNING: User [%s] is not allowed to upload to project [%s]."
                        % (login_name, project))
                return

        if login_name == 'guest':
            # let the site handle the guest completely
            guest_wdg = site_obj.get_guest_wdg(self.hash)
            if guest_wdg:
                web_app = WebApp()
                web_app.get_display(guest_wdg)
                return

        # some extra precautions in guest mode
        if login_name == 'guest' and guest_mode != "full":
            # show a restricted guest mode
            from pyasm.widget import WebLoginWdg, BottomWdg
            from tactic.ui.app import TitleTopWdg

            from pyasm.biz import Project
            from tactic.ui.panel import HashPanelWdg
            web = WebContainer.get_web()

            widget = Widget()
            top = TitleTopWdg()
            widget.add(top)
            body = top.get_body()
            body.add_color("background", "background")
            body.add_color("color", "color")

            has_site = False

            # use the path to set the project and/or site
            path_info = site_obj.get_request_path_info()
            if path_info:
                path_site = path_info.get("site")

                try:
                    Site.set_site(path_site)
                    has_site = True
                except Exception as e:
                    print("WARNING: ", e)
                    current_project = web.get_context_name()
                else:
                    current_project = path_info.get("project_code")
                    if not current_project:
                        current_project = web.get_context_name()

            else:
                # get the project from the url because we are still
                # in the admin project at this stage
                current_project = web.get_context_name()

            sudo = Sudo()
            try:
                if current_project != "default":
                    project = Project.get_by_code(current_project,
                                                  use_cache=False)
                    if not project:
                        raise Exception("Project [%s] does not exist" %
                                        current_project)
            except Exception as e:
                print("WARNING: ", e)
                web_wdg = None
            else:
                if not current_project or current_project == "default":
                    current_project = Project.get_default_project()

                if current_project and current_project != "default":
                    try:
                        Project.set_project(current_project)
                    except SecurityException as e:
                        print(e)
                        if 'is not permitted to view project' in e.__str__():
                            pass
                        else:
                            raise

                    # find the guest views
                    #search = Search("config/url")
                    #urls = search.get_sobjects()
                    #open_hashes = [x.get("url").lstrip("/").split("/")[0] for x in urls]

                    link = "/%s" % "/".join(self.hash)

                    # guest views
                    open_hashes = site_obj.get_guest_hashes()

                    if len(self.hash) >= 1 and self.hash[0] in open_hashes:
                        web_wdg = HashPanelWdg.get_widget_from_hash(
                            link, return_none=True)
                    else:
                        web_wdg = None

                    if not web_wdg:
                        web_wdg = HashPanelWdg.get_widget_from_hash(
                            "/guest", return_none=True, kwargs={"hash": link})
                    if web_wdg:
                        if not isinstance(web_wdg, basestring):
                            web_wdg = web_wdg.get_buffer_display()
                        top.add(web_wdg)
                else:
                    web_wdg = None
            finally:
                sudo.exit()

                if has_site:
                    Site.pop_site()

            if not web_wdg:
                msg = "No default page defined for guest user. Please set up /guest in Custom URL."
                web.set_form_value(WebLoginWdg.LOGIN_MSG, msg)
                return self.handle_not_logged_in(allow_change_admin=False)

            # create a web app and run it through the pipeline
            web_app = WebApp()
            web_app.get_display(widget)
            return

        # Full access

        # if a guest has full access, then handle it here
        if login_name == 'guest' and guest_mode == "full":
            # some extra security for guest users
            guest_url_allow = Config.get_value("security", "guest_url_allow")
            if guest_url_allow:
                items = guest_url_allow.split("|")
                allowed = False
                if self.hash:
                    url = self.hash[0]
                else:
                    url = "index"
                for item in items:
                    item = item.strip("/")
                    if item == url:
                        allowed = True
                        break
                if not allowed:
                    return self.handle_not_logged_in()

        # Welcome message for first time run
        is_first_run = Environment.is_first_run()
        if is_first_run:
            from pyasm.widget import WebLoginWdg, BottomWdg
            top = self.get_top_wdg()

            from tactic.ui.app import PageHeaderWdg
            from tactic.ui.startup import DbConfigPanelWdg

            widget = DivWdg()
            widget.add(top)
            widget.add(DbConfigPanelWdg())
            widget.add(BottomWdg())

            web_app = WebApp()
            web_app.get_display(widget)
            return

        # handle licensing
        license = security.get_license()
        user_name = security.get_user_name()
        is_licensed = license.is_licensed()

        # handle url security
        url_security = UrlSecurity()
        html = url_security.get_display()
        if html:
            widget = Widget()
            widget.add(html.getvalue())
            widget.get_display()
            return

        web = WebContainer.get_web()

        # FIXME: although this works, it should be cleaned up

        # determine the type of request
        if '/UploadServer' in web.get_request_url().to_string():
            page_type = "upload"
        elif web.get_form_value("ajax") != "":
            page_type = "ajax"
        elif web.get_form_value("dynamic_file") != "":
            # this mode creates a file dynamically
            page_type = "dynamic_file"
        else:
            page_type = "normal"

        # TODO: the following could be combined into a page_init function
        # provide the opportunity to set some templates
        self.set_templates()
        self.add_triggers()

        self.init_web_container()

        # install the language
        Translation.install()

        path_info = site_obj.get_request_path_info()
        if path_info and path_info.get("site") != "default":
            Site.set_site(path_info.get("site"))
            project_code = path_info.get("project_code")

        # handle the case where the project does not exist
        project = Project.get(no_exception=True)
        if not project:
            from pyasm.widget import BottomWdg, Error404Wdg
            Project.set_project("admin")
            widget = Widget()
            top = self.get_top_wdg()
            widget.add(top)
            widget.add(Error404Wdg())
            widget.add(BottomWdg())
            widget.get_display()
            return widget

        # get the content of the page
        try:

            widget = self.get_content(page_type)

        except Exception as e:
            print("ERROR: ", e)
            from pyasm.widget import BottomWdg, Error403Wdg
            widget = Widget()
            top = self.get_top_wdg()
            widget.add(top)
            widget.add(Error403Wdg())
            widget.add(BottomWdg())
            widget.get_display()

        # put an annoying alert if there is a problem with the license
        if not is_licensed:
            # to be sure, reread license.  This gets around the problem
            # of the extra error message when uploading a new license
            license = security.reread_license()
            is_licensed = license.is_licensed()
            if not is_licensed:
                widget.add("<script>alert('%s')</script>" %
                           license.get_message())

        # create a web app and run it through the pipeline
        web_app = WebApp()
        web_app.get_display(widget)
示例#10
0
 def test_creation(self):
     widget = Widget("My Widget")
     self.assertEqual(widget.size(), (50, 50),
                      "Initial size is not (50, 50)")
示例#11
0
    def handle_not_logged_in(self, allow_change_admin=True):

        site_obj = Site.get()
        site_obj.set_site("default")

        DbResource.clear_cache()

        from pyasm.widget import WebLoginWdg, BottomWdg
        from tactic.ui.app import TitleTopWdg

        from pyasm.biz import Project
        from tactic.ui.panel import HashPanelWdg

        web = WebContainer.get_web()

        widget = Widget()

        top = TitleTopWdg()
        widget.add(top)
        body = top.get_body()
        #body.add_gradient("background", "background", 5, -20)
        body.add_color("background", "background")
        body.add_color("color", "color")

        reset_request = web.get_form_value('reset_request') == 'true'
        if reset_request:
            from tactic.ui.widget import ResetPasswordWdg
            top.add(ResetPasswordWdg())
        else:
            reset_msg = web.get_form_value('reset_msg')
            if reset_msg:
                web.set_form_value(WebLoginWdg.LOGIN_MSG, reset_msg)

            web_wdg = None
            sudo = Sudo()
            try:
                # get the project from the url because we are still
                # in the admin project at this stage
                current_project = web.get_context_name()
                try:
                    if current_project != "default":
                        project = Project.get_by_code(current_project)
                        assert project
                except Exception as e:
                    pass
                else:

                    # custom global site login widget
                    if not current_project or current_project == "default":
                        current_project = Project.get_default_project()
                    if current_project and current_project != "default":
                        try:
                            Project.set_project(current_project)
                        except SecurityException as e:
                            print(e)
                            if 'is not permitted to view project' not in e.__str__(
                            ):
                                raise

                        if not web_wdg:
                            web_wdg = site_obj.get_login_wdg()

                        if web_wdg:
                            if not isinstance(web_wdg, basestring):
                                web_wdg = web_wdg.get_buffer_display()
                            top.add(web_wdg)
                    else:
                        web_wdg = None

                # display default web login
                if not web_wdg:
                    # get login screen from Site
                    link = "/%s" % "/".join(self.hash)
                    web_wdg = site_obj.get_login_wdg(link)
                    if not web_wdg:
                        # else get the default one
                        web_wdg = WebLoginWdg(
                            allow_change_admin=allow_change_admin)

                    top.add(web_wdg)

            finally:
                # sudo out of scope here
                sudo.exit()
                pass

        # create a web app and run it through the pipeline
        web_app = WebApp()
        web_app.get_display(widget)
        return
示例#12
0
 def __init__(self):
     self._widget = Widget()
     #self._widget.load_json()
     self._result = ''
示例#13
0
 def setUp(self):
     self.widget = Widget("The widget")
示例#14
0
 def setUp(self):#setUp()方法进行测试前的初始化工作
     self.widget = Widget()
示例#15
0
def compound_interest_compare_discrete_vs_discrete():

    n_choices = list(compounding_choices.keys())

    n_1, n_2 = sample(n_choices, 2)

    # The way this works is that we come up with an interest rate for the highest compounding rate
    # then we come up with an interest rate that is some amount higher for the lower compounding rate
    # this way it's not dead easy to tell which is the better deal--and that's the point

    base_rate = randint(1, 15) / 100

    higher_rate = base_rate + choice(linspace(0.1, 0.3, 9)) / 100

    # The lower interest rate with the higher compounding rate should be fractional as
    # often as the other interest rate

    if bool(getrandbits(1)):
        old_base_rate = base_rate
        base_rate -= higher_rate - base_rate
        higher_rate = old_base_rate

    if n_1 > n_2:
        r_1 = base_rate
        r_2 = higher_rate
    else:
        r_1 = higher_rate
        r_2 = base_rate

    r_e_1 = ((1 + (r_1 / n_1)) ** n_1) - 1

    r_e_2 = ((1 + (r_2 / n_2)) ** n_2) - 1

    r_n_description_1 = (
        f"{fmath(format_percent(r_1,))} compounded {compounding_choices[n_1]}"
    )

    r_n_description_2 = (
        f"{fmath(format_percent(r_2,))} compounded {compounding_choices[n_2]}"
    )

    solution_description = r_n_description_1 if r_e_1 > r_e_2 else r_n_description_2

    problem_instruction = "Which of the following is a better investment?"

    description_set = [r_n_description_1, r_n_description_2]

    # Randomize the order
    if bool(getrandbits(1)):
        description_set = description_set.reverse()

    problem_text = f"{r_n_description_1} or {r_n_description_2}"

    solution_text = solution_description

    content = [
        Widget(TextWidgetOptions(problem_instruction)),
        Widget(TextWidgetOptions(problem_text)),
    ]

    solution = Widget(TextWidgetOptions(solution_text))

    return Problem(content, [solution])
示例#16
0
            access = True

        if not access:
            if login_name == "guest":
                from pyasm.widget import WebLoginWdg

                msg = web.get_form_value(WebLoginWdg.LOGIN_MSG)
                if not msg:
                    msg = "User [%s] is not allowed to see this project [%s]" % (
                        login_name, project)
                    web.set_form_value(WebLoginWdg.LOGIN_MSG, msg)
                return my.handle_not_logged_in(allow_change_admin=False)

            else:
                from pyasm.widget import BottomWdg, Error403Wdg
                widget = Widget()
                top = my.get_top_wdg()
                widget.add(top)
                widget.add(Error403Wdg())
                widget.add(BottomWdg())
                widget.get_display()

                return

        if login_name == 'guest' and guest_mode == "full":
            # some extra security for guest users
            guest_url_allow = Config.get_value("security", "guest_url_allow")
            if guest_url_allow:
                items = guest_url_allow.split("|")
                allowed = False
                if my.hash:
示例#17
0
 def parse(self, widgets):
     acc = []
     for widget in widgets:
         acc.append(Widget(self.app, widget))
     return acc
 def setUp(self):
     self.widget = Widget('The widget')
示例#19
0
 def __init__(self, options={}):
     self.label = Label()
     self.widget = Widget()
     self.error = Error()
     self.previous_data = options.get('previous_data')
     self.data = None
示例#20
0
文件: edit.py 项目: cznccsjd/StudySe
 def setUp(self):
     self.widget = Widget()
     print "this is setup"
示例#21
0
        #print '          adjusted self BBox=',self.BBox
        widget.set_indent( self.indent )
        
        return widget # for calls like: B = Lay.add_widget( Button() ) 
        
    def recalc(self):
        """Any changes to location of layout requires a recalc"""
        self.set_bbox() # uses current self.Top and self.Left
        for i,widget in enumerate(self.lay_widgetL):        
            if i==0:
                x1 = self.Left
                y0 = self.Top
            else:
                x0,y0,x1,y1 = self.lay_widgetL[i-1].BBox
            
            widget.set_bbox_upper_left(BBTop=y0,  BBLeft=x1)
            self.adjust_bbox_for_widget( widget )
            
            #print "Adjusted HStackPanel's",widget.full_widget_name,'y0=%i'%y0,'x1=%i'%x1


if __name__ == '__main__':
    from widget import Widget
    
    GP = GridPanel( )
    for i in [3,5,9]:
        for j in [2,6,8]:
            GP.add_widget( Widget( widget_type='Button'), row=i, col=j )
    
    GP.add_widget( Widget( widget_type='Button',  Width=100), row=5, col=6 )        
示例#22
0
 def steUp(self):
     self.widget = Widget()
示例#23
0
from widget import Widget

# create instances
a = Widget()
b = Widget()
c = Widget()
d = Widget()

# call instance methods
a.say_hi()  # "I'm widget number 1"
c.say_hi()  # "I'm widget number 3"

# access class methods/properties
Widget.say_num_items()  # "There are 4 Widget instances"
print(Widget.count)  # 4