lundi 1 juillet 2019

Python UnboundLocalError: Problems with a function for choosing words from a dictionary

I've written a function for choosing a single key (=word) from a dictionary. If the key has already been used, another key should be chosen. This is my function:

nom_acc = {"qeso":"qes", "os":"os", "sondra":"sondre", "mawizzi":"mawizze", "khewo":"khewe", "alegra":"alegre", "kendra":"kendre", "zhalia":"zhalie", "achrakh":"achrakh", "ador":"ador", "hoggi":"hogge", "soqwi":"soqwe"}
usedWords = []

def wordChoice():
    global usedWords
    print(usedWords) ### DELETE LATER

    word = random.choice(list(nom_acc))     ### randomly pick a key from a dictionary (which is the nominative form)
    print(word) ### DELETE LATER 
    if word in usedWords: 
        print("gotta pick another word") ### DELETE LATER
        wordChoice() 
    else: 
        usedWords.append(word)          
        accusative = nom_acc[word]

    return word, accusative

The function is embedded into a main program. When I run the code like this, it gives me an error message as soon as a word is chosen that has already been used: UnboundLocalError: local variable 'accusative' referenced before assignment

If I add a dummy value for the word and accusative variable it seems to work:

    if word in usedWords: 
        print("gotta pick another word") ### DELETE LATER
        word="DUMMY"
        accusative="DUMMY" 

But what I want is that another word is chosen from the dictionary if the word has already been used. How do I implement this?

Using ifelse in R when one of the options produces NAs?

I want to vectorize a function that relies on checking a condition and depending on whether this condition is TRUE or FALSE, return the outcome of one of two functions, respectively. The problem is that, when the condition is FALSE, the first function cannot be evaluated. Then, ifelse returns the correct values but it also produces a warning. I would like to produce a function that does not produce warnings.

I have tried ifelse(), but it does not work. I was expecting that this command would skip the evaluation of the first function when the condition is FALSE.

Here is an illustrative piece of R code

p = c(-1,1,-1,1,-1,-1,-1,1)

ifelse(p>0, sqrt(p), p^2)

which returns

[1] 1 1 1 1 1 1 1 1
Warning message:
In sqrt(p) : NaNs produced

As you can see, the outcome is correct but, for some reason, it evaluates the function at the first function when condition is FALSE. Thus, I would like to somehow avoid this issue.

How to match two cells in different sheets in Google Sheet using QUERY function?

I have a sheet with two tabs:

Tab1: The first tab contains data in three columns named A, B and C

Tab2: The second tab contains data in three columns named A, B and C. It also includes two cells which I'm going to use conditions. I called them OpenTime in cell D2 and CloseTime in cell D3.

Goal: I am trying to use query function to search columns in Tab1 and check if their conditions are true, return the value. These are three conditions: 1. Open Time > (June 30, 2019 5:00 PM) 2. Close Time < (June 30, 2019 6:00 PM) 3. C (Value in column C of Tab1) equals to C2 in Tab2 (Column C row 1 in Tab 2) This is what I wrote:

=query(Tab1!$A:$C,"select $B where $A> timestamp '"& text(D2,"yyyy-MM-dd HH:mm:ss")&"'" & "AND $A < timestamp '"&text(D3,"yyyy-MM-dd HH:mm:ss")&"'" & " AND $C Like '"&C2&"'",0)

If I apply the above query in Tab1, it works, However, when I paste it in the second Tab (Tab2) it returns an error. What am I doing wrong?

Here is the error:

Unable to parse query string for Function QUERY parameter 2: PARSE_ERROR: Encountered " "$ "" at line 1, column 8. Was expecting one of: "true" ... "false" ... "date" ... "timeofday" ... "datetime" ... "timestamp" ... "min" ... "max" ... "avg" ... "count" ... "sum" ... "no_values" ... "no_format" ... "is" ... "null" ... "year" ... "month" ... "day" ... "hour" ... "minute" ... "second" ... "millisecond" ... "with" ... "contains" ... "starts" ... "ends" ... "matches" ... "like" ... "now" ... "dateDiff" ... "quarter" ... "lower" ... "upper" ... "dayOfWeek" ... "toDate" ... ... ... ... ... ... "(" ... "*" ... "-" ...

Update: Link to the spreadsheet:

difference between if and when statements in sql

If i have a table with a 'number' column and want to create a new column with values of either 'high', 'medium' or 'low' based on the value in the number column can i use an if/else statement to do this? If so how would this be written?

I have this code for creating the column using a when/then statement:

use master
 select *, case
 when (number > 40) then 'high'
 when (number between 30 and 40) then 'medium'
 else 'low'
 end as 'newColumn'
 from myTable

Basically i'm trying to understand the difference between if/else and when/then statements and why one would be used over the other.

This if/else code doesn't work but i don't know if it's because i'm coding it incorrectly:

use master
select *,
 if (number > 40)
 'high'
 else if (number between 30 and 40)
 'medium'
 else 'low'
 from test

Need to check the condition if the value is `YES` or `NO`. And for the invalid values it should throw some error message

Here is the code what I have tried:

  if(!string.IsNullOrEmpty(Taskinfo.DoRollOver) &&(Taskinfo.DoRollOver != "YES" || Taskinfo.DoRollOver != "NO"))
  {
     throw new DataException("DoRollOver is not valid");
  }

But if I try to give the valid data such as YES or NO still it throws an exception.

How to set a variable to fulfill a condition outside a for loop cycle?

problem:

I created a search form where the user is asked to insert a string into an input form. The string is the name of the city and if it matches one of the 50 cities I have included into a JSON file some function is called. We may have three conditions:

1) The input form is left empty an error log appears.

2) The input form is not empty and the string matches one of the 50 strings in the JSON file a table is displayed.

3) The input form is not empty but the string doesn’t match any of the 50 strings in the JSON file a modal window is displayed

My problem is how and where to write the command:

$(‘#Modal#).show()

In other terms, how and where should I show the modal window whenever the city inserted doesn’t match with any of those included in my JSON file?

I have a cycle for: here the value of the strings in the JSON file is being checked; I wouldn’t put the command into there, otherwise the modal will be called 49 times: since I have 50 cities, one of them matches the string inserted in the input form but the other 49 don't.

I suppose I should create a new variable with a function outside the for loop cycle, setting the condition : "the string matches one and only one of the strings in the JSON file"; then the condition may be true inside the for loop (and then I display the table), whereas it's false outside the for loop (i.e. "if the number of cities found is 0" and then I show the modal window).

The code I wrote so far is the following:

function validateCitta() {
  let text = $('#inlineFormInputCitta').val();
  if (text === "") {
    $("#errorLog").show();
  } else {
    $("#errorLog").hide();
    $.ajax({
      url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCity").val()) + "&format=geocodejson",
      dataType: "json",
      success: function(data) {
        for (let i = 0; i < data.features.length; i++) {
          let typeCity = data.features[i].properties.geocoding.type;
          if (typeCity === "city") {
            let nameCity = data.features[i].properties.geocoding.name;
            for (let i = 0; i < json.tappe.length; i++) {
              let tappa = json.tappe[i];
              let city = json.tappe[i].city;
              if (city === nameCity) {
                console.log("JSON file has been activated");
                $("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");
                $("#tabella").show();
              };
            };
          }
        }
      }
    })
  }
};

How may I set the new variable to fulfill the third 3) condition above?

why the input process cannot go back after else in python

so I have 2 input for my app, I want to show the inputs if my initial variable is not 0, you can see my code below

 ```python 
import random
init = 100
while init > 0:
  x = random.randint(0,24)
  a = int(input("input value a:"))
  if a < 25:
    b = int(input("input value b"))
    if b <= init:
      init -= b
    else:
      print("b should smaller than init")
  else:
    print("a should between 0 and 24")

when I run and put value a more than 25, I got the else a < 25, and redirect again to input value a, but when I put value b more than init, I got the else from b <= init but not redirect to input value b but to value a after while ? can someone help me, thank you