Trying to get my python program to run but I keep getting a variable assignment error. Any ideas as to what I am doing wrong?

def main():
    
    name = ''.join(user_word.lower().split())
    name = name.replace('-','') # what?
    limit = len(name)
    phrase = True

    while running:
        temp_phrase = phrase.replace(' ', '')  
        if len(temp_phrase) < limit:
            print(f"length of anagram phrase = {len(temp_phrase)}")

            find_anagram(name, dict_file)
            print("Current anagram phrase =", end = " ")
            print(phrase, file=sys.stderr)

            choice, name = process_choice(name) 
            phrase += choice + ' '

        elif len(temp_phrase) == limit:
            print("n**FINISHED!!**n")
            print("Anagram of name", end = " ")
            print(phrase, file=sys.stderr)
            print()
            try_again = input("nnWant to try again? (Press Enter or else 'n' to quit)n")
            if try_again.lower() == 'n':
                running = False
                sys.exit()
            else:
                main()

after running my code I keep getting the error

UnboundLocalError: local variable 'running' referenced before assignment

so I tried making a variable named running in my main function’s argument but I got a different error so I just figure I would try to work out this first. Any clue as to how to fix it.

Side note: this problem is from the book impractical python projects (chapter 3 project 5), I copied almost every bit of code so I’m not sure how it isn’t working.

applescript – How to pass variable in bash script to osascript

I’ve spent hours researching this question, but none of the answers that I’ve found seem to work. I want to pass a POSIX path to some AppleScript running in a shell script, but nothing that I’ve tried lets AppleScript use the variable.

Here’s something that shows (in the simplest possible form) what I’m trying to do (my actual script will use Microsoft Word to open the file named in the path and then save it to another format):

#!/bin/bash

INFILE="$1"

osascript << 'EOD'
display dialog "$INFILE"
EOD

I’ve tried escaping the quotes; I’ve tried double-single-double quotes; I’ve tried parentheses and braces; I’ve tried using the filename as a parameter and setting a variable to item 1 of argv. Nothing works that I’ve tried. The answer is probably obvious to any expert, and I’ll be grateful for any help.

mysql – Can I use assignment operator `:=` on a local variable in a SELECT statement?

From my understanding the only difference between user variables @var and local variables like var is the latter are scoped between the BEGIN and END statements of a procedure whereas user variables exist for use in the connection as long as the connection remains open. So I would like to use local variables since I don’t care if the variables exist after the procedure is done. Actually I would prefer they didn’t exist outside of the procedure.

I am trying to use the following query:

DROP TABLE IF EXISTS my_test_table;
CREATE TABLE my_test_table(var INT DEFAULT 0);
INSERT INTO my_test_table VALUES (3);

DELIMITER //
DROP PROCEDURE IF EXISTS my_sp_test_function;
CREATE PROCEDURE my_sp_test_function() 
BEGIN
    DECLARE localVar INT DEFAULT 1;
    #SET @userVar = 1; ### If we swap this line for the one above the query works. ###

    SELECT
        localVar := t.var + 1 AS return_var
        #@userVar := t.var + 1 AS return_var
    FROM my_test_table AS t; 
END; //
DELIMITER ;

CALL my_sp_test_function();

but getting a syntax error near “:= t.var + 1”. If we change the DECLARE localVar line to SET @userVar this exact query works. So is there a syntax fix I can make or a different technique I can use to save off a variable from a select statement while using local variables?

probability – Finding the expectation from the cdf of a vector-valued random variable

We can calculate the expectation of a real-valued random variable by integrating its cumulative distribution function. What is the analogue of this fact for a random variable that takes values in a partially ordered vector space?

Suppose that $X$ is a random variable that takes values in a partially ordered vector space $V$. Let’s warm up with the case where $X$ takes only takes values in a finite set of positive vectors $U ⊂ V$. (Let $U$ contain $0$ for convenience.) In the totally ordered case, if we let $d(x) = x – y$ where $y$ is the immediate predecessor of $x$ in $U$ (and $d(0) = 0$), then we have
$$
sum_{x ∈ V} P(X = x) · x = sum_{x ∈ U} P(X geq x) · d(x)
$$

But this does not make sense if $V$ is only partially ordered, since $x$ need not have a single predecessor in $U$. We could try something like
$$d(x) = x – sum {y ∣ text{$y$ is an immediate predecessor of $x$ in $U$} }$$
But this doesn’t work either: we end up double-counting some values of $x$, when we have branches in $U$ that eventually join again. I’ve been trying out more elaborate definitions of $d(x)$ that compensate for this, and I think I might be able to get it to work, but it feels like I’m probably reinventing a wheel.

c# – Variable {…} cuelga la app

En ocasiones me sucede que tengo un error que yo supongo esta sin Try-Catch ya que me cierra de golpe la app.

Entonces reviso el codigo paso a paso y me encuentro con listas o variables que en lugar de decir:

-null
-""
-"algo"

Me muestra algo asi:

-{...}

Y al pasar sobre esta linea me cuelga la app hasta que la detengo a la fuerza.

A alguien mas le sucede?

He tenido que hacer cosas que en teoría considero que no debería tener que hacer como:

if (Lista.Count < 1)
{
   // Vacio
   Lista.Clear();
}

simplifying expressions – Why Mathematica is not assuming real variable as real?

I am dealing with the situation where despite of specifying my variables b1 and c to be greater than zero, Mathematica still returns the output with Re(b1+c)

  In(1):= mat1 = Simplify(( {
     {a - ( b1 + c)/2 I, d},
     {d, a - (b2 - c )/2 I}
    } ));

mat2 = ( {
    {0, 0, 1, 0},
    {0, 0, 0, 1},
    {-1, 0, 0, 0},
    {0, -1, 0, 0}
   } );

MatrixForm(FullSimplify(( {
    {Re(mat1((1))((1))), 
     Re(mat1((1))((2))), -Im(mat1((1))((1))), -Im(mat1((1))((2)))},
    {Re(mat1((2))((1))), 
     Re(mat1((2))((2))), -Im(mat1((2))((1))), -Im(mat1((2))((2)))},
    {Im(mat1((1))((1))), Im(mat1((1))((2))), Re(mat1((1))((1))), 
     Re(mat1((1))((2)))},
    {Im(mat1((2))((1))), Im(mat1((2))((2))), Re(mat1((2))((1))), 
     Re(mat1((2))((2)))}
   } ), {a >= 0, d >= 0, b1 >= 0, b2 >= 0, c >= 0}))

Out(3)//MatrixForm= !(
TagBox(
RowBox({"(", "", GridBox({
{"a", "d", 
FractionBox(
RowBox({"b1", "+", "c"}), "2"), "0"},
{"d", "a", "0", 
FractionBox(
RowBox({"b2", "-", "c"}), "2")},
{
RowBox({
RowBox({"-", 
FractionBox("1", "2")}), " ", 
RowBox({"Re", "(", 
RowBox({"b1", "+", "c"}), ")"})}), "0", "a", "d"},
{"0", 
RowBox({
FractionBox("1", "2"), " ", 
RowBox({"(", 
RowBox({
RowBox({"-", "b2"}), "+", "c"}), ")"})}), "d", "a"}
},
GridBoxAlignment->{
      "Columns" -> {{Center}}, "ColumnsIndexed" -> {}, 
       "Rows" -> {{Baseline}}, "RowsIndexed" -> {}},
GridBoxSpacings->{"Columns" -> {
Offset(0.27999999999999997`), {
Offset(0.7)}, 
Offset(0.27999999999999997`)}, "ColumnsIndexed" -> {}, "Rows" -> {
Offset(0.2), {
Offset(0.4)}, 
Offset(0.2)}, "RowsIndexed" -> {}}), "", ")"}),
Function(BoxForm`e$, 
MatrixForm(BoxForm`e$))))

Warning: Undefined variable $result in [fechada]

Boa noite, estou tentando passar informações retiradas do banco de dados para o html, porém não consegui resolver esse Warning.

Classe de conexão que possui a função:

public function recuperarProdutos() {
        $sql = $this->pdo->prepare('SELECT * FROM produtos');
        $sql->execute();
        $result = $sql->fetchAll();
        for($x = 0; $x < count($result); $x++) {
            echo '<pre>';
            print_r($result);
            echo '</pre>';
        }
    }

HTML

<?php
    require_once 'Classes/Connect.class.php';
    $conexao->recuperarProdutos();    
?>

<div class="col-md-3">
        <div class="text-center negrito">NOME</div>
            <div class="borda">
            <div class="text-center negrito2"><?php print_r($result(1)); ?></div>
            <div class="text-center negrito2">Categoria: Tecnologia</div>
        </div>
</div>

Ansible print debug message result variable

I have a simple task that I cannot overcome.

I have a playbook that returns AWS EC2 instance configuration. I need to only print (display) private_ip_address.

Here my playbook

---
- hosts: local
  connection: local
  gather_facts: false
  become: yes
  become_method: enable

  tasks:

  - name: gather-info-ec2
    community.aws.ec2_instance_info:
      instance_ids:
        - i-XXXXXAAAAAA

    register: ec2

  - debug: msg="{{ ec2.instances.network_interfaces.private_ip_address }}"

When I run it like this, I get the following error.

fatal: (localhost): FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'network_interfaces'nnThe error appears to be in '/etc/ansible/playbooks/AWSLinuxMigration/gather_ec2_info.yaml': line 16, column 5, but maynbe elsewhere in the file depending on the exact syntax problem.nnThe offending line appears to be:nnn  - debug: msg="{{ ec2.instances.network_interfaces.private_ip_address }}"n    ^ herenWe could be wrong, but this one looks like it might be an issue withnmissing quotes. Always quote template expression brackets when theynstart a value. For instance:nn    with_items:n      - {{ foo }}nnShould be written as:nn    with_items:n      - "{{ foo }}"n"}

When I execute it without DEBUG section and with -vvv it displays the below result. How to I extract and print this address? I shortened it a bit, but you get an idea

ok: (localhost) => {
    "msg": {
        "changed": false,
        "failed": false,
        "instances": (
            {
                "ami_launch_index": 0,
                "architecture": "x86_64",
                "block_device_mappings": (
                    {
                        "device_name": "/dev/xvda",
                        "ebs": {
                            "attach_time": "2020-04-15T16:11:19+00:00",
                            "delete_on_termination": true,
                            "status": "attached",
                            "volume_id": "xxxxxx"
                        }
                    }
                ),
                "capacity_reservation_specification": {
                    "capacity_reservation_preference": "open"
                },
                "client_token": "",
                "cpu_options": {
                    "core_count": 1,
                    "threads_per_core": 2
                },
                "ebs_optimized": true,
                "ena_support": true,
                "enclave_options": {
                    "enabled": false
                },
                "hibernation_options": {
                    "configured": false
                },
                "hypervisor": "xen",
                "iam_instance_profile": {
                    "arn": "xxxxxx",
                    "id": "xxxxxx"
                },
                "image_id": "xxxxx",
                "instance_id": "xxxxx",
                "instance_type": "t3.medium",
                "key_name": "xxxxx",
                "launch_time": "2021-04-21T00:01:25+00:00",
                "metadata_options": {
                    "http_endpoint": "enabled",
                    "http_put_response_hop_limit": 1,
                    "http_tokens": "optional",
                    "state": "applied"
                },
                "monitoring": {
                    "state": "disabled"
                },
                "network_interfaces": (
                    {
                        "association": {
                            "ip_owner_id": "xxxx",
                            "public_dns_name": "xxxxx",
                            "public_ip": "xxxx"
                        },
                        "attachment": {
                            "attach_time": "2020-04-15T16:11:18+00:00",
                            "attachment_id": "xxxxx",
                            "delete_on_termination": true,
                            "device_index": 0,
                            "network_card_index": 0,
                            "status": "attached"
                        },
                        "description": "Primary network interface",
                        "groups": (
                            {
                                "group_id": "xxxxx",
                                "group_name": "xxxxx"
                            }
                        ),
                        "interface_type": "interface",
                        "ipv6_addresses": (),
                        "mac_address": "xxxxx",
                        "network_interface_id": "xxxx",
                        "owner_id": "xxxxx",
                        "private_dns_name": "ip-10-0-1-161.ec2.internal",
                        "private_ip_address": "10.0.1.161",
                        "private_ip_addresses": (
                            {
                                "association": {
                                    "ip_owner_id": "xxxxx",
                                    "public_dns_name": "xxxx.compute-1.amazonaws.com",
                                    "public_ip": "2.2.2.2"
                                },
                                "primary": true,
                                "private_dns_name": "ip-333333.ec2.internal",
                                "private_ip_address": "1.1.1.1."
                            }
                        ),
                        "source_dest_check": true,
                        "status": "in-use"

                    }
                )
        )
    }
}

downvalues – Assignment with Span to Indexed Variable

If I use span to assign a value to every element in a “column”, it miraculously works:

arrayExample = {
   {a, b, c},
   {a, b, c},
   {a, b, c},
   {a, b, c}};
arrayExample((;; , 3)) = d;
arrayExample
out(...)={{a, b, d}, {a, b, d}, {a, b, d}, {a, b, d}}

The third column entries all became d! Wonderful.
Then I tried to do it to an indexed variable and I got a set::setps error that the indexed variable was not a variable:

indexedArrayExample(1) = {
   {a, b, c},
   {a, b, c},
   {a, b, c},
   {a, b, c}};
indexedArrayExample(1)((;; , 3)) = d;
...Set::setps: indexedArrayExample(1) in the part assignment is not a symbol.

This is not urgent because the workaround it simple. (Assign the value of the indexed variable to an unindexed one (temp=indexed...(1)), do the column assignment to temp and then assign it back to the indexed (indexed...(1)=temp). But that is not pretty.)

It seems that my question has to do with downvalues but I cannot figure how to make this work. I have gotten as far as understanding that temp has an ownvalue and that it why it can receive the assignment whereas an indexed variable has a downvalue but I do not understand how to assign “through” the indexed variable to its downvalues. The meta-question is what in the documentation would have answered my question?

sql server – How do I use insert data into a sqlserver table from a python socket using .split() to separate entries and executemany with a variable?

I am trying to insert rfid tag reads from a socket using python into a sqlserver database. since im using a tcp socket, the data will sometimes combine and put multiple entries into a single row and i need each read to be a different row. i have combed through multiple sites and the closest thing that i could find was this Python Socket is receiving inconsistent messages from Server but i wasnt able to make it work. i am able to use len to separate them, but i have no way of possibly knowing how many reads will be combined together. here is my current code (section that is commented out is using len)

while 1: 
def data_entry():
        c.execute('INSERT INTO ORFinishing(Tag) VALUES(?)',(data2))
       
        conn.commit()
    
data = s.recv(1024)

data2= data.decode("utf-8").rstrip('n')
print(data2)


if len(data2) ==24:

    print("correct")
    
    data_entry()
    del data2
    
    
else:
    print("wrong")
    data3 = str(data2)
    data4 = data3.split('n')
    print(data4)
    
    
    def many():
        c.executemany('INSERT INTO ORFinishing(Tag) VALUES(?)', data4)
        conn.commit()
        
        many()
    
    # one,two = data2(:24), data2(-24:)
        
    
    # if len(one)==24:
    #     def data_entry1():
    #         c.execute('INSERT INTO ORFinishing(Tag) VALUES(?)',(one))
       
    #         conn.commit()
    
    #     data_entry1()
        
    # if len(two)==24:
    #     def data_entry2():
    #         c.execute('INSERT INTO ORFinishing(Tag) VALUES(?)',(one))
       
    #         conn.commit()
    
    #     data_entry2()
        

I have seen several instances of people using executemany but it was always manually entering a tuple or list. I also tried turning it into a tuple. here is the output that i get.

runfile(‘C:/a/tcpsocket.py’, wdir=’C:/a’)
623037353035000000000000
correct
623031323638000000000000
623031323734000000000000
623033323830360000000000
wrong
(‘623031323638000000000000’, ‘623031323734000000000000’, ‘623033323830360000000000’)

but it doesnt put any of the data from the string split (wrong section) into the database. for the case above, it only had one read in the database. using len does put it into the database but it could be 5 reads combined or 100 reads combined so its not really a viable option.