问:
Execute javascript when another function exists
I'm writing two scripts in an web environment where I don't have control over the order in which they are loaded.  Let's say the two scripts are called MyUtil and DoSomething.

MyUtil contains utilities that I will bind to the window object using window.myUtil = myUtil.  I'm then going to call methods of myUtil from within DoSomething.

If MyUtil is loaded first, everything will work. If it's loaded second, window.myUtil will be undefined.

How can I modify the code in DoSomething (and/or MyUtil) to wait until window.myUtil exists before DoSomething executes its code?

NB: I'm using jQuery 1.2.3.

答:
Wait Until myUtil is Available

You could set a timer using window.setInterval() to wait until window.myUtil has been set before attempting to use it.

Example

Example: http://jsfiddle.net/CtJ8A/1/

Simulating a situation where window.myUtil is added after the script that requires it has been loaded:

```<code>window.setTimeout((function(){
    window.myUtil = {
        utility: function(){ alert('utility has great utility!'); }
    };
}), 5000);
</code>```

Elsewhere in your page:

```<code>// Declaration of function that requires window.myUtil
var doSomething = function() {
     window.myUtil.utility();
}

/*
 * Timer that checks for myUtil every 100 milliseconds
 * When myUtil does exist, the timer is cleared, and doSomething() is called.
 *
 * Alternatively, one could put this timer inside doSomething().
 */
var timer = window.setInterval(function(){
        if (window.myUtil != undefined) {
            window.clearInterval(timer);
            doSomething();
        }
    }, 100);
</code>```

Body:
Wait Until myUtil is Available

You could set a timer using window.setInterval() to wait until window.myUtil has been set before attempting to use it.

Example

Example: http://jsfiddle.net/CtJ8A/1/

Simulating a situation where window.myUtil is added after the script that requires it has been loaded:

window.setTimeout((function(){
    window.myUtil = {
        utility: function(){ alert('utility has great utility!'); }
    };
}), 5000);

Elsewhere in your page:

// Declaration of function that requires window.myUtil
var doSomething = function() {
     window.myUtil.utility();
}

/*
 * Timer that checks for myUtil every 100 milliseconds
 * When myUtil does exist, the timer is cleared, and doSomething() is called.
 *
 * Alternatively, one could put this timer inside doSomething().
 */
var timer = window.setInterval(function(){
        if (window.myUtil != undefined) {
            window.clearInterval(timer);
            doSomething();
        }
    }, 100);


来源: stackexchange

问:
How do I store an output of a function into an array in Kotlin
So for an assignment, I have to maker a program that generates 200 random numbers and then gets stored into the array and then called upon later.  so I thought about storing the function in an array like this

```<code>    fun main() {
    var randomValues = arrayOf( List(200) { Random.nextInt(0, 100) })
    println(randomValues)
}
</code>```

and that didn't work I get this output
[Ljava.util.List;@533ddba. I'm not too accustomed to arrays so I'm not sure what to do. Sorry if this has been asked before.

答:
You have created an Array<List<Int>>. So it's an array containing a list of numbers. Remove the surrounding arrayOf() and change List to Array.

And to print the contents of a collection, use joinToString(), so println(randomValues.joinToString()).

ContentLicense: CC BY-SA 4.0

Body:
So for an assignment, I have to maker a program that generates 200 random numbers and then gets stored into the array and then called upon later.  so I thought about storing the function in an array like this

    fun main() {
    var randomValues = arrayOf( List(200) { Random.nextInt(0, 100) })
    println(randomValues)
}

and that didn't work I get this output
[Ljava.util.List;@533ddba. I'm not too accustomed to arrays so I'm not sure what to do. Sorry if this has been asked before.


问:
Hive select a column based on a second column where the second column values are different
Let's say we have a hive table with 4 different columns and I want to select from it for those values in the first column while make sure the values are different in the second column. Any help or guidance to how to do it?

```<code>  ---------------------
  | C1 | C2 | C3 | C4 |
  ---------------------
  | a     1    g.   h |
  | a     1    f.   l |
  | a     3    t.   p |
  | b     1    r.   o |
  | b     1    e.   q |
  | c     1    w.   w |
  | c     2    z.   p |
   -------------------
</code>```

In the above example, I want to hive select return a and c because their values at C2 are different.

答:
As I understand your question, you want c1s that have more than one distinct value in c2.

You can group by c1, and use a having clause with count(distinct) to implement the filtering:

```<code>select c1
from mytable
group by c1
having count(distinct c2) > 1;
</code>```

Body:
Let's say we have a hive table with 4 different columns and I want to select from it for those values in the first column while make sure the values are different in the second column. Any help or guidance to how to do it?

  ---------------------
  | C1 | C2 | C3 | C4 |
  ---------------------
  | a     1    g.   h |
  | a     1    f.   l |
  | a     3    t.   p |
  | b     1    r.   o |
  | b     1    e.   q |
  | c     1    w.   w |
  | c     2    z.   p |
   -------------------

In the above example, I want to hive select return a and c because their values at C2 are different.

Body:
As I understand your question, you want c1s that have more than one distinct value in c2.

You can group by c1, and use a having clause with count(distinct) to implement the filtering:

select c1
from mytable
group by c1
having count(distinct c2) > 1;


问:
How to continue subscribing to publisher after error?
I am trying to set up a publisher that will publish a set of integers and at some point may fail. It's slightly contrived but hopefully illustrates principle. Example below.

```<code>enum NumberError: Int, Error {
   case isFatal, canContinue
}

struct Numbers {
    let p = PassthroughSubject<Int, NumberError>()

    func start(max: Int) {

        let errorI = Int.random(in: 1...max)
        for i in (1...max) {
            if errorI == i {
                p.send(completion: .failure(NumberError.canContinue))
            } else {
                p.send(i)
            }
        }
        p.send(completion: .finished)

    }
}
</code>```

I then subscribe using:

```<code>let n = Numbers()
let c = n.p
    .catch {_ in return Just(-1)}

    .sink(receiveCompletion: {result in
        switch result {
        case .failure:
            print("Error")
        case .finished:
            print("Finished")
        }
    }, receiveValue: {
        print($0)
    })

n.start(max: 5)
</code>```

This works in that it replaces errors with -1 but I would then like to continue receiving values. Does anyone know if this is possible?
Having read and looked around it seems that flatMap may be the way to go but I can't work out what publisher to use in the closure? Any help much appreciated.

答:
I think you have an incorrect belief that a PassthroughSubject can publish more outputs after publishing a failure. It cannot. After you call p.send(completion: ...), any calls to p.send(...) will be ignored. Furthermore, if you subscribe to p after you call p.send(completion: ...), p will immediately complete the new subscription and not send any outputs.

So you can't send your error as .failure if you want to send more values after. Instead, change your publisher's Output type to Result<Int, NumberError> and its Failure type to Never:

```<code>import Combine

enum NumberError: Int, Error {
   case isFatal, canContinue
}

struct Numbers {
    let p = PassthroughSubject<Result<Int, NumberError>, Never>()

    func start(max: Int) {
        let bad = (max + 1) / 2
        for i in (1...max) {
            if bad == i {
                p.send(.failure(NumberError.canContinue))
            } else {
                p.send(.success(i))
            }
        }
        p.send(completion: .finished)
    }
}
</code>```

But now you can't use catch to handle the error, because it's not coming through as a failure. Instead, you can use map:

```<code>let n = Numbers()
let c = n.p
    .map({
        switch $0 {
        case .success(let i): return i
        case .failure(_): return -1
        }
    })
    .sink(receiveCompletion: {result in
        switch result {
        case .failure:
            print("Error")
        case .finished:
            print("Finished")
        }
    }, receiveValue: {
        print($0)
    })

n.start(max: 5)
</code>```

Output:

1
2
-1
4
5
Finished
```

Body:
I am trying to set up a publisher that will publish a set of integers and at some point may fail. It's slightly contrived but hopefully illustrates principle. Example below.

enum NumberError: Int, Error {
   case isFatal, canContinue
}

struct Numbers {
    let p = PassthroughSubject<Int, NumberError>()

    func start(max: Int) {

        let errorI = Int.random(in: 1...max)
        for i in (1...max) {
            if errorI == i {
                p.send(completion: .failure(NumberError.canContinue))
            } else {
                p.send(i)
            }
        }
        p.send(completion: .finished)

    }
}

I then subscribe using:

let n = Numbers()
let c = n.p
    .catch {_ in return Just(-1)}

    .sink(receiveCompletion: {result in
        switch result {
        case .failure:
            print("Error")
        case .finished:
            print("Finished")
        }
    }, receiveValue: {
        print($0)
    })

n.start(max: 5)

This works in that it replaces errors with -1 but I would then like to continue receiving values. Does anyone know if this is possible?
Having read and looked around it seems that flatMap may be the way to go but I can't work out what publisher to use in the closure? Any help much appreciated.

Body:
I think you have an incorrect belief that a PassthroughSubject can publish more outputs after publishing a failure. It cannot. After you call p.send(completion: ...), any calls to p.send(...) will be ignored. Furthermore, if you subscribe to p after you call p.send(completion: ...), p will immediately complete the new subscription and not send any outputs.

So you can't send your error as .failure if you want to send more values after. Instead, change your publisher's Output type to Result<Int, NumberError> and its Failure type to Never:

import Combine

enum NumberError: Int, Error {
   case isFatal, canContinue
}

struct Numbers {
    let p = PassthroughSubject<Result<Int, NumberError>, Never>()

    func start(max: Int) {
        let bad = (max + 1) / 2
        for i in (1...max) {
            if bad == i {
                p.send(.failure(NumberError.canContinue))
            } else {
                p.send(.success(i))
            }
        }
        p.send(completion: .finished)
    }
}

But now you can't use catch to handle the error, because it's not coming through as a failure. Instead, you can use map:

let n = Numbers()
let c = n.p
    .map({
        switch $0 {
        case .success(let i): return i
        case .failure(_): return -1
        }
    })
    .sink(receiveCompletion: {result in
        switch result {
        case .failure:
            print("Error")
        case .finished:
            print("Finished")
        }
    }, receiveValue: {
        print($0)
    })

n.start(max: 5)

Output:

1
2
-1
4
5
Finished


问:
What is \363\353\377\377\377\177?

(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"
```

It doesn't look like ascii nor multibyte,what's that?

答:
It's not text. It looks like the address you're examining contains another pointer to something on the stack. Try it as (char **)0x7fffffffe9c8, or some other double pointer type.

Edit: To elaborate, OP is examining non-text data in a debugger and asking the encoding. The correct answer is simply that it's not text. It's an integer 0x7fffffffebf3 and it's almost certainly a pointer to a string (since it's not aligned and points somewhere on the stack), meaning that the original pointer was probably of type char ** not char *.

Title: What is \363\353\377\377\377\177?

Body:
(gdb) p (char*)0x7fffffffe9c8
$16 = 0x7fffffffe9c8 "\363\353\377\377\377\177"

It doesn't look like ascii nor multibyte,what's that?

ContentLicense: CC BY-SA 3.0


问:
Angular login page
I’m new to Angular. I’ve been watching tutorials on YouTube and all of them teach routing with a sticky navigation bar. Is it possible to click on a link and navigate into a completely new page without the navigation bar?

This is the index.html displaying. The blue words are navigation and are routed.

I’m trying to route into the Login Page without the navigation bar showing. Is it possible to do that?

Here is the code for the index.html and the app.component.html just in case its necessary

答:
You can achieve this by removing <app-nav-menu></app-nav-menu> tag  from app.component.html and add it to individual components that require the nav menu

With that, the nav menu won't be included in routed components unless you add it to the component

Title: Angular login page


问:
Using Optional.map() instead of Optional.ifPresent() to execute code that may throw an exception and returning any exceptions as the return value
I'm trying to get a feel for the proper way to use the java.util.Optional class.  Given the following example code:

```<code>public void doSomething(File destDir, String classifier) throws IOException {
    URL resourceRoot = introspectionService.getResourceRoot(pattern);

    if (resourceRoot != null) {
        JarFile jarFile = (JarFile) resourceRoot.getContent(); //this can throw IOException
        ... snipped for brevity ...
    }
}
</code>```

I would like to convert this method to use an Optional<URL> value from the introspectionService.

```<code>public void doSomething(File destDir, String classifier) throws IOException {
    Optional<URL> resourceRoot = introspectionService.getResourceRoot(pattern);

    resourceRoot.ifPresent(rootUrl-> {
        JarFile jarFile = (JarFile) rootUrl.getContent(); //this can throw IOException
        ... snipped for brevity ...
    });
}
</code>```

This obviously fails to compile because the signature of ifPresent() takes a Consumer which does not allow exceptions to be thrown from the accept() method.

I came up with the following work-around and was wondering if there is a better way:

```<code>public void doSomething(File destDir, String classifier) throws IOException {
    Optional<URL> resourceRoot = introspectionService.getResourceRoot(pattern);

    Optional<IOException> ioException =
    resourceRoot.map(rootUrl-> {
        try {
            JarFile jarFile = (JarFile) rootUrl.getContent(); //this can throw IOException
        ... snipped for brevity ...
            return null;
        }
        catch(IOException e) {
            return e;
        }
    });
    if (ioException.isPresent()) {
        throw ioException.get();
    }
}
</code>```

Is there a better alternative?

答:
I think this is not the right place to use Optional while you have other classes that handle the same thing you looking for.

it's worth to look at the Files class and change your design accordingly

Body:
I'm trying to get a feel for the proper way to use the java.util.Optional class.  Given the following example code:

public void doSomething(File destDir, String classifier) throws IOException {
    URL resourceRoot = introspectionService.getResourceRoot(pattern);

    if (resourceRoot != null) {
        JarFile jarFile = (JarFile) resourceRoot.getContent(); //this can throw IOException
        ... snipped for brevity ...
    }
}

I would like to convert this method to use an Optional<URL> value from the introspectionService.

public void doSomething(File destDir, String classifier) throws IOException {
    Optional<URL> resourceRoot = introspectionService.getResourceRoot(pattern);

    resourceRoot.ifPresent(rootUrl-> {
        JarFile jarFile = (JarFile) rootUrl.getContent(); //this can throw IOException
        ... snipped for brevity ...
    });
}

This obviously fails to compile because the signature of ifPresent() takes a Consumer which does not allow exceptions to be thrown from the accept() method.

I came up with the following work-around and was wondering if there is a better way:

public void doSomething(File destDir, String classifier) throws IOException {
    Optional<URL> resourceRoot = introspectionService.getResourceRoot(pattern);

    Optional<IOException> ioException =
    resourceRoot.map(rootUrl-> {
        try {
            JarFile jarFile = (JarFile) rootUrl.getContent(); //this can throw IOException
        ... snipped for brevity ...
            return null;
        }
        catch(IOException e) {
            return e;
        }
    });
    if (ioException.isPresent()) {
        throw ioException.get();
    }
}

Is there a better alternative?


问:
convert a class component to hooks and pass methods to child component
I am trying to convert the class component below to a  function component with hooks and so far I been unsuccessful.

I cant see any error on the page nor terminal on the page but my goal is to see the form on the page but there is no form showing at the moment.

class component

```<code># PARENT

import React, { Component } from 'react';
import PersonalInfo from './PersonalInfo';
import AllInfo from './AllInfo';

class Main extends Component {
    state = {
        step: 1,

        firstName: '',
        lastName: '',

    }

    handleChange = input => e => {
        this.setState({[input]: e.target.value});
    }

    showSteps = () => {
        const {step, firstName, lastName } = this.state;

        if(step === 1)
            return (
                <PersonalInfo
                        handleChange = {this.handleChange}
                        nextStep = {this.nextStep}
                        firstName = {firstName}
                        lastName = {lastName}
                />);
        if(step === 3)
            return (
                <AllInfo
                        firstName = {firstName}
                lastName = {lastName}
    }

    render() {
        const {step} = this.state;
        return(
            <>
                <h2>Step {step} of 3.</h2>
                {this.showSteps()}
            </>
        );
    }
}

export default Main;

# CHILD

import React, { Component } from 'react';

class PersonalInfo extends Component {
    render() {
        const { handleChange, firstName, lastName } = this.props;

        return (
            <div>
                <h2>Enter your personal information</h2>
                <label>
                    <input
                        type="text"
                        name="firstName"
                        placeholder="First name"
                        value = {firstName}
                        onChange={handleChange('firstName')}
                    />
                </label>
                <label>
                    <input
                        type="text"
                        name="lastName"
                        placeholder="Last name"
                        value = {lastName}
                        onChange={handleChange('lastName')}
                    />
                </label>
            </div>
        );
    }
}

export default PersonalInfo;
</code>```

Functional component

```<code># PARENT

import React, { useState } from "react";
import PersonalInfo from './PersonalInfo';

type Props = {
  state: Object,
};

const MultiSteps = (props: Props) => {
  const [state, setState] = useState({
    step: 1,
    firstName: '',
  });

  const handleChange = (e) => {
    e.preventDefault();
    setState({...state, [input]: e.target.value});
  }

  const showSteps = () => {
    if (state && state.step === 1)
      return (
        <PersonalInfo
          handleChange = {handleChange}
          firstName = {state.firstName}
        />);

    if (state && state.step === 2)
      return (
        <AllInfo
          firstName = {state.firstName}
        />);
  }

  return(
        <>
        <h2>Step {state.step} of 3.</h2>
        Hello - {showSteps()}
        </>
  );
}

export default MultiSteps;

# CHILD

import React from "react";

const PersonalInfo = (props) => {

  return (
    <div>
      <h2>Enter personal information</h2>
      <label>
        <input
          type="text"
          name="firstName"
          placeholder="First name"
          value={props.firstName}
          onChange={handleChange('firstName')}
        />
      </label>
    </div>
  );
}

export default PersonalInfo;

</code>```

Currently there is no error on the page nor the terminal but i am not able to see any form on the page.

New Error below

```<code>ReferenceError: handleChange is not defined

  12 |     placeholder: "First name" // value={firstName}
  13 |     ,
  14 |     value: "Lorenzo",
> 15 |     onChange: handleChange('firstName')
  16 |   })));
  17 | };
  18 |
</code>```

Any help would be very helpful!

答:
The problem here is that you are creating a new const value named state inside your function.

```<code>const { state } = props;
</code>```

If you just remove this line from your function, the "state" word would now make reference to your state const defined via useState(), instead of your newly created const, that is referencing props.state (that is undefined and causes the invalid acesses and makes the form doesn't show up)

The step value should however be accessed directly from the state variable defined in your component (not props.state)

Old answer, kept if anyone find this with the same message

Change from

```<code>if (state.step === 1)
</code>```

to

```<code>if(state && state.step == 1)
</code>```

should make the error message stop.

The error happens because state is undefined and you are trying to acces a field of it. On the class example it dont happen because you are using an object destructor to acces the step value, so it has no unsafe accesses.

Body:
I am trying to convert the class component below to a  function component with hooks and so far I been unsuccessful.

I cant see any error on the page nor terminal on the page but my goal is to see the form on the page but there is no form showing at the moment.

class component

# PARENT

import React, { Component } from 'react';
import PersonalInfo from './PersonalInfo';
import AllInfo from './AllInfo';

class Main extends Component {
    state = {
        step: 1,

        firstName: '',
        lastName: '',

    }

    handleChange = input => e => {
        this.setState({[input]: e.target.value});
    }

    showSteps = () => {
        const {step, firstName, lastName } = this.state;

        if(step === 1)
            return (
                <PersonalInfo
                        handleChange = {this.handleChange}
                        nextStep = {this.nextStep}
                        firstName = {firstName}
                        lastName = {lastName}
                />);
        if(step === 3)
            return (
                <AllInfo
                        firstName = {firstName}
                lastName = {lastName}
    }

    render() {
        const {step} = this.state;
        return(
            <>

Step {step} of 3.

                {this.showSteps()}
            </>
        );
    }
}

export default Main;

# CHILD

import React, { Component } from 'react';

class PersonalInfo extends Component {
    render() {
        const { handleChange, firstName, lastName } = this.props;

        return (

Enter your personal information

                    <input
                        type="text"
                        name="firstName"
                        placeholder="First name"
                        value = {firstName}
                        onChange={handleChange('firstName')}
                    />

                    <input
                        type="text"
                        name="lastName"
                        placeholder="Last name"
                        value = {lastName}
                        onChange={handleChange('lastName')}
                    />

        );
    }
}

export default PersonalInfo;

Functional component

# PARENT

import React, { useState } from "react";
import PersonalInfo from './PersonalInfo';

type Props = {
  state: Object,
};

const MultiSteps = (props: Props) => {
  const [state, setState] = useState({
    step: 1,
    firstName: '',
  });

  const handleChange = (e) => {
    e.preventDefault();
    setState({...state, [input]: e.target.value});
  }

  const showSteps = () => {
    if (state && state.step === 1)
      return (
        <PersonalInfo
          handleChange = {handleChange}
          firstName = {state.firstName}
        />);

    if (state && state.step === 2)
      return (
        <AllInfo
          firstName = {state.firstName}
        />);
  }

  return(
        <>

Step {state.step} of 3.

        Hello - {showSteps()}
        </>
  );
}

export default MultiSteps;

# CHILD

import React from "react";

const PersonalInfo = (props) => {

  return (

Enter personal information

        <input
          type="text"
          name="firstName"
          placeholder="First name"
          value={props.firstName}
          onChange={handleChange('firstName')}
        />

  );
}

export default PersonalInfo;

Currently there is no error on the page nor the terminal but i am not able to see any form on the page.

New Error below

ReferenceError: handleChange is not defined

  12 |     placeholder: "First name" // value={firstName}
  13 |     ,
  14 |     value: "Lorenzo",
> 15 |     onChange: handleChange('firstName')
  16 |   })));
  17 | };
  18 |

Any help would be very helpful!

Body:
The problem here is that you are creating a new const value named state inside your function.

const { state } = props;

If you just remove this line from your function, the "state" word would now make reference to your state const defined via useState(), instead of your newly created const, that is referencing props.state (that is undefined and causes the invalid acesses and makes the form doesn't show up)

The step value should however be accessed directly from the state variable defined in your component (not props.state)

Old answer, kept if anyone find this with the same message

Change from

if (state.step === 1)

to

if(state && state.step == 1)

should make the error message stop.

The error happens because state is undefined and you are trying to acces a field of it. On the class example it dont happen because you are using an object destructor to acces the step value, so it has no unsafe accesses.


问:
calculating in python
What I have done so far:

```<code>import datetime
   distance_tobecovered = float(input("Please enter a number for the startime = input("Please input the time for the alarm in format HH:")
    fixed_charge = 3.5
    perkilo_charge = 2.1 * distance_tobecovered
    valueforall = fixed_charge + perkilo_charge
    v = valueforall + (2 * distance_tobecovered * 0.99
</code>```

)

答:
If you enter the time as: 10:24, this: datetime.datetime.strptime(startime,"%H:%M") will work.   If you enter the time as 10, your example will work.

All depends on how you define your time input.

Also, your comparison seems off.

```<code>import datetime
distance_tobecovered = float(input("Please enter a number for the distance: "))
startime = input("Please input the time for the alarm in format HH:MM :")
fixed_charge = 3.5
perkilo_charge = 2.1 * distance_tobecovered
valueforall = fixed_charge + perkilo_charge
v = valueforall + (2 * distance_tobecovered * 0.99)

input_time = datetime.datetime.strptime(startime, "%H:%M")

if ((input_time.hour>=23) or (input_time.hour < 6)):
    print("night or early morning")
    print(v)#does some calculation
else:
    print("day")
    print("#does some calculation ")
</code>```

Title: calculating in python

Body:
What I have done so far:

import datetime
   distance_tobecovered = float(input("Please enter a number for the startime = input("Please input the time for the alarm in format HH:")
    fixed_charge = 3.5
    perkilo_charge = 2.1 * distance_tobecovered
    valueforall = fixed_charge + perkilo_charge
    v = valueforall + (2 * distance_tobecovered * 0.99

)

Body:
If you enter the time as: 10:24, this: datetime.datetime.strptime(startime,"%H:%M") will work.   If you enter the time as 10, your example will work.

All depends on how you define your time input.

Also, your comparison seems off.

import datetime
distance_tobecovered = float(input("Please enter a number for the distance: "))
startime = input("Please input the time for the alarm in format HH:MM :")
fixed_charge = 3.5
perkilo_charge = 2.1 * distance_tobecovered
valueforall = fixed_charge + perkilo_charge
v = valueforall + (2 * distance_tobecovered * 0.99)

input_time = datetime.datetime.strptime(startime, "%H:%M")

if ((input_time.hour>=23) or (input_time.hour < 6)):
    print("night or early morning")
    print(v)#does some calculation
else:
    print("day")
    print("#does some calculation ")


问:
How do I implement the Luhn algorithm?
I am trying to create a program to validate 10 to 12 digit long number sequences based on the luhn algorithm, but my program keeps on telling me that every number is invalid even though they're not.

This number should be valid, but my code doesn't think so: 8112189876

This number should not be valid, which my program agrees with, as it thinks every number is invalid: 8112189875

Here is my code:

```<code>static void luhn(){
    System.out.print("Enter number to validate:\n");
    String pnr = input.nextLine();
    int length = pnr.length();
    int sum = 0;
    for (int i = 1, pos = length - 1; i < 10; i++, pos--){
        char tmp = pnr.charAt(pos);
        int num = tmp - 0
        int product;
        if (i % 2 != 0){
            product = num * 1;
        }
        else{
            product = num * 2;
        }
        if (product > 9)
            product -= 9;
        sum+= product;
        boolean valid = (sum % 10 == 0);
        if (valid){
            System.out.print("Valid!\r");
        }
        else{
            System.out.print("Invalid!");
        }
    }
}
</code>```

答:
```<code>package randomNumGen;

public class JavaLuhnAlgorithm {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        validateCreditCardNumber("8112189876");
        String imei = "012850003580200";
        validateCreditCardNumber(imei);
    }

    private static void validateCreditCardNumber(String str) {

        int[] ints = new int[str.length()];
        for (int i = 0; i < str.length(); i++) {
            ints[i] = Integer.parseInt(str.substring(i, i + 1));
        }
        for (int i = ints.length - 2; i >= 0; i = i - 2) {
            int j = ints[i];
            j = j * 2;
            if (j > 9) {
                j = j % 10 + 1;
            }
            ints[i] = j;
        }
        int sum = 0;
        for (int i = 0; i < ints.length; i++) {
            sum += ints[i];
        }
        if (sum % 10 == 0) {
            System.out.println(str + " is a valid credit card number");
        } else {
            System.out.println(str + " is an invalid credit card number");
        }
    }

}
</code>```

Title: How do I implement the Luhn algorithm?

Body:
I am trying to create a program to validate 10 to 12 digit long number sequences based on the luhn algorithm, but my program keeps on telling me that every number is invalid even though they're not.

This number should be valid, but my code doesn't think so: 8112189876

This number should not be valid, which my program agrees with, as it thinks every number is invalid: 8112189875

Here is my code:

static void luhn(){
    System.out.print("Enter number to validate:\n");
    String pnr = input.nextLine();
    int length = pnr.length();
    int sum = 0;
    for (int i = 1, pos = length - 1; i < 10; i++, pos--){
        char tmp = pnr.charAt(pos);
        int num = tmp - 0
        int product;
        if (i % 2 != 0){
            product = num * 1;
        }
        else{
            product = num * 2;
        }
        if (product > 9)
            product -= 9;
        sum+= product;
        boolean valid = (sum % 10 == 0);
        if (valid){
            System.out.print("Valid!\r");
        }
        else{
            System.out.print("Invalid!");
        }
    }
}


问:
Python 3.X NameError
I am using Python 3 and this code was written in PyCharm. I changed probability to p to prevent conflicts of it not being declared link to tutorial article here the site I got it from</p>

```<code>import numpy as np

def coinFlip(p):
    #perform the binomial distribution (returns 1 or 0)
    result = np.random.binomial (1 , p)
    #return flip to be added to numpy array
    return result

'''Main Area'''
#probability of heads vs. tails. this can be changed
p = .5
#num of flips required. this can be changed
n = 10

#initiate array
FullResults = np.arrange(n)

#perform the desired number of flips required probability set above
for i in range(0, n):
    fullResults[i] = coinFlip(p)
    i+=1

#print results
print("probability is set to ", p)
print("Tails = 0, Heads = 1: ", fullResults)
#Total up heads and tails for easy user experience
print("head count: ", np.count_nonzero(fullResults == 1))
print("Tail count: ", np.count_nonzero(fullResults == 0))
</code>```

答:
```<code>import numpy as np
def coinFlip(p):
    #perform the binomial distribution (returns 1 or 0)
    result = np.random.binomial (1 , p)
    #return flip to be added to numpy array
    return result
'''Main Area'''
#probability of heads vs. tails. this can be changed
p = .5
#num of flips required. this can be changed
n = 10

#initiate array
#################FullResults = np.arrange(n)
FullResults = np.arange(n)
#perform the desired number of flips required probability set above
fullResults = np.zeros(n)
for i in range(0, n):
    fullResults[i] = coinFlip(p)
    i+=1
#print results
print("probability is set to ", p)
print("Tails = 0, Heads = 1: ", fullResults)
#Total up heads and tails for easy user experience
print("head count: ", np.count_nonzero(fullResults == 1))
print("Tail count: ", np.count_nonzero(fullResults == 0))
</code>```

I had to make two minor modifications -

np.arange(n) instead of np.arrange(n)

I initialized the array fullResults with zeros

Here is the output -

```<code>  probability is set to  0.5
    Tails = 0, Heads = 1:  [0. 0. 0. 1. 1. 1. 0. 0. 0. 1.]
    head count:  4
    Tail count:  6
</code>```

Title: Python 3.X NameError

Body:
I am using Python 3 and this code was written in PyCharm. I changed probability to p to prevent conflicts of it not being declared link to tutorial article here the site I got it from

import numpy as np

def coinFlip(p):
    #perform the binomial distribution (returns 1 or 0)
    result = np.random.binomial (1 , p)
    #return flip to be added to numpy array
    return result

'''Main Area'''
#probability of heads vs. tails. this can be changed
p = .5
#num of flips required. this can be changed
n = 10

#initiate array
FullResults = np.arrange(n)

#perform the desired number of flips required probability set above
for i in range(0, n):
    fullResults[i] = coinFlip(p)
    i+=1

#print results
print("probability is set to ", p)
print("Tails = 0, Heads = 1: ", fullResults)
#Total up heads and tails for easy user experience
print("head count: ", np.count_nonzero(fullResults == 1))
print("Tail count: ", np.count_nonzero(fullResults == 0))

Body:
import numpy as np
def coinFlip(p):
    #perform the binomial distribution (returns 1 or 0)
    result = np.random.binomial (1 , p)
    #return flip to be added to numpy array
    return result
'''Main Area'''
#probability of heads vs. tails. this can be changed
p = .5
#num of flips required. this can be changed
n = 10

#initiate array
#################FullResults = np.arrange(n)
FullResults = np.arange(n)
#perform the desired number of flips required probability set above
fullResults = np.zeros(n)
for i in range(0, n):
    fullResults[i] = coinFlip(p)
    i+=1
#print results
print("probability is set to ", p)
print("Tails = 0, Heads = 1: ", fullResults)
#Total up heads and tails for easy user experience
print("head count: ", np.count_nonzero(fullResults == 1))
print("Tail count: ", np.count_nonzero(fullResults == 0))

I had to make two minor modifications -

np.arange(n) instead of np.arrange(n)

I initialized the array fullResults with zeros

Here is the output -

  probability is set to  0.5
    Tails = 0, Heads = 1:  [0. 0. 0. 1. 1. 1. 0. 0. 0. 1.]
    head count:  4
    Tail count:  6


问:
Threadsafety question for Python collections in Scrapy Item Pipelines (using Twisted for concurrency)
Scrapy has a notion of Item Pipelines that concurrently process (via Twisted) items returned from a Scrapy Spider. The following code example is provided for filtering duplicate items (code copied below). How is it that the set can be used safely by concurrent calls to process_item? It seems that Scrapy invokes item pipelines here.

```<code>from scrapy.exceptions import DropItem

class DuplicatesPipeline:

    def __init__(self):
        self.ids_seen = set()

    def process_item(self, item, spider):
        if item['id'] in self.ids_seen:
            raise DropItem("Duplicate item found: %s" % item)
        else:
            self.ids_seen.add(item['id'])
            return item
</code>```

答: Twisted and Scrapy are largely single-threaded.  Instead of preemptive multi-threading they provide concurrency by way of cooperative multi-tasking.  In a cooperative multi-tasking system, there is no preemption.  This means that a function like process_item above is perfectly safe to assume self.ids_seen will not change between its first and second to last lines.  Only this process_item method is running.  No other work can happen until process_item cooperatively gives up control.  It does this by raising an exception or return a value.  When this happens, control returns to its caller (or whatever the nearest except handler is).  That code then gets to run until it decides to give up control, and so on.  Eventually control is returned all the way to the Twisted reactor which picks another event to service by calling some application method.  Then the process repeats.

Body:
Scrapy has a notion of Item Pipelines that concurrently process (via Twisted) items returned from a Scrapy Spider. The following code example is provided for filtering duplicate items (code copied below). How is it that the set can be used safely by concurrent calls to process_item? It seems that Scrapy invokes item pipelines here.

from scrapy.exceptions import DropItem

class DuplicatesPipeline:

    def __init__(self):
        self.ids_seen = set()

    def process_item(self, item, spider):
        if item['id'] in self.ids_seen:
            raise DropItem("Duplicate item found: %s" % item)
        else:
            self.ids_seen.add(item['id'])
            return item


问:
call mmap from assembly on Macos Catalina to reserve memory
I have an assembly file with no linked libraries on MacOs Catalina that wants to call mmap to reserve some memory dynamically. I had thought I need to do something like

```<code>#define __NR_mmap 0x20000c5

#define PROT_READ 0x01
#define PROT_WRITE 0x02
#define PROT_EXEC 0x04
#define PROT_ALL (PROT_READ | PROT_WRITE | PROT_EXEC)

#define MAP_ANON 0x1000
#define MAP_SHARED      0x0001
#define MAP_PRIVATE     0x0002

#define USER_DEFS_SIZE 0x20000

        mov $__NR_mmap, %rax            //mmap
        xor %rdi,%rdi                   // start address
        and $USER_DEFS_SIZE,%rsi        // length
        mov $PROT_READ, %rdx            // rwx
        mov $(MAP_ANON|MAP_SHARED),%rcx // flags
        xor %r8,%r8                     // file descriptor
        xor %r9,%r9                     // offset
        syscall
</code>```

but that returns 0x13 (ENODEV) in %rax. I tried passing file descriptor $-1 but that gives me an expected "bad file descriptor" error.
]

Question1: What am I doing wrong - how do I call mmap correctly to reserve memory?

Question2: how is the return address and errno returned? Can't rally both be in %rax, or can they? I'm unsure of the calling convention.

Thanks for helping me out.

答:
First, there's the problem with %rsi being uninitialized, as Jester pointed out.

After that, you've got the system call ABI wrong. The fourth argument (the flags) should be passed in %r10, not %rcx.

An error is indicated by the CF flag of the flags register. If that is set, then %rax contains the errno; otherwise, the return value.

Finally, I should point out that Apple specifically states that the syscall ABI may be unstable from release to release of the OS. The stable ABI is the library wrapper layer (i.e. you should call _mmap from libSystem.dylib). They reserve the right to break at any time anything that does syscalls directly.

Body:
I have an assembly file with no linked libraries on MacOs Catalina that wants to call mmap to reserve some memory dynamically. I had thought I need to do something like

#define __NR_mmap 0x20000c5

#define PROT_READ 0x01
#define PROT_WRITE 0x02
#define PROT_EXEC 0x04
#define PROT_ALL (PROT_READ | PROT_WRITE | PROT_EXEC)

#define MAP_ANON 0x1000
#define MAP_SHARED      0x0001
#define MAP_PRIVATE     0x0002

#define USER_DEFS_SIZE 0x20000

        mov $__NR_mmap, %rax            //mmap
        xor %rdi,%rdi                   // start address
        and $USER_DEFS_SIZE,%rsi        // length
        mov $PROT_READ, %rdx            // rwx
        mov $(MAP_ANON|MAP_SHARED),%rcx // flags
        xor %r8,%r8                     // file descriptor
        xor %r9,%r9                     // offset
        syscall

but that returns 0x13 (ENODEV) in %rax. I tried passing file descriptor $-1 but that gives me an expected "bad file descriptor" error.
]

Question1: What am I doing wrong - how do I call mmap correctly to reserve memory?

Question2: how is the return address and errno returned? Can't rally both be in %rax, or can they? I'm unsure of the calling convention.

Thanks for helping me out.


问:
Display cv::Mat as QVideoFrame in a QML VideoOutput
I have an OpenCV backend which retrieves the video frame from a camera device through cv::VideoCapture, does some processing and then passes the cv::Mat frame to a Qt5 application for display in a QML VideoOutput.

The problem is the frames drawn are empty/white.

The CameraService class is receiving a cv::Mat from a backend object which runs on its own thread using a Qt::QueuedConnection signal. Then I convert to it to a QImage, which I use to initialize a QVideoFrame and pass it to a QAbstractVideoSurface received from a QML VideoOutput, after setting a pixel format on it.

I have checked whether the cv::Mat has valid content before conversion to QVideoFrame, so this is not the case.

Or am I doing it completely wrong and should instead draw an image?

Relevant code:

```<code>CameraService.cpp

CameraService::CameraService(Video::Backend *backend)
  : QObject(),
  surface(nullptr),
  isFormatSet(false) {

  this->backend = backend;

  connect(
    backend, &Video::Backend::onFrameReady,
    this, &CameraService::onVideoFrameReady,
    Qt::QueuedConnection);
}

CameraService::~CameraService() {

  backend->deleteLater();
}

QAbstractVideoSurface *CameraService::getVideoSurface() const {

  return surface;
}

void CameraService::setVideoSurface(QAbstractVideoSurface *surface) {

  if (!this->surface && surface)
    backend->start();

  if (this->surface && this->surface != surface && this->surface->isActive())
    this->surface->stop();

  this->surface = surface;

  if (this->surface && format.isValid()) {

    format = this->surface->nearestFormat(format);
    this->surface->start(format);
  }
}

void CameraService::setFormat(
  int width,
  int height,
  QVideoFrame::PixelFormat frameFormat
){
    QSize size(width, height);
    QVideoSurfaceFormat format(size, frameFormat);

    this->format = format;

    if (surface) {

        if (surface->isActive())
            surface->stop();

        this->format = surface->nearestFormat(this->format);

        surface->start(this->format);
    }
}

void CameraService::onVideoFrameReady(cv::Mat currentFrame) {

  if (!surface || currentFrame.empty())
    return;

  cv::Mat continuousFrame;

  if (!currentFrame.isContinuous())
    continuousFrame = currentFrame.clone();
  else
    continuousFrame = currentFrame;

  if (!isFormatSet) {

    setFormat(
      continuousFrame.cols,
      continuousFrame.rows,
      QVideoFrame::PixelFormat::Format_BGR32);
    isFormatSet = true;
  }

  frame = QImage(
    (uchar *)continuousFrame.data,
    continuousFrame.cols,
    continuousFrame.rows,
    continuousFrame.step,
    QVideoFrame::imageFormatFromPixelFormat(
      QVideoFrame::PixelFormat::Format_BGR32));

  surface->present(QVideoFrame(frame));
}

</code>```

QML object:

```<code>    VideoOutput {
        objectName: "videoOutput";
        anchors.fill: parent;
        fillMode: VideoOutput.PreserveAspectCrop;
        source: CameraService;
    }
</code>```

The CameraService object is made available as a singleton to QML using this statement:

qmlRegisterSingletonInstance<Application::CameraService>("Application.CameraService", 1, 0, "CameraService", service);

答:
Analyzing the code I have noticed that the conversion is not supported (I recommend you check if the format is valid or). For this I have made some changes:...

#ifndef CAMERASERVICE_H
#define CAMERASERVICE_H

#include "backend.h"

#include <QObject>
#include <QPointer>
#include <QVideoFrame>
#include <QVideoSurfaceFormat>
#include <opencv2/core/mat.hpp>

class QAbstractVideoSurface;

class CameraService : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QAbstractVideoSurface* videoSurface READ videoSurface WRITE setVideoSurface NOTIFY surfaceChanged)
public:
    explicit CameraService(Backend *backend, QObject *parent = nullptr);
    QAbstractVideoSurface* videoSurface() const;

public Q_SLOTS:
    void setVideoSurface(QAbstractVideoSurface* surface);
Q_SIGNALS:
    void surfaceChanged(QAbstractVideoSurface* surface);
private Q_SLOTS:
    void onVideoFrameReady(cv::Mat currentFrame);
private:
    void setFormat(int width, int height, QVideoFrame::PixelFormat frameFormat);

    QPointer<QAbstractVideoSurface> m_surface;
    QScopedPointer<Backend> m_backend;
    QVideoSurfaceFormat m_format;
    bool m_isFormatSet;
    QImage m_image;
};

#endif // CAMERASERVICE_H
```

```#include "backend.h"
#include "cameraservice.h"

#include <QAbstractVideoSurface>
#include <iostream>

CameraService::CameraService(Backend *backend, QObject *parent)
    : QObject(parent), m_backend(backend), m_isFormatSet(false)
{
    connect(m_backend.data(), &Backend::frameReady, this, &CameraService::onVideoFrameReady);
}

QAbstractVideoSurface *CameraService::videoSurface() const
{
    return m_surface;
}

void CameraService::setVideoSurface(QAbstractVideoSurface *surface){
    if (m_surface == surface)
        return;
    if(m_surface && m_surface != surface && m_surface->isActive())
        m_surface->stop();
    m_surface = surface;
    Q_EMIT surfaceChanged(m_surface);
    m_backend->start();
    if (m_surface && m_format.isValid()) {
        m_format = m_surface->nearestFormat(m_format);
        m_surface->start(m_format);
    }
}

void CameraService::setFormat(
        int width,
        int height,
        QVideoFrame::PixelFormat frameFormat
        ){
    QSize size(width, height);
    QVideoSurfaceFormat format(size, frameFormat);
    m_format = format;
    if (m_surface) {
        if (m_surface->isActive())
            m_surface->stop();
        m_format = m_surface->nearestFormat(m_format);
        m_surface->start(m_format);
    }
}

void CameraService::onVideoFrameReady(cv::Mat currentFrame){
    if (!m_surface || currentFrame.empty())
        return;
    cv::Mat continuousFrame;
    if (!currentFrame.isContinuous())
        continuousFrame = currentFrame.clone();
    else
        continuousFrame = currentFrame;
    if (!m_isFormatSet) {
        setFormat(continuousFrame.cols,
                  continuousFrame.rows,
                  QVideoFrame::Format_RGB32);
        m_isFormatSet = true;
    }
    m_image = QImage(continuousFrame.data,
                     continuousFrame.cols,
                     continuousFrame.rows,
                     continuousFrame.step,
                     QImage::Format_RGB888);
    m_image = m_image.rgbSwapped();
    m_image.convertTo(QVideoFrame::imageFormatFromPixelFormat(QVideoFrame::Format_RGB32));
    m_surface->present(QVideoFrame(m_image));
}
```

You can find the complete example here.

Body:
I have an OpenCV backend which retrieves the video frame from a camera device through cv::VideoCapture, does some processing and then passes the cv::Mat frame to a Qt5 application for display in a QML VideoOutput.

The problem is the frames drawn are empty/white.

The CameraService class is receiving a cv::Mat from a backend object which runs on its own thread using a Qt::QueuedConnection signal. Then I convert to it to a QImage, which I use to initialize a QVideoFrame and pass it to a QAbstractVideoSurface received from a QML VideoOutput, after setting a pixel format on it.

I have checked whether the cv::Mat has valid content before conversion to QVideoFrame, so this is not the case.

Or am I doing it completely wrong and should instead draw an image?

Relevant code:

CameraService.cpp

CameraService::CameraService(Video::Backend *backend)
  : QObject(),
  surface(nullptr),
  isFormatSet(false) {

  this->backend = backend;

  connect(
    backend, &Video::Backend::onFrameReady,
    this, &CameraService::onVideoFrameReady,
    Qt::QueuedConnection);
}

CameraService::~CameraService() {

  backend->deleteLater();
}

QAbstractVideoSurface *CameraService::getVideoSurface() const {

  return surface;
}

void CameraService::setVideoSurface(QAbstractVideoSurface *surface) {

  if (!this->surface && surface)
    backend->start();

  if (this->surface && this->surface != surface && this->surface->isActive())
    this->surface->stop();

  this->surface = surface;

  if (this->surface && format.isValid()) {

    format = this->surface->nearestFormat(format);
    this->surface->start(format);
  }
}

void CameraService::setFormat(
  int width,
  int height,
  QVideoFrame::PixelFormat frameFormat
){
    QSize size(width, height);
    QVideoSurfaceFormat format(size, frameFormat);

    this->format = format;

    if (surface) {

        if (surface->isActive())
            surface->stop();

        this->format = surface->nearestFormat(this->format);

        surface->start(this->format);
    }
}

void CameraService::onVideoFrameReady(cv::Mat currentFrame) {

  if (!surface || currentFrame.empty())
    return;

  cv::Mat continuousFrame;

  if (!currentFrame.isContinuous())
    continuousFrame = currentFrame.clone();
  else
    continuousFrame = currentFrame;

  if (!isFormatSet) {

    setFormat(
      continuousFrame.cols,
      continuousFrame.rows,
      QVideoFrame::PixelFormat::Format_BGR32);
    isFormatSet = true;
  }

  frame = QImage(
    (uchar *)continuousFrame.data,
    continuousFrame.cols,
    continuousFrame.rows,
    continuousFrame.step,
    QVideoFrame::imageFormatFromPixelFormat(
      QVideoFrame::PixelFormat::Format_BGR32));

  surface->present(QVideoFrame(frame));
}

QML object:

    VideoOutput {
        objectName: "videoOutput";
        anchors.fill: parent;
        fillMode: VideoOutput.PreserveAspectCrop;
        source: CameraService;
    }

The CameraService object is made available as a singleton to QML using this statement:

qmlRegisterSingletonInstance<Application::CameraService>("Application.CameraService", 1, 0, "CameraService", service);

Body:
Analyzing the code I have noticed that the conversion is not supported (I recommend you check if the format is valid or). For this I have made some changes:...

#ifndef CAMERASERVICE_H
#define CAMERASERVICE_H

#include "backend.h"

#include <QObject>
#include <QPointer>
#include <QVideoFrame>
#include <QVideoSurfaceFormat>
#include <opencv2/core/mat.hpp>

class QAbstractVideoSurface;

class CameraService : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QAbstractVideoSurface* videoSurface READ videoSurface WRITE setVideoSurface NOTIFY surfaceChanged)
public:
    explicit CameraService(Backend *backend, QObject *parent = nullptr);
    QAbstractVideoSurface* videoSurface() const;

public Q_SLOTS:
    void setVideoSurface(QAbstractVideoSurface* surface);
Q_SIGNALS:
    void surfaceChanged(QAbstractVideoSurface* surface);
private Q_SLOTS:
    void onVideoFrameReady(cv::Mat currentFrame);
private:
    void setFormat(int width, int height, QVideoFrame::PixelFormat frameFormat);

    QPointer<QAbstractVideoSurface> m_surface;
    QScopedPointer<Backend> m_backend;
    QVideoSurfaceFormat m_format;
    bool m_isFormatSet;
    QImage m_image;
};

#endif // CAMERASERVICE_H

#include "backend.h"
#include "cameraservice.h"

#include <QAbstractVideoSurface>
#include <iostream>

CameraService::CameraService(Backend *backend, QObject *parent)
    : QObject(parent), m_backend(backend), m_isFormatSet(false)
{
    connect(m_backend.data(), &Backend::frameReady, this, &CameraService::onVideoFrameReady);
}

QAbstractVideoSurface *CameraService::videoSurface() const
{
    return m_surface;
}

void CameraService::setVideoSurface(QAbstractVideoSurface *surface){
    if (m_surface == surface)
        return;
    if(m_surface && m_surface != surface && m_surface->isActive())
        m_surface->stop();
    m_surface = surface;
    Q_EMIT surfaceChanged(m_surface);
    m_backend->start();
    if (m_surface && m_format.isValid()) {
        m_format = m_surface->nearestFormat(m_format);
        m_surface->start(m_format);
    }
}

void CameraService::setFormat(
        int width,
        int height,
        QVideoFrame::PixelFormat frameFormat
        ){
    QSize size(width, height);
    QVideoSurfaceFormat format(size, frameFormat);
    m_format = format;
    if (m_surface) {
        if (m_surface->isActive())
            m_surface->stop();
        m_format = m_surface->nearestFormat(m_format);
        m_surface->start(m_format);
    }
}

void CameraService::onVideoFrameReady(cv::Mat currentFrame){
    if (!m_surface || currentFrame.empty())
        return;
    cv::Mat continuousFrame;
    if (!currentFrame.isContinuous())
        continuousFrame = currentFrame.clone();
    else
        continuousFrame = currentFrame;
    if (!m_isFormatSet) {
        setFormat(continuousFrame.cols,
                  continuousFrame.rows,
                  QVideoFrame::Format_RGB32);
        m_isFormatSet = true;
    }
    m_image = QImage(continuousFrame.data,
                     continuousFrame.cols,
                     continuousFrame.rows,
                     continuousFrame.step,
                     QImage::Format_RGB888);
    m_image = m_image.rgbSwapped();
    m_image.convertTo(QVideoFrame::imageFormatFromPixelFormat(QVideoFrame::Format_RGB32));
    m_surface->present(QVideoFrame(m_image));
}

You can find the complete example here.


问:
How does a Redis List allow both indexing and left and right push/pop with constant time?
What kind of internal data structure does a redis list implement to allow this? A linked list would require O(n) indexing, and an array would require O(n) left/right push/pop.</p>

答:
According to the official documentation they are implemented as linked list.

Redis lists are implemented via Linked Lists. This means that even if you have millions of elements inside a list, the operation of adding a new element in the head or in the tail of the list is performed in constant time. The speed of adding a new element with the LPUSH command to the head of a list with ten elements is the same as adding an element to the head of list with 10 million elements.

What's the downside? Accessing an element by index is very fast in lists implemented with an Array (constant time indexed access) and not so fast in lists implemented by linked lists (where the operation requires an amount of work proportional to the index of the accessed element).

Because of that LPOP/RPOP or LPUSH/PUSH time complexity's are O(1) since they are dealing with heads/tails. Whereas LINDEXs time complexity is O(N).


问:
Python recursion to split string by sliding window
Recently, I face an interesting coding task that involves splitting a string multiple permutations with a given K-limit size.

For example:

```<code>s = "iamfoobar"
k = 4  # the max number of the items on a list after the split
</code>```

The s can split into the following combinations

```<code>[
    ["i", "a", "m", "foobar"],
    ["ia", "m", "f", "oobar"],
    ["iam", "f", "o", "obar"]
# etc
]
</code>```

I tried to figure out how to do that with a quick recursively function, but I cannot get it to work.

I have try this out, but didn't seem to work

```<code>def sliding(s, k):
    if len(s) < k:
        return []
    else:
        for i in range(0, k):
            return [s[i:i+1]] + sliding(s[i+1:len(s) - i], k)

print(sliding("iamfoobar", 4))

</code>```

And only got this

```<code>['i', 'a', 'm', 'f', 'o', 'o']
</code>```

答:
The main issue in your implementation is that your loop does not do what is supposed to do as it returns the first result instead of appending the results.

Here's an example of an implementation:

def sliding(s, k):
    # If there is not enough values of k is below 0
    # there is no combination possible
    if len(s) < k or k < 1:
        return []

    # If k is one, we return a list containing all the combinations,
    # which is a single list containing the string
    if k == 1:
        return [[s]]

    results = []
    # Iterate through all the possible values for the first value
    for i in range(1, len(s) - k + 2):
        first_value = s[:i]
        # Append the result of the sub call to the first values
        for sub_result in sliding(s[i:], k - 1):
            results.append([first_value] + sub_result)

    return results

print(sliding("iamfoobar", 4))
```

Body:
Recently, I face an interesting coding task that involves splitting a string multiple permutations with a given K-limit size.

For example:

s = "iamfoobar"
k = 4  # the max number of the items on a list after the split

The s can split into the following combinations

[
    ["i", "a", "m", "foobar"],
    ["ia", "m", "f", "oobar"],
    ["iam", "f", "o", "obar"]
# etc
]

I tried to figure out how to do that with a quick recursively function, but I cannot get it to work.

I have try this out, but didn't seem to work

def sliding(s, k):
    if len(s) < k:
        return []
    else:
        for i in range(0, k):
            return [s[i:i+1]] + sliding(s[i+1:len(s) - i], k)

print(sliding("iamfoobar", 4))

And only got this

['i', 'a', 'm', 'f', 'o', 'o']


答:
You could use dynamic loading to load the javascript, but if you also arent in control of where the script located then i suppose this could be an issue as well.

Anyhow in do something you would basiically pull down the script via ajax or use a document.write to insert a new script tag:

```<code>function doSomething(){
  if(!window.myUtil){
    // method of choice for loading script
    doSomething();
  }
  else {
    // normal logic for doSomething
  }
}
</code>```

Then in your util you would need to modify it so it checks for an existing window.myUtil before assigning it. How that would need to look depends on how my utl operates - whether its an object instance or jsut a a literal collection of static functions.

See this link for some methods to actually load the script source.

Title: Execute javascript when another function exists

Body:
I'm writing two scripts in an web environment where I don't have control over the order in which they are loaded.  Let's say the two scripts are called MyUtil and DoSomething.

MyUtil contains utilities that I will bind to the window object using window.myUtil = myUtil.  I'm then going to call methods of myUtil from within DoSomething.

If MyUtil is loaded first, everything will work. If it's loaded second, window.myUtil will be undefined.

How can I modify the code in DoSomething (and/or MyUtil) to wait until window.myUtil exists before DoSomething executes its code?

NB: I'm using jQuery 1.2.3.

Body:
You could use dynamic loading to load the javascript, but if you also arent in control of where the script located then i suppose this could be an issue as well.

Anyhow in do something you would basiically pull down the script via ajax or use a document.write to insert a new script tag:

function doSomething(){
  if(!window.myUtil){
    // method of choice for loading script
    doSomething();
  }
  else {
    // normal logic for doSomething
  }
}

Then in your util you would need to modify it so it checks for an existing window.myUtil before assigning it. How that would need to look depends on how my utl operates - whether its an object instance or jsut a a literal collection of static functions.

See this link for some methods to actually load the script source.


问:
dynamic serializer resolving in flask rest plus based on serialized value in another field
Is there any option for dynamic serialization based on certain field?

assume model like this:

```<code>class Action(base):
    id = Column(Integer, primary_key=True)
    action_type = Column(Enum(SubscriptionActionType, inherit_schema=True), nullable=False)
    parameters = Column(JSONB)
</code>```

based on obj value in action_type I would like to use appropriate serializer inside the fields.Nested

is there any option without writing custom field? and if I write custom field, then can I access there whole serialized object and not just the serialized field?

答:
using polymorphism should do the trick.

```<code>class Action(base):
    id = Column(Integer, primary_key=True)
    action_type = Column(Enum(SubscriptionActionType, inherit_schema=True), nullable=False)
    parameters = Column(JSONB)

    __mapper_args__ = {
        'polymorphic_on' : action_type
    }

class ActionOne(Action):

    __mapper_args__ = {
        'polymorphic_identity': 'action_one'
    }

class ActionTwo(Action):

    __mapper_args__ = {
        'polymorphic_identity': 'action_two'
    }
</code>```

then using fields.Polymorph

```<code>mapping = {
    ActionOne: action_one_serializer,
    ActionTwo: action_two_serializer,
}

fields = api.model('Action', {
    owner: fields.Polymorph(mapping)
})
</code>```

and providing definitions for serializers using api.inherit like this:

```<code>base_action_serializer = api.model('BaseAction', {
    'id': fields.Integer(readonly=True),
    'action_type': fields.String(discriminator=True)
})

action_one_serializer = api.inherit('ActionOne', parent, {
    'extra_one': fields.String(attribute('parameters.extraOne'))
})

action_two_serializer = api.inherit('ActionTwo', parent, {
    'extra_two': fields.String(attribute('parameters.extraTwo'))
})
</code>```

Body:
Is there any option for dynamic serialization based on certain field?

assume model like this:

class Action(base):
    id = Column(Integer, primary_key=True)
    action_type = Column(Enum(SubscriptionActionType, inherit_schema=True), nullable=False)
    parameters = Column(JSONB)

based on obj value in action_type I would like to use appropriate serializer inside the fields.Nested

is there any option without writing custom field? and if I write custom field, then can I access there whole serialized object and not just the serialized field?

Body:
using polymorphism should do the trick.

class Action(base):
    id = Column(Integer, primary_key=True)
    action_type = Column(Enum(SubscriptionActionType, inherit_schema=True), nullable=False)
    parameters = Column(JSONB)

    __mapper_args__ = {
        'polymorphic_on' : action_type
    }

class ActionOne(Action):

    __mapper_args__ = {
        'polymorphic_identity': 'action_one'
    }

class ActionTwo(Action):

    __mapper_args__ = {
        'polymorphic_identity': 'action_two'
    }

then using fields.Polymorph

mapping = {
    ActionOne: action_one_serializer,
    ActionTwo: action_two_serializer,
}

fields = api.model('Action', {
    owner: fields.Polymorph(mapping)
})

and providing definitions for serializers using api.inherit like this:

base_action_serializer = api.model('BaseAction', {
    'id': fields.Integer(readonly=True),
    'action_type': fields.String(discriminator=True)
})

action_one_serializer = api.inherit('ActionOne', parent, {
    'extra_one': fields.String(attribute('parameters.extraOne'))
})

action_two_serializer = api.inherit('ActionTwo', parent, {
    'extra_two': fields.String(attribute('parameters.extraTwo'))
})


问:
ArgumentNullException when deserializing JSON
I'm trying to deserialize a json like this

```<code>{
"geneslist": [
{
  "seqid": "NC_045512.2",
  "source": "RefSeq",
  "type": "region",
  "start": "1",
  "end": "29903",
  "score": ".",
  "strand": "+",
  "phase": ".",
  "attributes": "ID=NC_045512.2:1..29903;Dbxref=taxon:2697049;collectiondate=Dec-2019;country=China;gbacronym=SARS-CoV2;gbkey=Src;genome=genomic;isolate=Wuhan-Hu-1;mol_type=genomic RNA;nathost=Homo sapiens;oldname=Wuhan seafood market pneumonia virus",
  "ID": "NC_045512.2:1..29903",
  "Note": null,
  "Dbxref": "taxon:2697049",
  "collectiondate": "Dec-2019",
  "country": "China",
  "gbacronym": "SARS-CoV2",
  "gbkey": "Src",
  "gene": null,
  "inference": null,
  "genome": "genomic",
  "isolate": "Wuhan-Hu-1",
  "locus_tag": null,
  "gene_biotype": null,
  "product": null,
  "protein_id": null,
  "mol_type": "genomic RNA",
  "nathost": "Homo sapiens",
  "oldname": "Wuhan seafood market pneumonia virus"
},
{
  "seqid": "NC_045512.2",
  "source": "RefSeq",
  "type": "five_prime_UTR",
  "start": "1",
  "end": "265",
  "score": ".",
  "strand": "+",
  "phase": ".",
  "attributes": "ID=id-NC_045512.2:1..265;gbkey=5'UTR",
  "ID": "id-NC_045512.2:1..265",
  "Note": null,
  "function": null,
  "Dbxref": null,
  "collectiondate": null,
  "country;": null,
  "gbkey": "5'UTR",
  "Dbxrref": null,
  "country": null,
  "gbacronym": null,
  "gene": null,
  "inference": null,
  "genome": null,
  "isolate": null,
  "locus_tag": null,
  "gene_biotype": null,
  "product": null,
  "protein_id": null,
  "mol_type": null,
  "nathost": null,
  "oldname": null
},{..} ]
}
</code>```

where some data might be null or existing, I made two objects for this:

```<code>public class GenesList
{

    private string seqid;
    private string source;
    private string type;
    private int start;
    private int end;
    private string score;
    private string strand;
    private string phase;
    private string attributes;
    private string ID;
    private string Note;
    private string function;
    private string Dbxref;
    private string collectiondate;
    private string country;
    private string gbacronym;
    private string gbkey;
    private string gene;
    private string inference;
    private string genome;
    private string isolate;
    private string locus_tag;
    private string gene_biotype;
    private string product;
    private string protein_id;
    private string mol_type;
    private string nathost;
    private string oldname;

    public string Seqid { get => seqid; set => seqid = value; }
    public string Source {get => source; set => source = value; }
    public string Type { get => type; set => type = value; }
    public int Start { get => start; set => start = value; }
    public int End { get => end; set => end = value; }
    public string Score { get => score; set => score = value; }
    public string Strand { get => strand; set => strand = value; }
    public string Phase { get => phase; set => phase = value; }
    public string Attributes { get => attributes; set => attributes = value; }
    public string ID1 { get => ID; set => ID = value; }
    public string Dbxref1 { get => Dbxref; set => Dbxref = value; }
    public string Collectiondate { get => collectiondate; set => collectiondate = value; }
    public string Country { get => country; set => country = value; }
    public string Gbacronym { get => gbacronym; set => gbacronym = value; }
    public string Gbkey { get => gbkey; set => gbkey = value; }
    public string Genome { get => genome; set => genome = value; }
    public string Isolate { get => isolate; set => isolate = value; }
    public string Mol_type { get => mol_type; set => mol_type = value; }
    public string Nathost { get => nathost; set => nathost = value; }
    public string Oldname { get => oldname; set => oldname = value; }
    public string Locus_tag { get => locus_tag; set => locus_tag = value; }
    public string Gene_biotype { get => gene_biotype; set => gene_biotype = value; }
    public string Function { get => function; set => function = value; }
    public string Inference { get => inference; set => inference = value; }
    public string Product { get => product; set => product = value; }
    public string Protein_id { get => protein_id; set => protein_id = value; }

    public string GetGene()
    {
        return gene;
    }

    public void SetGene(string value)
    {
        gene = value;
    }
}
</code>```

and

```<code> public class GenesWrapper
{
    private List<GenesList> geneslist;

    public List<GenesList> Genes { get => geneslist; set => geneslist = value; }
}
</code>```

but when I'm trying to deserialize with

```<code> GenesWrapper genesList = new GenesWrapper();

 genesList = JsonConvert.DeserializeObject<GenesWrapper>(file2);
</code>```

I'm getting an ArgomentNullException because the object is null after deserializing, did I build a bad object? At first I tought it could have had some problems with the null values or maybe the order the json file has been made. I used NullValueHandling.Ignore but the values are still null, how can I solve?
 Sorry for the wall of text, thank you

答:
This cannot work. Your json is not suitable for creating C# classes. The property "country" occurs two times in your one (the second one) json object.

```<code>  "country;": null,
  "gbkey": "5'UTR",
  "Dbxrref": null,
  "country": null,
</code>```

Moreover, visual studio can create the code for you to prevent human errors. Just create the C# code like this, and it will be fine.

Body:
I'm trying to deserialize a json like this

{
"geneslist": [
{
  "seqid": "NC_045512.2",
  "source": "RefSeq",
  "type": "region",
  "start": "1",
  "end": "29903",
  "score": ".",
  "strand": "+",
  "phase": ".",
  "attributes": "ID=NC_045512.2:1..29903;Dbxref=taxon:2697049;collectiondate=Dec-2019;country=China;gbacronym=SARS-CoV2;gbkey=Src;genome=genomic;isolate=Wuhan-Hu-1;mol_type=genomic RNA;nathost=Homo sapiens;oldname=Wuhan seafood market pneumonia virus",
  "ID": "NC_045512.2:1..29903",
  "Note": null,
  "Dbxref": "taxon:2697049",
  "collectiondate": "Dec-2019",
  "country": "China",
  "gbacronym": "SARS-CoV2",
  "gbkey": "Src",
  "gene": null,
  "inference": null,
  "genome": "genomic",
  "isolate": "Wuhan-Hu-1",
  "locus_tag": null,
  "gene_biotype": null,
  "product": null,
  "protein_id": null,
  "mol_type": "genomic RNA",
  "nathost": "Homo sapiens",
  "oldname": "Wuhan seafood market pneumonia virus"
},
{
  "seqid": "NC_045512.2",
  "source": "RefSeq",
  "type": "five_prime_UTR",
  "start": "1",
  "end": "265",
  "score": ".",
  "strand": "+",
  "phase": ".",
  "attributes": "ID=id-NC_045512.2:1..265;gbkey=5'UTR",
  "ID": "id-NC_045512.2:1..265",
  "Note": null,
  "function": null,
  "Dbxref": null,
  "collectiondate": null,
  "country;": null,
  "gbkey": "5'UTR",
  "Dbxrref": null,
  "country": null,
  "gbacronym": null,
  "gene": null,
  "inference": null,
  "genome": null,
  "isolate": null,
  "locus_tag": null,
  "gene_biotype": null,
  "product": null,
  "protein_id": null,
  "mol_type": null,
  "nathost": null,
  "oldname": null
},{..} ]
}

where some data might be null or existing, I made two objects for this:

public class GenesList
{

    private string seqid;
    private string source;
    private string type;
    private int start;
    private int end;
    private string score;
    private string strand;
    private string phase;
    private string attributes;
    private string ID;
    private string Note;
    private string function;
    private string Dbxref;
    private string collectiondate;
    private string country;
    private string gbacronym;
    private string gbkey;
    private string gene;
    private string inference;
    private string genome;
    private string isolate;
    private string locus_tag;
    private string gene_biotype;
    private string product;
    private string protein_id;
    private string mol_type;
    private string nathost;
    private string oldname;

    public string Seqid { get => seqid; set => seqid = value; }
    public string Source {get => source; set => source = value; }
    public string Type { get => type; set => type = value; }
    public int Start { get => start; set => start = value; }
    public int End { get => end; set => end = value; }
    public string Score { get => score; set => score = value; }
    public string Strand { get => strand; set => strand = value; }
    public string Phase { get => phase; set => phase = value; }
    public string Attributes { get => attributes; set => attributes = value; }
    public string ID1 { get => ID; set => ID = value; }
    public string Dbxref1 { get => Dbxref; set => Dbxref = value; }
    public string Collectiondate { get => collectiondate; set => collectiondate = value; }
    public string Country { get => country; set => country = value; }
    public string Gbacronym { get => gbacronym; set => gbacronym = value; }
    public string Gbkey { get => gbkey; set => gbkey = value; }
    public string Genome { get => genome; set => genome = value; }
    public string Isolate { get => isolate; set => isolate = value; }
    public string Mol_type { get => mol_type; set => mol_type = value; }
    public string Nathost { get => nathost; set => nathost = value; }
    public string Oldname { get => oldname; set => oldname = value; }
    public string Locus_tag { get => locus_tag; set => locus_tag = value; }
    public string Gene_biotype { get => gene_biotype; set => gene_biotype = value; }
    public string Function { get => function; set => function = value; }
    public string Inference { get => inference; set => inference = value; }
    public string Product { get => product; set => product = value; }
    public string Protein_id { get => protein_id; set => protein_id = value; }

    public string GetGene()
    {
        return gene;
    }

    public void SetGene(string value)
    {
        gene = value;
    }
}

and

 public class GenesWrapper
{
    private List<GenesList> geneslist;

    public List<GenesList> Genes { get => geneslist; set => geneslist = value; }
}

but when I'm trying to deserialize with

 GenesWrapper genesList = new GenesWrapper();

 genesList = JsonConvert.DeserializeObject<GenesWrapper>(file2);

I'm getting an ArgomentNullException because the object is null after deserializing, did I build a bad object? At first I tought it could have had some problems with the null values or maybe the order the json file has been made. I used NullValueHandling.Ignore but the values are still null, how can I solve?
 Sorry for the wall of text, thank you

Body:
This cannot work. Your json is not suitable for creating C# classes. The property "country" occurs two times in your one (the second one) json object.

  "country;": null,
  "gbkey": "5'UTR",
  "Dbxrref": null,
  "country": null,

Moreover, visual studio can create the code for you to prevent human errors. Just create the C# code like this, and it will be fine.


问:
Couchbase community edition 6.0 could not create index?
I tried to test Couchbase community edition, by installing using these steps:

```<code>echo '
deb [ arch=amd64 ] http://packages.couchbase.com/releases/couchbase-server/enterprise/deb/ xenial xenial/main
deb [ arch=amd64 ] http://packages.couchbase.com/releases/couchbase-server/community/deb/ xenial xenial/main
deb http://packages.couchbase.com/ubuntu xenial xenial/main
' | sudo tee /etc/apt/sources.list.d/couchbase.list
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 6EF1EAC479CF7903
sudo apt-get update
sudo apt-get install couchbase-server-community
apt list -a couchbase-server-community

# make command line available
echo '
export PATH=$PATH:/opt/couchbase/bin
' | tee -a .bashrc
export PATH=$PATH:/opt/couchbase/bin

# init cluster
couchbase-cli cluster-init -c 127.0.0.1 \
--cluster-username Administrator \
--cluster-password YourPassword \
--services data,index,query \
--cluster-ramsize 512 \
--cluster-index-ramsize 256

# create bucket
couchbase-cli bucket-create -c 127.0.0.1:8091 --username Administrator \
 --password YourPassword --bucket test1 --bucket-type couchbase \
 --bucket-ramsize 512

# start n1ql
cbq -u Administrator -p YourPassword -engine=http://127.0.0.1:8091/
</code>```

And the source code:

package main

import (
    "fmt"
    "github.com/kokizzu/gotro/L"
    "gopkg.in/couchbase/gocb.v1"
    "math/rand"
    "time"
)

const Username = `Administrator`
const Password = `YourPassword`
const Bucket = `test1`

type Score struct {
    User  int64  `json:"user"`
    RefId int64  `json:"ref_id"`
    Epoch int64  `json:"epoch"`
    Score int    `json:"score"`
    Type  string `json:"type"`
}

func main() {
    cluster, err := gocb.Connect("couchbase://127.0.0.1")
    if L.IsError(err,`cannot connect to couchbase`) {
        return
    }
    cluster.Authenticate(gocb.PasswordAuthenticator{Username: Username, Password: Password})
    bucket, _ := cluster.OpenBucket(Bucket, "")
    m := bucket.Manager("", "")
    err = m.CreatePrimaryIndex("", true, false)
    if L.IsError(err, `failed create primary index`) {
        return
    }
    indexes := []string{`type`, `epoch`, `user`, `refid`}
    for _, index := range indexes {
        err = m.CreateIndex(index, []string{index}, true, false)
        if L.IsError(err, `failed create index %s`, index) {
            return
        }
    }

    for x := 0; x < 10000; x++ {
        userId := 1 + rand.Intn(1000)
        refId := 1 + rand.Intn(100)
        epoch := time.Now().AddDate(0, 0, rand.Intn(365)+1).Unix()
        score := 10 + rand.Intn(100)
        _, err := bucket.Upsert(
            fmt.Sprintf("user%dref%d", userId, refId),
            Score{
                User:  int64(userId),
                RefId: int64(refId),
                Epoch: epoch,
                Score: score,
                Type:  `score`,
            }, 0)
        if L.IsError(err, `failed upsert`) {
            return
        }
    }

    // Use query
    sql := `SELECT user,SUM(score) FROM ` + Bucket + ` WHERE epoch > $1 GROUP BY user ORDER BY 2 DESC`
    query := gocb.NewN1qlQuery(sql)
    window := []int{1, 7, 30, 365}
    for _, delta := range window {
        fmt.Println(delta)
        epoch := time.Now().AddDate(0, 0, delta).Unix()
        rows, err := bucket.ExecuteN1qlQuery(query, []interface{}{epoch})
        if L.IsError(err, `failed query %s`, sql) {
            return
        }
        var row interface{}
        defer rows.Close()
        for rows.Next(&row) {
            fmt.Printf("Row: %v", row)
        }
    }

}

```

<p>It shows error:</p>

```2020-02-15 23:58:33.271 IsError ▶ &gocb.n1qlMultiError{
    {Code:0x1388, Message:"GSI CreateIndex() - cause: Fails to create index.  There is no available index service that can process this request at this time. Index Service can be in bootstrap, recovery, or non-reachable. Please retry the operation at a later time."},
}

```

Am I missing some steps? or is this the limitation of Couchbase Community Edition 6.0?

On the web UI, the cluster already has "data,index,query" label, so shouldn't index can be created on that cluster?

答:
A likely reason this is occurring is because there is another process that is running on the same port that Couchbase is listening too in order to create indexes.

You can view the ports Couchbase uses here:

https://docs.couchbase.com/server/current/install/install-ports.html

To fix this you can either change the index port as stated in the article, or end the process/service that currently is using that port.

To find the PID of the process using the port, you can run netstat -aob in the Windows Command Prompt when running as an admin.

For me, I removed a service running on port 9100 and was then able to create the index.

Body:
I tried to test Couchbase community edition, by installing using these steps:

echo '
deb [ arch=amd64 ] http://packages.couchbase.com/releases/couchbase-server/enterprise/deb/ xenial xenial/main
deb [ arch=amd64 ] http://packages.couchbase.com/releases/couchbase-server/community/deb/ xenial xenial/main
deb http://packages.couchbase.com/ubuntu xenial xenial/main
' | sudo tee /etc/apt/sources.list.d/couchbase.list
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 6EF1EAC479CF7903
sudo apt-get update
sudo apt-get install couchbase-server-community
apt list -a couchbase-server-community

# make command line available
echo '
export PATH=$PATH:/opt/couchbase/bin
' | tee -a .bashrc
export PATH=$PATH:/opt/couchbase/bin

# init cluster
couchbase-cli cluster-init -c 127.0.0.1 \
--cluster-username Administrator \
--cluster-password YourPassword \
--services data,index,query \
--cluster-ramsize 512 \
--cluster-index-ramsize 256

# create bucket
couchbase-cli bucket-create -c 127.0.0.1:8091 --username Administrator \
 --password YourPassword --bucket test1 --bucket-type couchbase \
 --bucket-ramsize 512

# start n1ql
cbq -u Administrator -p YourPassword -engine=http://127.0.0.1:8091/

And the source code:

package main

import (
    "fmt"
    "github.com/kokizzu/gotro/L"
    "gopkg.in/couchbase/gocb.v1"
    "math/rand"
    "time"
)

const Username = `Administrator`
const Password = `YourPassword`
const Bucket = `test1`

type Score struct {
    User  int64  `json:"user"`
    RefId int64  `json:"ref_id"`
    Epoch int64  `json:"epoch"`
    Score int    `json:"score"`
    Type  string `json:"type"`
}

func main() {
    cluster, err := gocb.Connect("couchbase://127.0.0.1")
    if L.IsError(err,`cannot connect to couchbase`) {
        return
    }
    cluster.Authenticate(gocb.PasswordAuthenticator{Username: Username, Password: Password})
    bucket, _ := cluster.OpenBucket(Bucket, "")
    m := bucket.Manager("", "")
    err = m.CreatePrimaryIndex("", true, false)
    if L.IsError(err, `failed create primary index`) {
        return
    }
    indexes := []string{`type`, `epoch`, `user`, `refid`}
    for _, index := range indexes {
        err = m.CreateIndex(index, []string{index}, true, false)
        if L.IsError(err, `failed create index %s`, index) {
            return
        }
    }

    for x := 0; x < 10000; x++ {
        userId := 1 + rand.Intn(1000)
        refId := 1 + rand.Intn(100)
        epoch := time.Now().AddDate(0, 0, rand.Intn(365)+1).Unix()
        score := 10 + rand.Intn(100)
        _, err := bucket.Upsert(
            fmt.Sprintf("user%dref%d", userId, refId),
            Score{
                User:  int64(userId),
                RefId: int64(refId),
                Epoch: epoch,
                Score: score,
                Type:  `score`,
            }, 0)
        if L.IsError(err, `failed upsert`) {
            return
        }
    }

    // Use query
    sql := `SELECT user,SUM(score) FROM ` + Bucket + ` WHERE epoch > $1 GROUP BY user ORDER BY 2 DESC`
    query := gocb.NewN1qlQuery(sql)
    window := []int{1, 7, 30, 365}
    for _, delta := range window {
        fmt.Println(delta)
        epoch := time.Now().AddDate(0, 0, delta).Unix()
        rows, err := bucket.ExecuteN1qlQuery(query, []interface{}{epoch})
        if L.IsError(err, `failed query %s`, sql) {
            return
        }
        var row interface{}
        defer rows.Close()
        for rows.Next(&row) {
            fmt.Printf("Row: %v", row)
        }
    }

}

It shows error:

2020-02-15 23:58:33.271 IsError ▶ &gocb.n1qlMultiError{
    {Code:0x1388, Message:"GSI CreateIndex() - cause: Fails to create index.  There is no available index service that can process this request at this time. Index Service can be in bootstrap, recovery, or non-reachable. Please retry the operation at a later time."},
}

Am I missing some steps? or is this the limitation of Couchbase Community Edition 6.0?

On the web UI, the cluster already has "data,index,query" label, so shouldn't index can be created on that cluster?


问:
Custom user manager: only required fields being populated
I switched to a custom user manager to use email as a username. Since making that change, all fields aside from email and password are not being populated on register, eg, a user is created but has no first_name, last_name, etc. I was under the impression django classes could be overridden on a field fo field basis without disrupting other fields. Is that not the case?

Manager:

```<code>class CustomUserManager(BaseUserManager):
    """
    Custom user model manager where email is the unique identifiers
    for authentication instead of usernames.
    """
def create_user(self, email, password, **extra_fields):
    """
    Create and save a User with the given email and password.
    """
    if not email:
        raise ValueError(_('The Email must be set'))
    email = self.normalize_email(email)
    user = self.model(email=email, **extra_fields)
    user.set_password(password)
    user.save()
    return user

def create_superuser(self, email, password, **extra_fields):
    """
    Create and save a SuperUser with the given email and password.
    """
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)
    extra_fields.setdefault('is_active', True)

    if extra_fields.get('is_staff') is not True:
        raise ValueError(_('Superuser must have is_staff=True.'))
    if extra_fields.get('is_superuser') is not True:
        raise ValueError(_('Superuser must have is_superuser=True.'))
    return self.create_user(email, password, **extra_fields)
</code>```

Serializer:

```<code>class RegisterSerializer(serializers.ModelSerializer):

class Meta:
    User = get_user_model()
    model = User
    fields = ('first_name', 'last_name', 'email', 'password', 'startTime', 'groups')
    extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        request = self.context["request"]
        if (request.data.get("groups", None) == 1):
            is_staff = True
        else:
            is_staff = False
        user = User.objects.create_user(validated_data['first_name'],
                                        validated_data['last_name'],
                                        validated_data['email'],
                                        validated_data['password'],
                                        validated_data['startTime'],
                                        validated_data['groups'],
                                        validated_data['is_staff'])
        return user
</code>```

Model:

```<code>class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

startTime = models.TimeField(null=True)
# add additional fields in here
objects = CustomUserManager()
def __str__(self):
    return self.email
</code>```

View:

```<code>class RegisterAPI(generics.GenericAPIView):
  permission_classes = [
    permissions.IsAdminUser
  ]
  serializer_class = RegisterSerializer

  def post(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    user = serializer.save()
    return Response({
      "user": UsersSerializer(user, context=self.get_serializer_context()).data,
      #"token": AuthToken.objects.create(user)
    })
</code>```

答:
You need to populate these through named parameters, not positional ones:

```<code>user = User.objects.create_user(
    <b>first_name=</b>validated_data['first_name'],
    <b>last_name=</b>validated_data['last_name'],
    <b>email=</b>validated_data['email'],
    <b>password=</b>validated_data['password'],
    <b>startTime=</b>validated_data['startTime'],
    <b>groups=</b>validated_data['groups'],
    <b>is_staff=</b>is_staff
)</code>```

or through dictionary unpacking:

```<code>user = User.objects.create_user(
    <b>**validated_data</b>,
    <b>is_staff=</b>is_staff
)</code>```

Body:
I switched to a custom user manager to use email as a username. Since making that change, all fields aside from email and password are not being populated on register, eg, a user is created but has no first_name, last_name, etc. I was under the impression django classes could be overridden on a field fo field basis without disrupting other fields. Is that not the case?

Manager:

class CustomUserManager(BaseUserManager):
    """
    Custom user model manager where email is the unique identifiers
    for authentication instead of usernames.
    """
def create_user(self, email, password, **extra_fields):
    """
    Create and save a User with the given email and password.
    """
    if not email:
        raise ValueError(_('The Email must be set'))
    email = self.normalize_email(email)
    user = self.model(email=email, **extra_fields)
    user.set_password(password)
    user.save()
    return user

def create_superuser(self, email, password, **extra_fields):
    """
    Create and save a SuperUser with the given email and password.
    """
    extra_fields.setdefault('is_staff', True)
    extra_fields.setdefault('is_superuser', True)
    extra_fields.setdefault('is_active', True)

    if extra_fields.get('is_staff') is not True:
        raise ValueError(_('Superuser must have is_staff=True.'))
    if extra_fields.get('is_superuser') is not True:
        raise ValueError(_('Superuser must have is_superuser=True.'))
    return self.create_user(email, password, **extra_fields)

Serializer:

class RegisterSerializer(serializers.ModelSerializer):

class Meta:
    User = get_user_model()
    model = User
    fields = ('first_name', 'last_name', 'email', 'password', 'startTime', 'groups')
    extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        request = self.context["request"]
        if (request.data.get("groups", None) == 1):
            is_staff = True
        else:
            is_staff = False
        user = User.objects.create_user(validated_data['first_name'],
                                        validated_data['last_name'],
                                        validated_data['email'],
                                        validated_data['password'],
                                        validated_data['startTime'],
                                        validated_data['groups'],
                                        validated_data['is_staff'])
        return user

Model:

class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

startTime = models.TimeField(null=True)
# add additional fields in here
objects = CustomUserManager()
def __str__(self):
    return self.email

View:

class RegisterAPI(generics.GenericAPIView):
  permission_classes = [
    permissions.IsAdminUser
  ]
  serializer_class = RegisterSerializer

  def post(self, request, *args, **kwargs):
    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    user = serializer.save()
    return Response({
      "user": UsersSerializer(user, context=self.get_serializer_context()).data,
      #"token": AuthToken.objects.create(user)
    })

Body:
You need to populate these through named parameters, not positional ones:

user = User.objects.create_user(
    first_name=validated_data['first_name'],
    last_name=validated_data['last_name'],
    email=validated_data['email'],
    password=validated_data['password'],
    startTime=validated_data['startTime'],
    groups=validated_data['groups'],
    is_staff=is_staff
)

or through dictionary unpacking:

user = User.objects.create_user(
    **validated_data,
    is_staff=is_staff
)


问:
How to combine two XPath expressions?
I have two XPath expressions that I need to combine.

First XPath is:

(//div[@class="filtername"])

This returns "New York Hotels" for example.

Second XPath is:

(//div[@class="filternumber"])

This returns “100” for example.

So when combining the two expressions I want the result to look like this: "New York Hotels 100"

How do I achieve this?

I think I need to use the concat function but I don’t know how to use it.

Thanks so much in advance.

答:
If both XPath-1.0 expression each yield only one result, you can use the following fn:concat expression:

```<code>concat(//div[@class="filtername"], ' ', //div[@class="filternumber"])
</code>```

This should return "New York Hotels 100".

(But without an XML file, this cannot be verified by us).

Title: How to combine two XPath expressions?

Body:
If both XPath-1.0 expression each yield only one result, you can use the following fn:concat expression:

concat(//div[@class="filtername"], ' ', //div[@class="filternumber"])

This should return "New York Hotels 100".

(But without an XML file, this cannot be verified by us).