问:
Can I create my own conditional compilation attributes?
There are several ways of doing something in my crate, some result in fast execution, some in low binary size, some have other advantages, so I provide the user interfaces to all of them. Unused functions will be optimized away by the compiler. Internal functions in my crate have to use these interfaces as well, and I would like them to respect the user choice at compile time.

There are conditional compilation attributes like target_os, which store a value like linux or windows. How can I create such an attribute, for example prefer_method, so I and the user can use it somewhat like in the following code snippets?

My crate:

#[cfg(not(any(
    not(prefer_method),
    prefer_method = "fast",
    prefer_method = "small"
)))]
compile_error("invalid `prefer_method` value");

pub fn bla() {
    #[cfg(prefer_method = "fast")]
    foo_fast();

    #[cfg(prefer_method = "small")]
    foo_small();

    #[cfg(not(prefer_method))]
    foo_default();
}

pub fn foo_fast() {
    // Fast execution.
}

pub fn foo_small() {
    // Small binary file.
}

pub fn foo_default() {
    // Medium size, medium fast.
}
```

<p>The user crate:</p>

<pre class="lang-rust prettyprint-override"><code>#[prefer_method = "small"]
extern crate my_crate;

fn f() {
    // Uses the `foo_small` function, the other `foo_*` functions will not end up in the binary.
    my_crate::bla();

    // But the user can also call any function, which of course will also end up in the binary.
    my_crate::foo_default();
}
</code>```

I know there are --cfg attributes, but AFAIK these only represent boolean flags, not enumeration values, which allow setting multiple flags when only one enumeration value is valid.

答:
Firstly, the --cfg flag supports key-value pairs using the syntax --cfg 'prefer_method="fast"'. This will allow you to write code like:

#[cfg(prefer_method = "fast")]
fn foo_fast() { }
```

<p>You can also set these cfg options from a build script. For example:</p>

<pre class="lang-rust prettyprint-override"><code>// build.rs
fn main() {
    println!("cargo:rustc-cfg=prefer_method=\"method_a\"");
}
</code>```

// src/main.rs
#[cfg(prefer_method = "method_a")]
fn main() {
    println!("It's A");
}

#[cfg(prefer_method = "method_b")]
fn main() {
    println!("It's B");
}

#[cfg(not(any(prefer_method = "method_a", prefer_method = "method_b")))]
fn main() {
    println!("No preferred method");
}
```

<p>The above code will result in an executable that prints "It's A".</p>

<p>There's no syntax like the one you suggest to specify cfg settings. The best thing to expose these options to your crates' users is through Cargo features.</p>

<p>For example:</p>

```# Library Cargo.toml
# ...
[features]
method_a = []
method_b = []
```

```// build.rs
fn main() {
    // prefer method A if both method A and B are selected
    if cfg!(feature = "method_a") {
        println!("cargo:rustc-cfg=prefer_method=\"method_a\"");
    } else if cfg!(feature = "method_b") {
        println!("cargo:rustc-cfg=prefer_method=\"method_b\"");
    }
}
```

```# User Cargo.toml
# ...
[dependencies.my_crate]
version = "..."
features = ["method_a"]
```

However, in this case, I'd recommend just using the Cargo features directly in your code (i.e. #[cfg(feature = "fast")]) rather than adding the build script since there's a one-to-one correspondence between the cargo feature and the rustc-cfg being added.

Body:
There are several ways of doing something in my crate, some result in fast execution, some in low binary size, some have other advantages, so I provide the user interfaces to all of them. Unused functions will be optimized away by the compiler. Internal functions in my crate have to use these interfaces as well, and I would like them to respect the user choice at compile time.

There are conditional compilation attributes like target_os, which store a value like linux or windows. How can I create such an attribute, for example prefer_method, so I and the user can use it somewhat like in the following code snippets?

My crate:

#[cfg(not(any(
    not(prefer_method),
    prefer_method = "fast",
    prefer_method = "small"
)))]
compile_error("invalid `prefer_method` value");

pub fn bla() {
    #[cfg(prefer_method = "fast")]
    foo_fast();

    #[cfg(prefer_method = "small")]
    foo_small();

    #[cfg(not(prefer_method))]
    foo_default();
}

pub fn foo_fast() {
    // Fast execution.
}

pub fn foo_small() {
    // Small binary file.
}

pub fn foo_default() {
    // Medium size, medium fast.
}

The user crate:

#[prefer_method = "small"]
extern crate my_crate;

fn f() {
    // Uses the `foo_small` function, the other `foo_*` functions will not end up in the binary.
    my_crate::bla();

    // But the user can also call any function, which of course will also end up in the binary.
    my_crate::foo_default();
}

I know there are --cfg attributes, but AFAIK these only represent boolean flags, not enumeration values, which allow setting multiple flags when only one enumeration value is valid.

Body:
Firstly, the --cfg flag supports key-value pairs using the syntax --cfg 'prefer_method="fast"'. This will allow you to write code like:

#[cfg(prefer_method = "fast")]
fn foo_fast() { }

You can also set these cfg options from a build script. For example:

// build.rs
fn main() {
    println!("cargo:rustc-cfg=prefer_method=\"method_a\"");
}

// src/main.rs
#[cfg(prefer_method = "method_a")]
fn main() {
    println!("It's A");
}

#[cfg(prefer_method = "method_b")]
fn main() {
    println!("It's B");
}

#[cfg(not(any(prefer_method = "method_a", prefer_method = "method_b")))]
fn main() {
    println!("No preferred method");
}

The above code will result in an executable that prints "It's A".

There's no syntax like the one you suggest to specify cfg settings. The best thing to expose these options to your crates' users is through Cargo features.

For example:

# Library Cargo.toml
# ...
[features]
method_a = []
method_b = []

// build.rs
fn main() {
    // prefer method A if both method A and B are selected
    if cfg!(feature = "method_a") {
        println!("cargo:rustc-cfg=prefer_method=\"method_a\"");
    } else if cfg!(feature = "method_b") {
        println!("cargo:rustc-cfg=prefer_method=\"method_b\"");
    }
}

# User Cargo.toml
# ...
[dependencies.my_crate]
version = "..."
features = ["method_a"]

However, in this case, I'd recommend just using the Cargo features directly in your code (i.e. #[cfg(feature = "fast")]) rather than adding the build script since there's a one-to-one correspondence between the cargo feature and the rustc-cfg being added.


来源: stackexchange

问:
Access built-in functions like Year() and Date() are not recognized
I tried the simple query:

select Year ( #5/1/1990# );

It shows error dialog:

Not defined function "Year" in expression

Also, when I use Date() in the form it shows #NAME. I added it with expression builder in Access. What am I doing wrong?

答: I just renamed my database after dealing with my database not running any queries that had expressions.  Try copying and renaming your database first.</p>

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
How can I make a button trigger a Javascript popup (Divi + ActiveCampaign)
I just got off support with ActiveCampaign and they said they couldn't provide me with code examples on how to add their modal pop-up forms to be triggered by wordpress buttons.

I found a few resources online but they are all slightly different than the functionality I'm looking for.

I already added the ActiveCampaign plugin to my wordpress site and there are two options of embedding the form within the site.

shortcode "[activeCampaign formId=1]" or

I'm currently using the divi theme, and the buttons have sections for CSS ID's and CSS Classes.

so to summarize, I would like to be able to click a button and have the activecampaign modal form popup.

If you could show me how I can add code to the button and my site to trigger the modal popup that'd be amazing.

Let me know if you have any other information.

Thanks!

答:
Sugesstion:

This involves DOM manipulation. create a css class called active which should be set to the form container to show. Here's an example:

var formToggle = document.getElementById("form-toggler");

var formContainer = document.querySelector(".form-container");

formToggle.addEventListener('click', function(){
  // When you click the button, first check if the form is open
  //  so that you know if you should close or open
  if(formContainer.classList.contains("active")){
    // Form is currently open, because it has active as one of it's classes
    // so remove active to hide it.
    formContainer.classList.remove("active");
  }else{
    // Form is currently closed, because it does not have active as one of it's classes
    // so add active to show it.
    formContainer.classList.add("active");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.form-container{
  width: 100%;
  height: 100%;
  min-height: 200px;
  background-color: rgba(0,0,0,0.2);
  display: none;
}

/* When form has active class, set display to block */
.form-container.active{
  display: block !important;
}</code>```

Yey, form is active!!

<button id="form-toggler">OpenForm<button>```

This is just at the basic level of approaching your scenario. So you've got to work on your css to make your Modal cover the entire window and add a close button on it in case someone decides to close it.

Body:
Sugesstion:

This involves DOM manipulation. create a css class called active which should be set to the form container to show. Here's an example:

var formToggle = document.getElementById("form-toggler");

var formContainer = document.querySelector(".form-container");

formToggle.addEventListener('click', function(){
  // When you click the button, first check if the form is open
  //  so that you know if you should close or open
  if(formContainer.classList.contains("active")){
    // Form is currently open, because it has active as one of it's classes
    // so remove active to hide it.
    formContainer.classList.remove("active");
  }else{
    // Form is currently closed, because it does not have active as one of it's classes
    // so add active to show it.
    formContainer.classList.add("active");
  }
});

.form-container{
  width: 100%;
  height: 100%;
  min-height: 200px;
  background-color: rgba(0,0,0,0.2);
  display: none;
}

/* When form has active class, set display to block */
.form-container.active{
  display: block !important;
}

<div class="form-container">
    <!-- your Form Here -->
    <h1>Yey, form is active!!</h1>
</div>

<button id="form-toggler">OpenForm<button>

This is just at the basic level of approaching your scenario. So you've got to work on your css to make your Modal cover the entire window and add a close button on it in case someone decides to close it.


问:
Exact math with big numbers in Python 3
I'm trying to implement a system for encryption similar to Shamir's Secret Sharing using Python. Essentially, I have code that will generate a list of points that can be used to find a password at the y-intercept of the gradient formed by these points. The password is a number in ASCII (using two digits per ASCII character), thus is gets to be a pretty big number with larger passwords. For example, the password ThisIsAPassword will generate a list of points that looks like this:

```<code>x    y
9556 66707086867915126140753213946756441607861037300900
4083 28502040182447127964404994111341362715565457349000
9684 67600608880657662915204624898507424633297513499300
9197 64201036847801292531159022293017356403707170463200
</code>```

To be clear, these points are generated upon a randomly chosen slope (this is fine since it's the y-intercept that matters).

The problem arises in trying to make a program to decode a password. Using normal math, Python is unable to accurately find the password because of the size of the numbers. Here's the code I have:

```<code>def findYint(x,y):
    slope = (y[1] - y[0]) / (x[1] - x[0])
    yint = int(y[0] - slope * x[0])
    return yint

def asciiToString(num):
    chars = [num[i:i+3] for i in range(0, len(num), 3)]

    return ''.join(chr(int(i)) for i in chars)

def main():
    fi = open('pass.txt','r')
    x,y = [], []
    for i in fi:
        row = i.split()
        x.append(int(row[0]))
        y.append(int(row[1]))
    fi.close()
    yint = findYint(x,y)
    pword = asciiToString(str(yint))

    print(pword)

main()
</code>```

Output (with the password "ThisIsAPassword"):

```<code>͉)3 ǢΜĩũć»¢ǔ¼
</code>```

Typically my code will work with shorter passwords such as "pass" or "word", but the bigger numbers presumably aren't computed with the exact accuracy needed to convert them into ASCII. Any solutions for using either precise math or something else?

Also here's the code for generating points in case it's important:

```<code>import random

def encryptWord(word):
    numlist = []
    for i in range(len(word)):
        numlist.append(str(ord(word[i])).zfill(3))
    num = int("".join(numlist))
    return num

def createPoints(pwd, pts):
    yint = pwd
    gradient = pwd*random.randint(10,100)
    xvals = []
    yvals = []
    for i in range(pts):
        n = random.randint(1000,10000)
        xvals.append(n)
        yvals.append(((n) * gradient) + pwd)

    return xvals, yvals

def main():
    pword = input("Enter a password to encrypt: ")
    pword = encryptWord(pword)
    numpoints = int(input("How many points to generate? "))
    if numpoints < 2:
        numpoints = 2
    xpts, ypts = createPoints(pword, numpoints)

    fi = open("pass.txt","w")
    for i in range(len(xpts)):
        fi.write(str(xpts[i]))
        fi.write(' ')
        fi.write(str(ypts[i]))
        fi.write('\n')
    fi.close()
    print("Sent to file (pass.txt)")
main()
</code>```

答:
It should be possible to do this only with integer-based math:

```<code>def findYint(x,y):
    return (y[0] * (x[1] - x[0]) - (y[1] - y[0]) * x[0])  // (x[1] - x[0])
</code>```

This way you avoid the floating point arithmetic and the precision constraints it has.

Title: Exact math with big numbers in Python 3

Body:
I'm trying to implement a system for encryption similar to Shamir's Secret Sharing using Python. Essentially, I have code that will generate a list of points that can be used to find a password at the y-intercept of the gradient formed by these points. The password is a number in ASCII (using two digits per ASCII character), thus is gets to be a pretty big number with larger passwords. For example, the password ThisIsAPassword will generate a list of points that looks like this:

x    y
9556 66707086867915126140753213946756441607861037300900
4083 28502040182447127964404994111341362715565457349000
9684 67600608880657662915204624898507424633297513499300
9197 64201036847801292531159022293017356403707170463200

To be clear, these points are generated upon a randomly chosen slope (this is fine since it's the y-intercept that matters).

The problem arises in trying to make a program to decode a password. Using normal math, Python is unable to accurately find the password because of the size of the numbers. Here's the code I have:

def findYint(x,y):
    slope = (y[1] - y[0]) / (x[1] - x[0])
    yint = int(y[0] - slope * x[0])
    return yint

def asciiToString(num):
    chars = [num[i:i+3] for i in range(0, len(num), 3)]

    return ''.join(chr(int(i)) for i in chars)

def main():
    fi = open('pass.txt','r')
    x,y = [], []
    for i in fi:
        row = i.split()
        x.append(int(row[0]))
        y.append(int(row[1]))
    fi.close()
    yint = findYint(x,y)
    pword = asciiToString(str(yint))

    print(pword)

main()

Output (with the password "ThisIsAPassword"):

͉)3 ǢΜĩũć»¢ǔ¼

Typically my code will work with shorter passwords such as "pass" or "word", but the bigger numbers presumably aren't computed with the exact accuracy needed to convert them into ASCII. Any solutions for using either precise math or something else?

Also here's the code for generating points in case it's important:

import random

def encryptWord(word):
    numlist = []
    for i in range(len(word)):
        numlist.append(str(ord(word[i])).zfill(3))
    num = int("".join(numlist))
    return num

def createPoints(pwd, pts):
    yint = pwd
    gradient = pwd*random.randint(10,100)
    xvals = []
    yvals = []
    for i in range(pts):
        n = random.randint(1000,10000)
        xvals.append(n)
        yvals.append(((n) * gradient) + pwd)

    return xvals, yvals

def main():
    pword = input("Enter a password to encrypt: ")
    pword = encryptWord(pword)
    numpoints = int(input("How many points to generate? "))
    if numpoints < 2:
        numpoints = 2
    xpts, ypts = createPoints(pword, numpoints)

    fi = open("pass.txt","w")
    for i in range(len(xpts)):
        fi.write(str(xpts[i]))
        fi.write(' ')
        fi.write(str(ypts[i]))
        fi.write('\n')
    fi.close()
    print("Sent to file (pass.txt)")
main()

Body:
It should be possible to do this only with integer-based math:

def findYint(x,y):
    return (y[0] * (x[1] - x[0]) - (y[1] - y[0]) * x[0])  // (x[1] - x[0])

This way you avoid the floating point arithmetic and the precision constraints it has.


问:
Q Language for usage in KDB
I was challenged to either learn Q language, or to continue analyzing the query responses with Python.

So learning Q would give advantage of small traffic generated, while the query response to process with Python would be in the range of 160GB a day.

Do you have recommendations on programming in Q, especially dealing with tables?

All the manuals I find are too generic. The only one which is somewhat close to what I need is the vendor's manual, but it is pretty old, from 2009.

Abridged Q Language Manual, 2009.03.16

Specifically the idea is to send such a query to the KDB server that most of the analysis to be already done by the server, and what is left to be analyzed to be not so much, or perfectly, just to dump the results on the disk and to prepare the next query.

Is there a crash course, or at least more up-to-date manual?

答:
There are many of us kdb+ devs here on SO who are happy to help with any specific questions you have, if they’re tagged with kdb.

If you’re looking for a “crash course”, AquaQ offer a free kdb+ bootcamp taster that may provide the basics required to get going. (Full disclaimer, I’m an employee of AquaQ). The taster includes basic operations in q, some qSQL querying and connecting to a q session via a web browser. There is also the opportunity to purchase the full bootcamp course if that’s an option for you.

All of this, alongside the Kx reference site, should set you on your way.

Title: Q Language for usage in KDB


问:
matchAll Throws error when g flag is missing now?
From the MDN docs it states

matchAll only returns the first match if the g flag is missing.

But if you run this code:

const regexp = RegExp('[a-c]', '');
const str = 'abc';
console.log(Array.from(str.matchAll(regexp), m => m[0]));
// Array [ "a" ]```

in a recent version of chrome you get the following error:

Error: undefineds called with a non-global RegExp argument

I'm on chrome version 80.0.3987.116

I'm not sure if this is a chrome issue or the MDN documentation needs to be updated.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll

答:
The information presented to you on MDN, in this instance, is wrong.

The Official ECMA Specification, ECMA-262 as of February 15, 2020( See here ), states that if there is no g flag present, that matchAll should throw a TypeError.

See specifically 2.b.iii below.

The error message is obviously fairly confusing with its phrasing, but still correct.

Body:
From the MDN docs it states

matchAll only returns the first match if the g flag is missing.

But if you run this code:

const regexp = RegExp('[a-c]', '');
const str = 'abc';
console.log(Array.from(str.matchAll(regexp), m => m[0]));
// Array [ "a" ]

in a recent version of chrome you get the following error:

Error: undefineds called with a non-global RegExp argument

I'm on chrome version 80.0.3987.116

I'm not sure if this is a chrome issue or the MDN documentation needs to be updated.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll


问:
Solr Container
What is better container for SOLR: Tomcat or Jetty</p>

答:
It runs in a Java servlet container such as Tomcat.

It shouldn't matter since they are both servlet containers. Use whatever you feel most comfortable with.

OwnerDisplayName: Mote

ContentLicense: CC BY-SA 2.5

Title: Solr Container

OwnerDisplayName: cherouvim


问:
Add class when (...) with jQuery
I've this simple code:

HTML:

```<code><input type="text" name="name" class="required" />

<select id="options" name="options" size="1">
  <option value="0"> YES </option>
  <option value="1"> NO </option>
</select>

<input type="text" name="email" />
<input type="text" name="city" />
</code>```

Question:

I want to add class = "required"  to email and city fields when options is equal to 1

答:
assign ids to the inputs and do following logic , ids are always better as it takes less time to execute in case of complex DOMs.</p>

```<code>$('#options').change(function(){
if($(this).val() == 1) {
 $('#inputemail').addClass('required');
 $('#city').addClass('required');
}else {
$('#inputemail').removeClass('required');
 $('#city').removeClass('required');
}
});
</code>```

Title: Add class when (...) with jQuery

Body:
I've this simple code:

HTML:

<input type="text" name="name" class="required" />

<select id="options" name="options" size="1">
  <option value="0"> YES </option>
  <option value="1"> NO </option>
</select>

<input type="text" name="email" />
<input type="text" name="city" />

Question:

I want to add class = "required"  to email and city fields when options is equal to 1

Body:
assign ids to the inputs and do following logic , ids are always better as it takes less time to execute in case of complex DOMs.

$('#options').change(function(){
if($(this).val() == 1) {
 $('#inputemail').addClass('required');
 $('#city').addClass('required');
}else {
$('#inputemail').removeClass('required');
 $('#city').removeClass('required');
}
});


问:
How to properly implement Navigator pattern
I am following John Sundell's post to implement a Navigator pattern (https://www.swiftbysundell.com/posts/navigation-in-swift). The basic idea is that, in contrast to Coordinator pattern, each view controller could simply call navigator.navigate(to: .someScreen) without having to know other view controllers.

My question is that, since in order to construct a view controller I need a navigator, to construct a navigator I need a navigation controller, but I want to make the view controller the root of the navigation controller, what's the best way to resolve this circular dependency in a way that respects the best practices of dependency injection?

Below is the idea of Navigator pattern as illustrated by Sundell

Navigator

```<code>protocol Navigator {
    associatedtype Destination
    func navigate(to destination: Destination)
}

class LoginNavigator: Navigator {
    enum Destination {
        case loginCompleted(user: User)
        case signup
    }

    private weak var navigationController: UINavigationController?
    private let viewControllerFactory: LoginViewControllerFactory

    init(navigationController: UINavigationController,
         viewControllerFactory: LoginViewControllerFactory) {
        self.navigationController = navigationController
        self.viewControllerFactory = viewControllerFactory
    }

    func navigate(to destination: Destination) {
        let viewController = makeViewController(for: destination)
        navigationController?.pushViewController(viewController, animated: true)
    }

    private func makeViewController(for destination: Destination) -> UIViewController {
        switch destination {
        case .loginCompleted(let user):
            return viewControllerFactory.makeWelcomeViewController(forUser: user)
        case .signup:
            return viewControllerFactory.makeSignUpViewController()
        }
    }
}
</code>```

View Controller

```<code>class LoginViewController: UIViewController {
    private let navigator: LoginNavigator

    init(navigator: LoginNavigator) {
        self.navigator = navigator
        super.init(nibName: nil, bundle: nil)
    }

    private func handleLoginButtonTap() {
        navigator.navigate(to: .loginCompleted(user: user))
    }

    private func handleSignUpButtonTap() {
        navigator.navigate(to: .signup)
    }
}
</code>```

Now in AppDelegate I want to do something like

```<code>let factory = LoginViewControllerFactory()
let loginViewController = factory.makeLoginViewController()
let rootNavigationController = UINavigationController(rootViewController: loginViewController)
window?.rootViewController = rootNavigationController
</code>```

But I somehow have to pass the rootNavigationController into the factory in order for the loginViewController to be properly constructed right? Because it needs a navigator, which needs the navigation controller. How to do that?

答:
I also was recently trying to implement Sundell's Navigator pattern and ran into  this same circular dependency. I had to add some additional behavior to the initial Navigator to handle this odd bootstrap issue. I believe subsequent Navigators in your app can perfectly follow the blog's suggestion.

Here is the new initial Navigator code using JGuo's (the OP) example:

```<code>class LoginNavigator: Navigator {
    enum Destination {
        case loginCompleted(user: User)
        case signup
    }

    private var navigationController: UINavigationController?
    // This ^ doesn't need to be weak, as we will instantiate it here.

    private let viewControllerFactory: LoginViewControllerFactory

    // New:
    private let appWindow: UIWindow?
    private var isBootstrapped = false
    // We will use this ^ to know whether or not to set the root VC

    init(appWindow: UIWindow?, // Pass in your app's UIWindow from the AppDelegate
         viewControllerFactory: LoginViewControllerFactory) {
        self.appWindow = appWindow
        self.viewControllerFactory = viewControllerFactory
    }

    func navigate(to destination: Destination) {
        let viewController = makeViewController(for: destination)

        // We'll either call bootstrap or push depending on
        // if this is the first time we've launched the app, indicated by isBootstrapped
        if self.isBootstrapped {
            self.pushViewController(viewController)
        } else {
            bootstrap(rootViewController: viewController)
            self.isBootstrapped = true
        }
    }

    private func makeViewController(for destination: Destination) -> UIViewController {
        switch destination {
        case .loginCompleted(let user):
            return viewControllerFactory.makeWelcomeViewController(forUser: user)
        case .signup:
            return viewControllerFactory.makeSignUpViewController()
        }
    }

    // Add these two new helper functions below:
    private func bootstrap(rootViewController: UIViewController) {
        self.navigationController = UINavigationController(rootViewController: rootViewController)
        self.appWindow?.rootViewController = self.navigationController
    }

    private func pushViewController(_ viewController: UIViewController) {
        // Setup navigation look & feel appropriate to your app design...
        navigationController?.setNavigationBarHidden(true, animated: false)
        self.navigationController?.pushViewController(viewController, animated: true)
    }
}
</code>```

And inside the AppDelegate now:

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        window = UIWindow(frame: UIScreen.main.bounds)
        let factory = LoginViewControllerFactory()
        let loginViewController = factory.makeLoginViewController()
        loginViewController.navigate(to: .signup) // <- Ideally we wouldn't need to signup on app launch always, but this is the basic idea.
        window?.makeKeyAndVisible()

        return true
    }
...
}
</code>```

Body:
I am following John Sundell's post to implement a Navigator pattern (https://www.swiftbysundell.com/posts/navigation-in-swift). The basic idea is that, in contrast to Coordinator pattern, each view controller could simply call navigator.navigate(to: .someScreen) without having to know other view controllers.

My question is that, since in order to construct a view controller I need a navigator, to construct a navigator I need a navigation controller, but I want to make the view controller the root of the navigation controller, what's the best way to resolve this circular dependency in a way that respects the best practices of dependency injection?

Below is the idea of Navigator pattern as illustrated by Sundell

Navigator

protocol Navigator {
    associatedtype Destination
    func navigate(to destination: Destination)
}

class LoginNavigator: Navigator {
    enum Destination {
        case loginCompleted(user: User)
        case signup
    }

    private weak var navigationController: UINavigationController?
    private let viewControllerFactory: LoginViewControllerFactory

    init(navigationController: UINavigationController,
         viewControllerFactory: LoginViewControllerFactory) {
        self.navigationController = navigationController
        self.viewControllerFactory = viewControllerFactory
    }

    func navigate(to destination: Destination) {
        let viewController = makeViewController(for: destination)
        navigationController?.pushViewController(viewController, animated: true)
    }

    private func makeViewController(for destination: Destination) -> UIViewController {
        switch destination {
        case .loginCompleted(let user):
            return viewControllerFactory.makeWelcomeViewController(forUser: user)
        case .signup:
            return viewControllerFactory.makeSignUpViewController()
        }
    }
}

View Controller

class LoginViewController: UIViewController {
    private let navigator: LoginNavigator

    init(navigator: LoginNavigator) {
        self.navigator = navigator
        super.init(nibName: nil, bundle: nil)
    }

    private func handleLoginButtonTap() {
        navigator.navigate(to: .loginCompleted(user: user))
    }

    private func handleSignUpButtonTap() {
        navigator.navigate(to: .signup)
    }
}

Now in AppDelegate I want to do something like

let factory = LoginViewControllerFactory()
let loginViewController = factory.makeLoginViewController()
let rootNavigationController = UINavigationController(rootViewController: loginViewController)
window?.rootViewController = rootNavigationController

But I somehow have to pass the rootNavigationController into the factory in order for the loginViewController to be properly constructed right? Because it needs a navigator, which needs the navigation controller. How to do that?

Body:
I also was recently trying to implement Sundell's Navigator pattern and ran into  this same circular dependency. I had to add some additional behavior to the initial Navigator to handle this odd bootstrap issue. I believe subsequent Navigators in your app can perfectly follow the blog's suggestion.

Here is the new initial Navigator code using JGuo's (the OP) example:

class LoginNavigator: Navigator {
    enum Destination {
        case loginCompleted(user: User)
        case signup
    }

    private var navigationController: UINavigationController?
    // This ^ doesn't need to be weak, as we will instantiate it here.

    private let viewControllerFactory: LoginViewControllerFactory

    // New:
    private let appWindow: UIWindow?
    private var isBootstrapped = false
    // We will use this ^ to know whether or not to set the root VC

    init(appWindow: UIWindow?, // Pass in your app's UIWindow from the AppDelegate
         viewControllerFactory: LoginViewControllerFactory) {
        self.appWindow = appWindow
        self.viewControllerFactory = viewControllerFactory
    }

    func navigate(to destination: Destination) {
        let viewController = makeViewController(for: destination)

        // We'll either call bootstrap or push depending on
        // if this is the first time we've launched the app, indicated by isBootstrapped
        if self.isBootstrapped {
            self.pushViewController(viewController)
        } else {
            bootstrap(rootViewController: viewController)
            self.isBootstrapped = true
        }
    }

    private func makeViewController(for destination: Destination) -> UIViewController {
        switch destination {
        case .loginCompleted(let user):
            return viewControllerFactory.makeWelcomeViewController(forUser: user)
        case .signup:
            return viewControllerFactory.makeSignUpViewController()
        }
    }

    // Add these two new helper functions below:
    private func bootstrap(rootViewController: UIViewController) {
        self.navigationController = UINavigationController(rootViewController: rootViewController)
        self.appWindow?.rootViewController = self.navigationController
    }

    private func pushViewController(_ viewController: UIViewController) {
        // Setup navigation look & feel appropriate to your app design...
        navigationController?.setNavigationBarHidden(true, animated: false)
        self.navigationController?.pushViewController(viewController, animated: true)
    }
}

And inside the AppDelegate now:

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        window = UIWindow(frame: UIScreen.main.bounds)
        let factory = LoginViewControllerFactory()
        let loginViewController = factory.makeLoginViewController()
        loginViewController.navigate(to: .signup) // <- Ideally we wouldn't need to signup on app launch always, but this is the basic idea.
        window?.makeKeyAndVisible()

        return true
    }
...
}


问:
Persisting state into Kafka using Kafka Streams
I am trying to wrap my head around Kafka Streams and having some fundamental questions that I can't seem to figure out on my own. I understand the concept of a KTable and Kafka State Stores but am having trouble deciding how to approach this. I am also using Spring Cloud Streams, which adds another level of complexity on top of this.

My use case:

I have a rule engine that reads in a Kafka event, processes the event, returns a list of rules that matched and writes it into another topic. This is what I have so far:

```<code>@Bean
public Function<KStream<String, ProcessNode>, KStream<String, List<IndicatorEvaluation>>> process() {
    return input -> input.mapValues(this::analyze).filter((host, evaluation) -> evaluation != null);
}

public List<IndicatorEvaluation> analyze(final String host, final ProcessNode process) {
    // Does stuff
}
</code>```

Some of the stateful rules look like:

[some condition] REPEATS 5 TIMES WITHIN 1 MINUTE
[some condition] FOLLOWEDBY [some condition] WITHIN 1 MINUTE
[rule A exists and rule B exists]
```

My current implementation is storing all this information in memory to be able to perform the analysis. For obvious reasons, it is not easily scalable. So I figured I would persist this into a Kafka State Store.

I am unsure of the best way to go about it. I know there is a way to create custom state stores that allow for a higher level of flexibility. I'm not sure if the Kafka DSL will support this.

Still new to Kafka Streams and wouldn't mind hearing a variety of suggestions.

答:
From the description you have given, I believe this use case can still be implemented using the DSL in Kafka Streams. The code you have shown above does not track any state. In your topology, you need to add state by tracking the counts of the rules and store them in a state store. Then you only need to send the output rules when that count hits a threshold. Here is the general idea behind this as a pseudo-code. Obviously, you have to tweak this to satisfy the particular specifications of your use case.</p>

```<code>@Bean
public Function<KStream<String, ProcessNode>, KStream<String, List<IndicatorEvaluation>>> process() {
    return input -> input
                     .mapValues(this::analyze)
                     .filter((host, evaluation) -> evaluation != null)
                     ...
                     .groupByKey(...)
                     .windowedBy(TimeWindows.of(Duration.ofHours(1)))
                     .count(Materialized.as("rules"))
                     .filter((key, value) -> value > 4)
                     .toStream()
                    ....
}
</code>```

Body:
I am trying to wrap my head around Kafka Streams and having some fundamental questions that I can't seem to figure out on my own. I understand the concept of a KTable and Kafka State Stores but am having trouble deciding how to approach this. I am also using Spring Cloud Streams, which adds another level of complexity on top of this.

My use case:

I have a rule engine that reads in a Kafka event, processes the event, returns a list of rules that matched and writes it into another topic. This is what I have so far:

@Bean
public Function<KStream<String, ProcessNode>, KStream<String, List<IndicatorEvaluation>>> process() {
    return input -> input.mapValues(this::analyze).filter((host, evaluation) -> evaluation != null);
}

public List<IndicatorEvaluation> analyze(final String host, final ProcessNode process) {
    // Does stuff
}

Some of the stateful rules look like:

[some condition] REPEATS 5 TIMES WITHIN 1 MINUTE
[some condition] FOLLOWEDBY [some condition] WITHIN 1 MINUTE
[rule A exists and rule B exists]

My current implementation is storing all this information in memory to be able to perform the analysis. For obvious reasons, it is not easily scalable. So I figured I would persist this into a Kafka State Store.

I am unsure of the best way to go about it. I know there is a way to create custom state stores that allow for a higher level of flexibility. I'm not sure if the Kafka DSL will support this.

Still new to Kafka Streams and wouldn't mind hearing a variety of suggestions.

Body:
From the description you have given, I believe this use case can still be implemented using the DSL in Kafka Streams. The code you have shown above does not track any state. In your topology, you need to add state by tracking the counts of the rules and store them in a state store. Then you only need to send the output rules when that count hits a threshold. Here is the general idea behind this as a pseudo-code. Obviously, you have to tweak this to satisfy the particular specifications of your use case.

@Bean
public Function<KStream<String, ProcessNode>, KStream<String, List<IndicatorEvaluation>>> process() {
    return input -> input
                     .mapValues(this::analyze)
                     .filter((host, evaluation) -> evaluation != null)
                     ...
                     .groupByKey(...)
                     .windowedBy(TimeWindows.of(Duration.ofHours(1)))
                     .count(Materialized.as("rules"))
                     .filter((key, value) -> value > 4)
                     .toStream()
                    ....
}


问:
Rank and unrank combinations to distribute k balls into n bins of different capacities
I want to distribute k balls into n bins of different capacities. How can I rank and unrank the distributions given n, k, and the bin capacities?

Example:

n := 3

k := 4

bin capacities := 3,2,1

Balls in bins:

1,2,1, 2,1,1, 2,2,0, 3,0,1, 3,1,0 := 5

Is there a formula?

答:
I do not know if there is a standard name for this technique, but this is a kind of problem that I have successfully solved many times with a twist on dynamic programming.

What I do using dynamic programming to build a data structure from which the rank/unrank can happen, and then build logic to do the rank/unrank thing.

The dynamic programming piece is hardest.

import collections
BallSolutions = collections.namedtuple('BallSolutions', 'bin count balls next_bin_solutions next_balls_solutions');

def find_ball_solutions (balls, bin_capacities):
    # How many balls can fit in the remaining bins?
    capacity_sum = [0 for _ in bin_capacities]
    capacity_sum[-1] = bin_capacities[-1]

    for i in range(len(bin_capacities) - 2, -1, -1):
        capacity_sum[i] = capacity_sum[i+1] + bin_capacities[i]

    cache = {}
    def _search (bin_index, remaining_balls):
        if len(bin_capacities) <= bin_index:
            return None
        elif capacity_sum[bin_index] < remaining_balls:
            return None
        elif (bin_index, remaining_balls) not in cache:
            if bin_index + 1 == len(bin_capacities):
                cache[(bin_index, remaining_balls)] = BallSolutions(
                    bin=bin_index, count=1, balls=remaining_balls, next_bin_solutions=None, next_balls_solutions=None)
            else:
                this_solution = None
                for this_balls in range(min([remaining_balls, bin_capacities[bin_index]]), -1, -1):
                    next_bin_solutions = _search(bin_index+1, remaining_balls - this_balls)
                    if next_bin_solutions is None:
                        break # We already found the fewest balls that can go in this bin.
                    else:
                        this_count = next_bin_solutions.count
                        if this_solution is not None:
                            this_count = this_count + this_solution.count
                        next_solution = BallSolutions(
                            bin=bin_index, count=this_count,
                            balls=this_balls, next_bin_solutions=next_bin_solutions,
                            next_balls_solutions=this_solution)
                        this_solution = next_solution
                cache[(bin_index, remaining_balls)] = this_solution
        return cache[(bin_index, remaining_balls)]

    return _search(0, balls)
```
<p>Here is code to produce a ranked solution:</p>
<pre class="lang-py prettyprint-override"><code>def find_ranked_solution (solutions, n):
    if solutions is None:
        return None
    elif n < 0:
        return None
    elif solutions.next_bin_solutions is None:
        if n == 0:
            return [solutions.balls]
        else:
            return None
    elif n < solutions.next_bin_solutions.count:
        return [solutions.balls] + find_ranked_solution(solutions.next_bin_solutions, n)
    else:
        return find_ranked_solution(solutions.next_balls_solutions, n - solutions.next_bin_solutions.count)
</code>```

Here is code to produce the rank for a solution.  Note that it will blow up if provided with an invalid answer.

def find_solution_rank (solutions, solution):
    n = 0
    while solutions.balls < solution[0]:
        n = n + solutions.next_bin_solutions.count
        solutions = solutions.next_balls_solutions
    if 1 < len(solution):
        n = n + find_solution_rank(solutions.next_bin_solutions, solution[1:])
    return n
```
<p>And here is some test code:</p>
<pre class="lang-py prettyprint-override"><code>s = find_ball_solutions(4, [3, 2, 1])
for i in range(6):
    r = find_ranked_solution(s, i)
    print((i, r, find_solution_rank(s, r)))
</code>```

Body:
I do not know if there is a standard name for this technique, but this is a kind of problem that I have successfully solved many times with a twist on dynamic programming.

What I do using dynamic programming to build a data structure from which the rank/unrank can happen, and then build logic to do the rank/unrank thing.

The dynamic programming piece is hardest.

import collections
BallSolutions = collections.namedtuple('BallSolutions', 'bin count balls next_bin_solutions next_balls_solutions');

def find_ball_solutions (balls, bin_capacities):
    # How many balls can fit in the remaining bins?
    capacity_sum = [0 for _ in bin_capacities]
    capacity_sum[-1] = bin_capacities[-1]

    for i in range(len(bin_capacities) - 2, -1, -1):
        capacity_sum[i] = capacity_sum[i+1] + bin_capacities[i]

    cache = {}
    def _search (bin_index, remaining_balls):
        if len(bin_capacities) <= bin_index:
            return None
        elif capacity_sum[bin_index] < remaining_balls:
            return None
        elif (bin_index, remaining_balls) not in cache:
            if bin_index + 1 == len(bin_capacities):
                cache[(bin_index, remaining_balls)] = BallSolutions(
                    bin=bin_index, count=1, balls=remaining_balls, next_bin_solutions=None, next_balls_solutions=None)
            else:
                this_solution = None
                for this_balls in range(min([remaining_balls, bin_capacities[bin_index]]), -1, -1):
                    next_bin_solutions = _search(bin_index+1, remaining_balls - this_balls)
                    if next_bin_solutions is None:
                        break # We already found the fewest balls that can go in this bin.
                    else:
                        this_count = next_bin_solutions.count
                        if this_solution is not None:
                            this_count = this_count + this_solution.count
                        next_solution = BallSolutions(
                            bin=bin_index, count=this_count,
                            balls=this_balls, next_bin_solutions=next_bin_solutions,
                            next_balls_solutions=this_solution)
                        this_solution = next_solution
                cache[(bin_index, remaining_balls)] = this_solution
        return cache[(bin_index, remaining_balls)]

    return _search(0, balls)

Here is code to produce a ranked solution:

def find_ranked_solution (solutions, n):
    if solutions is None:
        return None
    elif n < 0:
        return None
    elif solutions.next_bin_solutions is None:
        if n == 0:
            return [solutions.balls]
        else:
            return None
    elif n < solutions.next_bin_solutions.count:
        return [solutions.balls] + find_ranked_solution(solutions.next_bin_solutions, n)
    else:
        return find_ranked_solution(solutions.next_balls_solutions, n - solutions.next_bin_solutions.count)

Here is code to produce the rank for a solution.  Note that it will blow up if provided with an invalid answer.

def find_solution_rank (solutions, solution):
    n = 0
    while solutions.balls < solution[0]:
        n = n + solutions.next_bin_solutions.count
        solutions = solutions.next_balls_solutions
    if 1 < len(solution):
        n = n + find_solution_rank(solutions.next_bin_solutions, solution[1:])
    return n

And here is some test code:

s = find_ball_solutions(4, [3, 2, 1])
for i in range(6):
    r = find_ranked_solution(s, i)
    print((i, r, find_solution_rank(s, r)))


问:
Invalid input syntax for integer but type is date?
I'm trying to use a query to get date type value but it doesn't work...

tables:

```<code>Create table Clients1(
    login char(30) primary key,
    password varchar(30),
    date_ad date,
    name_c varchar(30),
    adress varchar(30),
    card_c varchar(30)
);

Create table clients_pay(
    payment_ID char(15) primary key,
    login char(15)
);
</code>```

The following error appears:

22P02: invalid input syntax for integer: "2019/12/02"

My query is as follows:

```<code>SELECT DISTINCT login, COUNT(payment_ID) AS p
FROM Clients1
NATURAL INNER JOIN Payments1
NATURAL INNER JOIN clients_pay
GROUP BY login
HAVING COUNT(payment_ID) >='2019/12/02';
</code>```

Since it's type date why it appears as integer?

I'm trying to see which clients can use service at date 2019/12/02?
(They can if payed)

Thank you

答:
It looks like you want to have a WHERE clause limiting the payment_ids returned by a date, such as:

```<code>SELECT login, COUNT(payment_ID) AS p
FROM clients1
INNER JOIN clients_pay
ON clients_pay.login = Clients1.login
WHERE date_ad >='2019/12/02'
GROUP BY login ;
</code>```

I also made some assumptions about the intention of your query and your data model, please edit your question to clarify those things if this doesn't meet your needs.  Also note, Postgres identifiers are coerced to lowercase by default, unless you specify the casing by putting double quotes around the identifier during object creation.  That practice is highly discouraged, though.

Body:
I'm trying to use a query to get date type value but it doesn't work...

tables:

Create table Clients1(
    login char(30) primary key,
    password varchar(30),
    date_ad date,
    name_c varchar(30),
    adress varchar(30),
    card_c varchar(30)
);

Create table clients_pay(
    payment_ID char(15) primary key,
    login char(15)
);

The following error appears:

22P02: invalid input syntax for integer: "2019/12/02"

My query is as follows:

SELECT DISTINCT login, COUNT(payment_ID) AS p
FROM Clients1
NATURAL INNER JOIN Payments1
NATURAL INNER JOIN clients_pay
GROUP BY login
HAVING COUNT(payment_ID) >='2019/12/02';

Since it's type date why it appears as integer?

I'm trying to see which clients can use service at date 2019/12/02?
(They can if payed)

Thank you

Body:
It looks like you want to have a WHERE clause limiting the payment_ids returned by a date, such as:

SELECT login, COUNT(payment_ID) AS p
FROM clients1
INNER JOIN clients_pay
ON clients_pay.login = Clients1.login
WHERE date_ad >='2019/12/02'
GROUP BY login ;

I also made some assumptions about the intention of your query and your data model, please edit your question to clarify those things if this doesn't meet your needs.  Also note, Postgres identifiers are coerced to lowercase by default, unless you specify the casing by putting double quotes around the identifier during object creation.  That practice is highly discouraged, though.


问:
How to capture every SQL call made via .net Entity Framework 6.2
Looking to capture and log every calls to the DB made by entity framework. What's the best way of doing this? is that the best way https://www.entityframeworktutorial.net/entityframework6/database-command-interception.aspx ?

Thanks!

答:
REFERENCE: Logging and intercepting database operations

You can set the context.Database.Log to Console.Write:

```<code>using (var context = new BlogContext())
{
    context.Database.Log = Console.Write;

    var blog = context.Blogs.First(b => b.Title == "One Unicorn");

    blog.Posts.First().Title = "Green Eggs and Ham";

    blog.Posts.Add(new Post { Title = "I do not like them!" });

    context.SaveChangesAsync().Wait();
}
</code>```

This will generate the following output:

```<code>SELECT TOP (1)
    [Extent1].[Id] AS [Id],
    [Extent1].[Title] AS [Title]
    FROM [dbo].[Blogs] AS [Extent1]
    WHERE (N'One Unicorn' = [Extent1].[Title]) AND ([Extent1].[Title] IS NOT NULL)
-- Executing at 10/8/2013 10:55:41 AM -07:00
-- Completed in 4 ms with result: SqlDataReader

SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Title] AS [Title],
    [Extent1].[BlogId] AS [BlogId]
    FROM [dbo].[Posts] AS [Extent1]
    WHERE [Extent1].[BlogId] = @EntityKeyValue1
-- EntityKeyValue1: '1' (Type = Int32)
-- Executing at 10/8/2013 10:55:41 AM -07:00
-- Completed in 2 ms with result: SqlDataReader

UPDATE [dbo].[Posts]
SET [Title] = @0
WHERE ([Id] = @1)
-- @0: 'Green Eggs and Ham' (Type = String, Size = -1)
-- @1: '1' (Type = Int32)
-- Executing asynchronously at 10/8/2013 10:55:41 AM -07:00
-- Completed in 12 ms with result: 1

INSERT [dbo].[Posts]([Title], [BlogId])
VALUES (@0, @1)
SELECT [Id]
FROM [dbo].[Posts]
WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()
-- @0: 'I do not like them!' (Type = String, Size = -1)
-- @1: '1' (Type = Int32)
-- Executing asynchronously at 10/8/2013 10:55:41 AM -07:00
-- Completed in 2 ms with result: SqlDataReader
</code>```

Body:
REFERENCE: Logging and intercepting database operations

You can set the context.Database.Log to Console.Write:

using (var context = new BlogContext())
{
    context.Database.Log = Console.Write;

    var blog = context.Blogs.First(b => b.Title == "One Unicorn");

    blog.Posts.First().Title = "Green Eggs and Ham";

    blog.Posts.Add(new Post { Title = "I do not like them!" });

    context.SaveChangesAsync().Wait();
}

This will generate the following output:

SELECT TOP (1)
    [Extent1].[Id] AS [Id],
    [Extent1].[Title] AS [Title]
    FROM [dbo].[Blogs] AS [Extent1]
    WHERE (N'One Unicorn' = [Extent1].[Title]) AND ([Extent1].[Title] IS NOT NULL)
-- Executing at 10/8/2013 10:55:41 AM -07:00
-- Completed in 4 ms with result: SqlDataReader

SELECT
    [Extent1].[Id] AS [Id],
    [Extent1].[Title] AS [Title],
    [Extent1].[BlogId] AS [BlogId]
    FROM [dbo].[Posts] AS [Extent1]
    WHERE [Extent1].[BlogId] = @EntityKeyValue1
-- EntityKeyValue1: '1' (Type = Int32)
-- Executing at 10/8/2013 10:55:41 AM -07:00
-- Completed in 2 ms with result: SqlDataReader

UPDATE [dbo].[Posts]
SET [Title] = @0
WHERE ([Id] = @1)
-- @0: 'Green Eggs and Ham' (Type = String, Size = -1)
-- @1: '1' (Type = Int32)
-- Executing asynchronously at 10/8/2013 10:55:41 AM -07:00
-- Completed in 12 ms with result: 1

INSERT [dbo].[Posts]([Title], [BlogId])
VALUES (@0, @1)
SELECT [Id]
FROM [dbo].[Posts]
WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()
-- @0: 'I do not like them!' (Type = String, Size = -1)
-- @1: '1' (Type = Int32)
-- Executing asynchronously at 10/8/2013 10:55:41 AM -07:00
-- Completed in 2 ms with result: SqlDataReader


问:
Python 3.7 MultiThreading strategy
I have a work load that consist of a very slow query that returns a HUGE amount of data that has to be parsed and calculated, all that on a loop. Basically, it looks like this:

```<code>for x in lastTenYears
    myData = DownloadData(x)             # takes about   ~40-50 [sec]
    parsedData.append(ParseData(myData)) # takes another +30-60 [sec]
</code>```

As I believe you have noticed, if I could run the data parsing on a thread, I could download the next batch of data while the parsing happens.

How can I achieve this parallelism of operations?

Ideally speaking, I would like to have 1 thread always downloading, and N threads doing the parsing. The download part is actually a query against a database, so it's not good to have a bunch o parallel of them...

Details:

The parsing of the data is a heavily CPU bound, and
 consists of raw math calculations and nothing else.

Using Python 3.7.4

答:
Q : How can I achieve this parallelism of operations?

The step number one is to realise, the above requested use-case is not a [PARALLEL] code-execution, but an un-ordered batch of resources-use policy limited execution of a strict sequence of pairs of :

First-a-remote-[DB-Query](returning (cit.) HUGE amount of data)

Next-a-local-[CPU-process]( of (cit.) HUGE amount of data just returned here)

The latency of the first could be masked
( if it were permitted, but it is not permitted - due to a will not to overload the DB-host ),
the latency for the second not
( can start but a next I/O-bound DB-Query, yet only if not violating the rule of keeping the DB-machine but under a mild workload ).

As I believe you have noticed, if I could run the data parsing on a thread, I could download the next batch of data while the parsing happens.

It is high time to make thing clear and sound :

Facts :

A )

The CPU-bound tasks will never run faster in whatever number N of threads in python-GIL-lock controlled ecosystem( since ever and forever, as Guido ROSSUM has expressed ),
as the GIL-lock enforces a re-[SERIAL]-isation, so the more threads "work", the more threads actually wait for acquiring the GIL-lock, before they "get" it but for a 1 / ( N + 1 )-th fraction of time of the resulting, thanks to the GIL-lock policing again pure-[SERIAL], duration of N * ( 30 - 60 ) [sec]

B )

The I/O-bound task makes no sense to off-load into a full process-based, concurrent execution, as the full-copy of the python process ( in Windows also with duplicating the whole python interpreter state with all data, during the sub-process instantiation  ) makes no sense, as there are smarter techniques for I/O-bound processing ( where GIL-lock does not hurt so much.

C )

The whole concept of N-parsing : 1-querying is principally wrong - the maximum achievable goal is to mask the latency of the I/O-process ( where making sense ), yet here each one and every query takes those said ~ 40-50 [sec] so no second pack-of-data to parse will ever be present here before running those said ~ 40-50 [sec] next time, so
no second worker will ever get anything to parse anytime before T0 + ~ 80~100 [sec] - so one could dream a wish to have N-(unbound)-workers working ( yet have 'em but actually waiting for data ) is possible, but awfully anti-productive ( the worse for N-(GIL-MUTEX-ed)-"waiting"-agents ).

Title: Python 3.7 MultiThreading strategy

Body:
I have a work load that consist of a very slow query that returns a HUGE amount of data that has to be parsed and calculated, all that on a loop. Basically, it looks like this:

for x in lastTenYears
    myData = DownloadData(x)             # takes about   ~40-50 [sec]
    parsedData.append(ParseData(myData)) # takes another +30-60 [sec]

As I believe you have noticed, if I could run the data parsing on a thread, I could download the next batch of data while the parsing happens.

How can I achieve this parallelism of operations?

Ideally speaking, I would like to have 1 thread always downloading, and N threads doing the parsing. The download part is actually a query against a database, so it's not good to have a bunch o parallel of them...

Details:

The parsing of the data is a heavily CPU bound, and
 consists of raw math calculations and nothing else.

Using Python 3.7.4


问:
Getting Difference of two dataframe on Apache Spark (Scala)
I have two dataframes which are large csv files which I am reading into dataframes in Spark (Scala)

First Dataframe is something like

```<code>key| col1 | col2  |
-------------------
1  | blue | house |
2  | red  | earth |
3  | green| earth |
4  | cyan | home  |
</code>```

Second dataframe is something like

```<code>key| col1 | col2  | col3
-------------------
1  | blue | house | xyz
2  | cyan | earth | xy
3  | green| mars  | xy
</code>```

I want to get differences like this for common keys & common columns (keys are like primary key) in a different dataframe

```<code>key| col1         | col2           |
------------------------------------
1  | blue         | house          |
2  | red --> cyan | earth          |
3  | green        | home--> mars   |
</code>```

Below is my approach so far:

```<code>//read the files into dataframe
val src_df = read_df(file1)
val tgt_df = read_df(file2)

//truncate dataframe to only contain common keys
val common_src = spark.sql(
"""
    select *
    from src_df src
    where src.key IN(
        select tgt.key
        from tgt_df tgt
"""

val tgt_common = spark.sql(
"""
    select *
    from tgt_df tgt
    where tgt.key IN(
        select src.key
        from src_df src
"""
//merge both the dataframes
val joined_df = src_common.join(tgt_common, src_common(key) === tgt_common(key), "inner")
</code>```

I was unsuccessfully trying to do something like this

```<code>joined_df
.groupby(key)
.apply(some_function(?))
</code>```

I have tried looking in existing solutions posted online . But I couldn't get the desired result.

PS: Also hoping the solution would be able to scale for large data

Thanks

答:
Try the following:</p>

```<code>spark.sql(
"""
    select
        s.id,
        if(s.col1 = t.col1, s.col1, s.col1 || ' --> ' || t.col1) as col1,
        if(s.col2 = t.col2, s.col2, s.col2 || ' --> ' || t.col2) as col2
    from src_df s
    inner join tgt_df t on s.id = t.id
""").show
</code>```

Body:
I have two dataframes which are large csv files which I am reading into dataframes in Spark (Scala)

First Dataframe is something like

key| col1 | col2  |
-------------------
1  | blue | house |
2  | red  | earth |
3  | green| earth |
4  | cyan | home  |

Second dataframe is something like

key| col1 | col2  | col3
-------------------
1  | blue | house | xyz
2  | cyan | earth | xy
3  | green| mars  | xy

I want to get differences like this for common keys & common columns (keys are like primary key) in a different dataframe

key| col1         | col2           |
------------------------------------
1  | blue         | house          |
2  | red --> cyan | earth          |
3  | green        | home--> mars   |

Below is my approach so far:

//read the files into dataframe
val src_df = read_df(file1)
val tgt_df = read_df(file2)

//truncate dataframe to only contain common keys
val common_src = spark.sql(
"""
    select *
    from src_df src
    where src.key IN(
        select tgt.key
        from tgt_df tgt
"""

val tgt_common = spark.sql(
"""
    select *
    from tgt_df tgt
    where tgt.key IN(
        select src.key
        from src_df src
"""
//merge both the dataframes
val joined_df = src_common.join(tgt_common, src_common(key) === tgt_common(key), "inner")

I was unsuccessfully trying to do something like this

joined_df
.groupby(key)
.apply(some_function(?))

I have tried looking in existing solutions posted online . But I couldn't get the desired result.

PS: Also hoping the solution would be able to scale for large data

Thanks

Body:
Try the following:

spark.sql(
"""
    select
        s.id,
        if(s.col1 = t.col1, s.col1, s.col1 || ' --> ' || t.col1) as col1,
        if(s.col2 = t.col2, s.col2, s.col2 || ' --> ' || t.col2) as col2
    from src_df s
    inner join tgt_df t on s.id = t.id
""").show


问:
How can I use randomisation to specify different object parameters to a single iteration in a loop?
I currently have a simple for-loop with 5 iterations that creates 'brick' game objects, adds them into the 'bricks' array and laying them out across the x axis of my javaFX scene. currently, as you can see on the Gameobj parameters; they are all blue. However, I want to have one of these bricks set as yellow on a random iteration of the loop. Here is my code:

```<code>    public void initialiseGame()
    {
        bricks = new ArrayList<>();
        for(int i=0; i<5; i++) {
            GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);
            brick.moveX(75);
            brick.visible = true;
            bricks.add(brick);
            System.out.println("Model:: Create Brick =" + brick);
        }
    }
</code>```

Here is the game object method setup:

```<code>    public GameObj( int x, int y, int w, int h, Color c )
    {
        topX   = x;
        topY = y;
        width  = w;
        height = h;
        colour = c;
    }
</code>```

How exactly can I use some sort of randomiser to change the colour of the brick on a single iteration?

答:
You can call GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);.

For example:
You can call int random = ThreadLocalRandom.current().nextInt(0, 5) outside the for-loop. And then use this inside the for-loop:

```<code>if (random != i) {
  GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);
} else {
  GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.YELLOW);
}
</code>```

For more information on Color visit Java™ Platform
Standard Ed. 8 Documentation

Or you can use the Math.random() function.

Body:
I currently have a simple for-loop with 5 iterations that creates 'brick' game objects, adds them into the 'bricks' array and laying them out across the x axis of my javaFX scene. currently, as you can see on the Gameobj parameters; they are all blue. However, I want to have one of these bricks set as yellow on a random iteration of the loop. Here is my code:

    public void initialiseGame()
    {
        bricks = new ArrayList<>();
        for(int i=0; i<5; i++) {
            GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);
            brick.moveX(75);
            brick.visible = true;
            bricks.add(brick);
            System.out.println("Model:: Create Brick =" + brick);
        }
    }

Here is the game object method setup:

    public GameObj( int x, int y, int w, int h, Color c )
    {
        topX   = x;
        topY = y;
        width  = w;
        height = h;
        colour = c;
    }

How exactly can I use some sort of randomiser to change the colour of the brick on a single iteration?

Body:
You can call GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);.

For example:
You can call int random = ThreadLocalRandom.current().nextInt(0, 5) outside the for-loop. And then use this inside the for-loop:

if (random != i) {
  GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.BLUE);
} else {
  GameObj brick = new GameObj(i*100, 100, BRICK_WIDTH, BRICK_HEIGHT, Color.YELLOW);
}

For more information on Color visit Java™ Platform
Standard Ed. 8 Documentation

Or you can use the Math.random() function.


问:
DocuSign API - How to get callback response after user authentication?
I'm trying to implement the Implicit Grant REST API of DocuSign. I'm confused as to what needs to happen right after the user logs in. This is a stand-alone native Windows desktop application, not a web service or page.

I got as far as to open an embedded browser window, navigating to the correct URI for login, and the user is able to successfully login. I further have an HTTP server running in this application as well which is to receive the callback. In fact, the callback does work, I do get an incoming HTTP GET command. However, there is nothing usable in this callback response. No special headers, parameters, body, nothing.

Before I tried the Implicit Grant API, I first tried the JWT Grant method, before realizing it wasn't the right approach. But my point is, at least I had a code parameter in the callback command. But after shifting over to use the Implicit Grant method, this response is empty.

According to the documentation:

After consent has been granted, the Authentication Service verifies that the client application is valid and has access to the requested scope. If so, it redirects the access token to the provided callback URI in a hash fragment.

The response contains the following hash fragment parameters:

.......

It even shows an example response:

```<code>http://localhost/#access_token=eyJ0eXAi.....9LyiFrUqvdw&expires_in=28800&token_type=bearer&state=a39fh23hnf23
</code>```

But, as mentioned, the callback response I receive has nothing of notable value. It's essentially just empty.

What am I missing here? What's the correct approach to complete the authentication process and proceed to actually using the API?

NOTE: I'm using Delphi, so none of the examples provided by DocuSign are compatible.

答: Implicit Grant is mainly for Mobile Apps, for Desktop Applications you need to use Authorization Code Grant, with this approach you will get code back in the RedirectUrl. Also please note to select Authorization Code Grant radio option in your Integrator Key configuration.

Body:
I'm trying to implement the Implicit Grant REST API of DocuSign. I'm confused as to what needs to happen right after the user logs in. This is a stand-alone native Windows desktop application, not a web service or page.

I got as far as to open an embedded browser window, navigating to the correct URI for login, and the user is able to successfully login. I further have an HTTP server running in this application as well which is to receive the callback. In fact, the callback does work, I do get an incoming HTTP GET command. However, there is nothing usable in this callback response. No special headers, parameters, body, nothing.

Before I tried the Implicit Grant API, I first tried the JWT Grant method, before realizing it wasn't the right approach. But my point is, at least I had a code parameter in the callback command. But after shifting over to use the Implicit Grant method, this response is empty.

According to the documentation:

After consent has been granted, the Authentication Service verifies that the client application is valid and has access to the requested scope. If so, it redirects the access token to the provided callback URI in a hash fragment.

The response contains the following hash fragment parameters:

.......

It even shows an example response:

http://localhost/#access_token=eyJ0eXAi.....9LyiFrUqvdw&expires_in=28800&token_type=bearer&state=a39fh23hnf23

But, as mentioned, the callback response I receive has nothing of notable value. It's essentially just empty.

What am I missing here? What's the correct approach to complete the authentication process and proceed to actually using the API?

NOTE: I'm using Delphi, so none of the examples provided by DocuSign are compatible.


问:
How to make an image/object jump infinite times?
I am trying to make a clone of flappy bird to learn pygame and I'm a beginner. Just doing the basics, and I want the image to jump whenever the user presses space button or else the image keeps falling down. The problem I'm getting is that if I keep the space button pressed, it will keep flying upwards rather than just a single jump at a time. How do I fix this? (Someone explain the basic physics required to apply for the jump in flappy bird)

```<code>import pygame
pygame.init()

screen = pygame.display.set_mode((500,500))
c = pygame.image.load('cookie.png')

run = True
x,y = 50,50

while run:
    screen.fill((255,255,255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE]:
        y -= 1
    else:
        y += 0.2

    screen.blit(c, (x,y))
    pygame.display.update()

pygame.quit()

</code>```

答:
Try using the KEYDOWN event instead of get_pressed(). get_pressed() returns an array containing the state of every key on the keyboard, and you're calling it every time your loop runs - so if you hold the key down, it's going to fire repeatedly.

```<code>for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run = False
    elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
        y -= 1
    else:
        y += 0.2
</code>```

Something along those lines should work for you.

Body:
I am trying to make a clone of flappy bird to learn pygame and I'm a beginner. Just doing the basics, and I want the image to jump whenever the user presses space button or else the image keeps falling down. The problem I'm getting is that if I keep the space button pressed, it will keep flying upwards rather than just a single jump at a time. How do I fix this? (Someone explain the basic physics required to apply for the jump in flappy bird)

import pygame
pygame.init()

screen = pygame.display.set_mode((500,500))
c = pygame.image.load('cookie.png')

run = True
x,y = 50,50

while run:
    screen.fill((255,255,255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE]:
        y -= 1
    else:
        y += 0.2

    screen.blit(c, (x,y))
    pygame.display.update()

pygame.quit()

Body:
Try using the KEYDOWN event instead of get_pressed(). get_pressed() returns an array containing the state of every key on the keyboard, and you're calling it every time your loop runs - so if you hold the key down, it's going to fire repeatedly.

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run = False
    elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
        y -= 1
    else:
        y += 0.2

Something along those lines should work for you.


问:
Python Datastructure Suggestion
i am building a small search engine to search a collection of pdfs. From each pdf i extract a set of tokens and store it in database. I do not want to store duplicate tokens in database, instead i want to store count of each token in the database. Does python has any special datastructure that do not store duplicates but stores the counts of each token?</p>

答: Python >=2.7 has the Counter.

Title: Python Datastructure Suggestion

Body: Python >=2.7 has the Counter.


问:
"assimp/config.h" not found, It's in the folder though
I'm using Visual Studio 2019 to make a simple scene with OpenGL. The libraries and includes seem to be correctly configured since I can access the header files and the assimp folderstructure.
When I try to include any assimp headers though I get this error, the weird thing is that the file is in the folder. It is called "config.h.in" when removing the ".in" from the file I get the error code "E0011" in line 1016 of the "config.h" file. Which reads as follows

```<code>// ---------- All the Build/Compile-time defines ------------

/** @brief Specifies if double precision is supported inside assimp
 *
 * Property type: Bool. Default value: undefined.
 */

#cmakedefine ASSIMP_DOUBLE_PRECISION 1

#endif // !! AI_CONFIG_H_INC

</code>```

Those are lines 1009 to 1018, while the file is open in VS19 I get no error only when switching to another file. I get the error again.

EDIT. I did use CMake and VS to build the Library and .dll files

答:
The config.h.in file is the input-file for the configuation-generation-process which is performed during the cmake-build-generation we are using in the Asset-Impoprter-Lib. The cmake-run will read the config.h.in file, replace the defines coming from cmake in the config.h .in and write the generated config.h file in you include folder. So if you want to generate a valid config.h file you have to run the assimp-cmake run before running your own build.

I guess you are just using a solution-file for your opengl-example. So you can install cmake, run it in the root-folder of your assimp-installation and you will be able to find a valid config.h file.

The config.h file contains the defines for your assimp-configuration like which kind of precision will be used and so on.

Body:
I'm using Visual Studio 2019 to make a simple scene with OpenGL. The libraries and includes seem to be correctly configured since I can access the header files and the assimp folderstructure.
When I try to include any assimp headers though I get this error, the weird thing is that the file is in the folder. It is called "config.h.in" when removing the ".in" from the file I get the error code "E0011" in line 1016 of the "config.h" file. Which reads as follows

// ---------- All the Build/Compile-time defines ------------

/** @brief Specifies if double precision is supported inside assimp
 *
 * Property type: Bool. Default value: undefined.
 */

#cmakedefine ASSIMP_DOUBLE_PRECISION 1

#endif // !! AI_CONFIG_H_INC

Those are lines 1009 to 1018, while the file is open in VS19 I get no error only when switching to another file. I get the error again.

EDIT. I did use CMake and VS to build the Library and .dll files


问:
Arduino : I am trying to convert the string coming via Bluetooth into an char array
Hello Everyone : I am trying to convert the string coming via Bluetooth into an char array
what i want to is that get the string (which will be a word) from the Bluetooth and the convert it into a char array:
for example:

Arduino Receives from Bluetooth : water

I want this to be converted into : char arrayThing[30] = {'w','a','t','e','r',0};

Following is the code what I am trying to do please help me out in this guys

char arrayThing[30];
        arrayThing[30]= Serial.read();

```<code> for (int index = 0; index < 30; index++)
 {
    Serial.write(arrayThing[index]);
 }
   //  char arrayThing[30] = {'w','a','t','e','r',0};
    ouijaPrint(arrayThing);
    homeing();//Go back to home after each massage is printed
</code>```

答:
Serial.read() returns max. 1 character, which you put into the desired position of your char array. Serial transmission is slow, so you better do not wait, but transmit an end-of-message character, e.g. < newline > aka. '\n'

```<code>char arrayThing[30];
byte pos = 0;
void loop() {
  if (Serial1.available() {
      arrayThing[pos] = Serial1.read();
      if (arrayThing[pos] == '\n') {
         arrayThing[pos] = 0;  // text end
         pos = 0; // prepare to receive the next text line
         Serial.println(arrayThing); // work with the result
      } else {
          if (pos < 29) pos++; // prepare for next character
      }
   }
}
</code>```

Serial1 is your Bluetooth, Serial your debug output (for this test)

Body:
Hello Everyone : I am trying to convert the string coming via Bluetooth into an char array
what i want to is that get the string (which will be a word) from the Bluetooth and the convert it into a char array:
for example:

Arduino Receives from Bluetooth : water

I want this to be converted into : char arrayThing[30] = {'w','a','t','e','r',0};

Following is the code what I am trying to do please help me out in this guys

char arrayThing[30];
        arrayThing[30]= Serial.read();

 for (int index = 0; index < 30; index++)
 {
    Serial.write(arrayThing[index]);
 }
   //  char arrayThing[30] = {'w','a','t','e','r',0};
    ouijaPrint(arrayThing);
    homeing();//Go back to home after each massage is printed

Body:
Serial.read() returns max. 1 character, which you put into the desired position of your char array. Serial transmission is slow, so you better do not wait, but transmit an end-of-message character, e.g. < newline > aka. '\n'

char arrayThing[30];
byte pos = 0;
void loop() {
  if (Serial1.available() {
      arrayThing[pos] = Serial1.read();
      if (arrayThing[pos] == '\n') {
         arrayThing[pos] = 0;  // text end
         pos = 0; // prepare to receive the next text line
         Serial.println(arrayThing); // work with the result
      } else {
          if (pos < 29) pos++; // prepare for next character
      }
   }
}

Serial1 is your Bluetooth, Serial your debug output (for this test)


问:
flask-wtf form not sending form data?
For context, I'm trying to create a flask-wtf form. I've done that and it's presented correctly:

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Sign In')

@APP.route('/')
def index():
    return render_template('login.html', form=LoginForm())

@APP.route('/login', methods=['POST', 'GET'])
def login():
    print(request.method, request.get_json())
    return redirect('/')  # temporary
```

<p>Here's the html:</p>

<pre class="lang-html prettyprint-override"><code>{% block content %}
    <h1>Sign In</h1>
    <form action="/login" method="post" enctype='application/json'>
        {{ form.hidden_tag() }}
        <p>
            {{ form.username.label }}<br>
            {{ form.username(size=32) }}
        </p>
        <p>
            {{ form.password.label }}<br>
            {{ form.password(size=32) }}
        </p>
        <p>{{ form.submit() }}</p>
    </form>
{% endblock %}
</code>```

However, when I enter anything and click submit, what gets printed from login() is POST None. I don't understand why there's no data being sent. As an attempt to force it to be json, I added enctype='application/json' and nothing before or after.

What am I missing?

答:
You can't POST a form as JSON, there are only 3 options for enctype.

In your login() function you can access the form through request.form, or when using wtforms, initialise the form in your view for hte data to be populated:

```<code>def login():
    login_form = LoginForm()

    if login_form.validate_on_submit(): # this runs only on POST, and checks validation
        username = form.username.data
        password = form.password.data
    ...
</code>```

Title: flask-wtf form not sending form data?

Body:
For context, I'm trying to create a flask-wtf form. I've done that and it's presented correctly:

class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Sign In')

@APP.route('/')
def index():
    return render_template('login.html', form=LoginForm())

@APP.route('/login', methods=['POST', 'GET'])
def login():
    print(request.method, request.get_json())
    return redirect('/')  # temporary

Here's the html:

{% block content %}

Sign In

    <form action="/login" method="post" enctype='application/json'>
        {{ form.hidden_tag() }}

            {{ form.username.label }}

            {{ form.username(size=32) }}

            {{ form.password.label }}

            {{ form.password(size=32) }}

{{ form.submit() }}

    </form>
{% endblock %}

However, when I enter anything and click submit, what gets printed from login() is POST None. I don't understand why there's no data being sent. As an attempt to force it to be json, I added enctype='application/json' and nothing before or after.

What am I missing?

Body:
You can't POST a form as JSON, there are only 3 options for enctype.

In your login() function you can access the form through request.form, or when using wtforms, initialise the form in your view for hte data to be populated:

def login():
    login_form = LoginForm()

    if login_form.validate_on_submit(): # this runs only on POST, and checks validation
        username = form.username.data
        password = form.password.data
    ...


问:
How to avoid + signs getting replaced with spaces in GET parameters (Django)?
I've found myself in need of passing email addresses in GET parameters, but I noticed + signs get replaced by spaces, so that an URL like example.com?param=myemail+alias@example.com will, when captured through something like request.GET.get("param", None), yield myemail alias@example.com.

For now I opted for the arguably crude and risky way of replace()ing spaces with + signs but I'd like to know: is there a better way to pass email addresses in GET parameters (that will work with Django 3+)?

答:
You need to url encode them. </p>

```<code>import urllib.parse
urllib.parse.quote_plus({'email': 'myemail+alias@example.com'})
</code>```

Body:
You need to url encode them.

import urllib.parse
urllib.parse.quote_plus({'email': 'myemail+alias@example.com'})


问:
Uninstalling python3 on MacOs
I have uninstalled python3 using brew on macOS Catalina 10.15.3:

```<code>brew uninstall python3

brew list | grep python
python@2
</code>```

But it still there:

```<code>which python3
/usr/bin/python3

python3 -V
Python 3.7.3

/usr/bin/python3 -V
Python 3.7.3

ls -ltah /usr/bin/ | grep python

-rwxr-xr-x     1 root   wheel    31K Jan 23 16:58 python3
lrwxr-xr-x     1 root   wheel    75B Dec 16 06:20 python2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x     1 root   wheel    82B Dec 16 06:20 python-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
lrwxr-xr-x     1 root   wheel    76B Dec 16 06:20 pythonw2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/pythonw2.7
lrwxr-xr-x     1 root   wheel    82B Dec 16 06:20 python2.7-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
lrwxr-xr-x     1 root   wheel    76B Dec 16 06:20 pythonw -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/pythonw2.7
lrwxr-xr-x     1 root   wheel    75B Dec 16 06:20 python2 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x     1 root   wheel    75B Dec 16 06:20 python -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
</code>```

It's interesting but on error it shows different location of python:

```<code>python3 -bla

Unknown option: -l
usage: /Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Try `python -h' for more information.
</code>```

Seems it's related to Xcode.

How to delete this version python3 and reinstall python using brew?

Update:

```<code>sudo rm -f /usr/bin/python3
rm: /usr/bin/python3: Operation not permitted
</code>```

答:
Catalina comes with python3 installed by default**. You can't delete it, because /usr/bin is on the System's read-only volume.

If you install your new python to a bin folder that comes before /usr/bin in your $PATH, then it should take precedence.

** (Well OK, the first time you run it, you have to install Xcode command line tools to make it work. But that file itself is a system install.)

Title: Uninstalling python3 on MacOs

Body:
I have uninstalled python3 using brew on macOS Catalina 10.15.3:

brew uninstall python3

brew list | grep python
python@2

But it still there:

which python3
/usr/bin/python3

python3 -V
Python 3.7.3

/usr/bin/python3 -V
Python 3.7.3

ls -ltah /usr/bin/ | grep python

-rwxr-xr-x     1 root   wheel    31K Jan 23 16:58 python3
lrwxr-xr-x     1 root   wheel    75B Dec 16 06:20 python2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x     1 root   wheel    82B Dec 16 06:20 python-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
lrwxr-xr-x     1 root   wheel    76B Dec 16 06:20 pythonw2.7 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/pythonw2.7
lrwxr-xr-x     1 root   wheel    82B Dec 16 06:20 python2.7-config -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7-config
lrwxr-xr-x     1 root   wheel    76B Dec 16 06:20 pythonw -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/pythonw2.7
lrwxr-xr-x     1 root   wheel    75B Dec 16 06:20 python2 -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
lrwxr-xr-x     1 root   wheel    75B Dec 16 06:20 python -> ../../System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7

It's interesting but on error it shows different location of python:

python3 -bla

Unknown option: -l
usage: /Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Try `python -h' for more information.

Seems it's related to Xcode.

How to delete this version python3 and reinstall python using brew?

Update:

sudo rm -f /usr/bin/python3
rm: /usr/bin/python3: Operation not permitted