问:
How to hide args to argparse when running script with exec?
I have 2 files, runner.py that runs target.py with subprocess or exec.

They both have command line options.

If runner runs target with subprocess it's ok:

```<code>$ python runner.py
run target.py with subprocess...
target.py: running with dummy = False
</code>```

If runner runs target code with exec (with the -e option):

```<code>$ python runner.py -e
run target.py with exec...
usage: runner.py [-h] [-d]
runner.py: error: unrecognized arguments: -e
</code>```

the command line argument -e is "seen" by target.py code (which accepts only one --dummy option) and raises an error.

How can I hide args to argparse when running script with exec?

Here's the code:

runner.py

```<code>import subprocess
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-e", "--exec", help="run with exec", action="store_true")
    args = parser.parse_args()

    target_filename = "target.py"

    if args.exec:
        print("run target.py with exec...")
        source_code = open(target_filename).read()
        compiled = compile(source_code, filename=target_filename, mode="exec")
        exec(compiled) # OPTION 1 - error on argparse
        # exec(compiled, {}) # OPTION 2 - target does not go inside "if main"
        # exec(compiled, dict(__name__="__main__")) # OPTION 3 - same error as OPTION 1
    else:
        print("run target.py with subprocess...")
        subprocess.run(["python3", target_filename])
</code>```

I tried to hide the globals with the commented options above, but without luck.

Seems related to how argparse works.

target.py

```<code>import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--dummy", help="a dummy option", action="store_true")
    args = parser.parse_args()

    print(f"target.py: running with dummy = {args.dummy}")
</code>```

答:
There is the argparse conflict_handler option so one can write

argparse.ArgumentParser(conflict_handler='resolve') in target script.

resolve removes the conflicting options, but that doesn't handle well similar cases where the options have the same name both in runner and target or the case where you can't or don't want to change the target file.

Here's the solution I have found.

Internally argparse uses sys.argv to retrieve options set with command line.

You can directly set sys.argv = [target_filename] which removes the options, but changing sys can give a lot of other problems.

Using unittest.mock.patch (python3.4+) the sys.argv can be securely altered like this:

```<code>from unittest.mock import patch

# [...]

source_code = open(target_filename).read()
compiled = compile(source_code, filename=target_filename, mode="exec")

# remove command args
with patch('sys.argv', [target_filename]):
    exec(compiled)
</code>```

So one can also run target script code with options:

```<code># run target
with patch('sys.argv', [target_filename]):
    exec(compiled)

# run target with -d
with patch('sys.argv', [target_filename, "-d"]):
    exec(compiled)
</code>```

Body:
I have 2 files, runner.py that runs target.py with subprocess or exec.

They both have command line options.

If runner runs target with subprocess it's ok:

$ python runner.py
run target.py with subprocess...
target.py: running with dummy = False

If runner runs target code with exec (with the -e option):

$ python runner.py -e
run target.py with exec...
usage: runner.py [-h] [-d]
runner.py: error: unrecognized arguments: -e

the command line argument -e is "seen" by target.py code (which accepts only one --dummy option) and raises an error.

How can I hide args to argparse when running script with exec?

Here's the code:

runner.py

import subprocess
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-e", "--exec", help="run with exec", action="store_true")
    args = parser.parse_args()

    target_filename = "target.py"

    if args.exec:
        print("run target.py with exec...")
        source_code = open(target_filename).read()
        compiled = compile(source_code, filename=target_filename, mode="exec")
        exec(compiled) # OPTION 1 - error on argparse
        # exec(compiled, {}) # OPTION 2 - target does not go inside "if main"
        # exec(compiled, dict(__name__="__main__")) # OPTION 3 - same error as OPTION 1
    else:
        print("run target.py with subprocess...")
        subprocess.run(["python3", target_filename])

I tried to hide the globals with the commented options above, but without luck.

Seems related to how argparse works.

target.py

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--dummy", help="a dummy option", action="store_true")
    args = parser.parse_args()

    print(f"target.py: running with dummy = {args.dummy}")

Body:
There is the argparse conflict_handler option so one can write

argparse.ArgumentParser(conflict_handler='resolve') in target script.

resolve removes the conflicting options, but that doesn't handle well similar cases where the options have the same name both in runner and target or the case where you can't or don't want to change the target file.

Here's the solution I have found.

Internally argparse uses sys.argv to retrieve options set with command line.

You can directly set sys.argv = [target_filename] which removes the options, but changing sys can give a lot of other problems.

Using unittest.mock.patch (python3.4+) the sys.argv can be securely altered like this:

from unittest.mock import patch

# [...]

source_code = open(target_filename).read()
compiled = compile(source_code, filename=target_filename, mode="exec")

# remove command args
with patch('sys.argv', [target_filename]):
    exec(compiled)

So one can also run target script code with options:

# run target
with patch('sys.argv', [target_filename]):
    exec(compiled)

# run target with -d
with patch('sys.argv', [target_filename, "-d"]):
    exec(compiled)


来源: stackexchange

问:
Tools for Domain Specific Language/Functions
Our users can enter questions that get answered by students. Our users need a extensible, flexible way to define the correct answers to these questions (which are stored as a simple string).

I would like to expose a library of domain specific functions that users can call on to describe the correct answer. Eg:

```<code>exact_match("puppy") // means the correct answer is the string 'puppy'
</code>```

or

```<code>contains("yesterday") // means any answer with the word 'yesterday' is correct
</code>```

The naive implementation would involve eval'ing user supplied strings in a sandboxed runtime (like a javascript vm or ruby vm). But I'd like to go further and only allow specific functions to be called. Any other scripting would be discarded. Such that:

```<code>puts("foo"); contains("yesterday")
</code>```

would be illegal. Since we don't expose or allow puts().

How can I constrain the execution environment to only run a whitelist of functions? Or is there a different approach to build this kind of external-facing DSL instead of trying to constrain an existing language to a subset of functions?

答:
Just because you're creating a DSL, that doesn't necessarily mean that you have to give the user the ability to enter the code in text.

The key to this is providing a list of method names and your special keyword for them, the "FunCode" tag in the code example below:

Create a mapping from keyword to code, and letting them define everything they need, and then use it.  And I would actually build my own XML parser so that it's not hackable, at least not on a list of zero-day-exploits hackable.

```<code><strDefs>
  <strDef><strNam>sickStr</strNam>
          <strText>sick</strText><strNum>01</strNum><strDef>
  <strDef><strNam>pupStr</strNam>
          <strText>puppy</strText><strNum>02</strNum><strDef>
</strDefs>
<funDefs>
  <funDef><funCode>pfContainsStr</funCode><funLabel>contains</funLabel>
          <funNum>01</funNum></funDef>
  <funDef><funCode>pfXact</funCode><funLabel>exact_match</funLabel>
          <funNum>02</funNum></funDef>
</funDefs>
<queries>
 <query><fun>01</fun><str>02</str>
   </query>
</queries>
</code>```

The above XML more represents the idea and the structure of what to do, but rather in a user interface, so the user is constrained.  The user interface code that allows the data-entry of the above data should be running on your server, and they only interact with it.  Any code that runs on their browser is hackable, because they can just save the page, edit the HTML (and/or JavaScript), and run that, which is their code now, not yours anymore.

You can't really open the door (pandora's box) and allow just anyone to write just any code and have it evaluated / interpreted by the language parser, because some hacker is going to exploit it.  You must lock down the strings, probably by having them enter them into your database in an earlier step, and each string gets its own token that YOU generate (a SQL Server primary key is very simple, usable, and secure), but give them a display representation so it's readable to them.

Then give them a list of methods / functions they can use, along with a token (a primary key can also serve here, perhaps with a kind of table prefix) and also a display representation (label).

If you have them put all of their labels into yet another table, you can have SQL make sure that all of their labels are unique to each other in the whole "language", and then you can allow them to try to define their expressions in the language they want to use.  This has the advantage that foreign languages can be used, but you don't have to do anything terribly special.

An important piece would be the verify button, that would translate their expression into unique tokens and back again, checking that the round-trip was successful.  If it wasn't successful, there's some kind of ambiguity, and you might be able to allow them an option to use the list of tokens as the source in that case.

If you heavily rely on set-based logic for the underlying foundation of the language and your tables, you should be able to produce a coherent DSL that works.  Many DSL creation problems are ones of integrity, where there are underlying assumptions that are contradictory, unintentionally mutually exclusive, or nonsensical.  Truth is an unshakeable foundation.  Anything else has a lie somewhere -- that you're trying to build on.

Sudoku is illustrative here.  When you screw up a Sudoku, you often don't know that you have done so, and you keep building on that false foundation, until you get to the completion of the puzzle, and one whole string of assumptions disagrees with a different string of assumptions.  They can't both be true.  But you can't tell where you went wrong because you're too far away from the mistake and can not work backwards (easily).  All steps taken look correct.  A DSL, a database schema, and code, are all this way.  Baby steps, that are double- and even triple-checked, and hopefully "correct by inspection", are the best way to "grow" a DSL, slowly, piece-by-piece.  The best way to not have flaws is to not add them in the first place.

You don't want bugs in your DSL. Keep it spartan.  KISS - Keep it simple, Sparticus! And I have personally found that keeping it set-based, if not overtly, under the covers, accomplishes this very well.

Finally, to be able to think this way, I've studied languages for a long time, and have cultivated a curiosity about how languages have come to be.  Books are a good quality source of information, as they have a higher quality level than the internet, which is nevertheless also an indispensable source.  Some of my favorite languages:  Forth, Factor, SETL, F#, C#, Visual FoxPro (especially for its embedded SQL), T-SQL, Common LISP, Clojure, and probably my favorite, Dylan, an INFIX Lisp without parentheses that Apple experimented with and abandoned, with a syntax that seems to me reminiscent of Pascal, which I sort of liked.  The language list is actually much longer than that (and I haven't written code for many of them -- just studied them or their genesis), but that's enough for now.

One of my favorite books, and immensely interesting for the "people" side of it, is "Masterminds of Programming: Conversations with the Creators of Major Programming Languages" (Theory in Practice (O'Reilly)) 1st Edition, Kindle Edition
by Federico Biancuzzi (Author), Chromatic (Author)

By the way, don't let them compromise the integrity of your DSL -- require that it is expressible set-based, and things should go well (IMHO). I hope it works out well for you. Add a comment to my answer telling me how it worked out, if you think of it. And don't forget to choose my answer if you think it's the best!  We work hard for the money! ;-)

ContentLicense: CC BY-SA 4.0

Body:
Our users can enter questions that get answered by students. Our users need a extensible, flexible way to define the correct answers to these questions (which are stored as a simple string).

I would like to expose a library of domain specific functions that users can call on to describe the correct answer. Eg:

exact_match("puppy") // means the correct answer is the string 'puppy'

or

contains("yesterday") // means any answer with the word 'yesterday' is correct

The naive implementation would involve eval'ing user supplied strings in a sandboxed runtime (like a javascript vm or ruby vm). But I'd like to go further and only allow specific functions to be called. Any other scripting would be discarded. Such that:

puts("foo"); contains("yesterday")

would be illegal. Since we don't expose or allow puts().

How can I constrain the execution environment to only run a whitelist of functions? Or is there a different approach to build this kind of external-facing DSL instead of trying to constrain an existing language to a subset of functions?

Body:
Just because you're creating a DSL, that doesn't necessarily mean that you have to give the user the ability to enter the code in text.

The key to this is providing a list of method names and your special keyword for them, the "FunCode" tag in the code example below:

Create a mapping from keyword to code, and letting them define everything they need, and then use it.  And I would actually build my own XML parser so that it's not hackable, at least not on a list of zero-day-exploits hackable.

<strDefs>
  <strDef><strNam>sickStr</strNam>
          <strText>sick</strText><strNum>01</strNum><strDef>
  <strDef><strNam>pupStr</strNam>
          <strText>puppy</strText><strNum>02</strNum><strDef>
</strDefs>
<funDefs>
  <funDef><funCode>pfContainsStr</funCode><funLabel>contains</funLabel>
          <funNum>01</funNum></funDef>
  <funDef><funCode>pfXact</funCode><funLabel>exact_match</funLabel>
          <funNum>02</funNum></funDef>
</funDefs>
<queries>
 <query><fun>01</fun><str>02</str>
   </query>
</queries>

The above XML more represents the idea and the structure of what to do, but rather in a user interface, so the user is constrained.  The user interface code that allows the data-entry of the above data should be running on your server, and they only interact with it.  Any code that runs on their browser is hackable, because they can just save the page, edit the HTML (and/or JavaScript), and run that, which is their code now, not yours anymore.

You can't really open the door (pandora's box) and allow just anyone to write just any code and have it evaluated / interpreted by the language parser, because some hacker is going to exploit it.  You must lock down the strings, probably by having them enter them into your database in an earlier step, and each string gets its own token that YOU generate (a SQL Server primary key is very simple, usable, and secure), but give them a display representation so it's readable to them.

Then give them a list of methods / functions they can use, along with a token (a primary key can also serve here, perhaps with a kind of table prefix) and also a display representation (label).

If you have them put all of their labels into yet another table, you can have SQL make sure that all of their labels are unique to each other in the whole "language", and then you can allow them to try to define their expressions in the language they want to use.  This has the advantage that foreign languages can be used, but you don't have to do anything terribly special.

An important piece would be the verify button, that would translate their expression into unique tokens and back again, checking that the round-trip was successful.  If it wasn't successful, there's some kind of ambiguity, and you might be able to allow them an option to use the list of tokens as the source in that case.

If you heavily rely on set-based logic for the underlying foundation of the language and your tables, you should be able to produce a coherent DSL that works.  Many DSL creation problems are ones of integrity, where there are underlying assumptions that are contradictory, unintentionally mutually exclusive, or nonsensical.  Truth is an unshakeable foundation.  Anything else has a lie somewhere -- that you're trying to build on.

Sudoku is illustrative here.  When you screw up a Sudoku, you often don't know that you have done so, and you keep building on that false foundation, until you get to the completion of the puzzle, and one whole string of assumptions disagrees with a different string of assumptions.  They can't both be true.  But you can't tell where you went wrong because you're too far away from the mistake and can not work backwards (easily).  All steps taken look correct.  A DSL, a database schema, and code, are all this way.  Baby steps, that are double- and even triple-checked, and hopefully "correct by inspection", are the best way to "grow" a DSL, slowly, piece-by-piece.  The best way to not have flaws is to not add them in the first place.

You don't want bugs in your DSL. Keep it spartan.  KISS - Keep it simple, Sparticus! And I have personally found that keeping it set-based, if not overtly, under the covers, accomplishes this very well.

Finally, to be able to think this way, I've studied languages for a long time, and have cultivated a curiosity about how languages have come to be.  Books are a good quality source of information, as they have a higher quality level than the internet, which is nevertheless also an indispensable source.  Some of my favorite languages:  Forth, Factor, SETL, F#, C#, Visual FoxPro (especially for its embedded SQL), T-SQL, Common LISP, Clojure, and probably my favorite, Dylan, an INFIX Lisp without parentheses that Apple experimented with and abandoned, with a syntax that seems to me reminiscent of Pascal, which I sort of liked.  The language list is actually much longer than that (and I haven't written code for many of them -- just studied them or their genesis), but that's enough for now.

One of my favorite books, and immensely interesting for the "people" side of it, is "Masterminds of Programming: Conversations with the Creators of Major Programming Languages" (Theory in Practice (O'Reilly)) 1st Edition, Kindle Edition
by Federico Biancuzzi (Author), Chromatic (Author)

By the way, don't let them compromise the integrity of your DSL -- require that it is expressible set-based, and things should go well (IMHO). I hope it works out well for you. Add a comment to my answer telling me how it worked out, if you think of it. And don't forget to choose my answer if you think it's the best!  We work hard for the money! ;-)


问:
How can I replace simple text with a validated URL?
I have to inputs, one is for when you enter the a site name and the other one is only a readable input where the site name turns into the url. Like in the screenshot below:

So I have this:

  const handleChange = (e) => {
    setSiteInfoDataAction({
      ...siteInfoData,
      siteName: e.target.value, // for the Site Name input
      url: e.target.value.toLowerCase().replace(/\s/g, "-"), // for the URL input
    });

    e.preventDefault();
  };
```

So the only validation i am doing is that every time there is a space, a hyphen is replacing the space. But I need to validate that the user is entering a valid name to recreate the URL. Get it? I need to regex to allow the user to enter only URL friendly characters.

Any ideas on how I can achieve that?

EDIT
You should notice that the regex should validate only the part after the slash /. Just like in the input in the screenshot. So the regex won't validate any http/s or www. Just whatever is after the / should be URL friendly.

答:
There are two ways to achieve your goal:

1. slugify the input

2. use built-in encodeURI() method

Both result in valid URL. However, the question specification (like replace ' '  with -) has closer match to slug conversion.

Slugify URL

Other than whitespaces, additional characters need to be handled, e.g:

special characters

non-word characters

other formatting

In JS, a function to slugify string can be created like this (Source):

```<code>function slugify(string) {
  const a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;'
  const b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------'
  const p = new RegExp(a.split('').join('|'), 'g')

  return string.toString().toLowerCase()
    .replace(/\s+/g, '-') // Replace spaces with -
    .replace(p, c => b.charAt(a.indexOf(c))) // Replace special characters
    .replace(/&/g, '-and-') // Replace & with 'and'
    .replace(/[^\w\-]+/g, '') // Remove all non-word characters
    .replace(/\-\-+/g, '-') // Replace multiple - with single -
    .replace(/^-+/, '') // Trim - from start of text
    .replace(/-+$/, '') // Trim - from end of text
}
</code>```

Then, in the code, call the slugify function

```<code>... //other codes
  url: slugify(e.target.value)
... //other codes
</code>```

URL Encoding

This approach simply converts input characters to URL-encoded characters. encodeURI(string)  is built-in JS function to handle it. Just call it in the function:

```<code>... //other codes
  url: encodeURI(e.target.value)
... //other codes
</code>```

The drawback is the URL probably will not look pretty, although still valid.

The best choice depends on the use case. If URL for blog or article is desired, first approach would be the best. If it is used solely for converting plain text to valid URL, second approach would be faster.

Body:
I have to inputs, one is for when you enter the a site name and the other one is only a readable input where the site name turns into the url. Like in the screenshot below:

So I have this:

  const handleChange = (e) => {
    setSiteInfoDataAction({
      ...siteInfoData,
      siteName: e.target.value, // for the Site Name input
      url: e.target.value.toLowerCase().replace(/\s/g, "-"), // for the URL input
    });

    e.preventDefault();
  };

So the only validation i am doing is that every time there is a space, a hyphen is replacing the space. But I need to validate that the user is entering a valid name to recreate the URL. Get it? I need to regex to allow the user to enter only URL friendly characters.

Any ideas on how I can achieve that?

EDIT
You should notice that the regex should validate only the part after the slash /. Just like in the input in the screenshot. So the regex won't validate any http/s or www. Just whatever is after the / should be URL friendly.

Body:
There are two ways to achieve your goal:

1. slugify the input

2. use built-in encodeURI() method

Both result in valid URL. However, the question specification (like replace ' '  with -) has closer match to slug conversion.

Slugify URL

Other than whitespaces, additional characters need to be handled, e.g:

special characters

non-word characters

other formatting

In JS, a function to slugify string can be created like this (Source):

function slugify(string) {
  const a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;'
  const b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------'
  const p = new RegExp(a.split('').join('|'), 'g')

  return string.toString().toLowerCase()
    .replace(/\s+/g, '-') // Replace spaces with -
    .replace(p, c => b.charAt(a.indexOf(c))) // Replace special characters
    .replace(/&/g, '-and-') // Replace & with 'and'
    .replace(/[^\w\-]+/g, '') // Remove all non-word characters
    .replace(/\-\-+/g, '-') // Replace multiple - with single -
    .replace(/^-+/, '') // Trim - from start of text
    .replace(/-+$/, '') // Trim - from end of text
}

Then, in the code, call the slugify function

... //other codes
  url: slugify(e.target.value)
... //other codes

URL Encoding

This approach simply converts input characters to URL-encoded characters. encodeURI(string)  is built-in JS function to handle it. Just call it in the function:

... //other codes
  url: encodeURI(e.target.value)
... //other codes

The drawback is the URL probably will not look pretty, although still valid.

The best choice depends on the use case. If URL for blog or article is desired, first approach would be the best. If it is used solely for converting plain text to valid URL, second approach would be faster.


问:
Cut m and n letters from end of string, then find number of turns to get back original string
Question: Given are a string and m and n.

input 1: original string

input 2: m (less than length of string): cut m alphabets from end of string and then add to begining of string.

input 3: n (less than length of string) : cut n alphabets from end of string obtained from above step and then add to begining of that string.

This process is continued, need to find out the number turns it takes to get back original string.

def harry(str, m, n):
    le = len(str)
    org = str.upper()
    str = str.upper()
    turn = 0
    for i in str:
        str3 = str[-m:] # last n letters
        str = str.replace(' ', '')[:-m]
        str = str3 + str
        print(str)
        if org != str:
            turn = turn + 1
            str4 = str[-n:]
            str = str.replace(' ', '')[:-n]
            str= str4 + str
            print(str)
            turn = turn + 1
        if org == str:
            break
    print(turn)

str = input("Enter the string")
m=int(input("Enter the value of m"))
n=int(input("Enter the value of n"))
harry(str, m, n)
```

<p>output obtained:</p>

```Enter the stringarya
Enter the value of m1
Enter the value of n2
AARY
RYAA
ARYA
2
```

<p>original output to be obtained: </p>

```3
```

(It takes 3 turns to get back original string Arya.)

I am getting output for all words except words like this, especially when same letter occurs consecutively.
Please help me out with this.

答:
Actually you will take atleast one step to see whether they are equal or not. So your turn should start from 1.

See: https://ide.geeksforgeeks.org/Hw4AWx1O95

```<code>def harry(str, m, n):
    le = len(str)
    org = str.upper()
    str = str.upper()
    turn = 1 # <--------Here
    for i in str:
        str3 = str[-m:] # last n letters
        str = str.replace(' ', '')[:-m]
        str = str3 + str
        print(str)
        if org != str:
            turn = turn + 1
            str4 = str[-n:]
            str = str.replace(' ', '')[:-n]
            str= str4 + str
            print(str)
        if org == str:

            break
        turn = turn + 1 #< --------------- Here

    print(turn)

str = input("Enter the string\n")
m=int(input("Enter the value of m\n"))
n=int(input("Enter the value of n\n"))
harry(str, m, n)
</code>```

Body:
Question: Given are a string and m and n.

input 1: original string

input 2: m (less than length of string): cut m alphabets from end of string and then add to begining of string.

input 3: n (less than length of string) : cut n alphabets from end of string obtained from above step and then add to begining of that string.

This process is continued, need to find out the number turns it takes to get back original string.

def harry(str, m, n):
    le = len(str)
    org = str.upper()
    str = str.upper()
    turn = 0
    for i in str:
        str3 = str[-m:] # last n letters
        str = str.replace(' ', '')[:-m]
        str = str3 + str
        print(str)
        if org != str:
            turn = turn + 1
            str4 = str[-n:]
            str = str.replace(' ', '')[:-n]
            str= str4 + str
            print(str)
            turn = turn + 1
        if org == str:
            break
    print(turn)

str = input("Enter the string")
m=int(input("Enter the value of m"))
n=int(input("Enter the value of n"))
harry(str, m, n)

output obtained:

Enter the stringarya
Enter the value of m1
Enter the value of n2
AARY
RYAA
ARYA
2

original output to be obtained:

3

(It takes 3 turns to get back original string Arya.)

I am getting output for all words except words like this, especially when same letter occurs consecutively.
Please help me out with this.

Body:
Actually you will take atleast one step to see whether they are equal or not. So your turn should start from 1.

See: https://ide.geeksforgeeks.org/Hw4AWx1O95

def harry(str, m, n):
    le = len(str)
    org = str.upper()
    str = str.upper()
    turn = 1 # <--------Here
    for i in str:
        str3 = str[-m:] # last n letters
        str = str.replace(' ', '')[:-m]
        str = str3 + str
        print(str)
        if org != str:
            turn = turn + 1
            str4 = str[-n:]
            str = str.replace(' ', '')[:-n]
            str= str4 + str
            print(str)
        if org == str:

            break
        turn = turn + 1 #< --------------- Here

    print(turn)

str = input("Enter the string\n")
m=int(input("Enter the value of m\n"))
n=int(input("Enter the value of n\n"))
harry(str, m, n)


问:
No option of debug JS remotely on Android simulator
I am using android 8.1 simulator to debug my React Native (0.62) app with VS code on Win10. After firing up the app with react-native run-android, Ctrl+m brings up the dev menu:

But there is no option of Debug JS remotely in the menu. How can I bring up the option of Debug JS Remotely?

答:
You should be able to debug a RN app in Chrome dev tools, unless you are running a production build.
If you want to use another debugger, you can set it with the REACT_DEBUGGER env. variable. Example:

```<code>REACT_DEBUGGER="node /path/to/launchDebugger.js --port 2345 --type ReactNative"
</code>```

For VSCode there is this extension. There is a section explaining how to debug.

Body:
You should be able to debug a RN app in Chrome dev tools, unless you are running a production build.
If you want to use another debugger, you can set it with the REACT_DEBUGGER env. variable. Example:

REACT_DEBUGGER="node /path/to/launchDebugger.js --port 2345 --type ReactNative"

For VSCode there is this extension. There is a section explaining how to debug.


问:
Does a line of code run even a loop is not finished iterating yet?
As the title says.... does function2() run after the for loop finishes iterating or does it run even before the iteration is completed?

```<code>function1() {
    for () {
        <....>
    }
    this.function2();
}
</code>```

答:
A simple snippet to test this:

function loop(){
  for(var i = 0; i < 10; i++){
    console.log(i)
  }
  function2()
}

function function2(){
  console.log('done');
}

loop();```

So no it doesn't run before the loop is finished

Body:
As the title says.... does function2() run after the for loop finishes iterating or does it run even before the iteration is completed?

function1() {
    for () {
        <....>
    }
    this.function2();
}

Body:
A simple snippet to test this:

function loop(){
  for(var i = 0; i < 10; i++){
    console.log(i)
  }
  function2()
}

function function2(){
  console.log('done');
}

loop();

So no it doesn't run before the loop is finished


问:
how to combine two themes in android
Can someone please tell me how to combine two theme values(Ex:@android:style/Theme.Dialog and @android:style/Theme.NoTitleBar) for android:theme attribute in manifest file.

Thanks,
venu

答:
Try something like this:</p>

```<code> android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to combine two themes in android

Body:
Try something like this:

 android:theme="@android:style/Theme.NoTitleBar.Fullscreen"


问:
Why the nested dictionary cannot append into list correctly?
I try to append a dictionary into a list, but I find the sub-dictionary is always keep the last one I read from CSV file(deviceProfile.csv). Does anyone know why?
Here is my CSV file.

```<code>name,description,primaryTable,startingAddress,boolIndex
test_name_1,1,table_1,1,1
test_name_2,2,table_2,2,2
test_name_3,3,table_3,3,3
</code>```

Here is my python code.

```<code>import csv
import yaml
from pprint import pprint

resource = {
    'name': "",
    'description': "",
    'attributes':
      { 'primaryTable': "", 'startingAddress': "", 'boolIndex': "" },
}

resourceArray = []

with open("deviceProfile.csv") as f:
    myCsvDic = csv.DictReader(f)
    for row in myCsvDic:
        resource['name'] = row['name']
        resource['description'] = row['description']
        resource['attributes']['primaryTable'] = row['primaryTable']
        resource['attributes']['startingAddress'] = row['startingAddress']
        resource['attributes']['boolIndex'] = row['boolIndex']
        test = resource.copy()
        resourceArray.append(test)

pprint (resourceArray)
</code>```

And the result is

```<code>[{'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '1',
  'name': 'test_name_1'},
 {'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '2',
  'name': 'test_name_2'},
 {'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '3',
  'name': 'test_name_3'}]
</code>```

It is strange that name and description are appended into list correctly, but attributes. The attributes is always append the last sub-dictionary.

Any help will be appreciated. Thanks.

答:
This is because of copy. by default copy is shallow copy and it will copy just level-1 elements.
you should use deepcopy in your case. replace test = resource.copy() with:

```<code>from copy import deepcopy

test = deepcopy(resource)
</code>```

take a look at this Link for more information, or any other links that tells you about copy(shallow and deep).

Body:
I try to append a dictionary into a list, but I find the sub-dictionary is always keep the last one I read from CSV file(deviceProfile.csv). Does anyone know why?
Here is my CSV file.

name,description,primaryTable,startingAddress,boolIndex
test_name_1,1,table_1,1,1
test_name_2,2,table_2,2,2
test_name_3,3,table_3,3,3

Here is my python code.

import csv
import yaml
from pprint import pprint

resource = {
    'name': "",
    'description': "",
    'attributes':
      { 'primaryTable': "", 'startingAddress': "", 'boolIndex': "" },
}

resourceArray = []

with open("deviceProfile.csv") as f:
    myCsvDic = csv.DictReader(f)
    for row in myCsvDic:
        resource['name'] = row['name']
        resource['description'] = row['description']
        resource['attributes']['primaryTable'] = row['primaryTable']
        resource['attributes']['startingAddress'] = row['startingAddress']
        resource['attributes']['boolIndex'] = row['boolIndex']
        test = resource.copy()
        resourceArray.append(test)

pprint (resourceArray)

And the result is

[{'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '1',
  'name': 'test_name_1'},
 {'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '2',
  'name': 'test_name_2'},
 {'attributes': {'boolIndex': '3',
                 'primaryTable': 'table_3',
                 'startingAddress': '3'},
  'description': '3',
  'name': 'test_name_3'}]

It is strange that name and description are appended into list correctly, but attributes. The attributes is always append the last sub-dictionary.

Any help will be appreciated. Thanks.

Body:
This is because of copy. by default copy is shallow copy and it will copy just level-1 elements.
you should use deepcopy in your case. replace test = resource.copy() with:

from copy import deepcopy

test = deepcopy(resource)

take a look at this Link for more information, or any other links that tells you about copy(shallow and deep).


问:
Error: Could not find sqlite3-1.4.0 in any of the sources
I'm currently trying to get a run.rb file going, but I keep getting errors with sqlite3. When I type bundle install, I get this success message:

```<code>Fetching gem metadata from https://rubygems.org/.........
Resolving dependencies...
Using rake 12.3.2
Using concurrent-ruby 1.1.4
Using i18n 1.5.3
Using minitest 5.11.3
Using thread_safe 0.3.6
Using tzinfo 1.2.5
Using activesupport 5.2.2
Using activemodel 5.2.2
Using arel 9.0.0
Using activerecord 5.2.2
Using bundler 2.0.1
Using coderay 1.1.2
Using equatable 0.5.0
Using method_source 0.9.2
Using mustermann 1.0.3
Using necromancer 0.4.0
Using tty-color 0.4.3
Using pastel 0.7.2
Using pry 0.12.2
Using rack 2.0.6
Using rack-protection 2.0.5
Using require_all 2.0.0
Using tilt 2.0.9
Using sinatra 2.0.5
Using sinatra-activerecord 2.0.13
Using sqlite3 1.4.0
Using timers 4.3.0
Using tty-cursor 0.6.0
Using tty-screen 0.6.5
Using wisper 2.0.0
Using tty-reader 0.5.0
Using tty-prompt 0.18.1
Bundle complete! 7 Gemfile dependencies, 32 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
</code>```

However, when running ruby app/run.rb I get this message:

```<code>Could not find sqlite3-1.4.0 in any of the sources
</code>```

I've been trying for hours to figure out what the issue is, I've uninstalled and reinstalled sqlite3, bundle installed a million times, and nothing seems to be working. Any ideas would be much appreciated!

答:
You can try installing the libsqlite3-dev package:

sudo apt-get install -y sqlite3 libsqlite3-dev
```
<p>or</p>
```gem 'sqlite3', '~> 1.3', '>= 1.3.11'
```

Body:
I'm currently trying to get a run.rb file going, but I keep getting errors with sqlite3. When I type bundle install, I get this success message:

Fetching gem metadata from https://rubygems.org/.........
Resolving dependencies...
Using rake 12.3.2
Using concurrent-ruby 1.1.4
Using i18n 1.5.3
Using minitest 5.11.3
Using thread_safe 0.3.6
Using tzinfo 1.2.5
Using activesupport 5.2.2
Using activemodel 5.2.2
Using arel 9.0.0
Using activerecord 5.2.2
Using bundler 2.0.1
Using coderay 1.1.2
Using equatable 0.5.0
Using method_source 0.9.2
Using mustermann 1.0.3
Using necromancer 0.4.0
Using tty-color 0.4.3
Using pastel 0.7.2
Using pry 0.12.2
Using rack 2.0.6
Using rack-protection 2.0.5
Using require_all 2.0.0
Using tilt 2.0.9
Using sinatra 2.0.5
Using sinatra-activerecord 2.0.13
Using sqlite3 1.4.0
Using timers 4.3.0
Using tty-cursor 0.6.0
Using tty-screen 0.6.5
Using wisper 2.0.0
Using tty-reader 0.5.0
Using tty-prompt 0.18.1
Bundle complete! 7 Gemfile dependencies, 32 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.

However, when running ruby app/run.rb I get this message:

Could not find sqlite3-1.4.0 in any of the sources

I've been trying for hours to figure out what the issue is, I've uninstalled and reinstalled sqlite3, bundle installed a million times, and nothing seems to be working. Any ideas would be much appreciated!

Body:
You can try installing the libsqlite3-dev package:

sudo apt-get install -y sqlite3 libsqlite3-dev

or

gem 'sqlite3', '~> 1.3', '>= 1.3.11'


问:
Laravel event with socket-io [receive notifications]
For the first time attempt with laravel and socket-io I am trying to send very simple notification to admins. So far my event is firing but I need help with receiving event notifications.

Logic

It's very basic because I want to understand the process.

User opens page Add Product

Admin gets notification that user X is in App Product page.

So far

So far I can fire event and get user data (user that is in Add Product page)

Need help for

I need help to understand the way that admin receives notifications.

Code

Component script

```<code>created() {
  let user = JSON.parse(localStorage.getItem("user"))
  this.listenForBroadcast(user);
},
methods: {
  listenForBroadcast(user) {
    Echo.join('userInAddProduct')
    .here((Loggeduser) => {
      console.log('My user data', Loggeduser);
    });
  }
}
</code>```

Result of code above

```<code>My user data [{…}]
  0:
    id: 1
    name: "Test User"
    photo: "User-1588137335.png"
    __ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
    get id: ƒ reactiveGetter()
    set id: ƒ reactiveSetter(newVal)
    get name: ƒ reactiveGetter()
    set name: ƒ reactiveSetter(newVal)
    get photo: ƒ reactiveGetter()
    set photo: ƒ reactiveSetter(newVal)
    __proto__: Object
    length: 1
    __proto__: Array(0)
</code>```

Channels route

```<code>Broadcast::channel('userInAddProduct', function ($user) {
    return [
        'id' => $user->id,
        'photo' => $user->photo,
        'name' => $user->name
    ];
});
</code>```

MessagePushed (event file)

```<code>class MessagePushed implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function broadcastOn()
    {
        return new PresenceChannel('userInAddProduct');
    }
}
</code>```

Question

How can I receive notification about this event fire? I want to notify my admin users that user x is in page Add Product?

Update

Since I published this question I've made some changes and here is my latest code + questions.

bootstrap.js

```<code>window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001',
    auth: { // added authentication token (because all my events are private)
        headers: {
            Authorization: localStorage.getItem('access_token'),
        },
    },
});
</code>```

Add.vue (add product component where event has to be fired)

```<code>listenForBroadcast(user) {
    let ui = JSON.parse(localStorage.getItem("user"))
    Echo.join('userInAddProduct')
    .here((users) => {
        console.log('My user data', users)
    })
    .joining((user) => {
        this.$notify({
            title: '',
            message: user + 'joining',
            offset: 100,
            type: 'success'
        });
    })
    .leaving((user) => {
        this.$notify({
            title: '',
            message: user + 'is leaving new product',
            offset: 100,
            type: 'warning'
        });
    })
    .whisper('typing', (e) => {
        this.$notify({
            title: '',
            message: ui.username + 'is adding new product',
            offset: 100,
            type: 'success'
        })
    })
    .listenForWhisper('typing', (e) => {
        console.log(e)
        this.$notify({
            title: '',
            message: ui.username + 'is entered add new product page.',
            offset: 100,
            type: 'success'
        });
    })
    .notification((notification) => {
        console.log('noitication listener: ', notification.type);
    });
},
</code>```

Then I've made 4 files to handle events:

Event (passing data)

Event Listener (process the database storage and showing notifications to online admins)

Observer (firing event)

Notification (store data to database for admins in case when event fire they're not online so they can see notifications later on)

Event file

```<code>class MessagePushed extends Event implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;
    public $product;

    public function __construct(User $user, Product $product)
    {
        $this->user = $user;
        $this->product = $product;
    }

    public function broadcastOn()
    {
        return new PresenceChannel('userInAddProduct');
    }
}
</code>```

Listener file

```<code>class ThingToDoAfterEventWasFired implements ShouldQueue
{
    public function handle(MessagePushed $event)
    {
        //Log testing purpose only
        $user = $event->user->username;
        $product = $event->product->name;

        // Real data that should be broadcasts
        $user2 = $event->user;
        $product2 = $event->product;

        // inform all admins and authorized staffs about new product
        $admins = User::role(['admin', 'staff'])->get();
        foreach($admins as $admin) {
            $admin->notify(new UserAddProduct($user2, $product2));
        }

        Log::info("Product $product was Created, by worker: $user");
    }
}
</code>```

Notification

```<code>class UserAddProduct extends Notification implements ShouldQueue
{
    use Queueable;

    protected $product;
    protected $user;

    public function __construct(User $user, Product $product)
    {
        $this->product = $product;
        $this->user = $user;
    }

    public function via($notifiable)
    {
        return ['database', 'broadcast'];
    }

    public function toDatabase($notifiable)
    {
        return [
            'user_id' => $this->user->id,
            'user_username' => $this->user->username,
            'product_id' => $this->product->id,
            'product_name' => $this->product->name,
        ];
    }

    public function toArray($notifiable)
    {
        return [
            'id' => $this->id,
            'read_at' => null,
            'data' => [
                'user_id' => $this->user->id,
                'user_username' => $this->user->username,
                'product_id' => $this->product->id,
                'product_name' => $this->product->name,
            ],
        ];
    }
}
</code>```

Observer

```<code>public function created(Product $product)
{
    $user = Auth::user();
    event(new MessagePushed($user, $product));
}
</code>```

Questions

How can I return live notifications as soon as event is fired in whole app? currently as my code is placed in add.vue component admins get notify IF they are in same page only :/

How do I get notifications of multiple event? let say I have another event, listener, observer for other page actions I want admin be notified of both product event and other event in whole app.

thanks

答:
Solved

Here is how I done it based on my need and my question (it might be somehow different if your case is different than mine)

In component that activity happens (in my case Add.vue)

```<code>Echo.join('userInAddProduct')
.here((users) => {
    console.log('here: ', users);
})
.joining((user) => {
    console.log('joining: ', user);
})
.leaving((user) => {
    console.log('leaving: ', user);
})
.whisper('typing', {data: notf}) // this part sends my data
.notification((notification) => {
    console.log('noitication listener1: ', notification.type);
});
</code>```

As I needed my notification be visible in all pages to admins I've added my socket emit (i.e. Echo.listenForWhisper) into my navbar component.

```<code>mounted() {
  this.notifs();
    window.Echo.join('userInAddProduct')
       // listen to broadcast from Add.vue
      .listenForWhisper('typing', (product) => {
        // add it into my navbar notifications list
        this.notifications.unshift(product);
      });
}
</code>```

Now each time user adds new product to server admin gets notified.

note To see my other settings for this function to happen please scroll back to my update part and see Event, Listener & Observe files code. (you make those files and all this codes above to your preferred components then you'll have real time notifications).

Body:
For the first time attempt with laravel and socket-io I am trying to send very simple notification to admins. So far my event is firing but I need help with receiving event notifications.

Logic

It's very basic because I want to understand the process.

User opens page Add Product

Admin gets notification that user X is in App Product page.

So far

So far I can fire event and get user data (user that is in Add Product page)

Need help for

I need help to understand the way that admin receives notifications.

Code

Component script

created() {
  let user = JSON.parse(localStorage.getItem("user"))
  this.listenForBroadcast(user);
},
methods: {
  listenForBroadcast(user) {
    Echo.join('userInAddProduct')
    .here((Loggeduser) => {
      console.log('My user data', Loggeduser);
    });
  }
}

Result of code above

My user data [{…}]
  0:
    id: 1
    name: "Test User"
    photo: "User-1588137335.png"
    __ob__: Observer {value: {…}, dep: Dep, vmCount: 0}
    get id: ƒ reactiveGetter()
    set id: ƒ reactiveSetter(newVal)
    get name: ƒ reactiveGetter()
    set name: ƒ reactiveSetter(newVal)
    get photo: ƒ reactiveGetter()
    set photo: ƒ reactiveSetter(newVal)
    __proto__: Object
    length: 1
    __proto__: Array(0)

Channels route

Broadcast::channel('userInAddProduct', function ($user) {
    return [
        'id' => $user->id,
        'photo' => $user->photo,
        'name' => $user->name
    ];
});

MessagePushed (event file)

class MessagePushed implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function broadcastOn()
    {
        return new PresenceChannel('userInAddProduct');
    }
}

Question

How can I receive notification about this event fire? I want to notify my admin users that user x is in page Add Product?

Update

Since I published this question I've made some changes and here is my latest code + questions.

bootstrap.js

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001',
    auth: { // added authentication token (because all my events are private)
        headers: {
            Authorization: localStorage.getItem('access_token'),
        },
    },
});

Add.vue (add product component where event has to be fired)

listenForBroadcast(user) {
    let ui = JSON.parse(localStorage.getItem("user"))
    Echo.join('userInAddProduct')
    .here((users) => {
        console.log('My user data', users)
    })
    .joining((user) => {
        this.$notify({
            title: '',
            message: user + 'joining',
            offset: 100,
            type: 'success'
        });
    })
    .leaving((user) => {
        this.$notify({
            title: '',
            message: user + 'is leaving new product',
            offset: 100,
            type: 'warning'
        });
    })
    .whisper('typing', (e) => {
        this.$notify({
            title: '',
            message: ui.username + 'is adding new product',
            offset: 100,
            type: 'success'
        })
    })
    .listenForWhisper('typing', (e) => {
        console.log(e)
        this.$notify({
            title: '',
            message: ui.username + 'is entered add new product page.',
            offset: 100,
            type: 'success'
        });
    })
    .notification((notification) => {
        console.log('noitication listener: ', notification.type);
    });
},

Then I've made 4 files to handle events:

Event (passing data)

Event Listener (process the database storage and showing notifications to online admins)

Observer (firing event)

Notification (store data to database for admins in case when event fire they're not online so they can see notifications later on)

Event file

class MessagePushed extends Event implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;
    public $product;

    public function __construct(User $user, Product $product)
    {
        $this->user = $user;
        $this->product = $product;
    }

    public function broadcastOn()
    {
        return new PresenceChannel('userInAddProduct');
    }
}

Listener file

class ThingToDoAfterEventWasFired implements ShouldQueue
{
    public function handle(MessagePushed $event)
    {
        //Log testing purpose only
        $user = $event->user->username;
        $product = $event->product->name;

        // Real data that should be broadcasts
        $user2 = $event->user;
        $product2 = $event->product;

        // inform all admins and authorized staffs about new product
        $admins = User::role(['admin', 'staff'])->get();
        foreach($admins as $admin) {
            $admin->notify(new UserAddProduct($user2, $product2));
        }

        Log::info("Product $product was Created, by worker: $user");
    }
}

Notification

class UserAddProduct extends Notification implements ShouldQueue
{
    use Queueable;

    protected $product;
    protected $user;

    public function __construct(User $user, Product $product)
    {
        $this->product = $product;
        $this->user = $user;
    }

    public function via($notifiable)
    {
        return ['database', 'broadcast'];
    }

    public function toDatabase($notifiable)
    {
        return [
            'user_id' => $this->user->id,
            'user_username' => $this->user->username,
            'product_id' => $this->product->id,
            'product_name' => $this->product->name,
        ];
    }

    public function toArray($notifiable)
    {
        return [
            'id' => $this->id,
            'read_at' => null,
            'data' => [
                'user_id' => $this->user->id,
                'user_username' => $this->user->username,
                'product_id' => $this->product->id,
                'product_name' => $this->product->name,
            ],
        ];
    }
}

Observer

public function created(Product $product)
{
    $user = Auth::user();
    event(new MessagePushed($user, $product));
}

Questions

How can I return live notifications as soon as event is fired in whole app? currently as my code is placed in add.vue component admins get notify IF they are in same page only :/

How do I get notifications of multiple event? let say I have another event, listener, observer for other page actions I want admin be notified of both product event and other event in whole app.

thanks

Body:
Solved

Here is how I done it based on my need and my question (it might be somehow different if your case is different than mine)

In component that activity happens (in my case Add.vue)

Echo.join('userInAddProduct')
.here((users) => {
    console.log('here: ', users);
})
.joining((user) => {
    console.log('joining: ', user);
})
.leaving((user) => {
    console.log('leaving: ', user);
})
.whisper('typing', {data: notf}) // this part sends my data
.notification((notification) => {
    console.log('noitication listener1: ', notification.type);
});

As I needed my notification be visible in all pages to admins I've added my socket emit (i.e. Echo.listenForWhisper) into my navbar component.

mounted() {
  this.notifs();
    window.Echo.join('userInAddProduct')
       // listen to broadcast from Add.vue
      .listenForWhisper('typing', (product) => {
        // add it into my navbar notifications list
        this.notifications.unshift(product);
      });
}

Now each time user adds new product to server admin gets notified.

note To see my other settings for this function to happen please scroll back to my update part and see Event, Listener & Observe files code. (you make those files and all this codes above to your preferred components then you'll have real time notifications).


问:
how to combine two tables in django
There are two tables

Hookahs and tobacco for example

and for the basket model, you need to combine these two models, help

For example:

```<code>class Hookah(model.Model):
    name = models.Charfield()
    description = .....
    price = .......

class Tabacco(model.Model):
    name = models.Charfield()
    description = .....
    price = .......
</code>```

and OrderItem model:

```<code>class OrderItem(model.Model):
</code>```

and here I need to pass the top two models, as a product, how to do it?
i.e. combine Hookah and Tabacoo into one

please help me

答:
If I understand correctly, you want a Basket model that stores a link to other types?  You can do that by creating a parent model that each shopping item inherits from, or you can do it by using a GenericForeignKey which allows pointing to any model object.  The shared parent model is probably better as you don't have to duplicate code for shopping items such as name, price, etc.

class ShoppingItem(model.Model)
    name = models.Charfield()
    description = .....
    price = .......

class Hookah(ShoppingItem):
    height = ....

class Tabacco(ShoppingItem):
    flavour = ....
```

<p>Then you can do something like one of the following:</p>

<pre class="lang-py prettyprint-override"><code>class OrderItem(model.Model):  # info on a single ordered item
    item = models.ForeignKey(ShoppingItem, on_delete=models.DO_NOTHING)

class Basket(model.Model):  # basket of many `ShoppingItem`
    items = models.ManyToManyField(ShoppingItem)
</code>```

Title: how to combine two tables in django

Body:
There are two tables

Hookahs and tobacco for example

and for the basket model, you need to combine these two models, help

For example:

class Hookah(model.Model):
    name = models.Charfield()
    description = .....
    price = .......

class Tabacco(model.Model):
    name = models.Charfield()
    description = .....
    price = .......

and OrderItem model:

class OrderItem(model.Model):

and here I need to pass the top two models, as a product, how to do it?
i.e. combine Hookah and Tabacoo into one

please help me

Body:
If I understand correctly, you want a Basket model that stores a link to other types?  You can do that by creating a parent model that each shopping item inherits from, or you can do it by using a GenericForeignKey which allows pointing to any model object.  The shared parent model is probably better as you don't have to duplicate code for shopping items such as name, price, etc.

class ShoppingItem(model.Model)
    name = models.Charfield()
    description = .....
    price = .......

class Hookah(ShoppingItem):
    height = ....

class Tabacco(ShoppingItem):
    flavour = ....

Then you can do something like one of the following:

class OrderItem(model.Model):  # info on a single ordered item
    item = models.ForeignKey(ShoppingItem, on_delete=models.DO_NOTHING)

class Basket(model.Model):  # basket of many `ShoppingItem`
    items = models.ManyToManyField(ShoppingItem)


问:
Migrating from django user model to a custom user model
I am following these two references (one and two) to have a custom user model in order to authenticate via email and also to add an extra field to it.

```<code>class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        unique=True,
        max_length=254,
    )
    mobile_number = models.IntegerField(unique=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserManager()
    ...
    ...
    class Meta:
        db_table = 'auth_user'
    ...
    ...
</code>```

As you can see, I have added the db_table='auth_user' into the Meta fields of the class. Also, I have included AUTH_USER_MODEL = 'accounts.User' and User model app (i.e., accounts)into the INSTALLED_APPS in settings.py. Further more, I deleted the migrations folder from the app.

Then tried migrating:

```<code>$ python manage.py makemigrations accounts
Migrations for 'accounts':
  accounts/migrations/0001_initial.py:
    - Create model User

$ python manage.py migrate accounts
</code>```

Which gives me an error:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'.

How can I migrate from the existing django user model into a custom user model?

答:
Migrate zeroing didn't help me. I had to drop the whole database:

```<code>sudo -u postgres psql
drop database YOURDATABASENAME;
create database YOURDATABASENAME;
</code>```

Then:

```<code>python ./manage.py makemigrations MYAPPNAME
python ./manage.py migrate MYAPPNAME
python ./manage.py migrate
</code>```

And after these I got forward..

Body:
I am following these two references (one and two) to have a custom user model in order to authenticate via email and also to add an extra field to it.

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(
        unique=True,
        max_length=254,
    )
    mobile_number = models.IntegerField(unique=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    objects = UserManager()
    ...
    ...
    class Meta:
        db_table = 'auth_user'
    ...
    ...

As you can see, I have added the db_table='auth_user' into the Meta fields of the class. Also, I have included AUTH_USER_MODEL = 'accounts.User' and User model app (i.e., accounts)into the INSTALLED_APPS in settings.py. Further more, I deleted the migrations folder from the app.

Then tried migrating:

$ python manage.py makemigrations accounts
Migrations for 'accounts':
  accounts/migrations/0001_initial.py:
    - Create model User

$ python manage.py migrate accounts

Which gives me an error:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'.

How can I migrate from the existing django user model into a custom user model?

Body:
Migrate zeroing didn't help me. I had to drop the whole database:

sudo -u postgres psql
drop database YOURDATABASENAME;
create database YOURDATABASENAME;

Then:

python ./manage.py makemigrations MYAPPNAME
python ./manage.py migrate MYAPPNAME
python ./manage.py migrate

And after these I got forward..


问:
How do i calculate the mean squared error for time series?
```<code>univariate_past_history = 100
univariate_future_target = 0

x_train_uni, y_train_uni = univariate_data(uni_data, 0, TRAIN_SPLIT,
                                           univariate_past_history,
                                           univariate_future_target)
x_val_uni, y_val_uni = univariate_data(uni_data, TRAIN_SPLIT, None,
                                       univariate_past_history,
                                       univariate_future_target)

</code>```

The value to be predicted is y[0].numpy() and the predicted value is simple_lstm_model.predict(x)[0] how do I calculate the mean squared error between two of them?

```<code>BATCH_SIZE = 256
BUFFER_SIZE = 10000

train_univariate = tf.data.Dataset.from_tensor_slices((x_train_uni, y_train_uni))
train_univariate = train_univariate.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()

val_univariate = tf.data.Dataset.from_tensor_slices((x_val_uni, y_val_uni))
val_univariate = val_univariate.batch(BATCH_SIZE).repeat()

simple_lstm_model = tf.keras.models.Sequential([
    tf.keras.layers.LSTM(8, input_shape=x_train_uni.shape[-2:]),
    tf.keras.layers.Dense(1)
])

simple_lstm_model.compile(optimizer='adam', loss='mae')
for x, y in val_univariate.take(1):
    print(simple_lstm_model.predict(x).shape)
EVALUATION_INTERVAL = 200
EPOCHS = 10

simple_lstm_model.fit(train_univariate, epochs=EPOCHS,
                      steps_per_epoch=EVALUATION_INTERVAL,
                      validation_data=val_univariate, validation_steps=50)

for x, y in val_univariate.take(3):
  plot = show_plot([x[0].numpy(), y[0].numpy(),
                    simple_lstm_model.predict(x)[0]], 0, 'Simple LSTM model')
  plot.show()
print(simple_lstm_model.predict(x)[0])
</code>```

```<code>expected = y[0].numpy()
predicted = simple_lstm_model.predict(x)[0]
print(mean_squared_error(expected,predicted))
</code>```

if I do like the above i get this error
TypeError: Singleton array 0.05017540446704798 cannot be considered a valid collection.

Thanks in Advance

答:
The squared error between two scalars is (y_true - y_pred)**2. This is a scalar and we can understand how bad the error is or how good the model is from this scalar quantity.

The squared error of two vectors is a vector but since we want a scalar to understand the deviation between the two vectors we take the mean and hence MSE.

You can use below code to calculate MSE

```<code># Assuming y_train_uni is a list
# Error for single sample
y_pred = simple_lstm_model.predict(x).numpy()[0]
y_true = np.array(y_train_uni)[0]
print (np.power(y_true - y_pred, 2))

# Error for multiple samples
y_pred = simple_lstm_model.predict(x).numpy()
y_true = np.array(y_train_uni)
print (np.power(y_true - y_pred, 2).mean(())
</code>```

Body:
univariate_past_history = 100
univariate_future_target = 0

x_train_uni, y_train_uni = univariate_data(uni_data, 0, TRAIN_SPLIT,
                                           univariate_past_history,
                                           univariate_future_target)
x_val_uni, y_val_uni = univariate_data(uni_data, TRAIN_SPLIT, None,
                                       univariate_past_history,
                                       univariate_future_target)

The value to be predicted is y[0].numpy() and the predicted value is simple_lstm_model.predict(x)[0] how do I calculate the mean squared error between two of them?

BATCH_SIZE = 256
BUFFER_SIZE = 10000

train_univariate = tf.data.Dataset.from_tensor_slices((x_train_uni, y_train_uni))
train_univariate = train_univariate.cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE).repeat()

val_univariate = tf.data.Dataset.from_tensor_slices((x_val_uni, y_val_uni))
val_univariate = val_univariate.batch(BATCH_SIZE).repeat()

simple_lstm_model = tf.keras.models.Sequential([
    tf.keras.layers.LSTM(8, input_shape=x_train_uni.shape[-2:]),
    tf.keras.layers.Dense(1)
])

simple_lstm_model.compile(optimizer='adam', loss='mae')
for x, y in val_univariate.take(1):
    print(simple_lstm_model.predict(x).shape)
EVALUATION_INTERVAL = 200
EPOCHS = 10

simple_lstm_model.fit(train_univariate, epochs=EPOCHS,
                      steps_per_epoch=EVALUATION_INTERVAL,
                      validation_data=val_univariate, validation_steps=50)

for x, y in val_univariate.take(3):
  plot = show_plot([x[0].numpy(), y[0].numpy(),
                    simple_lstm_model.predict(x)[0]], 0, 'Simple LSTM model')
  plot.show()
print(simple_lstm_model.predict(x)[0])

expected = y[0].numpy()
predicted = simple_lstm_model.predict(x)[0]
print(mean_squared_error(expected,predicted))

if I do like the above i get this error
TypeError: Singleton array 0.05017540446704798 cannot be considered a valid collection.

Thanks in Advance

Body:
The squared error between two scalars is (y_true - y_pred)**2. This is a scalar and we can understand how bad the error is or how good the model is from this scalar quantity.

The squared error of two vectors is a vector but since we want a scalar to understand the deviation between the two vectors we take the mean and hence MSE.

You can use below code to calculate MSE

# Assuming y_train_uni is a list
# Error for single sample
y_pred = simple_lstm_model.predict(x).numpy()[0]
y_true = np.array(y_train_uni)[0]
print (np.power(y_true - y_pred, 2))

# Error for multiple samples
y_pred = simple_lstm_model.predict(x).numpy()
y_true = np.array(y_train_uni)
print (np.power(y_true - y_pred, 2).mean(())


问:
Declare custom Types in Swift and Java-Kotlin
I'm beginner in programming. I'm learning Swift and Java-Kotlin to develop apps.
Also I'm student in IT Engineering.

I have learnt in C Language modularity that means to have a library where declare the types and the actions and functions and I call these actions, functions and types in the main file declaring the files in the header.

I was trying to do something similar in Swift and Kotlin, to have a file where declare my custom types and call them in the different views-classes.

In Swift I know that is not necessary to import the file where the types are.

For instance, I have declared the following types in Swift

```<code>struct tUser {

    var userId: Int
    var name: String
    var birthday: tDate
    var location: String
    var province: String
    var email: String
    var userPassword: String
    var picture: Image
    var favorites: tFavorite
}

struct tDate {

    var day: Int
    var month: Int
    var year: Int
}

struct tFavorite {

    var identifyer: Int
}

If I would initialize the types in C I would do

tUser newUser;

newUser.userId = 001;
newUser.name = "John"
</code>```

I'm trying to do the same in Swift and Kotlin but, in Swift I get error "Expressions are not allowed at the top level" also in Kotlin I have errors.

Perhaps the answer is that there is no sense to do this in a Object Oriented Language,

Can someone help me in this matter?

Thanks,

答:
You can do exactly what you want in Kotlin (I don't know about Swift), by putting each type into a class and putting your code in a top-level function.  But that's not taking advantage of the benefits of objects.

Generally speaking, in an object-oriented language, you bundle the data (state) with the operations you can perform on that data (behaviour); together, that forms a class.

You don't show any operations here, but I'm sure you know what you're planning to do with your User, Date, and Favorite types.  For example, suppose one of the things you'll want to do with your Date is see whether today is an anniversary: you'd have a method (class function) for that.  Perhaps something along the lines of:

```<code>class Date(val day: Int, val month: Int, val year: Int) {

    fun isAnniversaryToday(): Boolean {
        // TODO Code here
    }
}
</code>```

Then you could create your Date with val myDate = Date(2, 6, 2000), and check whether it's a birthday with myDate.isAnniversaryToday().

That's a bad example, though, because writing your own date classes is a really bad idea — it's so easy to get wrong, or hit problems with timezones or leap seconds or summer time or calendar differences, and most languages have pretty good date handling in their standard library.  So in the case of Java and Kotlin/JVM, you should use the java.time classes instead.  And similarly for images, lists, and a host of other types.  Generally speaking, anything that's not specific to your app is likely to have been done before, so (unless you're writing for practice) you should avoid reinventing the wheel as much as possible!

So the main difference from what you've learned in C is the mind-set: in a procedural language like C a program is a collection of functions and data structures, while in an OO language a program is a collection of interrelated classes, each with some data and/or behaviour.  Each method is tied tightly to its class, easy to find and in the class's namespace, and it gets privileged access to the class's state (which you can restrict or hide from everything else).  That can take a bit of getting used to, but it turns out to be a really powerful technique for writing large systems safely.

None of this is specific to a particular language.  As I said, I don't know Swift, but I'd expect the principles work pretty much the same as in Kotlin, or C++, or many other modern languages.  So you might want to read a little about OO design, as well as any language tutorials.

(This site isn't the place for advice about which technologies to choose, but I can say that I love Kotlin: it's safer, cleaner, and more concise and expressive than any other language I've tried, and it's a real pleasure to use.  Now it's the official Android language, people associate it with that, but it's a perfectly good general-purpose language — we do all our back-end development in it, and I've written desktop apps with it.  All the docs are online, and there are some good books too.)

And one point that is specific to Kotlin: if your structure really is just a data holder and has no behaviour, then it's often best to make it a data class, e.g.:

```<code>data class Date(var day: Int, var month: Int, var year: Int)
</code>```

The compiler will then generate implementations for many standard methods (equals(), hashCode(), toString(), copy-constructors, &c) which will give it value semantics: for example, two objects with the same state will be treated as equal, which isn't the default for most classes.

Body:
I'm beginner in programming. I'm learning Swift and Java-Kotlin to develop apps.
Also I'm student in IT Engineering.

I have learnt in C Language modularity that means to have a library where declare the types and the actions and functions and I call these actions, functions and types in the main file declaring the files in the header.

I was trying to do something similar in Swift and Kotlin, to have a file where declare my custom types and call them in the different views-classes.

In Swift I know that is not necessary to import the file where the types are.

For instance, I have declared the following types in Swift

struct tUser {

    var userId: Int
    var name: String
    var birthday: tDate
    var location: String
    var province: String
    var email: String
    var userPassword: String
    var picture: Image
    var favorites: tFavorite
}

struct tDate {

    var day: Int
    var month: Int
    var year: Int
}

struct tFavorite {

    var identifyer: Int
}

If I would initialize the types in C I would do

tUser newUser;

newUser.userId = 001;
newUser.name = "John"

I'm trying to do the same in Swift and Kotlin but, in Swift I get error "Expressions are not allowed at the top level" also in Kotlin I have errors.

Perhaps the answer is that there is no sense to do this in a Object Oriented Language,

Can someone help me in this matter?

Thanks,

Body:
You can do exactly what you want in Kotlin (I don't know about Swift), by putting each type into a class and putting your code in a top-level function.  But that's not taking advantage of the benefits of objects.

Generally speaking, in an object-oriented language, you bundle the data (state) with the operations you can perform on that data (behaviour); together, that forms a class.

You don't show any operations here, but I'm sure you know what you're planning to do with your User, Date, and Favorite types.  For example, suppose one of the things you'll want to do with your Date is see whether today is an anniversary: you'd have a method (class function) for that.  Perhaps something along the lines of:

class Date(val day: Int, val month: Int, val year: Int) {

    fun isAnniversaryToday(): Boolean {
        // TODO Code here
    }
}

Then you could create your Date with val myDate = Date(2, 6, 2000), and check whether it's a birthday with myDate.isAnniversaryToday().

That's a bad example, though, because writing your own date classes is a really bad idea — it's so easy to get wrong, or hit problems with timezones or leap seconds or summer time or calendar differences, and most languages have pretty good date handling in their standard library.  So in the case of Java and Kotlin/JVM, you should use the java.time classes instead.  And similarly for images, lists, and a host of other types.  Generally speaking, anything that's not specific to your app is likely to have been done before, so (unless you're writing for practice) you should avoid reinventing the wheel as much as possible!

So the main difference from what you've learned in C is the mind-set: in a procedural language like C a program is a collection of functions and data structures, while in an OO language a program is a collection of interrelated classes, each with some data and/or behaviour.  Each method is tied tightly to its class, easy to find and in the class's namespace, and it gets privileged access to the class's state (which you can restrict or hide from everything else).  That can take a bit of getting used to, but it turns out to be a really powerful technique for writing large systems safely.

None of this is specific to a particular language.  As I said, I don't know Swift, but I'd expect the principles work pretty much the same as in Kotlin, or C++, or many other modern languages.  So you might want to read a little about OO design, as well as any language tutorials.

(This site isn't the place for advice about which technologies to choose, but I can say that I love Kotlin: it's safer, cleaner, and more concise and expressive than any other language I've tried, and it's a real pleasure to use.  Now it's the official Android language, people associate it with that, but it's a perfectly good general-purpose language — we do all our back-end development in it, and I've written desktop apps with it.  All the docs are online, and there are some good books too.)

And one point that is specific to Kotlin: if your structure really is just a data holder and has no behaviour, then it's often best to make it a data class, e.g.:

data class Date(var day: Int, var month: Int, var year: Int)

The compiler will then generate implementations for many standard methods (equals(), hashCode(), toString(), copy-constructors, &c) which will give it value semantics: for example, two objects with the same state will be treated as equal, which isn't the default for most classes.


问:
is ValueError() an instance of the Exception class in python3?
I'm a beginner in python.
I have to explain the difference between the following lines of code:

```<code>except ValueError as err:
    print(err,"in methodA is occured")
    raise ValueError("A Value Error")
</code>```

and

```<code>except ValueError as err:
    print(err,"in methodA is occured")
    raise Exception("A Value Error")
</code>```

I saw this "Exception hierarchy" in python documentation.

I know that in the second one we are passing the "Exception Class" to raise. but for the first one I'm not sure that the "ValueError" we are passing is an instance of exception class or is a subclass of exception class?

or am I getting this whole thing wrong?

thanks in advance.

答:
When in doubt, help function is often useful, just launch Python console and do help(ValueError) to get information that:

```<code> Help on class ValueError in module builtins:

class ValueError(Exception)
 |  Inappropriate argument value (of correct type).
 |
 |  Method resolution order:
 |      ValueError
 |      Exception
 |      BaseException
 |      object
 |
...
</code>```

in more verbose way: ValueError is class, ValueError is subclass of Exception, Exception is subclass of BaseException, BaseException is subclass of object.

Body:
I'm a beginner in python.
I have to explain the difference between the following lines of code:

except ValueError as err:
    print(err,"in methodA is occured")
    raise ValueError("A Value Error")

and

except ValueError as err:
    print(err,"in methodA is occured")
    raise Exception("A Value Error")

I saw this "Exception hierarchy" in python documentation.

I know that in the second one we are passing the "Exception Class" to raise. but for the first one I'm not sure that the "ValueError" we are passing is an instance of exception class or is a subclass of exception class?

or am I getting this whole thing wrong?

thanks in advance.

Body:
When in doubt, help function is often useful, just launch Python console and do help(ValueError) to get information that:

 Help on class ValueError in module builtins:

class ValueError(Exception)
 |  Inappropriate argument value (of correct type).
 |
 |  Method resolution order:
 |      ValueError
 |      Exception
 |      BaseException
 |      object
 |
...

in more verbose way: ValueError is class, ValueError is subclass of Exception, Exception is subclass of BaseException, BaseException is subclass of object.


问:
Check whether cell at indexPath is visible on screen UICollectionView
I have a CollectionView which displays images to the user. I download these in the background, and when the download is complete I call the following func to update the collectionViewCell and display the image.

```<code>func handlePhotoDownloadCompletion(notification : NSNotification) {
    let userInfo:Dictionary<String,String!> = notification.userInfo as! Dictionary<String,String!>
    let id = userInfo["id"]
    let index = users_cities.indexOf({$0.id == id})
    if index != nil {
        let indexPath = NSIndexPath(forRow: index!, inSection: 0)
        let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as! FeaturedCitiesCollectionViewCell
        if (users_cities[index!].image != nil) {
            cell.backgroundImageView.image = users_cities[index!].image!
        }
    }
}
</code>```

This works great if the cell is currently visible on screen, however if it is not I get a
fatal error: unexpectedly found nil while unwrapping an Optional value error on the following line :

```<code> let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as! FeaturedCitiesCollectionViewCell
</code>```

Now this function does not even need to be called if the collectionViewCell is not yet visible, because in this case the image will be set in the cellForItemAtIndexPath method anyway.

Hence my question, how can I alter this function to check whether the cell we are dealing with is currently visible or not. I know of the collectionView.visibleCells() however, I am not sure how to apply it here.

答:
You can get current index by</p>

```<code>// Called before the cell is displayed
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    print(indexPath.row)
}

// Called when the cell is displayed
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    print(indexPath.row)
}
</code>```

Body:
I have a CollectionView which displays images to the user. I download these in the background, and when the download is complete I call the following func to update the collectionViewCell and display the image.

func handlePhotoDownloadCompletion(notification : NSNotification) {
    let userInfo:Dictionary<String,String!> = notification.userInfo as! Dictionary<String,String!>
    let id = userInfo["id"]
    let index = users_cities.indexOf({$0.id == id})
    if index != nil {
        let indexPath = NSIndexPath(forRow: index!, inSection: 0)
        let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as! FeaturedCitiesCollectionViewCell
        if (users_cities[index!].image != nil) {
            cell.backgroundImageView.image = users_cities[index!].image!
        }
    }
}

This works great if the cell is currently visible on screen, however if it is not I get a
fatal error: unexpectedly found nil while unwrapping an Optional value error on the following line :

 let cell = followedCollectionView.cellForItemAtIndexPath(indexPath) as! FeaturedCitiesCollectionViewCell

Now this function does not even need to be called if the collectionViewCell is not yet visible, because in this case the image will be set in the cellForItemAtIndexPath method anyway.

Hence my question, how can I alter this function to check whether the cell we are dealing with is currently visible or not. I know of the collectionView.visibleCells() however, I am not sure how to apply it here.

Body:
You can get current index by

// Called before the cell is displayed
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    print(indexPath.row)
}

// Called when the cell is displayed
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    print(indexPath.row)
}


问:
How to evaluate index i in an if statement within a for loop in R?
I would like to create a new variable "Diff", which i-th value is the difference between the i-th value of the variable "Date" and the (i-1)th value of the variable "Date" itself.
Something like:

```<code>df$Date[2]-df$Date[1]
</code>```

iterated over the sequence 1:lenght(df$Date).

Obviously there is a problem when i is initialized at i=1, because i-1=0.

Trying to avoid this problem, nesting an if...else... statement within a for loop, I cannot manage to have "if" evaluating "i".

R gives me a syntax error which does not exist if I change the "if" condition.

This is my first attempt:

```<code>for (i in 1:length(df$Date)) {
  if (i=1) {
     df$Diff[[i]]<-0
  } else {
  df$Diff[[i]]<-df$Date[[i]] - df$Date[[i-1]]
  }
}
</code>```

The error is:

```<code>unexpected '}' in "  }"
</code>```

which is the "}" closing the else statement.

This is one of the (dirty) solutions I have found (sintax and parenthesis are the same):

```<code>for (i in 1:length(df$Date)) {
    if (df$Date[i]==df$Date[1]) {
        df$Diff[[i]]<-0
    } else {
        df$Diff[[i]]<-df$Date[[i]] - df$Date[[i-1]]
    }
}
</code>```

However, my question here is:
how can I directly evaluate the index (i, e.g.) of a for loop inside an if statement nested within the for loop?

Thank you for help and patience.

答:
You are reinventing the wheel here. You should just be able to do

```<code>diff(df$Date)
</code>```

Of course, the resulting vector is shorter by one than the original vector, and it is up to you decide whether to leave it that way, or to stick a 0 or NA on the beginning or end of the result depending on what makes the most sense for your application.

For example, if I have a vector of cumulative daily Coronavirus cases called covid, and I wanted to know the number of new cases per day, I would do:

```<code>diff(c(0, covid))
</code>```

Body:
I would like to create a new variable "Diff", which i-th value is the difference between the i-th value of the variable "Date" and the (i-1)th value of the variable "Date" itself.
Something like:

df$Date[2]-df$Date[1]

iterated over the sequence 1:lenght(df$Date).

Obviously there is a problem when i is initialized at i=1, because i-1=0.

Trying to avoid this problem, nesting an if...else... statement within a for loop, I cannot manage to have "if" evaluating "i".

R gives me a syntax error which does not exist if I change the "if" condition.

This is my first attempt:

for (i in 1:length(df$Date)) {
  if (i=1) {
     df$Diff[[i]]<-0
  } else {
  df$Diff[[i]]<-df$Date[[i]] - df$Date[[i-1]]
  }
}

The error is:

unexpected '}' in "  }"

which is the "}" closing the else statement.

This is one of the (dirty) solutions I have found (sintax and parenthesis are the same):

for (i in 1:length(df$Date)) {
    if (df$Date[i]==df$Date[1]) {
        df$Diff[[i]]<-0
    } else {
        df$Diff[[i]]<-df$Date[[i]] - df$Date[[i-1]]
    }
}

However, my question here is:
how can I directly evaluate the index (i, e.g.) of a for loop inside an if statement nested within the for loop?

Thank you for help and patience.

Body:
You are reinventing the wheel here. You should just be able to do

diff(df$Date)

Of course, the resulting vector is shorter by one than the original vector, and it is up to you decide whether to leave it that way, or to stick a 0 or NA on the beginning or end of the result depending on what makes the most sense for your application.

For example, if I have a vector of cumulative daily Coronavirus cases called covid, and I wanted to know the number of new cases per day, I would do:

diff(c(0, covid))


问:
Property 'reduce' does not exist on type 'IComponent'
How do I get rid of the error Property 'reduce' does not exist on type 'IComponent' on my method. Initially, components had an any type, so it worked fine. But now that I am strongly typing all my methods ad variables I am seeing issues.

```<code>  static addPlaceholdersOnMultiplePages(components: IComponent[]): IComponent[] {
    return components.map((obj) =>
      obj.reduce(
        (r, a) =>
          r.concat(a, {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          }),
        [
          {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          },
        ],
      ),
    );
  }
</code>```

My interface is as follows:

```<code>export interface IComponent
  extends IComponentDetail {
}
</code>```

答:
Try this :- </p>

```<code>static addPlaceholdersOnMultiplePages(components: IComponent[]): IComponent[] {
    return components.reduce(
        (r, a) =>
          r.concat(a, {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          }),
        [
          {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          },
        ],
      )
}
</code>```

Body:
How do I get rid of the error Property 'reduce' does not exist on type 'IComponent' on my method. Initially, components had an any type, so it worked fine. But now that I am strongly typing all my methods ad variables I am seeing issues.

  static addPlaceholdersOnMultiplePages(components: IComponent[]): IComponent[] {
    return components.map((obj) =>
      obj.reduce(
        (r, a) =>
          r.concat(a, {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          }),
        [
          {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          },
        ],
      ),
    );
  }

My interface is as follows:

export interface IComponent
  extends IComponentDetail {
}

Body:
Try this :-

static addPlaceholdersOnMultiplePages(components: IComponent[]): IComponent[] {
    return components.reduce(
        (r, a) =>
          r.concat(a, {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          }),
        [
          {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          },
        ],
      )
}


问:
SICP Ex. 1.17 - "fast-multiply" slower than "multiply"?
The following function as introduction to this exercise illustrates multiplication defined in terms of addition. This is the simplest "easy to write down", recursive definition.

(define (star a b)
  (if (= b 0)
      0
      (+ a (star a (- b 1)))))
```

<p>First thing I did when I saw that, following previous exercises, is write an iterative form which doesn't blow the stack:</p>

<pre class="lang-lisp prettyprint-override"><code>(define (star a b)
  (star-iter a b 0))
(define (star-iter a counter sum)
  (if (= counter 0)
      sum
      (star-iter a (- counter 1) (+ a sum))))
</code>```

Exercise 1.17 then encourages us to find an invariant so as to reduce the problem size, the idea being to get from O(n) to O(logn) number of steps (without, when that particular step is carried out, doing anything to update the result - all we do in that step is to reduce/transform the problem definition - that being what is meant by 'find an invariant') (see line 3 of the first code block below - nothing is being added to the result in that step).

For the fast version, the question says we should use the functions halve and double and seems to imply these would be available as machine operations (constant time?).  I've implemented the "fast" version just spoofing those functions as follows:

(define (fast-star a b)
  (cond ((or (= b 0) (= a 0)) 0)
        ((even? a)      (fast-star (/ a 2) (* 2 b)))
        (else      (+ a (fast-star a       (- b 1))))))
```

<p>And the same thing in iterative form (i.e. O(1) space):</p>

<p>(note how <code>+ a</code> on line 4 above just moves to the accumulator, end of line 6 below, to get this in tail position)</p>

<pre class="lang-lisp prettyprint-override"><code>(define (fast-star b)
  (fast-star-iter a b 0))
(define (fast-star-iter a b sum)
  (cond ((or (= a 0) (= b 0)) sum)
        ((even? a) (fast-star-iter (/ a 2) (* 2 b) sum))
        (else      (fast-star-iter a       (- b 1) (+ a sum)))))
</code>```

So this is kind of a "what's the point" question - these functions are slower than the first two given above. The first of these four functions blows the stack so it's not useful. But the second doesn't. That one is faster than any of these two "fast" versions under my testing.

Am I missing anything here?  Curious if there's a way to implement halve and double so they actually give the log(n) result being suggested here. There must be otherwise there would have been no sense in the question.

Note that the order of a & b matters a lot if they are different sizes - like multiplying 2, 100 times or 100, 2 times, the first being 100 steps, the latter 2 steps. That would be something to add to this function later. But curious about halve and double to start with.

答:
I think the main issue is that b is being both decremented and doubled, i.e., b should be halved not a.  Currently 2 * 100 would become 1 * 200 and require 200 decrements instead of 100.  Whereas if should become 4 * 50 and then 8 * 25, ...

Also if we decrement an odd number the result will be even so the next step will halve the value of b.  I.e, at least half the iterations will halve the value of b

E.g. if b < 1048576 (2^20) then the number steps should be less than 40.  Generally the number of iterations is less than (* 2 (log b 2)).

Body:
The following function as introduction to this exercise illustrates multiplication defined in terms of addition. This is the simplest "easy to write down", recursive definition.

(define (star a b)
  (if (= b 0)
      0
      (+ a (star a (- b 1)))))

First thing I did when I saw that, following previous exercises, is write an iterative form which doesn't blow the stack:

(define (star a b)
  (star-iter a b 0))
(define (star-iter a counter sum)
  (if (= counter 0)
      sum
      (star-iter a (- counter 1) (+ a sum))))

Exercise 1.17 then encourages us to find an invariant so as to reduce the problem size, the idea being to get from O(n) to O(logn) number of steps (without, when that particular step is carried out, doing anything to update the result - all we do in that step is to reduce/transform the problem definition - that being what is meant by 'find an invariant') (see line 3 of the first code block below - nothing is being added to the result in that step).

For the fast version, the question says we should use the functions halve and double and seems to imply these would be available as machine operations (constant time?).  I've implemented the "fast" version just spoofing those functions as follows:

(define (fast-star a b)
  (cond ((or (= b 0) (= a 0)) 0)
        ((even? a)      (fast-star (/ a 2) (* 2 b)))
        (else      (+ a (fast-star a       (- b 1))))))

And the same thing in iterative form (i.e. O(1) space):

(note how + a on line 4 above just moves to the accumulator, end of line 6 below, to get this in tail position)

(define (fast-star b)
  (fast-star-iter a b 0))
(define (fast-star-iter a b sum)
  (cond ((or (= a 0) (= b 0)) sum)
        ((even? a) (fast-star-iter (/ a 2) (* 2 b) sum))
        (else      (fast-star-iter a       (- b 1) (+ a sum)))))

So this is kind of a "what's the point" question - these functions are slower than the first two given above. The first of these four functions blows the stack so it's not useful. But the second doesn't. That one is faster than any of these two "fast" versions under my testing.

Am I missing anything here?  Curious if there's a way to implement halve and double so they actually give the log(n) result being suggested here. There must be otherwise there would have been no sense in the question.

Note that the order of a & b matters a lot if they are different sizes - like multiplying 2, 100 times or 100, 2 times, the first being 100 steps, the latter 2 steps. That would be something to add to this function later. But curious about halve and double to start with.


问:
Can any one please tell me proper way to Develop Separate Undefined component in ReactJs
ReactJs

I am trying to create separate reusable Undefined Component to handle undefined properties but initially its comes with undefined so passed children throwing "Cant read property error"
here is the component

Final Aim = how to show children  only if the passed property  not undefined

```<code> <CanUndefined property={schedules.review} message="Yet you dont have any reviews">
      <span>{schedules.review.message}</span>
 </CanUndefined>
</code>```

bellow component is ParentComponent

```<code>const CanUndefined = props => props.property ?
                             (props.children) :
                             (<span>
                                 {props.message}
                              </span>)
</code>```

thanks in advance

答:
You will need to test explicitly for the value. Try this:</p>

```<code>const CanUndefined = props => {
    if(props.property === undefined){
        return props.children
    }
    return <span>
        {props.message}
    </span>
</code>```

Body:
ReactJs

I am trying to create separate reusable Undefined Component to handle undefined properties but initially its comes with undefined so passed children throwing "Cant read property error"
here is the component

Final Aim = how to show children  only if the passed property  not undefined

 <CanUndefined property={schedules.review} message="Yet you dont have any reviews">
      {schedules.review.message}
 </CanUndefined>

bellow component is ParentComponent

const CanUndefined = props => props.property ?
                             (props.children) :
                             (
                                 {props.message}
                              )

thanks in advance

Body:
You will need to test explicitly for the value. Try this:

const CanUndefined = props => {
    if(props.property === undefined){
        return props.children
    }
    return <span>
        {props.message}
    </span>