Exemple #1
0
class Resistance(Sketchy):

    def setup(self):
        width, height = [600, 400]
        self.liquid = Liquid(width/2, height/2, width, height)
        self.balls = []
        for i in range(0, 10):
            self.balls.append(Ball(width, height))
        self.size(width, height)

    def update(self):
        width, height = [600, 400]
        for i in range(len(self.balls)):
            if self.liquid.isInside(self.balls[i]):
                self.balls[i].friction = self.liquid.resist(self.balls[i])
                applyForce(self.balls[i], self.balls[i].wind, self.balls[i].gravity, self.balls[i].friction)
            else:
                applyForce(self.balls[i], self.balls[i].wind, self.balls[i].gravity)
            self.balls[i].update(width, height)
            checkEdges(self.balls[i], width, height)

    def draw(self, g):
        g.background(1, 1, 1)

        self.liquid.draw(g)

        for i in range(len(self.balls)):
            self.balls[i].draw(g)
Exemple #2
0
def test_types():
    tpl = "The current user is {{ user.name }}"
    assert Liquid(tpl).render(user={"name": None}) == 'The current user is '

    tpl = """
    {%- for user in site.users %} {{ user }}
    {%- endfor -%}
    """
    assert Liquid(tpl).render(
        site={"users": ["Tobi", "Laura", "Tetsuro", "Adam"]
              }) == ' Tobi Laura Tetsuro Adam'

    tpl = "{{ site.users[0] }} {{ site.users[1] }} {{ site.users[3] }}"
    assert Liquid(tpl).render(
        site={"users": ["Tobi", "Laura", "Tetsuro", "Adam"]
              }) == 'Tobi Laura Adam'
Exemple #3
0
def test_include_extends_stacks(HERE):
    with pytest.raises(LiquidSyntaxError) as exc:
        liquid = Liquid("""
        {{%- mode compact %}}
        {{% extends {0}/templates/extends.liq %}}
        {{% block b2 %}}
        {{% include "{0}/templates/include4.liq" x %}}
        {{{{x}}}}
        {{% endblock %}}
        """.format(HERE),
                        liquid_loglevel='debug')

    stream = LiquidStream.from_string(str(exc.value))
    _, tag = stream.until(
        ["'for' node expects format: 'for var1, var2 in expr'"])
    assert bool(tag)
    _, tag = stream.until(["File <LIQUID TEMPLATE SOURCE>"])
    assert bool(tag)
    _, tag = stream.until(["> 5."])
    assert bool(tag)
    _, tag = stream.until(["File"])
    assert bool(tag)
    _, tag = stream.until(["> 1. {% include include3.liq %}"])
    assert bool(tag)
    _, tag = stream.until(["File"])
    assert bool(tag)
    _, tag = stream.until(["> 9."], wraps=[])
    assert bool(tag)
Exemple #4
0
def test_dot():
    a = lambda: None
    setattr(a, 'a-b', 1)
    b = lambda: None
    setattr(b, 'a-b', 2)
    assert Liquid("{{a | where: 'a-b', 1 | map: 'a-b' | first}}").render(
        a=[a, b]) == '1'
Exemple #5
0
 def setup(self):
     width, height = [600, 400]
     self.liquid = Liquid(width/2, height/2, width, height)
     self.balls = []
     for i in range(0, 10):
         self.balls.append(Ball(width, height))
     self.size(width, height)
Exemple #6
0
def test_basic_typecasting(set_default_standard):
    assert Liquid('{{ "1" | int | plus: 1 }}').render() == "2"
    assert Liquid('{{ "1" | float | plus: 1 }}').render() == "2.0"
    assert Liquid('{{ 1 | str | append: "1" }}').render() == "11"
    assert Liquid('{{ 1 | bool }}').render() == "True"
    assert Liquid('{{ int("1") | plus: 1 }}').render() == "2"
    assert Liquid('{{ float("1") | plus: 1 }}').render() == "2.0"
    assert Liquid('{{ str(1) | append: "1" }}').render() == "11"
    assert Liquid('{{ bool(1) }}').render() == "True"
Exemple #7
0
def compile_template(template_dict, template_name):
    """Compile template."""
    template_path = "tplbench/engines/liquidpy/"
    template = Liquid(
        template_dict[template_name],
        liquid_config={"extends_dir": [template_path]},
    )
    return template
Exemple #8
0
def test_unless(set_default_standard):
    tpl = """
    {% unless product.title == "Awesome Shoes" %}
      These shoes are not awesome.
    {% endunless %}
    """
    assert (Liquid(tpl).render(product={
        "title": "Not Awesome Shoes"
    }).strip() == "These shoes are not awesome.")

    # in python:
    # bool(0.0) == False
    # bool("") == False
    # assert Liquid('{% unless "" %}1{% endunless %}').render() == ""
    assert Liquid('{% unless "" %}{% else %}1{% endunless %}').render() == ""
    assert Liquid("{% unless 0.0 %}{% else %}1{% endunless %}").render() == ""
    assert Liquid("{% unless empty %}1{% endunless %}").render() == "1"
Exemple #9
0
def test_python_block(set_default_wild):
    tpl = """
    {% python %}
    a = 1
    {% endpython %}
    {{a}}
    """
    assert Liquid(tpl).render().strip() == "1"
Exemple #10
0
    def create_issue(cls, repository, event_object, issue_template=None):
        """
        Create an issue for an event.
        """

        if issue_template:
            with open(issue_template, "r") as template_file:
                liq = Liquid(template_file.read())
                rendered = liq.render(event_object=event_object,
                                      yaml=event_object.to_yaml())
        else:
            rendered = event_object.to_yaml()

        repository.issues.create({
            'title': event_object.name,
            'description': rendered
        })
Exemple #11
0
def test_capture(set_default_standard):
    tpl = """{% capture my_variable %}I am being captured.{% endcapture -%}
    {{ my_variable }}"""
    assert Liquid(tpl).render() == "I am being captured."

    tpl = """
    {% assign favorite_food = "pizza" %}
    {% assign age = 35 %}

    {% capture about_me %}
    I am {{ age }} and my favorite food is {{ favorite_food }}.
    {% endcapture %}

    {{ about_me }}
    """
    assert Liquid(tpl).render().strip() == (
        "I am 35 and my favorite food is pizza.")
Exemple #12
0
def test_or_and():
    tpl = """
    {%- if true or false and false -%}
      This evaluates to true, since the `and` condition is checked first.
    {%- endif -%}
    """
    assert Liquid(tpl).render() == (
        "This evaluates to true, since the `and` condition is checked first.")
Exemple #13
0
def test_raw():
    tpl = """
    {%- raw %}
      In Handlebars, {{ this }} will be HTML-escaped, but
      {{{ that }}} will not.
    {% endraw -%}
    """
    assert Liquid(tpl, dict(debug=True)).render() == """
Exemple #14
0
def test_addfilter_err(set_default_wild):
    tpl = """
    {% addfilter path_join %}
    x = 1
    {% endaddfilter %}
    """
    with pytest.raises(TemplateSyntaxError, match="No such filter defined"):
        Liquid(tpl)
Exemple #15
0
def test_for(set_default_standard):
    tpl = """
    {%- for product in collection.products %} {{ product.title }}
    {%- endfor -%}
    """
    assert (Liquid(tpl).render(
        collection={
            "products": [
                {
                    "title": "hat"
                },
                {
                    "title": "shirt"
                },
                {
                    "title": "pants"
                },
            ]
        }) == " hat shirt pants")

    tpl = """
    {%- for product in collection.products %}
      {{ product.title }}
    {% else %}
      The collection is empty.
    {%- endfor -%}
    """
    assert (Liquid(tpl).render(collection={
        "products": []
    }).strip() == "The collection is empty.")

    assert (Liquid("{{(1..5) | list}}", filters={
        "list": list
    }).render() == "[1, 2, 3, 4, 5]")

    tpl = """
    {% for i in (1..5) %}
    {% if i == 4 %}
        {% break %}
    {% else %}
        {{ i }}
    {% endif %}
    {% endfor %}
    """
    assert Liquid(tpl).render().split() == ["1", "2", "3"]
Exemple #16
0
def test_dot(set_default_standard):
    a = lambda: None
    setattr(a, "a-b", 1)
    b = lambda: None
    setattr(b, "a-b", 2)
    assert (
        Liquid("{{a | where: 'a-b', 1 | map: 'a-b' | first}}").render(a=[a, b])
        == "1"
    )
 def renderTemplate(type, foundation):
     template_file = open(eval('FoundationWelcomeTemplate.' + type), 'r')
     ret = Liquid(template_file.read()).render(**foundation)
     output_file = open(
         "welcome-" + foundation['foundation']['mailing_lists'][type] +
         ".txt", "w")
     output_file.write(ret)
     output_file.close()
     print("Created " + output_file.name)
 def renderTemplate(type, project):
     template_file = open(eval('UmbrellaWelcomeTemplate.' + type), 'r')
     ret = Liquid(template_file.read()).render(**project)
     output_file = open(
         "welcome-" + project['project']['mailing_lists'][type] + ".txt",
         "w")
     output_file.write(ret)
     output_file.close()
     print("Created " + output_file.name)
Exemple #19
0
def test_types(set_default_standard):
    tpl = "The current user is {{ user.name }}"
    assert Liquid(tpl).render(user={}) == "The current user is "

    tpl = """
    {%- for user in site.users %} {{ user }}
    {%- endfor -%}
    """
    assert (
        Liquid(tpl).render(site={"users": ["Tobi", "Laura", "Tetsuro", "Adam"]})
        == " Tobi Laura Tetsuro Adam"
    )

    tpl = "{{ site.users[0] }} {{ site.users[1] }} {{ site.users[3] }}"
    assert (
        Liquid(tpl).render(site={"users": ["Tobi", "Laura", "Tetsuro", "Adam"]})
        == "Tobi Laura Adam"
    )
Exemple #20
0
def test_for_reversed():
    tpl = """
    {% for item in array reversed %}
      {{ item }}
    {% endfor %}
    """
    assert Liquid(tpl).render(array=[1, 2, 3, 4, 5, 6]).split() == [
        "6", "5", "4", "3", "2", "1"
    ]
Exemple #21
0
def build_jvarkit(rev, date=None):
    date = date or get_date_of_commit(rev)
    print("- Rendering meta.yaml ...")
    METAFILE.write_text(
        Liquid(METATPL.read_text()).render(version=date.replace('-', '.'),
                                           rev=rev[:7]))

    print("- Start bulding the package ...")
    cmdy.conda.build(HERE).fg
Exemple #22
0
def test_addfilter(set_default_wild):
    tpl = """
    {% addfilter path_join %}
    import os
    path_join = os.path.join
    {% endaddfilter %}
    {{"a" | path_join: "b"}}
    """
    assert Liquid(tpl).render().strip() == "a/b"
Exemple #23
0
def test_if(set_default_standard):
    tpl = """
    {% if product.title == "Awesome Shoes" %}
      These shoes are awesome!
    {% endif %}
    """
    assert (Liquid(tpl).render(product={
        "title": "Awesome Shoes"
    }).strip() == "These shoes are awesome!")
Exemple #24
0
def test_concat(set_default_standard):
    tpl = """
    {%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
    {%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}
    {%- assign everything = fruits | concat: vegetables -%}
    {%- for item in everything %}
    - {{ item }}
    {%- endfor %}
    """
    assert (
        Liquid(tpl).render()
        == """
    - apples
    - oranges
    - peaches
    - carrots
    - turnips
    - potatoes
    """
    )

    tpl = """
    {%- assign fruits = "apples, oranges, peaches" | split: ", " -%}
    {%- assign furniture = "chairs, tables, shelves" | split: ", " -%}
    {%- assign vegetables = "carrots, turnips, potatoes" | split: ", " -%}
    {%- assign everything = fruits | concat: vegetables | concat: furniture -%}
    {%- for item in everything %}
    - {{ item }}
    {%- endfor %}
    """
    assert (
        Liquid(tpl).render()
        == """
    - apples
    - oranges
    - peaches
    - carrots
    - turnips
    - potatoes
    - chairs
    - tables
    - shelves
    """
    )
Exemple #25
0
def test_truthy_falsy():
    tpl = """
    {% assign tobi = "Tobi" %}

    {% if tobi %}
      This condition will always be true.
    {% endif %}
    """
    assert Liquid(
        tpl).render().strip() == 'This condition will always be true.'

    tpl = """
    {% if settings.fp_heading %}
      <h1>{{ settings.fp_heading }}</h1>
    {% endif %}
    """
    assert Liquid(tpl).render(settings={
        'fp_heading': ''
    }).strip() == '<h1></h1>'
Exemple #26
0
def test_no_parser_liquid_syntax_error():
    liq = Liquid(liquid_loglevel='debug')
    with pytest.raises(LiquidSyntaxError) as exc:
        raise LiquidSyntaxError(
            'message', Diot(
                filename='file',
                lineno=10,
                parser=None,
            ))
    assert "file:10\nmessage" in str(exc.value)
Exemple #27
0
def test_extends_stacks():
    # if lineno is correct
    with pytest.raises(LiquidSyntaxError) as exc:
        liq = Liquid("""
                    {% extends x %}
                    {% if 1 %}
                    {% endif %}
                    """,
                     liquid_loglevel='debug')
    assert '> 2.' in str(exc.value)
Exemple #28
0
def test_case_when(set_default_standard):
    tpl = """
    {% assign handle = handle %}
    {% case handle %}
        {% when "cake" %}
            This is a cake
        {% when "cookie" %}
            This is a cookie
        {% else %}
            This is not a cake nor a cookie
    {% endcase %}
    """
    assert Liquid(tpl).render(handle="cake").strip() == "This is a cake"

    assert (Liquid("""
    {% case true %}
    {% when false %}
    {% endcase %}
    """).render().strip() == "")
def test_find(set_default_jekyll):
    liq = Liquid('{{ obj | find: "a", 1 }}')
    out = liq.render(obj=[
        {
            "a": 1,
            "b": 2
        },
        {
            "a": 2,
            "b": 4
        },
    ])
    assert out == "{'a': 1, 'b': 2}"

    out = liq.render(obj=[])
    assert out == "None"

    out = liq.render(obj=[{}])
    assert out == "None"
Exemple #30
0
    def addLiquid(self, color):
        sx = self.sx
        sy = self.sy - self.height + \
            self.height_per_volume * (self.getNumLiquids())
        liquid = Liquid(sx, sy, self.width, self.height_per_volume, color)
        self.liquids.push(liquid)

        if color not in self.colors:
            self.colors[color] = 0

        self.colors[color] += 1
Exemple #31
0
def test_tablerow_arg_error(set_default_standard):
    tpl = """
    <table>
    {% tablerow product in collection.products limit:"a" %}
      {{ product.title }}
    {% endtablerow %}
    </table>
    """
    with pytest.raises(TemplateSyntaxError,
                       match="Expected an integer or a variable"):
        Liquid(tpl)
Exemple #32
0
def test_raw(set_default_standard):
    tpl = """
    {%- raw %}
      In Handlebars, {{ this }} will be HTML-escaped, but
      {{{ that }}} will not.
    {% endraw -%}
    """
    assert (Liquid(tpl).render() == """
      In Handlebars, {{ this }} will be HTML-escaped, but
      {{{ that }}} will not.
    """)
Exemple #33
0
incoming.bind(('', 1111))

incoming.listen(3)

while True:
     try:
         (client, addr) = incoming.accept()
         header = Header(client.recv(8))
         print("Receiving {} bytes from {}".format(header.size, addr))

         buf = client.recv(header.size - 8)
         while len(buf) < header.size - 8:
              buf += client.recv(header.size - 8 - len(buf))

         liquid = Liquid(buf)

         liquid.treat_hg()
         print("Found {} after mercury".format(len(liquid.hazmats)))
         liquid.treat_pb()
         print("Found {} after lead".format(len(liquid.hazmats)))
         liquid.treat_se()
         print("Found {} after selenium".format(len(liquid.hazmats)))

         print("Found {} hazardous contaminants from {}".format(len(liquid.hazmats),
         addr))

         hazmat_outgoing = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         hazmat_outgoing.connect(("downstream", 8888))
         header.type = 4
         header.size = 8 + 8*len(liquid.hazmats)