问:
Cannot connect to socket io server
I have bot socket IO client and server running. I want to have client communicate with server.

Server initialization

```<code>this.http_server = net.createServer();
// this didn't work too. Exxentially socket io does not work at all
//   this.io = io.listen(typeof port == "number" ? port : process.env.PORT);
console.log("[ManagementServer] Attaching socket IO to HTTP server.");
this.io = io(this.http_server);
/// The port does open
this.http_server.listen(typeof port == "number" ? port : process.env.PORT,
    () => {
        console.log('[ManagementServer] IO HTTP server listening on port', this.http_server.address().port)
    });
/// The connection listener is triggered, but IO doesn't bother
/// replying or something
this.http_server.on("connection", (req, res) => {
    console.log("[ManagementServer] Connection received, but IO ignores it.")
});
// Never happens
this.io.on("connection", (socket) => {
    this.connection(socket);
})
</code>```

Client initialization

```<code>const srvurl = "http://" + this.remoteAddr + ":" + this.remotePort;

console.log("[UDP_socketio] Connecting to server: ", srvurl)
this.client = socketioclient(srvurl);

this.client.once("connect", () => {
    console.log("[UDP_socketio] Connected to remote server, identificating.")
    this.sendIdentification();
});

this.client.on("error", () => {
    console.error("[UDP_socketio] Socket IO connection error.")
});
</code>```

Socket IO debug output

I enabled debug, but socket IO debug output is not very useful anyway:

```<code>[ManagementServer] Attaching socket IO to HTTP server.
  socket.io:server initializing namespace / +0ms
  socket.io-parser encoding packet {"type":0,"nsp":"/"} +0ms
  socket.io-parser encoded {"type":0,"nsp":"/"} as 0 +1ms
  socket.io:server creating engine.io instance with opts {"serveClient":false,"path":"/","initialPacket":["0"]} +3ms
[ManagementServer] IO HTTP server listening on port 80
[UDP_socketio] Connecting to server:  http://127.0.0.1:80
  socket.io-client:url parse http://127.0.0.1:80 +0ms
  socket.io-client new io instance for http://127.0.0.1:80 +0ms
  socket.io-client:manager readyState closed +0ms
  socket.io-client:manager opening http://127.0.0.1:80 +1ms
  engine.io-client:socket creating transport "polling" +0ms
  engine.io-client:polling polling +0ms
  engine.io-client:polling-xhr xhr poll +0ms
  engine.io-client:polling-xhr xhr open GET: http://127.0.0.1/?EIO=3&transport=polling&t=MEuBb8c&b64=1 +1ms
  engine.io-client:polling-xhr xhr data null +0ms
  engine.io-client:socket setting transport polling +10ms
  socket.io-client:manager connect attempt will timeout after 20000 +12ms
  socket.io-client:manager readyState opening +1ms
[ManagementServer] Connection received, but IO ignores it.
  socket.io-client:manager connect attempt timed out after 20000 +20s
  engine.io-client:socket socket close with reason: "forced close" +20s
  engine.io-client:polling transport not open - deferring close +20s
  engine.io-client:socket socket closing - telling transport to close +0ms
  socket.io-client:manager connect_error +2ms
  socket.io-client:manager cleanup +0ms
  socket.io-client:manager will wait 1178ms before reconnect attempt +1ms
  socket.io-client:manager attempting reconnect +1s
  socket.io-client:manager readyState closed +0ms
  socket.io-client:manager opening http://127.0.0.1:80 +1ms
</code>```

Notice that the listener for connection that I added triggers, but socket IO does nothing.

What did not help so far:

Removing the connection listener from the this.http_server

Changing port used for testing

Increasing delay after which client tries to connect

Reading socket.io documentation. It's confusing, incomplete, inaccurate and inconsistent.

What could make socket IO ignore all connections like this? Maybe the server is listening for request from different paths? If that's the case, how to check what path is IO listening on?

答:
Make sure you're inserting the socket.io.js file into your client code and using it. If you try to create your own WebSocket on the client-side, you'll probably run into problems.

Do something like this for your server:

```<code>var app = require('express').createServer()
  , io = require('socket.io').listen(app);

app.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
</code>```

and something like this for the HTML file you're serving:

```<code><script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>
</code>```

Make sure you're serving /socket.io/socket.io.js from your webserver dir. Then all you have to do is watch your console login to the web browser's Developer environment from the Options or with Firebug when you go to the page.

Title: Cannot connect to socket io server

Body:
I have bot socket IO client and server running. I want to have client communicate with server.

Server initialization

this.http_server = net.createServer();
// this didn't work too. Exxentially socket io does not work at all
//   this.io = io.listen(typeof port == "number" ? port : process.env.PORT);
console.log("[ManagementServer] Attaching socket IO to HTTP server.");
this.io = io(this.http_server);
/// The port does open
this.http_server.listen(typeof port == "number" ? port : process.env.PORT,
    () => {
        console.log('[ManagementServer] IO HTTP server listening on port', this.http_server.address().port)
    });
/// The connection listener is triggered, but IO doesn't bother
/// replying or something
this.http_server.on("connection", (req, res) => {
    console.log("[ManagementServer] Connection received, but IO ignores it.")
});
// Never happens
this.io.on("connection", (socket) => {
    this.connection(socket);
})

Client initialization

const srvurl = "http://" + this.remoteAddr + ":" + this.remotePort;

console.log("[UDP_socketio] Connecting to server: ", srvurl)
this.client = socketioclient(srvurl);

this.client.once("connect", () => {
    console.log("[UDP_socketio] Connected to remote server, identificating.")
    this.sendIdentification();
});

this.client.on("error", () => {
    console.error("[UDP_socketio] Socket IO connection error.")
});

Socket IO debug output

I enabled debug, but socket IO debug output is not very useful anyway:

[ManagementServer] Attaching socket IO to HTTP server.
  socket.io:server initializing namespace / +0ms
  socket.io-parser encoding packet {"type":0,"nsp":"/"} +0ms
  socket.io-parser encoded {"type":0,"nsp":"/"} as 0 +1ms
  socket.io:server creating engine.io instance with opts {"serveClient":false,"path":"/","initialPacket":["0"]} +3ms
[ManagementServer] IO HTTP server listening on port 80
[UDP_socketio] Connecting to server:  http://127.0.0.1:80
  socket.io-client:url parse http://127.0.0.1:80 +0ms
  socket.io-client new io instance for http://127.0.0.1:80 +0ms
  socket.io-client:manager readyState closed +0ms
  socket.io-client:manager opening http://127.0.0.1:80 +1ms
  engine.io-client:socket creating transport "polling" +0ms
  engine.io-client:polling polling +0ms
  engine.io-client:polling-xhr xhr poll +0ms
  engine.io-client:polling-xhr xhr open GET: http://127.0.0.1/?EIO=3&transport=polling&t=MEuBb8c&b64=1 +1ms
  engine.io-client:polling-xhr xhr data null +0ms
  engine.io-client:socket setting transport polling +10ms
  socket.io-client:manager connect attempt will timeout after 20000 +12ms
  socket.io-client:manager readyState opening +1ms
[ManagementServer] Connection received, but IO ignores it.
  socket.io-client:manager connect attempt timed out after 20000 +20s
  engine.io-client:socket socket close with reason: "forced close" +20s
  engine.io-client:polling transport not open - deferring close +20s
  engine.io-client:socket socket closing - telling transport to close +0ms
  socket.io-client:manager connect_error +2ms
  socket.io-client:manager cleanup +0ms
  socket.io-client:manager will wait 1178ms before reconnect attempt +1ms
  socket.io-client:manager attempting reconnect +1s
  socket.io-client:manager readyState closed +0ms
  socket.io-client:manager opening http://127.0.0.1:80 +1ms

Notice that the listener for connection that I added triggers, but socket IO does nothing.

What did not help so far:

Removing the connection listener from the this.http_server

Changing port used for testing

Increasing delay after which client tries to connect

Reading socket.io documentation. It's confusing, incomplete, inaccurate and inconsistent.

What could make socket IO ignore all connections like this? Maybe the server is listening for request from different paths? If that's the case, how to check what path is IO listening on?

Body:
Make sure you're inserting the socket.io.js file into your client code and using it. If you try to create your own WebSocket on the client-side, you'll probably run into problems.

Do something like this for your server:

var app = require('express').createServer()
  , io = require('socket.io').listen(app);

app.listen(80);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

and something like this for the HTML file you're serving:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

Make sure you're serving /socket.io/socket.io.js from your webserver dir. Then all you have to do is watch your console login to the web browser's Developer environment from the Options or with Firebug when you go to the page.


来源: stackexchange

问:
JS - Is there a more efficient way to compare values in an array to a target search term
I am aiming to search an array of objects for one that's title is similar or matches a search term exactly. The problem is I would like to prioritise exact matches over matches that only contain the string.

The current code does this by looping multiple times, each time with a different condition, and returns the object if it matches.

class Item {
    constructor(title) {
        this.title = title;
    }
}

function findMatch(term) {
    const items = [new Item("term"), new Item("Longer Term"), new Item("Completely Different Title")];

    // Check if any match the search term exactly
    for (var item of items) {
        if (item.title === term) return item;
    }

    // Check if any match the search term, ignoring case
    for (var item of items) {
        if (item.title.toLowerCase() === term.toLowerCase()) return item;
    }

    // Check if any start with the search term
    for (var item of items) {
        if (item.title.toLowerCase().startsWith(term.toLowerCase())) return item;
    }

    // Check if any end with the search term
    for (var item of items) {
        if (item.title.toLowerCase().endsWith(term.toLowerCase())) return item;
    }

    // Check if any contain the search term
    for (var item of items) {
        if (item.title.toLowerCase().includes(term.toLowerCase())) return item;
    }

    return null;
}

console.log(findMatch("different")); // Item with title "Completely Different Title"
```

Is there a way to do this more efficiently, like in one loop - or is there a better way to search strings?

I have looked into using the Levenshtein algorithm however this does not work for searching "Comp" and getting the Item with title "Completely Different Title", as a lot more is different between "Comp" and "Completely Different Title" than there is between "Comp" and "term" - Is there a way to incorporate the same idea into this search?

答:
You might assign a score to your items depending on "similarity" whatever it is, then filter and sort the items by that score and return the matches:

class Item {
  constructor(title) {
    this.title = title;
  }
}
const items = [new Item("term"), new Item("Longer Term"), new Item("Completely Different Title")];

function findMatch(term) {
  for (var item of items) {
    // Check if any match the search term exactly
    if (item.title === term) item.score = 10000;

    // Check if any match the search term, ignoring case
    else if (item.title.toLowerCase() === term.toLowerCase()) item.score = 1000;

    // Check if any start with the search term
    else if (item.title.toLowerCase().startsWith(term.toLowerCase())) item.score = 100;

    // Check if any end with the search term
    else if (item.title.toLowerCase().endsWith(term.toLowerCase())) item.score = 10;

    // Check if any contain the search term
    else if (item.title.toLowerCase().includes(term.toLowerCase())) item.score = 1;
  }
  return items.filter(i => 0  b.score - a.score).map(i => delete i.score && i)
}

console.log(findMatch("different")); // Item with title "Completely Different Title"
console.log(findMatch("term"));```

ContentLicense: CC BY-SA 4.0

Body:
I am aiming to search an array of objects for one that's title is similar or matches a search term exactly. The problem is I would like to prioritise exact matches over matches that only contain the string.

The current code does this by looping multiple times, each time with a different condition, and returns the object if it matches.

class Item {
    constructor(title) {
        this.title = title;
    }
}

function findMatch(term) {
    const items = [new Item("term"), new Item("Longer Term"), new Item("Completely Different Title")];

    // Check if any match the search term exactly
    for (var item of items) {
        if (item.title === term) return item;
    }

    // Check if any match the search term, ignoring case
    for (var item of items) {
        if (item.title.toLowerCase() === term.toLowerCase()) return item;
    }

    // Check if any start with the search term
    for (var item of items) {
        if (item.title.toLowerCase().startsWith(term.toLowerCase())) return item;
    }

    // Check if any end with the search term
    for (var item of items) {
        if (item.title.toLowerCase().endsWith(term.toLowerCase())) return item;
    }

    // Check if any contain the search term
    for (var item of items) {
        if (item.title.toLowerCase().includes(term.toLowerCase())) return item;
    }

    return null;
}

console.log(findMatch("different")); // Item with title "Completely Different Title"

Is there a way to do this more efficiently, like in one loop - or is there a better way to search strings?

I have looked into using the Levenshtein algorithm however this does not work for searching "Comp" and getting the Item with title "Completely Different Title", as a lot more is different between "Comp" and "Completely Different Title" than there is between "Comp" and "term" - Is there a way to incorporate the same idea into this search?

Body:
You might assign a score to your items depending on "similarity" whatever it is, then filter and sort the items by that score and return the matches:

class Item {
  constructor(title) {
    this.title = title;
  }
}
const items = [new Item("term"), new Item("Longer Term"), new Item("Completely Different Title")];

function findMatch(term) {
  for (var item of items) {
    // Check if any match the search term exactly
    if (item.title === term) item.score = 10000;

    // Check if any match the search term, ignoring case
    else if (item.title.toLowerCase() === term.toLowerCase()) item.score = 1000;

    // Check if any start with the search term
    else if (item.title.toLowerCase().startsWith(term.toLowerCase())) item.score = 100;

    // Check if any end with the search term
    else if (item.title.toLowerCase().endsWith(term.toLowerCase())) item.score = 10;

    // Check if any contain the search term
    else if (item.title.toLowerCase().includes(term.toLowerCase())) item.score = 1;
  }
  return items.filter(i => 0 < i.score).sort((a, b) => b.score - a.score).map(i => delete i.score && i)
}

console.log(findMatch("different")); // Item with title "Completely Different Title"
console.log(findMatch("term"));


问:
Spring - Paths in applicationContext.xml
I am defining a freemarker bean in my applicationContext.xml and this bean needs a path to my template-directory.
It used to be:

src/main/webapp/template/

But i now want to store my templates under:

src/main/resources/template/

It used to look like:

```<code><bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPath" value="/template/email/"/>
</bean>
</code>```

Can anyone please help me to correctly define the new path?

答:
Answering as a proper answer, so you can close the question.

You should use "classpath:" prefix to reference resources located in the classpath.

```<code><bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPath" value="classpath:/template/email/"/>
</bean>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am defining a freemarker bean in my applicationContext.xml and this bean needs a path to my template-directory.
It used to be:

src/main/webapp/template/

But i now want to store my templates under:

src/main/resources/template/

It used to look like:

<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPath" value="/template/email/"/>
</bean>

Can anyone please help me to correctly define the new path?

Body:
Answering as a proper answer, so you can close the question.

You should use "classpath:" prefix to reference resources located in the classpath.

<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPath" value="classpath:/template/email/"/>
</bean>


问:
how to get all log groups names
I have a lambda that exports all of our loggroups to s3, and am currently using cloudwatchlogs.describeLogGroups to list
all of our logGroups.

```<code>const logGroupsResponse = await cloudwatchlogs.describeLogGroups({ limit: 50 })
</code>```

The issue is that we have 69 logGroups is there any way to list (ids, and names) of absolutely all logGroups in an aws account. I see it's possible to have 1000 log groups. This is a screenshot of our console:

How come cloudwatchlogs.describeLogGroups just allows a limit of 50 which is very small?

答:
Assuming that you are using AWS JS SDK v2, describeLogGroups API provides a nextToken in its response and also accepts a nexToken. This token is used for retrieving multiple log groups (more than 50) by sending multiple requests. We can use the following pattern to accomplish this:

```<code>const cloudwatchlogs = new AWS.CloudWatchLogs({region: 'us-east-1'});
let nextToken = null;
do {
    const logGroupsResponse = await cloudwatchlogs.describeLogGroups({limit: 50, nextToken: nextToken}).promise();

    // Do something with the retrieved log groups
    console.log(logGroupsResponse.logGroups.map(group => group.arn));

    // Get the next token. If there are no more log groups, the token will be undefined
    nextToken = logGroupsResponse.nextToken;
} while (nextToken);
</code>```

We are querying the AWS API in loop until there are no more log groups left.

Title: how to get all log groups names

Body:
I have a lambda that exports all of our loggroups to s3, and am currently using cloudwatchlogs.describeLogGroups to list
all of our logGroups.

const logGroupsResponse = await cloudwatchlogs.describeLogGroups({ limit: 50 })

The issue is that we have 69 logGroups is there any way to list (ids, and names) of absolutely all logGroups in an aws account. I see it's possible to have 1000 log groups. This is a screenshot of our console:

How come cloudwatchlogs.describeLogGroups just allows a limit of 50 which is very small?

Body:
Assuming that you are using AWS JS SDK v2, describeLogGroups API provides a nextToken in its response and also accepts a nexToken. This token is used for retrieving multiple log groups (more than 50) by sending multiple requests. We can use the following pattern to accomplish this:

const cloudwatchlogs = new AWS.CloudWatchLogs({region: 'us-east-1'});
let nextToken = null;
do {
    const logGroupsResponse = await cloudwatchlogs.describeLogGroups({limit: 50, nextToken: nextToken}).promise();

    // Do something with the retrieved log groups
    console.log(logGroupsResponse.logGroups.map(group => group.arn));

    // Get the next token. If there are no more log groups, the token will be undefined
    nextToken = logGroupsResponse.nextToken;
} while (nextToken);

We are querying the AWS API in loop until there are no more log groups left.


问:
Inserting increment for each unique value in sql
I've been tasked with a SQL problem that is outside of the limited scope of sql knowledge that I have. I have the following problem.

I have a table that currently looks like this:

```<code> widgets
---------
    a
    a
    a
    b
    b
    c
    d
    d
    d
</code>```

I would like to have another table that has each unique value incrementally numbered... Like so:

```<code>widgets  | widget_id
--------- ----------
    a    |    1
    a    |    1
    a    |    1
    b    |    2
    b    |    2
    c    |    3
    d    |    4
    d    |    4
    d    |    4
</code>```

I'm not sure how this would be done with an insert statement?

答:
I think that server-side cursors are probably your best option for this.  I believe that the following will work:</p>

```<code>DECLARE @widgets varchar(20)
DECLARE @widget_id int
DECLARE @widget_count int
DECLARE @index int

DECLARE widgets_cursor CURSOR FOR
SELECT [widgets], COUNT(*)
FROM [original_widgets_table]
GROUP BY [widgets]

SET @widget_id = 0

OPEN widgets_cursor

FETCH NEXT FROM widgets_cursor INTO @widget, @widget_count
WHILE @@FETCH_STATUS = 0
BEGIN
  SET @widget_id = @widget_id + 1
  SET @index = 0

  WHILE @index < @widget_count
  BEGIN
    INSERT [new_widgets_table]
    (
    widget
    , widget_id
    )
    SELECT
    @widget
    , @widget_id

    SET @index = @index + 1
  END

  FETCH NEXT FROM widgets_cursor INTO @widget, @widget_count
END

CLOSE widgets_cursor

DEALLOCATE widgets_cursor
</code>```

OwnerDisplayName: Chris

ContentLicense: CC BY-SA 2.5

Body:
I've been tasked with a SQL problem that is outside of the limited scope of sql knowledge that I have. I have the following problem.

I have a table that currently looks like this:

 widgets
---------
    a
    a
    a
    b
    b
    c
    d
    d
    d

I would like to have another table that has each unique value incrementally numbered... Like so:

widgets  | widget_id
--------- ----------
    a    |    1
    a    |    1
    a    |    1
    b    |    2
    b    |    2
    c    |    3
    d    |    4
    d    |    4
    d    |    4

I'm not sure how this would be done with an insert statement?

Body:
I think that server-side cursors are probably your best option for this.  I believe that the following will work:

DECLARE @widgets varchar(20)
DECLARE @widget_id int
DECLARE @widget_count int
DECLARE @index int

DECLARE widgets_cursor CURSOR FOR
SELECT [widgets], COUNT(*)
FROM [original_widgets_table]
GROUP BY [widgets]

SET @widget_id = 0

OPEN widgets_cursor

FETCH NEXT FROM widgets_cursor INTO @widget, @widget_count
WHILE @@FETCH_STATUS = 0
BEGIN
  SET @widget_id = @widget_id + 1
  SET @index = 0

  WHILE @index < @widget_count
  BEGIN
    INSERT [new_widgets_table]
    (
    widget
    , widget_id
    )
    SELECT
    @widget
    , @widget_id

    SET @index = @index + 1
  END

  FETCH NEXT FROM widgets_cursor INTO @widget, @widget_count
END

CLOSE widgets_cursor

DEALLOCATE widgets_cursor

OwnerDisplayName: Templar


问:
RNA to Protein simulation program's TypeErorr?
Here's what I'm doing:

```<code>
def dna_complement(dna):
  coup = ""
  for letter in dna:
    if letter == "C":
      coup += "G"
    if letter == "G":
      coup += "C"
    if letter == "A":
      coup += "T"
    if letter == "T":
      coup += "A"
  return coup

def convert_to_rna(dna):
  coup2 = ""
  for letter in dna:
    if letter == "C":
      coup2 += "G"
    if letter == "G":
      coup2 += "C"
    if letter == "A":
      coup2 += "U"
    if letter == "T":
      coup2 += "A"
  return coup2

def translate(rna):
  amino_acid = ""
  for len in rna:
    if range(0, len(rna), 3) == "UUU" :
      amino_acid = CODON_TABLE.get("UUU")
    if range(0, len(rna), 3) == "UUC" :
      amino_acid = CODON_TABLE.get("UUC")
    if range(0, len(rna), 3) == "UUA" :
      amino_acid = CODON_TABLE.get("UUA")

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu','CUA':'Leu','CUG':'Leu','AUU':'Ile','AUC':'Ile','AUA':'Ile','AUG':'Met','GUU':'Val','GUC':'Val','GUA':'Val','GUG':'Val','UCU':'Ser','UCC':'Ser','UCA':'Ser','UCG':'Ser','CCU':'Pro','CCC':'Pro','CCA':'Pro','CCG':'Pro','ACU':'Thr','ACC':'Thr','ACA':'Thr','ACG':'Thr','GCU':'Ala','GCC':'Ala','GCA':'Ala','GCG':'Ala','UAU':'Tyr','UAC':'Tyr','UAA':'STOP','UAG':'STOP','CAU':'His','CAC':'His','CAA':'Gln','CAG':'Gln','AAU':'Asn','AAC':'Asn','AAA':'Lys','AAG':'Lys','GAU':'Asp','GAC':'Asp','GAA':'Glu','GAG':'Glu','UGU':'Cys','UGC':'Cys','UGA':'STOP','UGG':'Trp','CGU':'Arg','CGC':'Arg','CGA':'Arg','CGG':'Arg','AGU':'Ser','AGC':'Ser','AGA':'Arg','AGG':'Arg','GGU':'Gly','GGC':'Gly','GGA':'Gly','GGG':'Gly'}

""" the rna is "UUCUCUACGGUAACAGGGGGCCGGAGGACGACGACGAGAAUCGCCCCGGUGUAGCCGGUGGCGACGGGACGGGGACCUCCCACCGGGGUGGCCGGCAAUGUCGCUCGUAUG" # This is already converted from DNA to RNA so there's no worry about the original RNA
"""

dna="AAGAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTCTTAGCGGGGCCACATCGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGTTACAGCGAGCATAC"

def main():
  print("\nWelcome to the DNA program: The Code of Life.")
  print("\nSample DNA strand:\n")
  print("Regular DNA:")
  print_bases(dna)
  print("DNA after complement: ")
  dna2 = dna_complement(dna)
  print_bases(dna2)
  print("DNA after RNA convertion: ")
  rna = convert_to_rna(dna)
  print_bases(rna)
  print("The result of translation: ")
  amino_acid = translate(rna)
  print(amino_acid)
</code>```

As in the image above. (Thanks to a user called Random Davis telling me to correct my mistake on the description, now I have everything I'm having right now in display which might be a little better)

When I tried to run this the Type Error telling me that str object is not callable, can someone help me with this?

More information: Sorry for not saying this earlier, I was trying to get the conversion like UUU <-> Phe, UUA <-> Leu, and AUU <-> Ile. And stop the protein from generating once it detected UAA, UAG, UGA.

答:
So if you turn the whole RNA string into a codon string:

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu'} # etc

def translate(rna):
    amino_acid = ""
    for i in range(len(rna)-2):
        three_letter = rna[i:i+3]
        if three_letter in CODON_TABLE:
            amino_acid += CODON_TABLE[three_letter]
            # if a match is found, don't look for a new codon starting with
            # the second or third letter of this codon
            i += 2
        return amino_acid
```
<hr />
<p>Explanation:
<code>for i in range(len(rna)-2):</code> will give us an index number to the parts of the RNA string we want to read:</p>
```UUCUCUAC   len = 8
012345      i = 0-5 = range(6)
```
<p><code>rna[i:i+3]</code> gives us the three letters starting from the <code>i</code>th one</p>
```UUCUCUAC  = rna
UUC       i = 0, three_letter = rna[0:3]
 UCU      i = 1, tl = rna[1:4]
  CUC     i = 2, tl = rna[2:5]
   UCU    i = 3, tl = rna[3:6]
    CUA   i = 4, tl = rna[4:7]
     UAC  i = 5, tl = rna[5:8]
```
<p>For each three-letter sequence, if it's a codon, it adds the name of the codon to the amino acid</p>
<pre class="lang-py prettyprint-override"><code>amino_acid += CODON_TABLE[three_letter]
</code>```

Then it skips i forward by 2 to avoid looking for another codon starting with letters we've already used:

```<code>UUCUCUAC
UUC       Phe
 UCU      (skip)
  CUC     (skip)
   UCU    Ser
    CUA   (skip)
     UAC  (skip)
</code>```

If it finds something that's not a codon, it ignores it and moves onto the next three letters. (I'm not a biologist, I don't know if every three-letter sequence is a codon?)

```<code>UUCZUCUAC
UUC        Phe
 UCU       (skip)
  CUC      (skip)
   ZUC     (not found)
    UCU    Sre
</code>```

Body:
Here's what I'm doing:

def dna_complement(dna):
  coup = ""
  for letter in dna:
    if letter == "C":
      coup += "G"
    if letter == "G":
      coup += "C"
    if letter == "A":
      coup += "T"
    if letter == "T":
      coup += "A"
  return coup

def convert_to_rna(dna):
  coup2 = ""
  for letter in dna:
    if letter == "C":
      coup2 += "G"
    if letter == "G":
      coup2 += "C"
    if letter == "A":
      coup2 += "U"
    if letter == "T":
      coup2 += "A"
  return coup2

def translate(rna):
  amino_acid = ""
  for len in rna:
    if range(0, len(rna), 3) == "UUU" :
      amino_acid = CODON_TABLE.get("UUU")
    if range(0, len(rna), 3) == "UUC" :
      amino_acid = CODON_TABLE.get("UUC")
    if range(0, len(rna), 3) == "UUA" :
      amino_acid = CODON_TABLE.get("UUA")

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu','CUA':'Leu','CUG':'Leu','AUU':'Ile','AUC':'Ile','AUA':'Ile','AUG':'Met','GUU':'Val','GUC':'Val','GUA':'Val','GUG':'Val','UCU':'Ser','UCC':'Ser','UCA':'Ser','UCG':'Ser','CCU':'Pro','CCC':'Pro','CCA':'Pro','CCG':'Pro','ACU':'Thr','ACC':'Thr','ACA':'Thr','ACG':'Thr','GCU':'Ala','GCC':'Ala','GCA':'Ala','GCG':'Ala','UAU':'Tyr','UAC':'Tyr','UAA':'STOP','UAG':'STOP','CAU':'His','CAC':'His','CAA':'Gln','CAG':'Gln','AAU':'Asn','AAC':'Asn','AAA':'Lys','AAG':'Lys','GAU':'Asp','GAC':'Asp','GAA':'Glu','GAG':'Glu','UGU':'Cys','UGC':'Cys','UGA':'STOP','UGG':'Trp','CGU':'Arg','CGC':'Arg','CGA':'Arg','CGG':'Arg','AGU':'Ser','AGC':'Ser','AGA':'Arg','AGG':'Arg','GGU':'Gly','GGC':'Gly','GGA':'Gly','GGG':'Gly'}

""" the rna is "UUCUCUACGGUAACAGGGGGCCGGAGGACGACGACGAGAAUCGCCCCGGUGUAGCCGGUGGCGACGGGACGGGGACCUCCCACCGGGGUGGCCGGCAAUGUCGCUCGUAUG" # This is already converted from DNA to RNA so there's no worry about the original RNA
"""

dna="AAGAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTCTTAGCGGGGCCACATCGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGTTACAGCGAGCATAC"

def main():
  print("\nWelcome to the DNA program: The Code of Life.")
  print("\nSample DNA strand:\n")
  print("Regular DNA:")
  print_bases(dna)
  print("DNA after complement: ")
  dna2 = dna_complement(dna)
  print_bases(dna2)
  print("DNA after RNA convertion: ")
  rna = convert_to_rna(dna)
  print_bases(rna)
  print("The result of translation: ")
  amino_acid = translate(rna)
  print(amino_acid)

As in the image above. (Thanks to a user called Random Davis telling me to correct my mistake on the description, now I have everything I'm having right now in display which might be a little better)

When I tried to run this the Type Error telling me that str object is not callable, can someone help me with this?

More information: Sorry for not saying this earlier, I was trying to get the conversion like UUU <-> Phe, UUA <-> Leu, and AUU <-> Ile. And stop the protein from generating once it detected UAA, UAG, UGA.

Body:
So if you turn the whole RNA string into a codon string:

CODON_TABLE = {'UUU':'Phe','UUC':'Phe','UUA':'Leu','UUG':'Leu','CUU':'Leu','CUC':'Leu'} # etc

def translate(rna):
    amino_acid = ""
    for i in range(len(rna)-2):
        three_letter = rna[i:i+3]
        if three_letter in CODON_TABLE:
            amino_acid += CODON_TABLE[three_letter]
            # if a match is found, don't look for a new codon starting with
            # the second or third letter of this codon
            i += 2
        return amino_acid

Explanation:
for i in range(len(rna)-2): will give us an index number to the parts of the RNA string we want to read:

UUCUCUAC   len = 8
012345      i = 0-5 = range(6)

rna[i:i+3] gives us the three letters starting from the ith one

UUCUCUAC  = rna
UUC       i = 0, three_letter = rna[0:3]
 UCU      i = 1, tl = rna[1:4]
  CUC     i = 2, tl = rna[2:5]
   UCU    i = 3, tl = rna[3:6]
    CUA   i = 4, tl = rna[4:7]
     UAC  i = 5, tl = rna[5:8]

For each three-letter sequence, if it's a codon, it adds the name of the codon to the amino acid

amino_acid += CODON_TABLE[three_letter]

Then it skips i forward by 2 to avoid looking for another codon starting with letters we've already used:

UUCUCUAC
UUC       Phe
 UCU      (skip)
  CUC     (skip)
   UCU    Ser
    CUA   (skip)
     UAC  (skip)

If it finds something that's not a codon, it ignores it and moves onto the next three letters. (I'm not a biologist, I don't know if every three-letter sequence is a codon?)

UUCZUCUAC
UUC        Phe
 UCU       (skip)
  CUC      (skip)
   ZUC     (not found)
    UCU    Sre


问:
Solving a Positional Argument Error in a Pythonic Class and Method
Disclaimer
To preface this, I am new to programming and even newer to python, so my knowledge of the mechanics of the interpreter is very limited.

Explanation I am currently writing a pythonic code that simulates a text-based game of cheating hangman, which means the program changes the word to evade the player from guessing the correct word using "word families." The game requires three files: hangman.py, play_hangman.py, and dictionary.txt. In hangman.py, I have created a hangman class that contains the self-instance of the class, several methods for producing the necessary objects, and a play method that uses these methods. Then, in play_hangman.py, it calls the hangman instance, and the play method, and puts the play method into a while loop that repeats as long as the player enters "yes" to keep playing.

The Problem I have called the methods into the play function for executing the game. However, it gives me an error saying:

- "12 positional arguments: 'word_length', 'num_guesses',
'remaining_words', 'remainingWords', 'letters_already_guessed',
'askForWordLength', 'printGameStats', 'askForPlayerGuess',
'wordStatus', 'printCountOfRemainingWords', 'retreiveRemainingWords',
and 'askForNumberOfGuesses' "

These are the twelve variables and methods I have called in the def play(): function. I have researched that I need to call an object of the class before the method, which I attempted to do, but does not work. I am not sure how to avoid the error.

HANGMAN.PY

```<code>import re

class Hangman:

    # hangman self method
    def hangman(self):
        self.hangman = Hangman()  # object of the Hangman class

    def words(self):
        with open('dictionary.txt') as file:  # opens dictionary text file
            file_lines = file.read().splitlines()  # reads and splits each line

        all_words = []  # empty list to contain all words
        valid_words = []  # empty list to contain all valid words

        for word in file_lines:  # traverses all words in the file lines
            if len(word) >= 3:  # accepts word if it has at least 3 letters
                all_words.append(word)  # appends accepted word to list

        # list of all invalid characters in python
        CHARACTERS = ["~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(",
                      ")", "-", "_", "=", "+", "[", "]", "{", "}", "|", "\","
                      "", "'", "?", "/", ">", ".", "<", ",", "", ";", ":"]

        for i in CHARACTERS:    # traverse list of invalids
            for word in all_words:
                if i not in word:   # if invalid character is not in word
                    valid_words.append(word)    # accept and append to list

        return valid_words  # return list of valid words

    def askForWordLength(self, valid_words):

        word_lengths = []   # empty list for possible word lengths
        for word in valid_words:    # traverse list of valid words
            length = word.__len__()  # record length of current word
            if (length not in word_lengths):
                word_lengths.append(length)     # accept and append to list
        word_lengths.sort()

        # inform user of possible word lengths
        print('The available word lengths are: ' + str(word_lengths[0]) + '-'
              + str(word_lengths[-1]))
        print()

        # have user choose from possible word lengths
        while(1):
            try:
                length = int(input('Please enter the word length you want: '))
                if (length in word_lengths):
                    return length
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def askForNumberOfGuesses(self):
        while(1):
            try:
                num_guesses = int(input('Enter number of guesses you want: '))
                if (num_guesses >= 3):
                    return num_guesses
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def wordStatus(self, length):
        status = '-'
        for i in range(0, length):
            status += '-'
        return

    def remainingWords(self, lines, length):
        words = []
        for word in lines:
            if (word.__len__() == length):
                words.append(word)
        return words

    def printGameStats(self, letters_guessed, status, num_guesses):
        print('Game Status: ' + str(status))
        print()
        print('Attempted Guesses' + str(letters_guessed))
        print('Remaining Guesses' + str(num_guesses))

    def askPlayerForGuess(self, letters_guessed):
        letter = str(input('Guess a letter: ')).lower()
        pattern = re.compile("^[a-z]{1}$")
        invalid_guess = letter in letters_guessed or re.match(pattern, letter) == None

        if (invalid_guess):
            while (1):
                print()
                if (re.match(pattern, letter) == None):
                    print('Invalid guess. Please enter a correct character!')
                if (letter in letters_guessed):
                    print('\nYou already guessed that letter' + letter)

                letter = str(input('Please guess a letter: '))
                valid_guess = letter not in letters_guessed and re.match(pattern, letter) != None

                if (valid_guess):
                    return letter
        return letter

    def retrieveWordStatus(self, word_family, letters_already_guessed):
        status = ''
        for letter in word_family:
            if (letter in letters_already_guessed):
                status += letter
            else:
                status += '-'
        return status

    def retrieveRemainingWords(self, guess, num_guesses, remaining_words,
                               wordStatus, guesses_num, word_length,
                               createWordFamiliesDict,
                               findHighestCountWordFamily,
                               generateListOfWords):

        word_families = createWordFamiliesDict(remaining_words, guess)
        family_return = wordStatus(word_length)
        avoid_guess = num_guesses == 0 and family_return in word_families

        if (avoid_guess):
            family_return = wordStatus(word_length)
        else:
            family_return = findHighestCountWordFamily(word_families)

        words = generateListOfWords(remaining_words, guess, family_return)
        return words

    def createWordFamiliesDict(self, remainingWords, guess):
        wordFamilies = dict()
        for word in remainingWords:
            status = ''
            for letter in word:
                if (letter == guess):
                    status += guess
                else:
                    status += '-'

            if (status not in wordFamilies):
                wordFamilies[status] = 1
            else:
                wordFamilies[status] = wordFamilies[status] + 1
        return wordFamilies

    def generateListOfWords(self, remainingWords, guess, familyToReturn):
        words = []
        for word in remainingWords:
            word_family = ''
            for letter in word:
                if (letter == guess):
                    word_family += guess
                else:
                    word_family += '-'

            if (word_family == familyToReturn):
                words.append(word)
        return words

    def findHighestCountWordFamily(self, wordFamilies):
        familyToReturn = ''
        maxCount = 0
        for word_family in wordFamilies:
            if wordFamilies[word_family] > maxCount:
                maxCount = wordFamilies[word_family]
                familyToReturn = word_family
        return familyToReturn

    def printCountOfRemainingWords(self, remainingWords):
        show_remain_words = str(input('Want to view the remaining words?: '))
        if (show_remain_words == 'yes'):
            print('Remaining words: ' + str(len(remainingWords)))
        else:
            print()

    def play(self, askForWordLength, askForNumberOfGuesses, remainingWords,
             words, wordStatus, printCountOfRemainingWords, printGameStats,
             askPlayerForGuess, retrieveRemainingWords):
        MODE = 1
        openSession = 1

        while (openSession == 1):
            word_length = askForWordLength(words)
            num_guesses = askForNumberOfGuesses()

            wordStatus = wordStatus(word_length)
            letters_already_guessed = []
            print()

            game_over = 0
            while (game_over == 0):
                if (MODE == 1):
                    printCountOfRemainingWords(remainingWords)

            printGameStats(remainingWords, letters_already_guessed,
                           num_guesses, wordStatus)

            guess = askPlayerForGuess(letters_already_guessed)
            letters_already_guessed.append(guess)
            num_guesses -= 1

            remainingWords = retrieveRemainingWords(guess, remainingWords,
                                                    num_guesses, word_length)

            wordStatus = wordStatus(remainingWords[0], letters_already_guessed)
            print()

            if (guess in wordStatus):
                num_guesses += 1

            if ('-' not in wordStatus):
                game_over = 1
                print('Congratulations! You won!')
                print('Your word was: ' + wordStatus)

            if (num_guesses == 0 and game_over == 0):
                game_over = 1
                print('Haha! You Lose')
                print('Your word was: ' + remainingWords[0])

        print('Thanks for playing Hangman!')
</code>```

答:
Self as First Parameter

When creating functions inside classes, the first parameter should be 'self', as you've done in the function askForNumberOfGuesses. This happens because, when calling functions from an object, Python passes the object to 'self' so the method's logic can access its data.

When calling functions such as "play" (in which you haven't used the self parameter in the declaration), the first parameter will be handled as the self, even though it has a different name. So, actually, your code expects the variable 'words' to be a Hangman object.

Static Functions

If the function needs to know information about the object, you need to add the 'self' as the first parameter.
However, if your method does not use any data declared inside the Hangman class (such as self.hangman that you've created inside init) you can just add a "@staticmethod" to the line before the function definition. This way, Python will know that you don't need self and that the first parameter is not the object.

Notice that, if you want to use a static method, you can use the class itself to call the method. You don't even need to create an object:

```<code>Hangman.static_function_name(function_parameters)  # calls static function
hangman_object = Hangman()
hangman_object.non_static_function_name(function_parameters)  # calls non-static function
hangman_object.static_function_name(function_parameters)  # calls static function using object (there is no problem)
</code>```

Design Considerations

Also, I believe you should change your init implementation and use 'self' to store data that you use in more than one function, instead of passing arguments to all the functions and returning them.
Also note that, in order to create a Hangman object, you need to use ():

```<code>self.hangman = Hangman  # reference to the Hangman class
self.hangman = Hangman()  # Object of the Hangman class
</code>```

However, if you create a Hangman object inside init, it will call init again and this will go on "forever". So, you shouldn't create a Hangman object inside it's init method. I believe you should create the Hangman object in play_hangman.py file and call the play method from there.

In my opinion, init should create all the data you need as self.<var_name>, load should prepare words or whatever you need using self.<functions_you_create> and play should just start the game. play_hangman.py shouldn't need to know all these parameters.

hangman.py

```<code>class GameClass:
    def __init__(self):
        self.words = list()
        # TODO: Implement adding other game data

    def load(self):
        # TODO: Implement logic
        self.words.append('country')
        pass

    def play(self):
        # TODO: Implement loop logic
        print(self.words)
        # while(True):
        #    break
        pass
</code>```

play_hangman.py

```<code>game = GameClass()
game.load()
game.play()
</code>```

IDE

Use a good IDE so it will remember you to add self if you are not used yet.

Body:
Disclaimer
To preface this, I am new to programming and even newer to python, so my knowledge of the mechanics of the interpreter is very limited.

Explanation I am currently writing a pythonic code that simulates a text-based game of cheating hangman, which means the program changes the word to evade the player from guessing the correct word using "word families." The game requires three files: hangman.py, play_hangman.py, and dictionary.txt. In hangman.py, I have created a hangman class that contains the self-instance of the class, several methods for producing the necessary objects, and a play method that uses these methods. Then, in play_hangman.py, it calls the hangman instance, and the play method, and puts the play method into a while loop that repeats as long as the player enters "yes" to keep playing.

The Problem I have called the methods into the play function for executing the game. However, it gives me an error saying:

- "12 positional arguments: 'word_length', 'num_guesses',
'remaining_words', 'remainingWords', 'letters_already_guessed',
'askForWordLength', 'printGameStats', 'askForPlayerGuess',
'wordStatus', 'printCountOfRemainingWords', 'retreiveRemainingWords',
and 'askForNumberOfGuesses' "

These are the twelve variables and methods I have called in the def play(): function. I have researched that I need to call an object of the class before the method, which I attempted to do, but does not work. I am not sure how to avoid the error.

HANGMAN.PY

import re

class Hangman:

    # hangman self method
    def hangman(self):
        self.hangman = Hangman()  # object of the Hangman class

    def words(self):
        with open('dictionary.txt') as file:  # opens dictionary text file
            file_lines = file.read().splitlines()  # reads and splits each line

        all_words = []  # empty list to contain all words
        valid_words = []  # empty list to contain all valid words

        for word in file_lines:  # traverses all words in the file lines
            if len(word) >= 3:  # accepts word if it has at least 3 letters
                all_words.append(word)  # appends accepted word to list

        # list of all invalid characters in python
        CHARACTERS = ["~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(",
                      ")", "-", "_", "=", "+", "[", "]", "{", "}", "|", "\","
                      "", "'", "?", "/", ">", ".", "<", ",", "", ";", ":"]

        for i in CHARACTERS:    # traverse list of invalids
            for word in all_words:
                if i not in word:   # if invalid character is not in word
                    valid_words.append(word)    # accept and append to list

        return valid_words  # return list of valid words

    def askForWordLength(self, valid_words):

        word_lengths = []   # empty list for possible word lengths
        for word in valid_words:    # traverse list of valid words
            length = word.__len__()  # record length of current word
            if (length not in word_lengths):
                word_lengths.append(length)     # accept and append to list
        word_lengths.sort()

        # inform user of possible word lengths
        print('The available word lengths are: ' + str(word_lengths[0]) + '-'
              + str(word_lengths[-1]))
        print()

        # have user choose from possible word lengths
        while(1):
            try:
                length = int(input('Please enter the word length you want: '))
                if (length in word_lengths):
                    return length
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def askForNumberOfGuesses(self):
        while(1):
            try:
                num_guesses = int(input('Enter number of guesses you want: '))
                if (num_guesses >= 3):
                    return num_guesses
            except ValueError:
                print('Your input is invalid!. Please use a valid input!')
                print()

    def wordStatus(self, length):
        status = '-'
        for i in range(0, length):
            status += '-'
        return

    def remainingWords(self, lines, length):
        words = []
        for word in lines:
            if (word.__len__() == length):
                words.append(word)
        return words

    def printGameStats(self, letters_guessed, status, num_guesses):
        print('Game Status: ' + str(status))
        print()
        print('Attempted Guesses' + str(letters_guessed))
        print('Remaining Guesses' + str(num_guesses))

    def askPlayerForGuess(self, letters_guessed):
        letter = str(input('Guess a letter: ')).lower()
        pattern = re.compile("^[a-z]{1}$")
        invalid_guess = letter in letters_guessed or re.match(pattern, letter) == None

        if (invalid_guess):
            while (1):
                print()
                if (re.match(pattern, letter) == None):
                    print('Invalid guess. Please enter a correct character!')
                if (letter in letters_guessed):
                    print('\nYou already guessed that letter' + letter)

                letter = str(input('Please guess a letter: '))
                valid_guess = letter not in letters_guessed and re.match(pattern, letter) != None

                if (valid_guess):
                    return letter
        return letter

    def retrieveWordStatus(self, word_family, letters_already_guessed):
        status = ''
        for letter in word_family:
            if (letter in letters_already_guessed):
                status += letter
            else:
                status += '-'
        return status

    def retrieveRemainingWords(self, guess, num_guesses, remaining_words,
                               wordStatus, guesses_num, word_length,
                               createWordFamiliesDict,
                               findHighestCountWordFamily,
                               generateListOfWords):

        word_families = createWordFamiliesDict(remaining_words, guess)
        family_return = wordStatus(word_length)
        avoid_guess = num_guesses == 0 and family_return in word_families

        if (avoid_guess):
            family_return = wordStatus(word_length)
        else:
            family_return = findHighestCountWordFamily(word_families)

        words = generateListOfWords(remaining_words, guess, family_return)
        return words

    def createWordFamiliesDict(self, remainingWords, guess):
        wordFamilies = dict()
        for word in remainingWords:
            status = ''
            for letter in word:
                if (letter == guess):
                    status += guess
                else:
                    status += '-'

            if (status not in wordFamilies):
                wordFamilies[status] = 1
            else:
                wordFamilies[status] = wordFamilies[status] + 1
        return wordFamilies

    def generateListOfWords(self, remainingWords, guess, familyToReturn):
        words = []
        for word in remainingWords:
            word_family = ''
            for letter in word:
                if (letter == guess):
                    word_family += guess
                else:
                    word_family += '-'

            if (word_family == familyToReturn):
                words.append(word)
        return words

    def findHighestCountWordFamily(self, wordFamilies):
        familyToReturn = ''
        maxCount = 0
        for word_family in wordFamilies:
            if wordFamilies[word_family] > maxCount:
                maxCount = wordFamilies[word_family]
                familyToReturn = word_family
        return familyToReturn

    def printCountOfRemainingWords(self, remainingWords):
        show_remain_words = str(input('Want to view the remaining words?: '))
        if (show_remain_words == 'yes'):
            print('Remaining words: ' + str(len(remainingWords)))
        else:
            print()

    def play(self, askForWordLength, askForNumberOfGuesses, remainingWords,
             words, wordStatus, printCountOfRemainingWords, printGameStats,
             askPlayerForGuess, retrieveRemainingWords):
        MODE = 1
        openSession = 1

        while (openSession == 1):
            word_length = askForWordLength(words)
            num_guesses = askForNumberOfGuesses()

            wordStatus = wordStatus(word_length)
            letters_already_guessed = []
            print()

            game_over = 0
            while (game_over == 0):
                if (MODE == 1):
                    printCountOfRemainingWords(remainingWords)

            printGameStats(remainingWords, letters_already_guessed,
                           num_guesses, wordStatus)

            guess = askPlayerForGuess(letters_already_guessed)
            letters_already_guessed.append(guess)
            num_guesses -= 1

            remainingWords = retrieveRemainingWords(guess, remainingWords,
                                                    num_guesses, word_length)

            wordStatus = wordStatus(remainingWords[0], letters_already_guessed)
            print()

            if (guess in wordStatus):
                num_guesses += 1

            if ('-' not in wordStatus):
                game_over = 1
                print('Congratulations! You won!')
                print('Your word was: ' + wordStatus)

            if (num_guesses == 0 and game_over == 0):
                game_over = 1
                print('Haha! You Lose')
                print('Your word was: ' + remainingWords[0])

        print('Thanks for playing Hangman!')

Body:
Self as First Parameter

When creating functions inside classes, the first parameter should be 'self', as you've done in the function askForNumberOfGuesses. This happens because, when calling functions from an object, Python passes the object to 'self' so the method's logic can access its data.

When calling functions such as "play" (in which you haven't used the self parameter in the declaration), the first parameter will be handled as the self, even though it has a different name. So, actually, your code expects the variable 'words' to be a Hangman object.

Static Functions

If the function needs to know information about the object, you need to add the 'self' as the first parameter.
However, if your method does not use any data declared inside the Hangman class (such as self.hangman that you've created inside init) you can just add a "@staticmethod" to the line before the function definition. This way, Python will know that you don't need self and that the first parameter is not the object.

Notice that, if you want to use a static method, you can use the class itself to call the method. You don't even need to create an object:

Hangman.static_function_name(function_parameters)  # calls static function
hangman_object = Hangman()
hangman_object.non_static_function_name(function_parameters)  # calls non-static function
hangman_object.static_function_name(function_parameters)  # calls static function using object (there is no problem)

Design Considerations

Also, I believe you should change your init implementation and use 'self' to store data that you use in more than one function, instead of passing arguments to all the functions and returning them.
Also note that, in order to create a Hangman object, you need to use ():

self.hangman = Hangman  # reference to the Hangman class
self.hangman = Hangman()  # Object of the Hangman class

However, if you create a Hangman object inside init, it will call init again and this will go on "forever". So, you shouldn't create a Hangman object inside it's init method. I believe you should create the Hangman object in play_hangman.py file and call the play method from there.

In my opinion, init should create all the data you need as self.<var_name>, load should prepare words or whatever you need using self.<functions_you_create> and play should just start the game. play_hangman.py shouldn't need to know all these parameters.

hangman.py

class GameClass:
    def __init__(self):
        self.words = list()
        # TODO: Implement adding other game data

    def load(self):
        # TODO: Implement logic
        self.words.append('country')
        pass

    def play(self):
        # TODO: Implement loop logic
        print(self.words)
        # while(True):
        #    break
        pass

play_hangman.py

game = GameClass()
game.load()
game.play()

IDE

Use a good IDE so it will remember you to add self if you are not used yet.


问:
css img on navbar jumps when hover
I'm new at CSS and I'm trying to get this vertical right side menu to work.
The problem: when I hover over the images they get bigger (this is intended) but when I hover between the images everything seems to jump and I can't figure out why.

body {
  font-family: "Quicksand", sans-serif;
  font-size: 18px;
  font-weight: 400;
  color: #eee4e4;
  overflow-x: hidden;
}

ul {
  list-style-type: none;
  box-sizing: border-box;
  float: right;
  position: fixed;
  z-index: 1000;
  right: 0;
  top: 0;
  height: 100%;
  overflow: auto;
  text-align: center;
}

li {
  padding-bottom: 10px;
  padding-top: 10px;
  padding-right: 10px;
  border: solid 2px blue;
}

img {
  height: 40px;
  width: 40px;
}

img:hover {
  width: 50px;
  height: 50px;
}

li:hover {
  padding-right: 0px;
  padding-bottom: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <!-- Social Media NAV -->
  <nav>
    <ul>
      <li>
        <img src="img/facebook1.svg" alt="Facebook"></img>

      </li>
      <li>
        <img src="img/twitter1.svg" alt="Twitter"></img>

      </li>
      <li>
        <img src="img/instagram1.svg" alt="Instagram"></img>

      </li>
      <li>
        <img src="img/whatsapp1.svg" alt="Whatsapp"></img>

      </li>
    </ul>
  </nav>
</body></code>```

答:
This is because you also have a li:hover that is affecting the padding.

Maybe an alternative solution could be using transform in the  and remove the li:hover

```<code>img:hover {
   transform: scale(1.2)
}
</code>```

Title: css img on navbar jumps when hover

Body:
This is because you also have a li:hover that is affecting the padding.

Maybe an alternative solution could be using transform in the <img> and remove the li:hover

img:hover {
   transform: scale(1.2)
}


答:
Just a tad longer than @thelatemail's one-liner.

dt |>
  dplyr::select(
    ID,
    Rounds,
    s            = solution_resp,
  ) |>
  dplyr::mutate(
    s = gsub("\\[|\\]", "", s),               # Remove the brackets
  ) |>
  tibble::rowid_to_column("row_id") |>
  tidyr::separate_rows(s, sep = ",") |>
  dplyr::mutate(
    s = dplyr::recode(s, "-1" = T, "1" = F)   # Make the math easier later
  ) |>
  dplyr::group_by(row_id, ID, Rounds) |>
  dplyr::mutate(
    index       = seq_len(dplyr::n()),        # Remember the ordering
  ) |>
  dplyr::arrange(dplyr::desc(index)) |>       # Reverse
  dplyr::mutate(
    cumulative = dplyr::cumany(s),            # Find the first (last) 1/F.
    s = dplyr::recode(as.character(s), "TRUE" = "-1", "FALSE" = "1")
  ) |>
  dplyr::filter(cumulative) |>                # Drop everything afterwards
  dplyr::ungroup() |>
  dplyr::arrange(ID, Rounds, row_id, index) |>  # Reverse again
  dplyr::group_by(row_id, ID, Rounds) |>
  dplyr::summarize(
    solution_resp = paste(s, collapse = ", "),  # Smush back in a row
    element_count = dplyr::n(),                 # Quick count for inspection
  ) |>
  dplyr::ungroup()
```
<p>Output:</p>
```# A tibble: 12 x 5
   row_id    ID Rounds solution_resp             element_count
    <int> <dbl>  <dbl> <chr>                             <int>
 1      1     2      0 -1, 1, 1, 1, 1, 1, -1                 7
 2      2     2      1 1, -1, 1, -1, 1, -1                   6
 3      3     2      2 -1, 1, 1, 1, 1, -1, 1, -1             8
 4      4     2      3 -1, 1, 1, 1, 1, 1, -1                 7
 5      5     5      0 1, -1, 1, -1, 1, -1                   6
 6      6     5      1 -1, 1, 1, 1, 1, -1, 1, -1             8
 7      7     5      2 -1, 1, 1, 1, 1, 1, -1                 7
 8      8     5      3 1, -1, 1, -1, 1, -1                   6
 9      9     9      0 -1, 1, 1, 1, 1, -1, 1, -1             8
10     10     9      1 -1, 1, 1, 1, 1, 1, -1                 7
11     11     9      2 1, -1, 1, -1, 1, -1                   6
12     12     9      3 -1, 1, 1, 1, 1, -1, 1, -1             8
```

(I'm using the initial dt <- data.frame(ID,Rounds,solution,solution_resp) definition of dt).

Title: In R: shorten list from behind till a certain value

Body:
Suppose i have many and larger lists than in this example.

ID <- c(2,2,2,2,5,5,5,5,9,9,9,9)
Rounds <- c(0,1,2,3,0,1,2,3,0,1,2,3)
solution <- c(as.character('[[-1,1,1,-1],[1,-1,1,-1]]'),as.character('[[-1,1,-1,-1],[1,-1,1,-1]]'),as.character('[[-1,1,1,-1],[1,-1,-1,-1]]') )
solution_resp <- c(as.character('[[-1,1,1,1],[1,1,-1,1]]'),as.character('[[1,-1,1,-1],[1,-1,1,1]]'),as.character('[[-1,1,1,1],[1,-1,1,-1]]'))

dt <- data.frame(ID,Rounds,solution,solution_resp)

dt$solution <- gsub('],[',',', dt$solution, fixed=TRUE)
dt$solution <- gsub('[[',''  , dt$solution, fixed=TRUE)
dt$solution <- gsub(']]',''  , dt$solution, fixed=TRUE)

dt$solution <- as.list(strsplit(dt$solution, ","))

dt$solution_resp <- gsub('],[',',', dt$solution_resp, fixed=TRUE)
dt$solution_resp <- gsub('[[',''  , dt$solution_resp, fixed=TRUE)
dt$solution_resp <- gsub(']]',''  , dt$solution_resp, fixed=TRUE)

dt$solution_resp <- as.list(strsplit(dt$solution_resp, ","))

Looks like this:

   ID Rounds                    solution             solution_resp
1   2      0  -1, 1, 1, -1, 1, -1, 1, -1  -1, 1, 1, 1, 1, 1, -1, 1
2   2      1 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
3   2      2 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
4   2      3  -1, 1, 1, -1, 1, -1, 1, -1  -1, 1, 1, 1, 1, 1, -1, 1
5   5      0 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
6   5      1 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
7   5      2  -1, 1, 1, -1, 1, -1, 1, -1  -1, 1, 1, 1, 1, 1, -1, 1
8   5      3 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
9   9      0 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
10  9      1  -1, 1, 1, -1, 1, -1, 1, -1  -1, 1, 1, 1, 1, 1, -1, 1
11  9      2 -1, 1, -1, -1, 1, -1, 1, -1 1, -1, 1, -1, 1, -1, 1, 1
12  9      3 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1

In the lists dt$solution_resp I would like to drop all 1 from behind until the first -1 appears (counting from right to left).

In the example this would mean shortening the lists by taking off the last element in first row (and every third row). In the second row (and every third) the list shall be shorted by two elements. The third row remains as it is because there is a -1 at the last position already.

Then, I want the dt$solution lists to have the same length.

Solution:

   ID Rounds                    solution             solution_resp
1   2      0  -1, 1, 1, -1, 1, -1, 1     -1, 1, 1, 1, 1, 1, -1
2   2      1 -1, 1, -1, -1, 1, -1         1, -1, 1, -1, 1, -1
3   2      2 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
4   2      3  -1, 1, 1, -1, 1, -1, 1     -1, 1, 1, 1, 1, 1, -1
5   5      0 -1, 1, -1, -1, 1, -1         1, -1, 1, -1, 1, -1
6   5      1 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
7   5      2  -1, 1, 1, -1, 1, -1, 1     -1, 1, 1, 1, 1, 1, -1
8   5      3 -1, 1, -1, -1, 1, -1,        1, -1, 1, -1, 1, -1
9   9      0 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1
10  9      1  -1, 1, 1, -1, 1, -1, 1,    -1, 1, 1, 1, 1, 1, -1
11  9      2 -1, 1, -1, -1, 1, -1,        1, -1, 1, -1, 1, -1
12  9      3 -1, 1, 1, -1, 1, -1, -1, -1 -1, 1, 1, 1, 1, -1, 1, -1

Body:
Just a tad longer than @thelatemail's one-liner.

dt |>
  dplyr::select(
    ID,
    Rounds,
    s            = solution_resp,
  ) |>
  dplyr::mutate(
    s = gsub("\\[|\\]", "", s),               # Remove the brackets
  ) |>
  tibble::rowid_to_column("row_id") |>
  tidyr::separate_rows(s, sep = ",") |>
  dplyr::mutate(
    s = dplyr::recode(s, "-1" = T, "1" = F)   # Make the math easier later
  ) |>
  dplyr::group_by(row_id, ID, Rounds) |>
  dplyr::mutate(
    index       = seq_len(dplyr::n()),        # Remember the ordering
  ) |>
  dplyr::arrange(dplyr::desc(index)) |>       # Reverse
  dplyr::mutate(
    cumulative = dplyr::cumany(s),            # Find the first (last) 1/F.
    s = dplyr::recode(as.character(s), "TRUE" = "-1", "FALSE" = "1")
  ) |>
  dplyr::filter(cumulative) |>                # Drop everything afterwards
  dplyr::ungroup() |>
  dplyr::arrange(ID, Rounds, row_id, index) |>  # Reverse again
  dplyr::group_by(row_id, ID, Rounds) |>
  dplyr::summarize(
    solution_resp = paste(s, collapse = ", "),  # Smush back in a row
    element_count = dplyr::n(),                 # Quick count for inspection
  ) |>
  dplyr::ungroup()

Output:

# A tibble: 12 x 5
   row_id    ID Rounds solution_resp             element_count
    <int> <dbl>  <dbl> <chr>                             <int>
 1      1     2      0 -1, 1, 1, 1, 1, 1, -1                 7
 2      2     2      1 1, -1, 1, -1, 1, -1                   6
 3      3     2      2 -1, 1, 1, 1, 1, -1, 1, -1             8
 4      4     2      3 -1, 1, 1, 1, 1, 1, -1                 7
 5      5     5      0 1, -1, 1, -1, 1, -1                   6
 6      6     5      1 -1, 1, 1, 1, 1, -1, 1, -1             8
 7      7     5      2 -1, 1, 1, 1, 1, 1, -1                 7
 8      8     5      3 1, -1, 1, -1, 1, -1                   6
 9      9     9      0 -1, 1, 1, 1, 1, -1, 1, -1             8
10     10     9      1 -1, 1, 1, 1, 1, 1, -1                 7
11     11     9      2 1, -1, 1, -1, 1, -1                   6
12     12     9      3 -1, 1, 1, 1, 1, -1, 1, -1             8

(I'm using the initial dt <- data.frame(ID,Rounds,solution,solution_resp) definition of dt).


问:
'“1” is not a valid UUID.' Django
Getting this error when i try to delete a reservation from a user account on my restuarant booking app.

Tried a few things to no avail so if anyone can help I'd greatly apprecaite it.

Code is as follows:

Model.py file:

```<code>class Reservations(models.Model):

    """ reservation form categories and attributes """
    user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
    name = models.CharField(max_length=50)
    phone_number = models.CharField(validators=[phoneNumberRegex], max_length=16,
unique=True)
    email = models.EmailField()
    date = models.DateField()
    time = models.CharField(choices=time_options, default="12pm", max_length=10)
    number_of_party = models.IntegerField(choices=party_size, default=1)
    reservation_id = models.UUIDField(primary_key=True, default=uuid.uuid4,
editable=False)
</code>```

Views.py file:

```<code>class DeleteReservationView(LoginRequiredMixin,
UserPassesTestMixin, DeleteView):
    """ A view to delete an reservation """
    model = Reservations
    success_url = "/reservations_account/"

    def test_func(self):
        return self.request.user == self.get_object().user
</code>```

HTML file:

```<code>{% for reservation in reservations %}

<div class="card" style="width: 18rem;">
    <img class="card-img-top" src="{% static 'images/restuarant.jpg' %}" alt="Card restuarant image">
    <div class="card-body">
        <ul>
            <li>{{ reservation.name | capfirst }}</li>
            <li>{{ reservation.phone_number }}</li>
            <li>{{ reservation.email }}</li>
            <li>{{ reservation.date }}</li>
            <li>{{ reservation.time }}</li>
            <li>{{ reservation.number_of_party }}</li>
        </ul>
    </div>
</div>
<a href="{% url 'edit_reservation' user.id %}" type="button" class="btn btn-dark">Edit</a>
<a href="{% url 'delete_reservation' user.id %}" type="button" class="btn btn-dark">Delete</a>
</code>```

Not sure where the 1 is even coming from in this instance.
If you need to see more code ask and i'll edit the post.

Thanks in advance.

答:
Try running your code but instead of UUIDField use AutoField
https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.AutoField
'1' is probaby because UUID generated this as id.
But After all i think better version is to use AutoField</p>

Title: '“1” is not a valid UUID.' Django

Body:
Getting this error when i try to delete a reservation from a user account on my restuarant booking app.

Tried a few things to no avail so if anyone can help I'd greatly apprecaite it.

Code is as follows:

Model.py file:

class Reservations(models.Model):

    """ reservation form categories and attributes """
    user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
    name = models.CharField(max_length=50)
    phone_number = models.CharField(validators=[phoneNumberRegex], max_length=16,
unique=True)
    email = models.EmailField()
    date = models.DateField()
    time = models.CharField(choices=time_options, default="12pm", max_length=10)
    number_of_party = models.IntegerField(choices=party_size, default=1)
    reservation_id = models.UUIDField(primary_key=True, default=uuid.uuid4,
editable=False)

Views.py file:

class DeleteReservationView(LoginRequiredMixin,
UserPassesTestMixin, DeleteView):
    """ A view to delete an reservation """
    model = Reservations
    success_url = "/reservations_account/"

    def test_func(self):
        return self.request.user == self.get_object().user

HTML file:

{% for reservation in reservations %}

{{ reservation.name | capfirst }}

{{ reservation.phone_number }}

{{ reservation.email }}

{{ reservation.date }}

{{ reservation.time }}

{{ reservation.number_of_party }}

Edit
Delete

Not sure where the 1 is even coming from in this instance.
If you need to see more code ask and i'll edit the post.

Thanks in advance.


问:
How to Make Python Print something at nth Iteration within a For Loop?
I want to preface my question by saying that I am very new to Python and have only started using it for a specific class in grad school.

I have written a script to find the root of a function using iterative methods such as the Fixed-point, Bisection, and Newton-Raphson methods. The python code for my algorithms are as follows:

Fixed-Point Method:

```<code>def fixedpoint(func, g_func,x0,tol, MAXIT):

    def g(x):
        return eval(g_func)

    print(f"Seeking root of {func}.")
    print("FIXED POINT ITERATION:")
    iterated_x = g(x0)
    for i in range(0, MAXIT):
        iterated_x = g(iterated_x)
        print("Iteration", i + 1, iterated_x)
        condition = abs(g(iterated_x) - (iterated_x))
        if condition < tol:
            print(f"The root converges to {iterated_x} after {i+1} iterations.")
            break
        if i == MAXIT and condition >= tol:
            print("ERROR: The root did not converge after maximum iterations.")

fixedpoint('x**2 - 4*x + 2', '(x**2+2)/4', 0.75, 10**(-4), 100)
fixedpoint('math.exp(-x) + x - 7 ', '7 - math.exp(-x)', 0.75, 10**(-4), 100)
</code>```

Bisection Method:

```<code>def bisection(func,a, b, tol, MAXIT):

    def f(x):
        return eval(func)

    print(f"Seeking root of {func}")
    print("BISECTION METHOD:")
    if f(a)*f(b) <0:
        for i in range(0, MAXIT):
            c = (a+b)/2
            if f(a)*f(c) < 0:
                a = a
                b = c
                print(f"Iteration", i + 1, f(c))
            elif f(b)*f(c) < 0:
                b = b
                a = c
                print(f"Iteration", i + 1, f(c))
            if f(c) == 0 or abs(f(c)) < tol:
                print ("Exact Solution Found")
                print(f"Iteration", i + 1, c)
                print("The root converges to", c, "after", i + 1, "iterations.")
                break
            elif i == MAXIT and abs(f(c)) > tol:
                print("Bisection method fails.")

    return None

bisection('x**2 - 4*x + 2',0.5, 1, 10**(-4), 100)
bisection('math.exp(-x) + x - 7',6, 8, 10**(-4), 100)
</code>```

Newton-Raphson Method:

```<code>def newtonraphson(func, deriv, x0, tol, MAXIT):

    def f(x):
        return eval(func)

    def ddx(x):
        return eval(deriv)

    print(f"Seeking root of {func}.")
    print("NEWTON-RAPHSON METHOD:")

    for i in range(1, MAXIT):
        iterated_x = x0 - (f(x0)/ddx(x0))
        x0 = iterated_x
        print(f"Iteration", i, x0)

        if f(x0) < tol:
            print(f"The root converges to {x0} after {i} iterations.")
            break
        elif i==MAXIT and f(x0) > tol:
            print("After maximum iterations, root was not found.")

newtonraphson('x**2-4*x+2', '2*x-4', 0.75,10**(-4), 100)
newtonraphson('math.exp(-x) + x - 7', '-(math.exp(-x)) + 1', 0.75,10**(-4), 100)
</code>```

While my script is successfully able to find the roots for the equations I am interested in, I am stuck with a simpler problem. Basically, I want to tell my program that if after maximum iterations, my tolerance condition is not fulfilled, print "Method Failed".

However, my code does not print the statement I want it to when I experiment with functions that don't coverage when maximum iterations is set at 100 and tolerance is set to 0.0001.

Is my syntax right for the fail print statement?

Do conditions like "if i==MAXIT and f(x0) > tol" make sense in the context of the function I have written?

I would appreciate any and all advice for this issue as I am trying hard to improve at Python.

Thank you.

答:
The problem you are facing is that range in python only function from the start index to one before the end index. That is, range(0,3) goes over the numbers (0,1,2). What is happening in your code is that you simply fail to activate the fail condition because the index never actually reaches that value. However, the fix is easy. In your functions where you say:

```<code>for i in range(1,MAXIT):
    if f(x0) < tol:
        print(f"The root converges to {x0} after {i} iterations.")
        break
    elif i==MAXIT and f(x0) > tol:
        print("After maximum iterations, root was not found.")
</code>```

simply replace it with

```<code>for i in range(1,MAXIT):
    if f(x0) < tol:
        print(f"The root converges to {x0} after {i} iterations.")
        return

print("After maximum iterations, root was not found.")
</code>```

instead. What this will do is stop the function if it finds the solution, and give you your error message if you manage to get through the entire loop without finding the answer.

Body:
I want to preface my question by saying that I am very new to Python and have only started using it for a specific class in grad school.

I have written a script to find the root of a function using iterative methods such as the Fixed-point, Bisection, and Newton-Raphson methods. The python code for my algorithms are as follows:

Fixed-Point Method:

def fixedpoint(func, g_func,x0,tol, MAXIT):

    def g(x):
        return eval(g_func)

    print(f"Seeking root of {func}.")
    print("FIXED POINT ITERATION:")
    iterated_x = g(x0)
    for i in range(0, MAXIT):
        iterated_x = g(iterated_x)
        print("Iteration", i + 1, iterated_x)
        condition = abs(g(iterated_x) - (iterated_x))
        if condition < tol:
            print(f"The root converges to {iterated_x} after {i+1} iterations.")
            break
        if i == MAXIT and condition >= tol:
            print("ERROR: The root did not converge after maximum iterations.")

fixedpoint('x**2 - 4*x + 2', '(x**2+2)/4', 0.75, 10**(-4), 100)
fixedpoint('math.exp(-x) + x - 7 ', '7 - math.exp(-x)', 0.75, 10**(-4), 100)

Bisection Method:

def bisection(func,a, b, tol, MAXIT):

    def f(x):
        return eval(func)

    print(f"Seeking root of {func}")
    print("BISECTION METHOD:")
    if f(a)*f(b) <0:
        for i in range(0, MAXIT):
            c = (a+b)/2
            if f(a)*f(c) < 0:
                a = a
                b = c
                print(f"Iteration", i + 1, f(c))
            elif f(b)*f(c) < 0:
                b = b
                a = c
                print(f"Iteration", i + 1, f(c))
            if f(c) == 0 or abs(f(c)) < tol:
                print ("Exact Solution Found")
                print(f"Iteration", i + 1, c)
                print("The root converges to", c, "after", i + 1, "iterations.")
                break
            elif i == MAXIT and abs(f(c)) > tol:
                print("Bisection method fails.")

    return None

bisection('x**2 - 4*x + 2',0.5, 1, 10**(-4), 100)
bisection('math.exp(-x) + x - 7',6, 8, 10**(-4), 100)

Newton-Raphson Method:

def newtonraphson(func, deriv, x0, tol, MAXIT):

    def f(x):
        return eval(func)

    def ddx(x):
        return eval(deriv)

    print(f"Seeking root of {func}.")
    print("NEWTON-RAPHSON METHOD:")

    for i in range(1, MAXIT):
        iterated_x = x0 - (f(x0)/ddx(x0))
        x0 = iterated_x
        print(f"Iteration", i, x0)

        if f(x0) < tol:
            print(f"The root converges to {x0} after {i} iterations.")
            break
        elif i==MAXIT and f(x0) > tol:
            print("After maximum iterations, root was not found.")

newtonraphson('x**2-4*x+2', '2*x-4', 0.75,10**(-4), 100)
newtonraphson('math.exp(-x) + x - 7', '-(math.exp(-x)) + 1', 0.75,10**(-4), 100)

While my script is successfully able to find the roots for the equations I am interested in, I am stuck with a simpler problem. Basically, I want to tell my program that if after maximum iterations, my tolerance condition is not fulfilled, print "Method Failed".

However, my code does not print the statement I want it to when I experiment with functions that don't coverage when maximum iterations is set at 100 and tolerance is set to 0.0001.

Is my syntax right for the fail print statement?

Do conditions like "if i==MAXIT and f(x0) > tol" make sense in the context of the function I have written?

I would appreciate any and all advice for this issue as I am trying hard to improve at Python.

Thank you.

Body:
The problem you are facing is that range in python only function from the start index to one before the end index. That is, range(0,3) goes over the numbers (0,1,2). What is happening in your code is that you simply fail to activate the fail condition because the index never actually reaches that value. However, the fix is easy. In your functions where you say:

for i in range(1,MAXIT):
    if f(x0) < tol:
        print(f"The root converges to {x0} after {i} iterations.")
        break
    elif i==MAXIT and f(x0) > tol:
        print("After maximum iterations, root was not found.")

simply replace it with

for i in range(1,MAXIT):
    if f(x0) < tol:
        print(f"The root converges to {x0} after {i} iterations.")
        return

print("After maximum iterations, root was not found.")

instead. What this will do is stop the function if it finds the solution, and give you your error message if you manage to get through the entire loop without finding the answer.


问:
BC30311 Value of type 'Guna2TextBox' cannot be converted to 'TextBox'
how can i fix it. I try it with gunaUicheckbox to checkbox it can work. But now i trying gunaTextBox to textbox it will show error. i store it with array

Dim test As TextBox()
test = New TextBox() {txtAmatriciana, txtAmericano, txtApplePie, txtCafeLate, txtCappucino, txtCaramelMacciato, txtCheeseCake, txtChickenBBQParmSub, txtChickenLinguini}

答:
I found a solution.

Imports Guna.UI2.WinForms

And use Guna2Textbox() instead of Textbox()


问:
Google Sheet + Script + Textfinder + Check
Hi I'm using this code to get a list of rows that matches the searchtext from column "A" and that works great .
But what I'm trying to do is insert a checkmark in column C for each row that match
So basically how would I use the array from .map((r) => r.offset(0,3).getA1Notation()) to insert a checkmark on those rows in column "C"

Thanks

```<code>function check(){
  var rangeList = SpreadsheetApp.getActive().getSheetByName('sheet1').getRange('A2:A');
  var searchText = "dog";
  .createTextFinder(searchText)
  .matchEntireCell(true)
  .findAll()
  .map((r) => r.offset(0,3).getA1Notation())

   console.log(rangeList);
}
</code>```

答:
From how would I use the array from .map((r) => r.offset(0,3).getA1Notation()) to insert a checkmark on those rows in column "C", in this case, how about the following modification?

Modified script:

function check() {
  var searchText = "dog";

  var sheet = SpreadsheetApp.getActive().getSheetByName('sheet1');
  var rangeList = sheet
    .getRange('A2:A')
    .createTextFinder(searchText)
    .matchEntireCell(true)
    .findAll()
    .map((r) => r.offset(0, 2).getA1Notation());
  sheet.getRangeList(rangeList).insertCheckboxes().check(); // or sheet.getRangeList(rangeList).insertCheckboxes();
  console.log(rangeList);
}
```

I think that .createTextFinder(searchText).matchEntireCell(true).findAll().map((r) => r.offset(0,3).getA1Notation()) occurs an error.

In the case of .map((r) => r.offset(0, 3).getA1Notation()), an array including A1Notation is returned. You can use this for achieving your goal.

When you want to put the checkbox to the column "C", please modify r.offset(0,3).getA1Notation() to r.offset(0, 2).getA1Notation().

If you don't want to insert the checked checkboxes, please remove .check().

References:

getRangeList(a1Notations)

Class RangeList

Body:
Hi I'm using this code to get a list of rows that matches the searchtext from column "A" and that works great .
But what I'm trying to do is insert a checkmark in column C for each row that match
So basically how would I use the array from .map((r) => r.offset(0,3).getA1Notation()) to insert a checkmark on those rows in column "C"

Thanks

function check(){
  var rangeList = SpreadsheetApp.getActive().getSheetByName('sheet1').getRange('A2:A');
  var searchText = "dog";
  .createTextFinder(searchText)
  .matchEntireCell(true)
  .findAll()
  .map((r) => r.offset(0,3).getA1Notation())

   console.log(rangeList);
}

Body:
From how would I use the array from .map((r) => r.offset(0,3).getA1Notation()) to insert a checkmark on those rows in column "C", in this case, how about the following modification?

Modified script:

function check() {
  var searchText = "dog";

  var sheet = SpreadsheetApp.getActive().getSheetByName('sheet1');
  var rangeList = sheet
    .getRange('A2:A')
    .createTextFinder(searchText)
    .matchEntireCell(true)
    .findAll()
    .map((r) => r.offset(0, 2).getA1Notation());
  sheet.getRangeList(rangeList).insertCheckboxes().check(); // or sheet.getRangeList(rangeList).insertCheckboxes();
  console.log(rangeList);
}

I think that .createTextFinder(searchText).matchEntireCell(true).findAll().map((r) => r.offset(0,3).getA1Notation()) occurs an error.

In the case of .map((r) => r.offset(0, 3).getA1Notation()), an array including A1Notation is returned. You can use this for achieving your goal.

When you want to put the checkbox to the column "C", please modify r.offset(0,3).getA1Notation() to r.offset(0, 2).getA1Notation().

If you don't want to insert the checked checkboxes, please remove .check().

References:

getRangeList(a1Notations)

Class RangeList


问:
Restricting the size of widgets programmatically
I'd like to create the layout shown in the picture below. This shows up fine:

```<code>Column( Row, ListView()))
</code>```

While this renders errors:

```<code>Column( Row, Row( ListView(), Column ))
</code>```

As soon as I replace the inner ListView() with Row( ListView(), Column ), nothing shows up and I get varying error messages, based on various changes I did.

Most often, I see a 'viewport has unlimited horizontal size'.

I guess Listview to be the source of the problem. That said, I'm no aware how to fix it.

Furthermore, I did find various hints on SO, but none fixed the problem.

How do I fix the problem?

Update 1

While the right Column() may be fixed width, the ListView() should take all remaining space of the screen [= availableWidth - WidhtOf(Column())].

答:
put the ListView inside a Container And give it height/width

code

```<code>Column(
    children: [
      Row(
        children: [],
      ),
      Row(
        children: [
          Container(
              height: 100,
              width: 100,
              child: ListView(
                children: [
                  Text(
                      "1 C/G")
                ],
              )),
          Column(
            children: [],
          )
        ],
      )
    ],
  ),
</code>```

Body:
I'd like to create the layout shown in the picture below. This shows up fine:

Column( Row, ListView()))

While this renders errors:

Column( Row, Row( ListView(), Column ))

As soon as I replace the inner ListView() with Row( ListView(), Column ), nothing shows up and I get varying error messages, based on various changes I did.

Most often, I see a 'viewport has unlimited horizontal size'.

I guess Listview to be the source of the problem. That said, I'm no aware how to fix it.

Furthermore, I did find various hints on SO, but none fixed the problem.

How do I fix the problem?

Update 1

While the right Column() may be fixed width, the ListView() should take all remaining space of the screen [= availableWidth - WidhtOf(Column())].

Body:
put the ListView inside a Container And give it height/width

code

Column(
    children: [
      Row(
        children: [],
      ),
      Row(
        children: [
          Container(
              height: 100,
              width: 100,
              child: ListView(
                children: [
                  Text(
                      "1 C/G")
                ],
              )),
          Column(
            children: [],
          )
        ],
      )
    ],
  ),


问:
Need help updating time element with output from jq?
Current object with proposed format

```<code>[
  {
    "time": "2022-01-28T17:50:31.620Z"
  }
]
</code>```

Command executed to convert from iso8601 to unix

jq '.[].time | sub("\.[0-9]+Z$"; "Z") | fromdate' time_test.json

Output
1643392231

I've tried varying combinations but how to do I update the time value in the object. I can get the conversion to work but can't seem to update the value with the output.

Expected Result -

```<code>[
  {
    "time": "1643392231"
  }
]
</code>```

答:
Cancel the fractional seconds and you're good to go with fromdate. To escape within the regex, use double backslashes.

jq 'map(.time |= (sub("\\.\\d+"; "") | fromdate))'
```
<pre class="lang-json prettyprint-override"><code>[
  {
    "time": 1643392231
  }
]
</code>```

Demo

Body:
Current object with proposed format

[
  {
    "time": "2022-01-28T17:50:31.620Z"
  }
]

Command executed to convert from iso8601 to unix

jq '.[].time | sub("\.[0-9]+Z$"; "Z") | fromdate' time_test.json

Output
1643392231

I've tried varying combinations but how to do I update the time value in the object. I can get the conversion to work but can't seem to update the value with the output.

Expected Result -

[
  {
    "time": "1643392231"
  }
]

Body:
Cancel the fractional seconds and you're good to go with fromdate. To escape within the regex, use double backslashes.

jq 'map(.time |= (sub("\\.\\d+"; "") | fromdate))'

[
  {
    "time": 1643392231
  }
]

Demo


问:
General structure of classes suited for unittest
I'm working on a play app and want to improve my test coverage before going too far with the project.
So far I have quite good test coverage on the model layer, but the controllers tend to get a lot of logic in them (accumulating stuff and calculating from the model results).

Does anyone have a suggestion on how to structure my application so that all parts are easily testable? I could of course refactor all the logic out of the controller and only have one call to a different class for each controller method and then only use the render methods in the controller, but it seems a bit drastic.

Is there a way I can look at the results after a method has been run in the controller, e.g

```<code>public static void controllerMethod(String a){
    String result = doSomething();
    String calcResult = calculateSomething(a);
    render(result, calcResult)
}
</code>```

How can I test that after this method the expected result and calcResult is what I want it to be in a unittest?

All the examples on the play site is about testing the model layer. I know I can run Functional tests towards the controller, but that is a bit to shallow for what I want to test.

If you have any suggestions about how I can structure my classes in order to have an easily testable application, please let me know.

答:
" How can I test that after this method the expected result and calcResult is what I want it to be in a unittest?"
Don't run the JUnit test against controllerMethod(Sting a) but run two JUnit test against doSomething() and calculateSomething(a). As both return a String this is straight forward.

Edit. Also look into making a separate test project with the same package name as your "production" code as it makes it possible to test package scoped methods.

Body:
I'm working on a play app and want to improve my test coverage before going too far with the project.
So far I have quite good test coverage on the model layer, but the controllers tend to get a lot of logic in them (accumulating stuff and calculating from the model results).

Does anyone have a suggestion on how to structure my application so that all parts are easily testable? I could of course refactor all the logic out of the controller and only have one call to a different class for each controller method and then only use the render methods in the controller, but it seems a bit drastic.

Is there a way I can look at the results after a method has been run in the controller, e.g

public static void controllerMethod(String a){
    String result = doSomething();
    String calcResult = calculateSomething(a);
    render(result, calcResult)
}

How can I test that after this method the expected result and calcResult is what I want it to be in a unittest?

All the examples on the play site is about testing the model layer. I know I can run Functional tests towards the controller, but that is a bit to shallow for what I want to test.

If you have any suggestions about how I can structure my classes in order to have an easily testable application, please let me know.