c ++ – How to transform Parameter Pack into something other than std :: tuple?

It is best explained by an example:

template 
struct OnePair
{
    using TupleOfArgs = std::tuple;
    using TupleOfPairs = std::tuple>;
};

template 
struct TwoPairs
{
    using TupleOfArgs = std::tuple;
    using TupleOfPairs = std::tuple, std::pair>;
};

template 
struct NPairs
{
    using TupleOfArgs = std::tuple;
//  using TupleOfPairs = ???
};

OnePair defines a tuple with a pair.
TwoPairs defines a tuple with two pairs.

How to define TupleOfPairs in NPairs so that it transforms the parameter pack into std :: tuple of pairs?

Is it possible to achieve this with the std library? Maybe with boost :: mpl?

databases – Need help to understand relational tuple computation

We say that a request in a TRC is a declaration of the form $$ {T: P (T) } $$, or $$ T $$ is a tuple variable and $$ P (T) $$ is a formula.
Now my question is what are the possible T tuples to test, that is, what are the types and values ​​of the tested tuples.
As far as I know in set theory and in particular in set builder notation, the variables should come from another well defined set.

some questions about tuple

I noticed that Tuples[{0, 1}, 3] gives the eight vertices of a cube. Tuples[{0, 1}, 2] gives the four vertices of a square. Tuples[{0, 1}, 1] gives two points of a unitary segment. is it just a coincidence? Or something deeper below?

I don't know it's really Mathmetica question or Math question.

performance – in SQL databases, does an update rewrite all the columns of the row or only those of the tuple SET?

I was wondering how a sql update works in two scenarios:

3 column table: a, b, c

let's say that the data value for a has to be changed.

1: update on a line defining all the columns a, b, c (where b and c have not changed from what is stored)

2: update on a line parameter only a value of the column (since b and c have not changed)

is there a difference in performance between them? I'm having a hard time finding information on how they actually work behind the scenes. from the few articles I found that, in an update, the database:

  • load the row (all columns) in memory
  • set the values ​​of the defined tuple (in order)
  • rewrite the updated line

Tuple Relational Calculus – Find the names of people who own at least one home in every city in Canada

Using the Tuple Relationship Calculator, find the names of people who own at least one home in every city in Canada.

The keys are in bold type.

City(City Name, name of the country, region, population)

House(hno, # rooms, stno, owner's name)

Street(STNO, name of the city, length)

This is what I came up with:

{hostname | House (h) and forAll c (City (c) and c.name = "Canada") ->
(Exists s (Street (s) and s.city-name = c.name) and Exists x (House (x) and x.stno = s.stno and x.owner-name = h.owner-name))}

How I read this out loud: "For all Canadian cities, there is a street with a HOUSE x that has the same owner as the HOUSE H."

Is it correct? I'm pulling my hair to try to understand the relational calculus of the tuples.

Optimization – Group the tuple list in the dictionary optimally in Python

I have a list of tuples with the following structure:

lista = (('A', 25.5), ('B', 0.14), ('C', 0.0),('A', 28), ('C', 0.3), ('B', 0.18), ('A', 23))

I just put A, B and C But it can contain more types.

From this structure, I wish to group them in a dictionary in order to obtain the following result:

salida = {'A': (25.5, 28, 23), 'B': (0.14, 0.18), 'C': (0.0, 0.3)}

I managed to do it with the code transformation function that I put next, but I will have to do it with millions of disks, so it would have to be optimized, because it is likely there are better ways, but I have already struggled a lot with that.

To test, I created a list of 40 million tuples with the function listaPrueba and with the transformation function I took 19.63 seconds.
If someone finds a more effective way, I would appreciate it.

import itertools
import time

numero = 10000000

def listaPrueba(num):
    return (('A', 1), ('B', 2), ('C', 3), ('D', 4)) * num
lst_Pruebas = listaPrueba(numero)


def transformar(lista, diccionario={}):
    for clave, grupo in itertools.groupby(lista, lambda x: x(0)):
        for elemento in grupo:
            diccionario.setdefault(clave, ()).append(elemento(1))
    return diccionario


inicio = time.perf_counter()
salida = transformar(lst_Pruebas)

print(f'Tiempo: {time.perf_counter()-inicio}')


assert sum(salida('A')) == numero * 1
assert sum(salida('B')) == numero * 2
assert sum(salida('C')) == numero * 3
assert sum(salida('D')) == numero * 4

I've used itertools because I imagine it will be optimized for iterations, but I'm not sure, so I do not care how to fix it.

python – Loop through a tuple in Python3

Not sure if the name really matches the question, but let's say that my tuple is 3 elements long and if I want to address item 5, it will deal with item 2 because it has gone through all the tuple and went back to the beginning.

tupExample = ('foo','bar')
print(tupExample(3))

Exit:

foo

lua – Rule-Based Tuple Rewrite Language with IF Sample Game

I'm working on a minimalist DSL connection for creating interactive fiction and would like to have it reviewed. I am more interested in getting feedback on the language itself and ideas for improvement, but of course, comments on implementation are also welcome.

The project is tentatively titled "RIFE" for "Rules-Based Interactive Fiction Engine".

Here is a summary describing the language. It aims to be deepened,
but not overwhelming. Let me know if anything is confusing
or should be described in more detail.


Overall view

A program is composed of statements and rules.
The instructions define the current state of the program and
the rules describe the state transformations that can occur
during the execution of the program, when the appropriate conditions are met.
State transformations are performed by creating new instructions,
or remove the old ones, or both.

Statements

Each statement is represented as a tuple, composed of items.
There are two types of syntax for items in a tuple of statements:
words are sequences of non-space characters, and
sentences are character sequences enclosed in quotation marks.
There is no difference between them other than the most flexible
syntax for sentences, which can span multiple lines and include spaces.

Each instruction tuple contains at least one element.
The elements of a tuple are separated by spaces.
Declaration tuples are separated from each other
either with line breaks or with . character.
A line containing instructions should have no white space at the beginning.
Here is an example of four statements:

player is in foyer. cloakroom is west of foyer.
cloakroom is called "the cloakroom"
player moves west

Rules

Each rule has two parts, one question part followed by a result part.
The query and result parts each contain a list of tuples,
similar to the tuples described above.

  • In addition to words and sentences,
    these tuples may contain variables:

    • Scalar variables look like ordinary words preceded by the prefix $.

    • List variables also look like normal words, preceded by a @.

  • Each tuple of the query part is ended by ,, ; or ?.

    • Tuples completed by , are called reagents.

    • Tuples completed by ; are called reagents.

    • Tuples completed by ? are called catalysts.

The query part of a rule starts at the beginning of a line,
and the result part has white spaces.
The result part of a rule contains zero or more some products.
Each product looks like a statement,
except that it must be indented and may contain variables.
If a rule contains no product, only one point must be written
in the result section to indicate the end of the rule.

Here is an example of a rule:

player moves $direction, player is in $place,
$destination is $direction of $place?
    player is in $destination.

Scalar variables

The example rule above
corresponds to the examples of instructions described previously.
Here is how it works.

The tuples in the query are matched in a left-to-right order.
the player moves $direction matches player moves west,
and the $direction the variable is linked to the word west.
Similarly, player is in $place matches,
leaving $place linked to foyer.

The last tuple of the query is
$destination is $direction of $place.
Since $direction is now linked to west,
and $place is linked to foyer,
it's equivalent to $destination is west of foyer,
which corresponds to the cloakroom is west of foyer declaration,
restrictive $destination at cloakroom.

Since each part of the request corresponds to a declaration,
the rule is applied successfully.

List variables

List variables work similarly to scalar variables.
but they can succeed in matching any number of elements (including zero).
No more than one list variable is allowed per request tuple
(ie one per reagent, reagent or catalyst).

Here is an example of a rule containing a list variable:

you @act,
    player wants to @act.

This will correspond to statements like you look, you look at message,
or simply you.

Reagents and catalysts

When a rule is applied successfully,
all the instructions corresponding to the reagents (parts of the query completed by ,)
are removed from the program.
Declarations corresponding to catalysts (parts of the query completed by ?)
stay in the program.
The results of the rule are added as new instructions,
with all the variables replaced by their related values.

Use a catalyst to check the existence of a statement
without removing it.
Use a reagent to delete the corresponding instruction
in case of successful application of a rule.

Continuing with our example, applying the rule
leads to the deletion of the
player moves west and player is in foyer statements
and the addition of a new player is in cloakroom declaration.

Several variables can exist in a single element of a result.
all will be replaced by their related values.
This is usually used to build dynamic sentences,
but is also allowed in the word elements.

Reagents

Reagents (parts of the query completed by ;) are similar to the reagents,
except that when a rule containing reagents is successfully applied,
the rule is immediately applied repeatedly,
until it can no longer match anything new.

The instructions for the query parts containing the reagents are not deleted
until after these repeated applications of the rule.
Used with catalysts, the reagents are suitable for
iterate over several similar statements.

Here is an example of a rule containing a reagent:

$somebody tries to drop all; $somebody has $item?
    $somebody wants to drop $item.

assume Bob tries to drop all, Bob has apple, and Bob has banana
are all the existing statements. When the rule is applied,
Bob wants to drop apple and Bob wants to drop banana are created,
and finally Bob tries to drop all is removed.

Default values

It is possible to assign a default value to a scalar variable.
Consider the following rules:

game ends because you $left, turn count is $turns, your score is $score,
    say "You $left the game after $turns turns with a final score of $score."
    issue game command quit

game ends because you $left, turn count is $turns,
    say "You $left the game after $turns turns with a final score of 0."
    issue game command quit

game ends because you $left, your score is $score,
    say "You $left the game after 0 turns with a final score of $score."
    issue game command quit

game ends because you $left,
    say "You $left the game after 0 turns with a final score of 0."
    issue game command quit

It is possible that no statement exists
turn count is $turns or your score is $score, so
we need four rules to handle all possible combinations.
If we were to test a third statement that might not exist,
the number of rules would be double.

To handle this, a default value can be assigned to variables by placing
the value after the name of the variable, separated by a | character.
Here is the previous example, using a single rule:

game ends because you $left, turn count is $turns|0, your score is $score|0,
    say "You $left the game after $turns turns with a final score of $score."
    issue game command quit

A default value should only be placed on the first appearance of
a variable in a rule. When part of the query of a rule does not match anything,
If it contains variables with default values, the default values ​​are linked
to these variables and this part of the correspondence is considered successful.

Variable Expansion

Normally, a variable that appears in the product of a rule expands to
whatever the value to which it is linked.
This behavior can be modified with a special syntax:

  • $var# expands to the decimal representation of the number of characters
    in the chain related to $var.
    This can be used for unary to decimal conversion.

  • $var#2 develops at the second character of the chain related to $var.

  • $var+2 extends to all the characters of the second character in $var;
    it removes the first character.

  • $var*c or $var is bound to a value representing a positive integer
    grows into a string containing this number of characters "c".
    This can be used for a decimal to unary conversion.

Execution of the program

A program runs from a host application.
The host application is responsible for loading
and run the program.
Typically, the host application loads a program once,
then run it repeatedly in a loop.

When the program loads,
all instructions and rules are analyzed.
These are stored in two separate lists,
in the order in which they appear in the source file.
When the program is started,
each rule is tested against each statement.
When a rule matches a statement successfully, it is applied.
If the rule contains no reagent, the application is simple.
Declarations that the corresponding reagents are removed,
and the products (parts of result) of the rule are
placed at the end of the list of declarations.

If the rule contains reagents:

  1. All statements corresponding to the catalysts are removed from their
    current positions, and placed at the end
    from the list of declarations.

  2. The products of the rule are placed at the end
    from the list of declarations.

  3. Another match is attempted with the same rule.
    If it corresponds to something new, go back to step 1.
    Otherwise, go to step 4.

  4. Finally, delete all statements that match the reagents in the rule.

Note that in step 3, "corresponds to something new"
means that the rule corresponds to something different from
declarations matched with catalysts at the first iteration
of the current rule application.

This process is repeated for each rule
until no more rules can be applied.

At this point, the control is returned to the host application,
who will usually extract some statements,
produce something based on these statements,
query for user input, create new instructions from the input,
and run the program again.


cape.rifier

A port of Roger Firth's cloak of darkness to the tongue, with some extra props and objects thrown for test purposes.

# Cloak of Darkness
#
# This is a third-party port of Roger Firth's Cloak of Darkness example,
# which has been described as the "Hello World" of interactive fiction.
#
# This port exists to demonstrate an experimental programming language
# and minimal platform for authoring interactive fiction (RIFE).
#
# Roger Firth is the original author of most prose in this file.
# His Cloak of Darkness ports are not distributed with any license.
# Any use of copyrighted material here is intended as "fair use,"
# as described in Title 17 U.S.C. Section 107.
#
# See http://www.firthworks.com/roger/cloak/index.html

say "Cloak of Darkness: A basic IF demonstration."

# Foyer

player is in foyer
foyer is called "Foyer of the Opera House"
foyer is described as "
    You are standing in a spacious hall,
    splendidly decorated in red and gold,
    with glittering chandeliers overhead.
    The entrance from the street is to the north,
    and there are doorways south and west."

player tries to move north, player is in foyer?
    say "You've only just arrived, and besides, 
        the weather outside seems to be getting worse."

# Cloakroom

cloakroom is west of foyer. cloakroom is called "The Cloakroom"
cloakroom is described as "
    The walls of this small room
    were clearly once lined with hooks,
    though now only one remains.
    The exit is a door to the east."

cloakroom features hook.
hook is called "small brass hook"
hook is described as "It's just a small brass hook, screwed to the wall."
garment can be hanging on hook.

player examines hook,
    summarize things on hook as hooked.

after summarizing hooked list, hooked list summary is $stuff,
    say "It's just a small brass hook, with $stuff hanging on it."

after summarizing hooked list, hook is described as $description?
    say $description

# an extra container, for testing

cloakroom features barrel.
barrel is called "wooden barrel"
barrel is described as "The barrel seems out of place here."
anything can be sitting in barrel.

potato is called an "old potato"
potato is described as "It looks back at you."
potato is in cloakroom.
potato is in barrel.
potato is a type of food.

banana is called a "brown banana"
banana is described as "It's appealing."
banana is in cloakroom.
banana is on ground.
banana is a type of food.

# Bar

bar is south of foyer. bar is dark. bar is called "Foyer Bar"
bar is described as "
    The bar, much rougher than you'd have guessed
    after the opulence of the foyer to the north,
    is completely empty.
    There seems to be some sort of message
    scrawled in the sawdust on the floor."

bar features message
message is neat

you read message,
    you examine message

player examines message, player is in bar? bar is lit? message is trampled?
    say "The message has been carelessly trampled,
        making it difficult to read.
        You can just distinguish the words..."
    game ends because you lost.

player examines message; player is in bar? bar is lit?
    score 1 points.
    say "The message, neatly marked in the sawdust, reads..."
    game ends because you won.

player fails to move $direction, player is in bar? bar is dark?
    say "Blundering around in the dark isn't a good idea!"
    message is disturbed.

message is disturbed, message is neat,
    message is scuffed.

message is disturbed, message is scuffed,
    message is trampled.

message is disturbed,
    .

# Inventory

player has cloak.

cloak is a type of garment. cloak is called a "velvet cloak"
cloak is described as "A handsome cloak, of velvet trimmed with satin,
    and slightly splattered with raindrops. Its blackness is so deep that
    it almost seems to suck light from the room."

# Cloak fiddling

cloak has not been hung.

you hang cloak on hook,
    you put cloak on hook.

cloak has not been hung, cloak is on hook?
     score 1 points.

player puts cloak on hook? bar is dark,
    bar is lit.

player takes cloak? bar is lit,
    bar is dark.

player wants to drop cloak, player is in cloakroom?
    player tries to drop cloak.

player wants to drop cloak,
    decide to keep cloak.

player wants to put cloak @somewhere, player is in cloakroom?
    player tries to put cloak @somewhere.

player wants to put cloak @somewhere,
    decide to keep cloak.

decide to keep cloak,
    say "This isn't the best place to leave a smart cloak lying around."

# More random inventory stuff, for testing

player has onion.

onion is called an "odorous onion"
onion is described as "This onion smells pretty bad."

player has pants.

pants is a type of garment. pants are called some "leather pants"
pants is described as "Those are some snappy leather pants."

# Intro text

say "Hurrying through the rainswept November night,
    you're glad to see the bright lights of the Opera House.
    It's surprising that there aren't more people about but, hey,
    what do you expect in a cheap demo game...?"

# Load general data and rules from core.rife (always do this last).

(load core)


core.rife

General rules of the game and data, loaded by cape.rifier.

# General rules and statements.

# Always load this last; some routines depend on it.
# For example, some routines may clean up after themselves
# if earlier (game) rules don't intercept the data first.

# Directions.

east is a direction
west is a direction
north is a direction
south is a direction

northeast is a direction
northwest is a direction
southeast is a direction
southwest is a direction

east is the opposite of west
west is the opposite of east
north is the opposite of south
south is the opposite of north

northeast is the opposite of southwest
northwest is the opposite of southeast
southeast is the opposite of northwest
southwest is the opposite of northeast

# Prepositions.

in is the opposite of out
out is the opposite of in
off is the opposite of on
on is the opposite of off

# Global containers.

everywhere features ground
anything can be lying on ground

# Aliases.

# Most of the old Infocom shortcuts are here,
# except `g` for repeating the last command.
# Launch under `rlwrap` for command history.

e means east
w means west
n means north
s means south

ne means northeast
nw means northwest
se means southeast
sw means southwest

u means up
d means down

i means inventory
x means examine
l means look
q means quit

#
# First-person commands for player.
#

# Game commands.

you debug @level,
    issue game command debug @level.

you dump $info,
    issue game command dump $info.

you save $path,
    issue game command save $path.

you load $path,
    issue game command load $path.

you quit,
   game ends because you quit.

# Intend to do stuff before attempting to do it,
# so we can intercept desires, impose extra conditions,
# then begin attempts if the desires aren't rejected.

you $direction, $direction is a direction?
    player wants to move $direction.

you go $direction,
    player wants to move $direction.

you get $something,
    player wants to take $something.

you pick up $something,
    player wants to take $something.

you pick $something up,
    player wants to take $something.

you put down $something,
    player wants to drop $something.

you put $something down,
    player wants to drop $something.

you examine,
    player wants to look.

you look at $something,
    player wants to examine $something.

you inventory,
    player wants to check inventory.

you $alias @stuff, $alias means $do?
    you $do @stuff.

you @act,
    player wants to @act.

# If we still intend to do something, attempt to do it.

# Instant actions. No time passes, but these can still fail.

player wants to look,
    player tries to look.

player wants to examine $something,
    player tries to examine $something.

player wants to check inventory,
    player tries to check inventory.

# Attempting all other actions takes a turn.

player wants to @act,
    player tries to @act.
    time passes.

$somebody wants to @act,
    $somebody tries to @act.

# Travel.

$somebody tries to move $direction, $somebody is in $place,
$destination is $direction of $place?
    $somebody travels to $destination.

$somebody tries to move $direction, $somebody is in $place,
$direction is the opposite of $opposite?
$place is $opposite of $destination?
    $somebody travels to $destination.

$somebody tries to move $direction,
    $somebody fails to move $direction.

$somebody travels to $destination,
    $somebody is in $destination.
    $somebody tries to look.

player fails to move $direction,
    say "You can't go $direction from here."

$somebody fails to move $direction,
    .

# Examining things / looking around.

player tries to look, player is in $place? $place is dark?
    say "A Dark Place"
    say "It's too dark to see anything here."

player tries to look, player is in $place?
$place is called $name?
$place is described as $description?
    say $name. say $description.
    see containers in $place.
    see global containers in $place.

see global containers in $here; everywhere features $container?
$stuff can be $placed $in $container?
    regarding things $placed $in $container
    summarize things $in $container $here as "things $placed $in $container"

see global containers in $here,
    .

see containers in $here; $here features $container?
$stuff can be $placed $in $container?
    regarding things $placed $in $container
    summarize things $in $container $here as "things $placed $in $container"

see containers in $here,
    .

# containers with a single item
regarding things $placed $in $container,
after summarizing "things $placed $in $container" list,
$something is $in $container? $something $is called $a $thing?
"things $placed $in $container" list summary is "$a $thing",
    say "$a $thing $is here, $placed $in the $container."

# containers with multiple items
regarding things $placed $in $container,
after summarizing "things $placed $in $container" list,
"things $placed $in $container" list summary is $things,
    say "$things are here, $placed $in the $container."

# containers with no items
regarding things $placed $in $container,
after summarizing "things $placed $in $container" list,
    .

player tries to examine $something,
player is in $place? $place is dark?
    say "It's too dark to see anything here."

$somebody tries to examine $something,
$somebody has $something?
    $somebody examines $something.

$somebody tries to examine $something,
$somebody is in $place? $something is in $place?
    $somebody examines $something.

$somebody tries to examine $something,
$somebody is in $place? $place features $something?
    $somebody examines $something.

player tries to examine $something,
    say "You don't see anything like that here."

player examines $something, $something is described as $description?
    say $description.

player examines $something,
    say "You don't see anything special about it."

# Drop all items.

$somebody tries to drop all; $somebody has $item?
    $somebody wants to drop $item.

player tries to drop all,
    say "You don't have anything."

# Take all items.

$somebody tries to take all; $somebody is in $place?
$item is in $place? $item $is called $a $name?
    $somebody wants to take $item.

player tries to take all,
    say "You don't see anything useful here."

# Drop item.

$somebody tries to drop $item, $somebody has $item,
    $somebody drops $item.

player tries to drop $item,
    say "You don't have that."

player drops $item, player is in $place? $item $is called $a $name?
    $item is in $place. $item is on ground.
    say "You drop the $name."

# Put item in container.

player tries to put $item $in $container, player has $item?
everywhere features $container?
    player starts to put $item $in $container.

player tries to put $item $in $container, player has $item?
player is in $place? $place features $container?
    player starts to put $item $in $container.

player starts to put $item $in $container,
anything can be $placed $in $container?
    player puts $item $in $container

player starts to put $item $in $container,
$item is a type of $stuff? $stuff can be $placed $in $container?
    player puts $item $in $container

player starts to put $item $in $container,
    say "You consider trying to put the $item $in the $container,
        but decide against it."

player tries to put $item $in $container, player has $item?
    say "You don't see anything like that here."

player tries to put $item $in $container,
    say "You don't have that."

player puts $item $in $container, $item $is called $a $name?
player has $item, player is in $place?
    $item is in $place. $item is $in $container.
    say "You put the $name $in the $container."

# Take item.

$somebody tries to take $item, $somebody is in $place?
$item is in $place, $item $is called $a $name?
    $somebody takes $item.

$somebody takes $item, $item $is called $a $name?
     $somebody has $item. $somebody takes $item called $name.

$somebody takes $item,
     $somebody has $item. $somebody takes $item called $item.

player takes $item called $thing, $item is $in $container,
$stuff can be $placed $in $container?
$out is the opposite of $in?
    say "You take the $thing $out of the $container."

player takes $item called $thing, $item is $in $container,
$stuff can be $placed $in $container?
    say "You take the $thing from $in the $container."

player takes $item called $thing,
    say "You take the $thing."

player tries to take $feature,
player is in $place? $place features $feature?
    say "You can't take that with you."

player tries to take $item,
    say "You don't see anything like that here."

$somebody takes $item called $name,
    .

# List inventory

player tries to check inventory,
    inventory list is
    build inventory list
    summarize inventory list

build inventory list; inventory list is @list,
player has $item? $item $is called $a $name?
    inventory list is "$a $name" @list

build inventory list, inventory list is @list, summarize inventory list,
    say "You aren't carrying anything."

after summarizing inventory list, inventory list summary is $stuff,
    say "You are carrying $stuff."

# List things in container
# TODO: for portable containers, do the same thing without $here

summarize things $in $container $here as $contents,
    $contents list is
    summarize $contents list
    build list of $contents $in $container $here

build list of $contents $in $container $here; $contents list is @list,
$item is $in $container? $item $is called $a $name? $item is in $here?
    $contents list is "$a $name" @list

build list of $contents $in $container $here, $contents list is @list,
$contents list summary is $stuff,
    .

# Summarize a list of things.

summarize $thing list, $thing list summary is $summary|,
    $thing list summary is ""
    continue summarizing $thing list

continue summarizing $thing list?
$thing list is $first, $thing list summary is "",
    $thing list summary is "$first"

continue summarizing $thing list?
$thing list is $first $second, $thing list summary is "",
    $thing list summary is "$first and $second"

continue summarizing $thing list?
$thing list is $first, $thing list summary is $stuff,
    $thing list summary is "$stuff, and $first"

continue summarizing $thing list?
$thing list is $first @rest, $thing list summary is "",
    $thing list is @rest
    $thing list summary is "$first"

continue summarizing $thing list?
$thing list is $first @rest, $thing list summary is $stuff,
    $thing list is @rest
    $thing list summary is "$stuff, $first"

continue summarizing $thing list,
    after summarizing $thing list

after summarizing $thing list,
    .

# Scoring.

new score tally is $tally,
    your score is $tally#

score $points points, your score is $score|0,
    new score tally is $points*I$score*I
    say "Your score increased by $points."

# Turn count.

new turn count tally is $tally,
    turn count is $tally#

time passes, turn count is $turns|0,
    new turn count tally is I$turns*I

# Remove unhandled commands.

player tries to @act,
    say "Huh?"

$somebody tries to @act,
    .

# Game commands.

say $something,
    issue game command print $something

game ends because you $left, turn count is $turns|0, your score is $score|0,
    say "You $left the game after $turns turns with a final score of $score."
    issue game command quit


rife.lua

The game engine.

-- RIFE: a Rule-based Interactive Fiction Interpreter
-- Game launcher.

-- Protect against accidental globals.
setmetatable(_G, {
    __index = function(_, v) error('Referenced undefined global: ' .. v) end,
    __newindex = function(_, v) error('Attempt to create global: ' .. v) end,
})

local Interpreter = require 'interpreter'

-- Game class. Sets up interpreter and loads a program.
local Game = Interpreter.Class()

function Game:init(path)
    self.interpreter = Interpreter(path)
    self.commandRule = Interpreter.Rule()
    self.commandRule:parseQueryLine('issue game command $name @args,')
    self.gameOver = false
    return self
end

-- Set interpreter debug level. Called from extracted game command.
function Game:debug(level)
    level = tonumber(level) or level == 'off' and 0 or 1
    self.interpreter.debugLevel = level
    self:print(level == 1 and 'debug mode on.' or 'debug mode off.')
end

-- Dump program rules or data. Called from extracted game command.
function Game:dump(what)
    if what == 'rules' then
        self.interpreter:dumpRules()
    elseif what == 'data' then
        self.interpreter:dumpData()
    end
end

local function printLine(line)
    io.stdout:write('  ', line, 'rn')
end

local WRAP_COL = 70
local SPACE = 32
local BREAK = 10

-- Print a message.
-- Use word wrap and markdown-style line breaks and whitespace.
-- Called from extracted game command.
function Game:print(message)
    message = (message or '')
        :gsub('^.', string.upper):gsub('t', ' ')
        :gsub('n +', 'n'):gsub('nn+', 'r')
        :gsub('n', ' '):gsub('r', 'n')
        :gsub(' +', ' '):gsub('^ +', '')

    printLine('')
    while true do
        for i = 1, math.min(#message, WRAP_COL) do
            if message:byte(i) == BREAK then
                printLine(message:sub(1, i))
                message = message:sub(i + 1, -1)
                i = 1
            end
        end
        if #message < WRAP_COL then
            printLine(message)
            return
        end
        local i = WRAP_COL
        while i > 0 and message:byte(i) ~= SPACE do
            i = i - 1
        end
        printLine(message:sub(1, i))
        message = message:sub(i + 1, -1)
    end
end

-- Save game. Called from extracted game command.
function Game:save(name)
    local path = name .. '.save'
    local file = assert(io.open(path, 'w'))
    local data = self.interpreter.data
    for i = 1, #data do
        file:write('"', table.concat(data(i).value, '" "'), '"n')
    end
    file:close()
    self:print('Game "' .. name .. '" saved.')
end

-- Load game. Called from extracted game command.
function Game:load(name)
    local path = name .. '.save'
    self.interpreter.data = {}
    self.interpreter:loadProgram(path)
    self:print('Game "' .. name .. '" loaded.')
    self:issuePlayerCommand('look')
end

-- Quit game. Called from extracted game command.
function Game:quit()
    self.gameOver = true
end

-- Exctract, execute, and remove game commands.
function Game:invokeCommands()
    local _, binds, i = self.interpreter:matchRule(self.commandRule)
    while binds do
        table.remove(self.interpreter.data, i)
        local args = binds('@args')
        self(binds('$name'))(self, args(1), args(2), args(3))
        _, binds, i = self.interpreter:matchRule(self.commandRule)
    end
end

-- Handle player input, then apply rules and extract game commands.
-- Player input is converted to a tuple and appended to the dataset.
-- A `you` is inserted at the front of the tuple to prevent cheating.
function Game:issuePlayerCommand(text)
    self.interpreter:createData('you ' .. (text or ''))
    self.interpreter:applyRules()
    self:invokeCommands()
end

-- Warmup and main loop.
function Game:run()
    -- Apply rules first to print title screen info, etc.
    -- Wait for player to hit enter; discarding input...
    self.interpreter:applyRules()
    self:invokeCommands()
    io.stdout:write('rn  (press enter) ')
    io.stdin:read()

    -- ...then issue a "look" command to show the first room.
    self:issuePlayerCommand('look')

    -- Main loop.
    while not self.gameOver do
        io.stdout:write('rn> ')
        self:issuePlayerCommand(io.stdin:read())
    end
    io.stdout:write('rn')
end

-- Load and run the game specified on command line, or "cloak."
Game((...) or 'cloak.rife'):run()


interpreter.lua

The language interpreter. Charged by rife.lua.

-- RIFE: a Rule-based Interactive Fiction Interpreter
-- Language interpreter

local _ -- Dummy variable

-- Simple class implementation.
local classMeta = {
    __call = function(proto, ...)
        local object = setmetatable({}, { __index = proto })
        if object.init then object:init(...) end
        return object
    end
}

local function Class()
    return setmetatable({}, classMeta)
end

-- "Parser" helper functions

local sentinelPattern = '~`%s`~'
local sentinelsBySymbol = {}
local symbolsBySentinel = {}
local sentinelMatcher = sentinelPattern:format('%d+')
local symbolMatcher

local function defineSentinels(t)
    for i = 1, #t do
        local sentinel = sentinelPattern:format(i)
        local symbol = t(i)
        sentinelsBySymbol(symbol) = sentinel
        symbolsBySentinel(sentinel) = symbol
    end
    symbolMatcher = ('(%s)'):format(table.concat(t))
end

defineSentinels { ' ', ',', ';', '?', '.' }

local function escapeCb(text)
    return text:gsub(symbolMatcher, sentinelsBySymbol)
end

local function unescapeCb(text)
    return text:sub(2, -2):gsub(sentinelMatcher, symbolsBySentinel)
end

local function escape(text)
    return text:gsub('%b""', escapeCb)
end

local function unescape(text)
    return text:gsub('%b""', unescapeCb)
end

local function split(text, type)
    local r = { type = type }

    for word in text:gmatch('(^ )+') do
        r(#r + 1) = unescape(word)
    end
    return r
end

-- Check if some text represents a scalar variable
local function isScalarVariable(text)
    return text:find('^%$(%w_)+$') and true or false
end

-- Check if some text represents a list variable
local function isListVariable(text)
    return text:find('^@(%w_)+$') and true or false
end

-- Get indices for table.concat, using rules like string.sub
local function tableSubBounds(t, i, j)
    local n = #t
    i, j = tonumber(i) or 1, tonumber(j) or n
    if i < 0 then i = n + 1 + i end
    if j < 0 then j = n + 1 + j end
    if i < 1 then i = 1 end
    if j > n then j = n end
    return i, j
end

-- Like table.concat, but support negative indices
-- and correct out-of-bounds indices like string.sub
local function tableSub(t, sep, i, j)
    i, j = tableSubBounds(t, i, j)
    if i > j then return '' end

    return table.concat(t, sep, i, j)
end

-- Expand all variables in some text, using values in `binds`
local function expandVariables(text, binds)
    return text
        -- variable count or index
        :gsub('((@$)(%w_)+)(#)(%d*)', function(m, num, index)
            local value = binds(m)
            if not value then return '' end
            local n = #value
            if index == '' then return n end
            if type(value) == 'table' then
                return value(index)
            else
                return value:sub(index, index)
            end
        end)
        -- convert to unary
        :gsub('(%$(%w_)+)%*(.)', function(m, char)
            local value = tonumber(binds(m):match('^%d+$'))
            if not value then return '' end
            return char:rep(value)
        end)
        -- variable, optionally trimmed
        :gsub('((@$)(%w_)+)((+-)?%d*)((+-)?%d*)', function(m, from, to)
            local value = binds(m)
            if not value then return '' end
            if type(value) == 'table' then
                return tableSub(value, '', from, to)
            else
                return value:sub(tonumber(from) or 1, tonumber(to) or -1)
            end
        end)
end

-- Concatenate line of text to a field of table `t`.
local function appendFieldText(t, field, text)
    t(field) = (t(field) and (t(field) .. 'n') or '') .. text
end

-- Rule class.
-- A rule represents a possible state transformation of the program data.
-- It has two parts, a query and a result. The query part is used to
-- check if a rule should be applied to the current program data, and to
-- determine any data that should be removed on successful application.
-- The result part represents new data produced on successful application.
local Rule = Class()

function Rule:init()
    self.query = {}
    self.result = {}
    self.hasReagents = false
end

function Rule:isEmpty()
    return #self.query == 0 and #self.result == 0
end

-- Parse a line of text representing part of a query.
-- Update this rule with the extracted information.
function Rule:parseQueryLine(text)
    appendFieldText(self, 'queryText', text)
    for tuple, terminator in escape(text):gmatch('((^,;?)+)(.?)') do
        if terminator == ',' then
            self:addReactant(tuple)
        elseif terminator == ';' then
            self:addReagent(tuple)
        elseif terminator == '?' then
            self:addCatalyst(tuple)
        else
            error('Invalid rule: ' .. text)
        end
    end
end

-- Parse a line of text representing part of a result.
-- Update this rule with the extracted information.
function Rule:parseResultLine(text)
    appendFieldText(self, 'resultText', text)
    for tuple in escape(text):gmatch('(^.)+') do
        self:addProduct(tuple)
    end
end

-- Check query for list matcher; store index if it exists.
-- Store default values for variables.
-- Throw error if multiple list matchers exist.
-- Throw error if default value appears twice for same variable.
local function prepareQuery(query)
    local listMatcherCount = 0
    query.default = {}
    for i = 1, #query do
        if isListVariable(query(i)) then
            listMatcherCount = listMatcherCount + 1
            query.listMatcherIndex = i
        end

        if listMatcherCount > 1 then
            error("Multiple list matchers in query:n" ..
                table.concat(query, ' '))
        end

        local var, default = query(i):match('^(%$(%w_)+)|(.*)$')
        if default then
            if query.default(var) then
                error("Default value appears twice for same variable:n" ..
                    table.concat(query, ' '))
            end
            query.default(var) = default
            query(i) = var
            query.hasDefaults = true
        end
    end
    return query
end

-- Extract a "reactant" from `text`, and add it to the rule's query part.
-- Reactants are parts of a query which are removed from the dataset
-- immediately during the successful application of a rule.
function Rule:addReactant(text)
    self.query(#self.query + 1) = prepareQuery(split(text, 'reactant'))
end

-- Extract a "reagent" from `text`, and add it to the rule's query part.
-- Reagents are parts of a query which are removed from the dataset
-- after a rule is fully applied.
function Rule:addReagent(text)
    self.query(#self.query + 1) = prepareQuery(split(text, 'reagent'))
    self.hasReagents = true
end

-- Extract a "catalyst" from `text`, and add it to the rule's query part.
-- Catalysts are parts of a query which are not removed from the dataset
-- when a rule is sucessfully applied.
function Rule:addCatalyst(text)
    self.query(#self.query + 1) = prepareQuery(split(text, 'catalyst'))
end

-- Extract a "product" from `text`, and add it to the rule's result part.
-- Products represent new tuples to be appended to the dataset
-- when a rule is sucessfully applied.
function Rule:addProduct(text)
    self.result(#self.result + 1) = split(text, 'data')
end


-- Data class.
-- A tuple representing a single datapoint in the program data.
-- Used for statements appearing in the program, and for
-- products resulting from the successful application of rules.
local Data = Class()

function Data:init(value)
    self.value = value
end

function Data:isEmpty()
    return #self.value == 0
end

-- Expand all variables in the data, based on the values in `binds`.
-- Expansion of list matcher variables may result in a change in the number
-- of elements in the resulting tuple.
function Data:expandVariables(binds)
    local oldValue = self.value
    self.value = {}
    local k = 0
    for i = 1, #oldValue do
        local m, from, to = oldValue(i)
            :match('^(@(%w_)+)((+-)?%d*)((+-)?%d*)$')
        if m and binds(m) then
            -- list matcher, single element
            from, to = tableSubBounds(binds(m), from, to)
            for j = from, to do
                k = k + 1
                table.insert(self.value, k, binds(m)(j))
            end
        else
            -- normal element
            k = k + 1
            self.value(k) = expandVariables(oldValue(i), binds)
        end
    end
    return self
end

-- Parse a line of text containing data statements.
-- Extract each statement and create a new data tuple from it.
-- Return a list of extracted statements.
function Data.parseLine(text)
    local statements = {}
    for statement in escape(text):gmatch('(^.)+') do
        local data = Data(split(statement, 'data'))
        statements(#statements + 1) = data
    end
    return statements
end

-- Interpreter class. Loads and runs code written in our DSL.
local Interpreter = Class()

function Interpreter:init(path)
    self.rule = {}
    self.data = {}
    self.debugLevel = 0

    if path then self:loadProgram(path) end
end

-- Load and parse a program given a file path.
-- Populates the list of rules and initial program dataset.
-- Call this from the host application.
function Interpreter:loadProgram(path)
    local file = assert(io.open(path, 'r'))

    local section = 'rules'
    local part = 'query'
    local currentRule = Rule()

    -- Very quick and dirty line-by-line parsing.
    local line = file:read('*l')
    while line do
        line = line:gsub('r', '')
        -- while line has unbalanced quotes, append next line
        -- (allows multi-line quoted phrases).
        while select(2, line:gsub('"', {})) % 2 == 1 do
            line = line .. 'n' .. file:read('*l')
        end

        if line:find('^%s*%(') then
            -- preprocessor directive
            local command, arg = line:match('^%s*%(((%w_)+)%s+(.*))%s*$')
            if command == 'load' then
                self:loadProgram(arg .. '.rife')
            else
                error('Bad preprocessor directive: ' .. line)
            end
        elseif line:find('^%s*#') then
            -- ignore comment
        elseif line:find('^%s*$') then
            -- ignore blank line
        elseif line:find('(,;?)%s*$') then
            if part ~= 'query' then
                -- transition to new rule.
                -- add the current rule and ready the next one.
                self:addRule(currentRule)
                currentRule = Rule()
            end
            part = 'query'
            currentRule:parseQueryLine(line)
        elseif line:find('^%s') then
             -- result parts have leading whitespace
            part = 'result'
            currentRule:parseResultLine(line)
        else
            if part ~= 'data' then
                -- transition to data.
                -- add the current rule and ready the next one.
                self:addRule(currentRule)
                currentRule = Rule()
            end
            part = 'data'
            local statements = Data.parseLine(line)
            for i = 1, #statements do
                self:addData(statements(i))
            end
        end

        line = file:read('*l')
    end

    self:addRule(currentRule)
    file:close()

    return self
end

-- Add a rule to the list of rules.
-- Called as program is being loaded.
function Interpreter:addRule(rule)
    if rule:isEmpty() then return rule end
    self.rule(#self.rule + 1) = rule
    return rule
end

-- Add a data statement to the current dataset.
-- Called as program is being loaded; may be called from host application.
function Interpreter:addData(data)
    if data:isEmpty() then return data end
    self.data(#self.data + 1) = data
    return data
end

-- Convert text to a data statement and add it to the current dataset.
-- May be called from host application.
function Interpreter:createData(text)
    local data = Data()
    data.value = split(escape(text), 'data')
    self:addData(data)
    return data
end

-- Debug utility; dump all rules.
function Interpreter:dumpRules()
    for k, v in ipairs(self.rule) do
        print('')
        for k, v in ipairs(v.query) do
            print(v.type .. ' ', table.concat(v, ' / '))
        end
        for k, v in ipairs(v.result) do
            print('produces ', table.concat(v, ' / '))
        end
    end
end

-- Debug utility; dump all data.
function Interpreter:dumpData()
    for k, v in ipairs(self.data) do
        print(table.concat(v.value, ' / '))
    end
end

-- Apply a single query to a single data statement.
-- Update binds as free variables are resolved.
-- Return true if query matches statement, else false.
local function matchQuery(query, binds, statement)

    local countDiff = #statement.value - #query

    -- Query and statement tuples must have same element count to match
    -- when query doesn't have a list matcher.
    if not query.listMatcherIndex and countDiff ~= 0 then return false end
    -- When query has a list matcher, can have at most statement-1 elements
    -- (-1 allows matching empty list).
    if countDiff < -1 then return false end

    local j = 0
    for i = 1, #query do
        j = j + 1
        -- list matcher free variable
        if query.listMatcherIndex == i and not binds(query(i)) then
            local t = {}
            for k = 1, countDiff + 1 do
                t(k) = statement.value(j)
                j = j + 1
            end
            j = j - 1
            binds(query(i)) = t
        -- bound list matcher
        elseif query.listMatcherIndex == i then
            for k = 1, countDiff + 1 do
                if binds(query(i))(k) ~= statement.value(j) then
                    return false
                end
                j = j + 1
            end
            j = j - 1
        -- scalar free variable
        elseif isScalarVariable(query(i)) and not binds(query(i)) then
            binds(query(i)) = statement.value(j)
        -- fail if not matched after variable expansion
        elseif expandVariables(query(i), binds) ~= statement.value(j) then
            return false
        end
    end

    return true
end

-- Test a single query against the entire program dataset.
-- If a match is found, return the program data offset and new binds.
-- Otherwise, return nil and the current binds.
function Interpreter:query(query, binds, offset)
    local bindsMeta = { __index = binds }

    for i = offset or 1, #self.data do
        local statement = self.data(i)
        local newBinds = setmetatable({}, bindsMeta)
        local matched = matchQuery(query, newBinds, statement)

        if matched then return i, newBinds end
    end

    return nil, binds
end

function Interpreter:queryDefault(query, binds)
    local newBinds = setmetatable({}, { __index = binds })

    for i = 1, #query do
        local default = query.default(query(i))
        -- list matcher free variable
        if query.listMatcherIndex == i and not newBinds(query(i)) then
            if default then
                newBinds(query(i)) = default
            else
                return nil, binds
            end
        -- bound list matcher
        elseif query.listMatcherIndex == i then
        -- scalar free variable
        elseif isScalarVariable(query(i)) and not newBinds(query(i)) then
            if default then
                newBinds(query(i)) = default
            else
                return nil, binds
            end
        end
    end
    return 0, newBinds
end

-- Test a rule against the dataset. Calls Interpreter:query.
-- If the rule matches, return the binds, matched data, and data index.
-- Otherwise, return false.
function Interpreter:matchRule(rule)
    local dataIndex
    local binds = {}
    local matchedIndices = {}
    local matchedData = {}
    local offset = 1

    local i = 1
    while i <= #rule.query do
        local query = rule.query(i)
        dataIndex, binds = self:query(query, binds, offset)
        if not dataIndex and query.hasDefaults then
            dataIndex, binds = self:queryDefault(query, binds)
        end
        offset = 1
        if dataIndex then
            matchedIndices(i) = dataIndex
            matchedData(i) = self.data(dataIndex)
        else
            -- backtracked all the way, nothing matched
            if i <= 1 then return false end

            -- backtrack
            local m = getmetatable(binds)
            binds = m and m.__index or binds
            i = i - 1
            offset = matchedIndices(i) + 1
            matchedIndices(i) = 0
            i = i - 1
        end
        i = i + 1
    end

    if #matchedIndices == #rule.query then
        _ = self.debugLevel >= 1 and print('query matched: ', rule.queryText)
        return matchedData, binds, dataIndex
    end

    _ = self.debugLevel >= 1 and print 'no query result.'
    _ = self.debugLevel >= 1 and print(lastQueryPart, lastDataMatch)
    return false
end

-- Removes matched reagent data after applying a rule.
function Interpreter:removeReagents(matchedData)
    for i = #self.data, 1, -1 do
        for j = 1, #matchedData do
            if matchedData(j) == self.data(i) then
                _ = self.debugLevel >= 1 and print('data modified:',
                    '---', table.concat(self.data(i).value, ' / '))
                table.remove(self.data, i)
                break
            end
        end
    end
end

local function shouldRemoveType(queryType, removeCatalysts)
    if removeCatalysts then
        return queryType ~= 'reagent'
    else
        return queryType == 'reactant'
    end
end

-- Finalizes a matched rule, and appends new result data.
-- Move data matching catalysts to the back if rule includes reagents.
function Interpreter:finalizeRule(rule, binds, matchedData)
    -- remove reactants, and catalysts if we're moving those.
    for i = #self.data, 1, -1 do
        for j = 1, #matchedData do
            if matchedData(j) == self.data(i)
            and shouldRemoveType(rule.query(j).type, rule.hasReagents) then
                _ = self.debugLevel >= 1 and print('data modified:',
                    '---', table.concat(self.data(i).value, ' / '))
                table.remove(self.data, i)
                break
            end
        end
    end

    -- move catalysts to back of dataset if rule has reagents.
    if rule.hasReagents then
        for i = 1, #rule.query do
            if rule.query(i).type == 'catalyst' then
                self:addData(matchedData(i))
                _ = self.debugLevel >= 1 and print('data shuffled:',
                    '>>>', table.concat(matchedData(i).value, ' / '))
            end
        end
    end

    -- create data statements from products of query result,
    -- expanding any variables, and append them to the dataset.
    for i = 1, #rule.result do
        local data = Data(rule.result(i)):expandVariables(binds)
        self:addData(data)
        _ = self.debugLevel >= 1 and print('data modified:',
            '+++', table.concat(data.value, ' / '))
    end
end


-- Check if two lists of datapoints are similar, based on a query.
-- This is used to determine whether a query with reagents has matched
-- all possible catalysts and wrapped back around to the first match.
-- If two datapoints at the same index in each list are different, and
-- the part of the query at that index is a catalyst, they're dissimilar.
-- Otherwise, they're similar.
local function compareDataLists(a, b, query)
    if not (a and b) then return false end
    if #a ~= #b then return false end
    for i = 1, #a do
        if query(i).type == 'catalyst' and a(i) ~= b(i) then
            return false
        end
    end
    return true
end

-- Build a list of datapoints that were matched by a reagent,
-- so they can be removed after applying a rule.
local function collectReagentData(rule, matchedData, reagentData)
    for i = 1, #matchedData do
        if rule.query(i).type == 'reagent' then
            reagentData(#reagentData + 1) = matchedData(i)
        end
    end
    return reagentData
end

function Interpreter:applyRuleWithReagent(rule)
    local reagentData = {}
    local matchedData, binds = self:matchRule(rule)
    local first = matchedData
    while matchedData do
        collectReagentData(rule, matchedData, reagentData)
        self:finalizeRule(rule, binds, matchedData)
        matchedData, binds = self:matchRule(rule)
        -- IMPORTANT: If the first match shows up again, stop now.
        -- This makes iteration like `inventory` command possible,
        -- and greatly simplifies commands like `drop all`.
        -- This is why catalyst matches are shuffled to the back!
        if matchedData and compareDataLists(matchedData, first, rule.query) then
            self:removeReagents(reagentData)
            return true
        end
    end
    if first then
        self:removeReagents(reagentData)
        return true
    end
    return false
end

function Interpreter:applyRuleWithoutReagent(rule)
    local matchedData, binds = self:matchRule(rule)
    if not matchedData then return false end
    --while rule do
    --    self:finalizeRule(rule, binds, matchedData)
    --    rule, binds, matchedData = self:matchRule(rule)
    --end
    self:finalizeRule(rule, binds, matchedData)
    return true
end

-- Apply the first rule that matches.
-- Returns true if a rule matched. Otherwise, return false.
function Interpreter:applyFirstMatchingRule()
    for i = 1, #self.rule do
        local rule = self.rule(i)
        if rule.hasReagents then
            if self:applyRuleWithReagent(rule) then return true end
        else
            if self:applyRuleWithoutReagent(rule) then return true end
        end
    end
    return false
end

-- Apply all applicable rules. Repeat until no more rules can be applied.
function Interpreter:applyRules()
    while self:applyFirstMatchingRule() do end
end

Interpreter.Class = Class
Interpreter.Rule = Rule
Interpreter.Data = Data

return Interpreter


To try the game, save the four files using the specified file names and run lua rife.lua.

python – The object & # 39; tuple & # 39; AttributeError does not have attribute "pie" – matplotlib

I'm trying to create a pie chart with matplotlib to add it to a tkinter graphical interface, but I get this error.

enter the description of the image here

The code that is

    Labels = 'Pendientes positivas', 'Pendientes negativas', 'Resistencias horizontales'
    sizes = (pendientes_positivas, pendientes_negativas, horizontales)
    graficoTorta = plt.subplots()
    graficoTorta.pie(sizes, labels = Labels)
    canvas = FigureCanvasTkAgg(graficoTorta, frame_Resistencias_M5)
    canvas.get_tk_widget().place(x = 400, y = 60)

Variables in sizes are integers that acquire their values ​​in another part of the program.

In addition, when I open the list of classes, I do not see 'foot & # 39; as an attribute

enter the description of the image here

I do not know if this has anything to do but I imagine that it should be there.
I am based on a code taken from an example of the documentation of matplotlib

import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = (15, 30, 45, 10)
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()

What does the following chart generate for me?

enter the description of the image here

python – (Error) TypeError: tuple indexes must be integers or slices, not numpy.float64

I'm doing a program for a project and I have to average between a breast and a cosine:

def simul (near, max, ctrl):
prom = []
seconds = range (ctrl, 1000 + 1)
print ("Result:")
for s in seconds:
print (f "{s} seconds")
print (f "Pressure: {pres} mmHg.  n")
prom.append (pres)
if near <max:
test1 = np.sin (pres)
test2 = np.cos (pres)
close + = 4
prom = np.mean (test1, test2)
if not:
test1 = np.sin (pres)
test2 = np.cos (pres)
close - = 15
prom = np.mean (test1, test2)

This is a function and I use this input data:

simul (10, 90, 0)

I receive this error: TypeError: tuple indexes must be integers or slices, not numpy.float64

I do not know what to do