答:
This may be one possible way to achieve the desired objective.

Code Sample
This sample uses alert to pop-up the result, instead of document.write.

```<code>let num = 1;
while (!num || num % 7) {
  num = +prompt('enter a number');
  if (num && num % 7) {
    alert(
      `${num} is ${num > 0
        ? 'positive'
        : 'negative'
      }`
    );
  } else if (!num) alert('num is zero');
};
</code>```

Explanation

Set an initial value of num to 1

Set a while loop which will execute as long as num is not 0 (falsy, technically) and num % 7 is not 0.

Get the user-input using prompt into the variable num

If num is truthy (ie, non-zero) and num % 7 is truthy (ie, non-zero), pop an alert whether num is positive (if > 0) or negative (otherwise). This is achieved by using ` backtick symbol / template literal and ?: ternary-operator.

Else, if num is zero, then pop-up corresponding alert

Code Snippet

let num = 1;
while (!num || num % 7) {
  num = +prompt('enter a number');
  if (num && num % 7) {
    alert(
      `${num} is ${num > 0
        ? 'positive'
        : 'negative'
      }`
    );
  } else if (!num) alert('num is zero');
};```

Title: Receive numbers till the input is number that % 7 is without remainder

Body:
i got the next exercise in Javascript:

Receive whole numbers from the user, until he enters a number that % 7 with no remainder.
For each number received, state whether it is positive, negative or 0.
when inserting a number % by 7 with no remainder, end the program.

here is my code:

let num = +prompt("give us a number")
while (num % 7 != 0) {

    if (num > 0){
        document.write("positive ")
        num = +prompt("give us a number" )
    } else if (num < 0) {
        document.write("negative ")
        num = +prompt("give us a number" )
    } else if (num === 0) {
        document.write("zero ")
        num = +prompt("give us a number" )
    }

The thing is, when the user enter 0 ,obviously i wont get output "zero", cause 0 % 7 is 0 remainder, so it dosent even get into the loop..so how can i output "zero" when the user enter 0?

Body:
This may be one possible way to achieve the desired objective.

Code Sample
This sample uses alert to pop-up the result, instead of document.write.

let num = 1;
while (!num || num % 7) {
  num = +prompt('enter a number');
  if (num && num % 7) {
    alert(
      `${num} is ${num > 0
        ? 'positive'
        : 'negative'
      }`
    );
  } else if (!num) alert('num is zero');
};

Explanation

Set an initial value of num to 1

Set a while loop which will execute as long as num is not 0 (falsy, technically) and num % 7 is not 0.

Get the user-input using prompt into the variable num

If num is truthy (ie, non-zero) and num % 7 is truthy (ie, non-zero), pop an alert whether num is positive (if > 0) or negative (otherwise). This is achieved by using ` backtick symbol / template literal and ?: ternary-operator.

Else, if num is zero, then pop-up corresponding alert

Code Snippet

let num = 1;
while (!num || num % 7) {
  num = +prompt('enter a number');
  if (num && num % 7) {
    alert(
      `${num} is ${num > 0
        ? 'positive'
        : 'negative'
      }`
    );
  } else if (!num) alert('num is zero');
};


来源: stackexchange

问:
How make make await as useDispatch
Can you please explain why await on dispatch has no effect?.Use dispatch is synchronous by default. But is there any way to make it to async?

I have one issue by using dispatch and createAsyncthunk.I think it halts the render of other components. I may be wrong please suggest a better way to handle this rendering issue. I think dispatch is still synchronous.

```<code>//API services

    const getPersonLists = async (query) => {
        return await axios.get(`${endPoint}/person?page=${query.page}&perPage=${query.perPage}`);
    };

    const fetchPeronWithAsyncThunk = createAsyncThunk('userSlice/userList', async (query) => await getPersonLists(query));

//Slice

    const userSlice = createSlice({
        name: 'userSlice',
        initialState: {
            users: [],
            loading: false,
        },
        extraReducers: {
            [fetchPeronWithAsyncThunk.pending]: (state) => {
                state.loading = true;
            },
            [fetchPeronWithAsyncThunk.rejected]: (state) => {
                state.loading = false;
            },
            [fetchPeronWithAsyncThunk.fulfilled]: (state, action) => {
                state.loading = false;
                state.users = action.payload;
            },
        },
    });

//Component

    const MyComponent = () => {
        const { users } = useUserList(); //selector
        const dispatch = useDispatch();

        const getList = async () => {
            //await has no effect
            await dispatch(fetchPeronWithAsyncThunk({ page: 1, perPage: 10 }));
        };
        return (
            <div>
                <button onClick={getList}>Fetch user</button>
                <div>{users.length && users.map((user, index) => <div key={index}>{user?.name}</div>)}</div>
            </div>
        );
    };
</code>```

答:
await at that point has exactly the effect you are waiting for.
But since you are in a closure your state will not update within your getList function.

You can get the result of the thunk in your code though:

const result = await dispatch(fetchPeronWithAsyncThunk({ page: 1, perPage: 10 })).unwrap();
```

Also, you should be using the builder notation for extraReducers. We will deprecate the object notation you are using soon.

ContentLicense: CC BY-SA 4.0

Title: How make make await as useDispatch

Body:
Can you please explain why await on dispatch has no effect?.Use dispatch is synchronous by default. But is there any way to make it to async?

I have one issue by using dispatch and createAsyncthunk.I think it halts the render of other components. I may be wrong please suggest a better way to handle this rendering issue. I think dispatch is still synchronous.

//API services

    const getPersonLists = async (query) => {
        return await axios.get(`${endPoint}/person?page=${query.page}&perPage=${query.perPage}`);
    };

    const fetchPeronWithAsyncThunk = createAsyncThunk('userSlice/userList', async (query) => await getPersonLists(query));

//Slice

    const userSlice = createSlice({
        name: 'userSlice',
        initialState: {
            users: [],
            loading: false,
        },
        extraReducers: {
            [fetchPeronWithAsyncThunk.pending]: (state) => {
                state.loading = true;
            },
            [fetchPeronWithAsyncThunk.rejected]: (state) => {
                state.loading = false;
            },
            [fetchPeronWithAsyncThunk.fulfilled]: (state, action) => {
                state.loading = false;
                state.users = action.payload;
            },
        },
    });

//Component

    const MyComponent = () => {
        const { users } = useUserList(); //selector
        const dispatch = useDispatch();

        const getList = async () => {
            //await has no effect
            await dispatch(fetchPeronWithAsyncThunk({ page: 1, perPage: 10 }));
        };
        return (

                <button onClick={getList}>Fetch user</button>

{users.length && users.map((user, index) =>
{user?.name}
)}

        );
    };

Body:
await at that point has exactly the effect you are waiting for.
But since you are in a closure your state will not update within your getList function.

You can get the result of the thunk in your code though:

const result = await dispatch(fetchPeronWithAsyncThunk({ page: 1, perPage: 10 })).unwrap();

Also, you should be using the builder notation for extraReducers. We will deprecate the object notation you are using soon.


问:
Difference between Flink mysql and mysql-cdc connector?
In order to enrich the data stream, we are planning to connect the MySQL (MemSQL) server to our existing flink streaming application

As we can see that Flink provides a Table API with JDBC connector https://nightlies.apache.org/flink/flink-docs-master/docs/connectors/table/jdbc/

Additionally, I discovered another MySQL connector called Flink-CDC https://ververica.github.io/flink-cdc-connectors/master/content/about.html allowing to work with external database in a stream fashion

what is the difference between them?
what is better to choose in my case?

答:
Change Data Capture (CDC) connectors capture all changes that are happening in one or more tables. The schema usually has a before and an after record. The Flink CDC connectors can be used directly in Flink in an unbounded mode (streaming), without the need for something like Kafka in the middle.

The normal JDBC connector can used in bounded mode and as a lookup table.

If you're looking to enrich you existing stream, you most likely want to use the lookup functionality. That allows you to query a table for a specific key (coming from your stream) and enrich the stream with data from your table. Keep in mind that from a performance perspective you're best off to use a temporal table join. See the example in https://nightlies.apache.org/flink/flink-docs-master/docs/connectors/table/jdbc/#how-to-create-a-jdbc-table


问:
How to find results that do NOT match a keyword?
Is there any way I can user a NOT or other negation operator before a text search keyword for example,

```<code>NOT program
</code>```

When I do such a search there are 0 records returned.
Please let me know some way to achieve this option.

答: There aren't any search operators that perform the search parameters you are describing. My advice is to use the Google advanced search features. You can make your search much more specific in a number of ways, its really advanced.</p>

ContentLicense: CC BY-SA 3.0

Body:
Is there any way I can user a NOT or other negation operator before a text search keyword for example,

NOT program

When I do such a search there are 0 records returned.
Please let me know some way to achieve this option.


问:
How can I revoke a JWT token?
I am using Spring Security OAuth2 and JWT tokens. My question is: How can I revoke a JWT token?

As mentioned here
http://projects.spring.io/spring-security-oauth/docs/oauth2.html, revocation is done by refresh token. But it does not seem to work.

答:
In general, the answer about tokens by reference vs. tokens by value has nailed it. For those that stumble upon this space in future.

How to implement revocation on RS side:
TL;DR:
Take a cache or db that is visible to all your backend service instances that are verifying tokens. When a new token arrives for revocation, if it's a valid one, (i.e. verifies against your jwt verification algo), take the exp and jti claims, and save jti to cache until exp is reached. Then expire jti in cache once unixNow becomes > exp.

Then on authorization on other endpoints, you check everytime if a given jti is matching something in this cache, and if yes, you error with 403 saying token revoked. Once it expires, regular Token Expired error kicks in from your verification algo.

P.S. By saving only jti in cache, you make this data useless to anyone since it's just a unique token identifier.

Title: How can I revoke a JWT token?


问:
What is a Scriptive syntax for running stages in parallel
So I want to run following jobs in parallel -

```<code>ccsmp_tag_Android()

ccsmp_tag_OpenVms-ia64()

ccsmp_tag_epoll-linux26-x64()

ccsmp_tag_iphoneOS_176()

ccsmp_tag_linux26-i386()

ccsmp_tag_linux26-x64()

ccsmp_tag_multios()

ccsmp_tag_win_platform()
</code>```

I am trying to write a scripted syntax for this. Please help me with this any suggestions are highly appreciated

答:
Example of a scripted pipeline stage running parallel jobs:

```<code>stage('Parallel Jobs') {
  parallel(
    'Job 1': {
      ccsmp_tag_Android()
    },
    'Job 2': {
      ccsmp_tag_epoll-linux26-x64()
    },
    ... (and so on)
  )
}
</code>```

Depending on your jobs definition, you may also have to put a "node" around:

```<code>stage('Parallel Jobs') {
  parallel(
    'Job 1': {
      node {
        ccsmp_tag_Android()
      }
    },
    'Job 2': {
      node {
        ccsmp_tag_epoll-linux26-x64()
      }
    },
    ... (and so on)
  )
}
</code>```

See: https://www.jenkins.io/doc/book/pipeline/syntax/#scripted-pipeline

Body:
So I want to run following jobs in parallel -

ccsmp_tag_Android()

ccsmp_tag_OpenVms-ia64()

ccsmp_tag_epoll-linux26-x64()

ccsmp_tag_iphoneOS_176()

ccsmp_tag_linux26-i386()

ccsmp_tag_linux26-x64()

ccsmp_tag_multios()

ccsmp_tag_win_platform()

I am trying to write a scripted syntax for this. Please help me with this any suggestions are highly appreciated

Body:
Example of a scripted pipeline stage running parallel jobs:

stage('Parallel Jobs') {
  parallel(
    'Job 1': {
      ccsmp_tag_Android()
    },
    'Job 2': {
      ccsmp_tag_epoll-linux26-x64()
    },
    ... (and so on)
  )
}

Depending on your jobs definition, you may also have to put a "node" around:

stage('Parallel Jobs') {
  parallel(
    'Job 1': {
      node {
        ccsmp_tag_Android()
      }
    },
    'Job 2': {
      node {
        ccsmp_tag_epoll-linux26-x64()
      }
    },
    ... (and so on)
  )
}

See: https://www.jenkins.io/doc/book/pipeline/syntax/#scripted-pipeline


问:
Could not obtain information about Windows NT group/user
I have a Windows 2012 Server running SharePoint 2010 using an SQL Server Express locally installed. Unfortunately my logs are currently flooding with message "An exception occurred while enqueueing a message in the target queue. Error: 15404, State: 19. Could not obtain information about Windows NT group/user 'DOMAIN\user', error code 0x5." It can be 20 such messages every second!

(...and the 'DOMAIN\user' happens to be my personal account.)

Are there a job running that has missing rights? "Qoute from https://serverfault.com/questions/277551/mssqlserver-exception-occurred-while-enqueueing-a-message-in-the-target-queue-e "Try to changing the owner of the jobs to the sa account, on the properties of the job." If I'm correct the express version of SQL server cannot run jobs? Or is there someone/something that wants access to our AD? Why do that account wants to obtain information about my account 20 times every second?

I do find lot's of blogs and hints about this task, but I just dont understand the solutions. One says "To repair this, login as one of the SA accounts and grant SA access for the account that needs it." But what account needs sa access?

答: You should be connected with your domain. (VPN)</p>


问:
What is the best way to access elements of parent control from a child control?
I have a parent control (main form) and a child control (user control). The child control has some code, which determines what functions the application can perform (e.g. save files, write logs etc.). I need to show/hide, enable/disable main menu items of the main form according to the functionality. As I can't just write MainMenu.MenuItem1.Visible = false; (the main menu is not visible from the child control), I fire an event in the child control and handle this event on the main form. The problem is I need to pass what elements of the menu need to be shown/hidden. To do this I created an enum, showing what to do with the item

```<code>public enum ItemMode
{
    TRUE, FALSE, NONE
}
</code>```

Then I created my eventargs which have 6 parameters of type ItemMode (there are 6 menu items I need to manage). So any time I need to show the 1st item, hide the 2nd and do nothing with the rest I have to write something like this

```<code>e = new ItemModeEventArgs(ItemMode.TRUE, ItemMode.FALSE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE);
FireMyEvent(e);
</code>```

This seems like too much code to me and what's more, what if I need to manage 10 items in future? Then I will have to rewrite all the constructors just to add 4 more NONEs.

I believe there's a better way of doing this, but I just can't figure out what it is.

答:
Well, I can't speak to a "best" way unless except in specific cases, since there are often several equally good ways. My first thought, though, would be to create a class that has a property which the parent assigns a reference of its MainMenu, and which has functions for enabling/disabling individual menus or items. In a very simple case, this could be as simple as passing a list of strings like "OptionsScreen=enabled" etc. and then inside the class manually handling those cases, to something more generic like passing strings such as "mnuToolsOptions=enabled" and then finding the menu item via the .Name property.  So, on startup, create an instance of your menu handler class, then do something like MenuHandlerHelper.MenuToHandle = MainMenuStrip;.

On the child side, you could perhaps have your classes that update the MainMenu be derived UserObjects that derive from a common one you create that has a public MyMainMenuHandlerHelper MenuHandlerHelper property, and set that in your Parent form's constructor so the Child controls could call the menu updating function. Or, you could have an event that just passed back a List<string> containing all the rules, and fire that as you are doing now.

This is a very simple idea, and doesn't handle things like possible collisions, so you would probably either want to throw an exception (easiest).  You might also want to have rule priorities (easy), or try to chain functionality (could be hard to determine orders and such).

I would be happy to implement some examples of my thinking if you can constrain the problem a little for me (desired collision handling, etc.) and I actually wanted to see what some basic code would look like and try perhaps to test a couple of ideas, so if those come to anything I will post the code here for those as well.

Body:
I have a parent control (main form) and a child control (user control). The child control has some code, which determines what functions the application can perform (e.g. save files, write logs etc.). I need to show/hide, enable/disable main menu items of the main form according to the functionality. As I can't just write MainMenu.MenuItem1.Visible = false; (the main menu is not visible from the child control), I fire an event in the child control and handle this event on the main form. The problem is I need to pass what elements of the menu need to be shown/hidden. To do this I created an enum, showing what to do with the item

public enum ItemMode
{
    TRUE, FALSE, NONE
}

Then I created my eventargs which have 6 parameters of type ItemMode (there are 6 menu items I need to manage). So any time I need to show the 1st item, hide the 2nd and do nothing with the rest I have to write something like this

e = new ItemModeEventArgs(ItemMode.TRUE, ItemMode.FALSE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE);
FireMyEvent(e);

This seems like too much code to me and what's more, what if I need to manage 10 items in future? Then I will have to rewrite all the constructors just to add 4 more NONEs.

I believe there's a better way of doing this, but I just can't figure out what it is.


问:
How do I implement a python function that can gives the position of seris of zeros in a given string
I need to find positions of all series of zeroes in my string, and I am having really hard time implementing a python function that can do it.

It's output needs to be something like:

For Input: 100010001

Output: [(7,5), (3,1)]

Because there are series of zeroes at index 7 to 5 and 3 to 1 of the input string.

For Input: 11000010101

Output: [(8,5)]

Zeroes at position 1 and 3 are ignored because they are alone (not in a series)

答:
You can use something like this, we keep on incrementing i, once we see a 0, we start looking for all 0s starting from that 0. And add them to the list if number of continuous zeroes is more than 1 -

```<code>def get_zeroes(s):
    zeroes = []
    i = 0
    while i < len(s):
        digit = s[i]
        i += 1
        if digit != '0':
            continue
        start = i - 1
        while i < len(s) and s[i] == '0':
            i += 1
        if i - start > 1:
            zeroes.append((len(s) - start - 1, len(s) - i))
    return zeroes
</code>```
```<code>>>> get_zeroes('100010001')
[(7, 5), (3, 1)]
>>> get_zeroes('11000010101')
[(8, 5)]
>>> get_zeroes('10001000')
[(6, 4), (2, 0)]
>>> get_zeroes('00001000')
[(7, 4), (2, 0)]
</code>```

Body:
You can use something like this, we keep on incrementing i, once we see a 0, we start looking for all 0s starting from that 0. And add them to the list if number of continuous zeroes is more than 1 -

def get_zeroes(s):
    zeroes = []
    i = 0
    while i < len(s):
        digit = s[i]
        i += 1
        if digit != '0':
            continue
        start = i - 1
        while i < len(s) and s[i] == '0':
            i += 1
        if i - start > 1:
            zeroes.append((len(s) - start - 1, len(s) - i))
    return zeroes

>>> get_zeroes('100010001')
[(7, 5), (3, 1)]
>>> get_zeroes('11000010101')
[(8, 5)]
>>> get_zeroes('10001000')
[(6, 4), (2, 0)]
>>> get_zeroes('00001000')
[(7, 4), (2, 0)]


问:
Check if a variable exists in a list in Bash
I am trying to write a script in bash that check the validity of a user input.

I want to match the input (say variable x) to a list of valid values.

what I have come up with at the moment is:

```<code>for item in $list
do
    if [ "$x" == "$item" ]; then
        echo "In the list"
        exit
    fi
done
</code>```

My question is if there is a simpler way to do this,

something like a list.contains(x) for most programming languages.

Say list is:

```<code>list="11 22 33"
</code>```

my code will echo the message only for those values since list is treated as an array and not a string,
all the string manipulations will validate 1 while I would want it to fail.

答:
There's a cleaner way to check if string is in the list:</p>
```<code>if [[ $my_str = @(str1|str2|str3) ]]; then
    echo "string found"
fi
</code>```

Body:
I am trying to write a script in bash that check the validity of a user input.

I want to match the input (say variable x) to a list of valid values.

what I have come up with at the moment is:

for item in $list
do
    if [ "$x" == "$item" ]; then
        echo "In the list"
        exit
    fi
done

My question is if there is a simpler way to do this,

something like a list.contains(x) for most programming languages.

Say list is:

list="11 22 33"

my code will echo the message only for those values since list is treated as an array and not a string,
all the string manipulations will validate 1 while I would want it to fail.

Body:
There's a cleaner way to check if string is in the list:

if [[ $my_str = @(str1|str2|str3) ]]; then
    echo "string found"
fi


问:
Default Jenkins User Password
I have a fresh install of Jenkins as a service on my Linux machine. When Jenkins installs, it creates a 'jenkins' user, but I can't seem to find the default password for it anywhere.

I'm trying to secure my system, so if the default password is '123' or something insecure that I just haven't thought of yet, that's a problem.

Thanks!

答:
Default password for user jenkins is just "jenkins". However, logging into this user automatically closes your session (probably it is set to be used only to allow using particular computer as a jenkins agent, but I'm not sure). That't why su - jenkins and typing jenkins do not work.

You can try logging as a jenkins user with ssh and you will see that it works, but suddenly the session is closed:

I believe there is a solution for this, but maybe it is not needed in your case. Really need to use system as a jenkins user? Doubt it.

Title: Default Jenkins User Password


问:
How to use CommandBuffer.IssuePluginCustomBlit on Unity Engine?
On Unity Engine, I'm trying to convert an image effect (from the asset store) from the camera event OnRenderImage(RenderTexture source, RenderTexture destination) to a camera command buffer (UnityEngine.Rendering.CommandBuffer)(to control the rendering order of all the effects stack).

The image effect rendering C# method is pretty complicated and I would rather not modify it (redoing the effect from scratch might be faster).

So the ideal solution would be calling the effect rendering C# method by a command buffer triggered event.

CommandBuffer.IssuePluginCustomBlit looks like a solution, but I can't find any example how to set it up.

It references a callback method, a source render texture and a destination render texture.
There are examples of the method call (especially in the VRWorks plugin) :

buffer.IssuePluginCustomBlit(PluginExtGetIssueEventCallback(), (UInt32)command, source, dest, commandParam, commandFlags);
```
<pre class="lang-cs prettyprint-override"><code>[DllImport("GfxPluginVRWorks32", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
    private static extern IntPtr PluginExtGetIssueEventCallback();
</code>```

Nonetheless, I have no clue how the PluginExtGetIssueEventCallback is built and how it implement the source and destination render textures.

If someone would have an example to share of how to use CommandBuffer.IssuePluginCustomBlit and to create a callback method, it would be appreciated.

Thanks!

答:
I would suggest CommandBuffer.Blit() instead. You can easily use custom shaders with it.

To create a native render plugin you would need to write separate implementations of it for each 3d api (d3d11, d3d12, vulkan, metal) for each platform you want to support (windows, android, ios). All of this in c++ except for apple where you would rather use objective c. You would also have to write your own shaders for each 3d api separately.

Just look at this small example here:

https://github.com/Unity-Technologies/NativeRenderingPlugin

Bear in mind that Unity native render plugin API is very poorly documented. You're pretty much on your own.

Body:
On Unity Engine, I'm trying to convert an image effect (from the asset store) from the camera event OnRenderImage(RenderTexture source, RenderTexture destination) to a camera command buffer (UnityEngine.Rendering.CommandBuffer)(to control the rendering order of all the effects stack).

The image effect rendering C# method is pretty complicated and I would rather not modify it (redoing the effect from scratch might be faster).

So the ideal solution would be calling the effect rendering C# method by a command buffer triggered event.

CommandBuffer.IssuePluginCustomBlit looks like a solution, but I can't find any example how to set it up.

It references a callback method, a source render texture and a destination render texture.
There are examples of the method call (especially in the VRWorks plugin) :

buffer.IssuePluginCustomBlit(PluginExtGetIssueEventCallback(), (UInt32)command, source, dest, commandParam, commandFlags);

[DllImport("GfxPluginVRWorks32", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
    private static extern IntPtr PluginExtGetIssueEventCallback();

Nonetheless, I have no clue how the PluginExtGetIssueEventCallback is built and how it implement the source and destination render textures.

If someone would have an example to share of how to use CommandBuffer.IssuePluginCustomBlit and to create a callback method, it would be appreciated.

Thanks!


问:
Converting from do() to tap() from Angular 2 to Angular 6
I am trying to implement Server Side Pagination for a Grid in Angular 6 with Kendo Grid

The code below is from Angular 2 which I have taken from the below site

https://www.c-sharpcorner.com/article/server-side-paging-in-kendo-grid-for-angular-2/

```<code>public ngAfterViewInit(): void {
  this.grid.dataStateChange
      .do(({ skip, take }: DataStateChangeEvent) => {
          this.skip = skip;
          this.pageSize = take;
      })
      .subscribe(x => this.service.query(x));
}
</code>```

Because I am using Angular 6, it is expecting tap instead of do in the above code.

Currently I am getting red swiggly for do and the error says as below

Property 'do' does not exist on type 'EventEmitter<DataStateChangeEvent>'

How can I convert it into a usable code by using tap here?

答:
For tree shaking purposes RxJS changed its synthax from 6.0 upwards.</p>
```<code>public ngAfterViewInit(): void {
  this.grid.dataStateChange
      .pipe(
          tap(({ skip, take }: DataStateChangeEvent) => {
              this.skip = skip;
              this.pageSize = take;
          })
      )
      .subscribe(x => this.service.query(x));
}
</code>```

Body:
I am trying to implement Server Side Pagination for a Grid in Angular 6 with Kendo Grid

The code below is from Angular 2 which I have taken from the below site

https://www.c-sharpcorner.com/article/server-side-paging-in-kendo-grid-for-angular-2/

public ngAfterViewInit(): void {
  this.grid.dataStateChange
      .do(({ skip, take }: DataStateChangeEvent) => {
          this.skip = skip;
          this.pageSize = take;
      })
      .subscribe(x => this.service.query(x));
}

Because I am using Angular 6, it is expecting tap instead of do in the above code.

Currently I am getting red swiggly for do and the error says as below

Property 'do' does not exist on type 'EventEmitter<DataStateChangeEvent>'

How can I convert it into a usable code by using tap here?

Body:
For tree shaking purposes RxJS changed its synthax from 6.0 upwards.

public ngAfterViewInit(): void {
  this.grid.dataStateChange
      .pipe(
          tap(({ skip, take }: DataStateChangeEvent) => {
              this.skip = skip;
              this.pageSize = take;
          })
      )
      .subscribe(x => this.service.query(x));
}


问:
Can you programmatically accept a smart contract transaction?
When you connect your wallet, buy, sell, swap etc your prompted to accept the smart contract for connection and for gas fees etc.

Is it possible to accept these prompts without user input, in other words without a user clicking on the accept button and the same for gas fees.

Can you automate this process via API?

So say I first wanted to connect my wallet to some website, I'd click connect wallet, then I'd be promoted to accept this by clicking accept.

Then say I wanted to buy some BTC on a Dex like pancakeswap, I'd be promoted to accept the gas fees.

I want to know if I can auto accept these though API or whatever other method?

答:
From a perspective of the app developer: If you have a private key corresponding to the address, you don't need to invoke the wallet popup. Instead, you can just sign the transaction automatically with the private key.

Example using web3js:

```<code>web3.eth.accounts.wallet.add(senderPrivateKey);
web3.eth.sendTransaction({
    from: senderAddress,
    // ...
});
</code>```

From a perspective of the app user: You're limited by what the app offers. If they only allow signing the transaction through MetaMask (and no other way), you can only sign the transaction this way.

You could theoretically create macro that automates clicking on the MetaMask wallet UI, enters your password to the wallet, clicks the send button, ... But anytime the wallet software changes their UI or behavior, you'd need to update the macro.

Body:
From a perspective of the app developer: If you have a private key corresponding to the address, you don't need to invoke the wallet popup. Instead, you can just sign the transaction automatically with the private key.

Example using web3js:

web3.eth.accounts.wallet.add(senderPrivateKey);
web3.eth.sendTransaction({
    from: senderAddress,
    // ...
});

From a perspective of the app user: You're limited by what the app offers. If they only allow signing the transaction through MetaMask (and no other way), you can only sign the transaction this way.

You could theoretically create macro that automates clicking on the MetaMask wallet UI, enters your password to the wallet, clicks the send button, ... But anytime the wallet software changes their UI or behavior, you'd need to update the macro.


问:
NFOP.dll is causing error on 64bit OS
I have console application which uses the NFOP.dll to generate PDF document. It worked fine in the dev box, which is a 32 bit operating system.

When I moved it to another server which is having a 64 bit OS, it gave me the following error:

Could not load file or assembly 'nfop, Version=1.0.0.0,
  Culture=neutral, PublicKeyToken=null' or one of its dependencies

Any idea on how to resolve it? If this is an issue with using NFOP.dll on a 64 bit os, is there an alternative solution?

Thnks

答:
Follow the below steps on a 64bit machine to build a NFOP dll with platform target (anycpu)

Download and install the Microsoft Visual J#® 2.0 Redistributable Package – Second Edition (x64) from: http://www.microsoft.com/download/en/details.aspx?id=15468

Download the NFOP project code from: http://sourceforge.net/scm/?type=svn&group_id=65558

Open the ApacheFop.Net.vjsproj file from apachefop.net folder in the downloaded code base in any of the text editor.

Change the <Platform Condition=" '$(Platform)' == '' ">x86</Platform> to  <Platform Condition=" '$(Platform)' == '' ">anycpu</Platform>

Change the <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> to <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|anycpu' ">

Add the <PlatformTarget>anycpu</PlatformTarget> node to the <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|anycpu' "> node

Save the project file. (If you want to build in release mode, make these changes to the release configuration property group)

Open VS command prompt

Navigate to the apachefop.net folder in the downloaded code base

Run the following command in the command prompt:

msbuild ApacheFop.Net.vjsproj /t:rebuild /p:Configuration=Debug

You will get the apachefop.net.dll in the \apachefop.net\bin\Debug folder

You can use this dll to build the NFOP dll, which will be supported in both 32bit and 64 bit OS. Hope this helps!!!

Title: NFOP.dll is causing error on 64bit OS


问:
Serialize XML document with attributes
I'm trying to serialize an XML document containing entities to insert into Doctrine MySQL database.

I got, for example, these two attributes in my entity :

$companyId

$companyName

The problem is that instead of something like this into my XML doc :

```<code><company>
    <id>8888</id>
    <name>MyCompany</name>
</company>
</code>```

I got something like this :

```<code><company id="8888" name="MyCompany"/>
</code>```

The XML is generated by an independant company I work with ; so I can't change it.
So the Symfony2 serializer is creating an empty $company attribute :(

Is there a simple way to costumize the seralizing process like I want ? Or do I have to implement a complete independant method ?

Thanks a lot.

答:
Quite old, but I got to a much simpler solution using Serializator + xpath in SerializedName annotation, so this could be useful for someone.

Having for example this entry XML:

```<code><root>
    <company id="123456"/>
</root>
</code>```

Whe deserializing into an object you could use this annotation to populate the company id into "id" property:

```<code>/**
 * @Serializer\SerializedName(name="company/@id")
 */
public ?int $id = null;
</code>```

PS: tested on Symfony 5.4

Title: Serialize XML document with attributes

Body:
I'm trying to serialize an XML document containing entities to insert into Doctrine MySQL database.

I got, for example, these two attributes in my entity :

$companyId

$companyName

The problem is that instead of something like this into my XML doc :

<company>
    <id>8888</id>
    <name>MyCompany</name>
</company>

I got something like this :

<company id="8888" name="MyCompany"/>

The XML is generated by an independant company I work with ; so I can't change it.
So the Symfony2 serializer is creating an empty $company attribute :(

Is there a simple way to costumize the seralizing process like I want ? Or do I have to implement a complete independant method ?

Thanks a lot.

Body:
Quite old, but I got to a much simpler solution using Serializator + xpath in SerializedName annotation, so this could be useful for someone.

Having for example this entry XML:

<root>
    <company id="123456"/>
</root>

Whe deserializing into an object you could use this annotation to populate the company id into "id" property:

/**
 * @Serializer\SerializedName(name="company/@id")
 */
public ?int $id = null;

PS: tested on Symfony 5.4


问:
I'm making a card game and I want to change the image once it has been clicked

import Deck from "./deck2.js"

const deck = new Deck()
var playerCardImg = deck.cards[0].image;

createCard()
createCard()
createCard()

var cards = Array.from(document.getElementsByClassName("card"))
cards.forEach(card => {
    card.addEventListener("click", () => {
        card.classList.toggle("flipCard")

        var playerCard = deck.pop()
        playerCardImg = playerCard.image
        cardImg.setAttribute("src", playerCardImg);
        innerInnerCardDiv.appendChild(cardImg)
    });
});

function createCard() {
    var cardImg = document.createElement('IMG')
    var cardText = document.createElement('h1')
    var cardDiv = document.createElement('div')
    var innerCardDiv = document.createElement('div')
    var innerInnerCardDiv = document.createElement('div')
    var innerInnerCardDiv2 = document.createElement('div')

    cardDiv.classList.add("maincontainer")
    innerCardDiv.classList.add("card")
    innerInnerCardDiv2.classList.add("back")

    cardImg.setAttribute("src", playerCardImg);
    cardImg.classList.add("front")

    cardText.innerText = "Beast Battle"

    document.body.appendChild(cardDiv)
    cardDiv.appendChild(innerCardDiv)
    innerCardDiv.appendChild(innerInnerCardDiv)
    innerCardDiv.appendChild(innerInnerCardDiv2)
    innerInnerCardDiv.appendChild(cardImg)
    innerInnerCardDiv2.appendChild(cardText)

    return cardDiv
}```
</div>
</div>
</p>
<p>I thought by doing this:</p>
```cardImg.setAttribute("src", playerCardImg);
```

I'd be able to change the image but it doesn't work
Note: When I click the card, it does flip. The problem is that since it doesn't change the image, all the cards have the same image.

Edit: here's a link to all the files

github.com/LyshaJaufar/CardGame.git

答:
You can use :

```<code>element.onclick = functionRef
</code>```

See documentation

Body:
import Deck from "./deck2.js"

const deck = new Deck()
var playerCardImg = deck.cards[0].image;

createCard()
createCard()
createCard()

var cards = Array.from(document.getElementsByClassName("card"))
cards.forEach(card => {
    card.addEventListener("click", () => {
        card.classList.toggle("flipCard")

        var playerCard = deck.pop()
        playerCardImg = playerCard.image
        cardImg.setAttribute("src", playerCardImg);
        innerInnerCardDiv.appendChild(cardImg)
    });
});

function createCard() {
    var cardImg = document.createElement('IMG')
    var cardText = document.createElement('h1')
    var cardDiv = document.createElement('div')
    var innerCardDiv = document.createElement('div')
    var innerInnerCardDiv = document.createElement('div')
    var innerInnerCardDiv2 = document.createElement('div')

    cardDiv.classList.add("maincontainer")
    innerCardDiv.classList.add("card")
    innerInnerCardDiv2.classList.add("back")

    cardImg.setAttribute("src", playerCardImg);
    cardImg.classList.add("front")

    cardText.innerText = "Beast Battle"

    document.body.appendChild(cardDiv)
    cardDiv.appendChild(innerCardDiv)
    innerCardDiv.appendChild(innerInnerCardDiv)
    innerCardDiv.appendChild(innerInnerCardDiv2)
    innerInnerCardDiv.appendChild(cardImg)
    innerInnerCardDiv2.appendChild(cardText)

    return cardDiv
}

I thought by doing this:

cardImg.setAttribute("src", playerCardImg);

I'd be able to change the image but it doesn't work
Note: When I click the card, it does flip. The problem is that since it doesn't change the image, all the cards have the same image.

Edit: here's a link to all the files

github.com/LyshaJaufar/CardGame.git

Body:
You can use :

element.onclick = functionRef

See documentation


问:
Enabling offline_access scope in OIDC application
I am using an application called CodeTogether which supports SSO via OIDC. For the SSO provider, we are using OneLogin where we have set up an OIDC application with some very basic config.

```<code>Login redirect URI: https://<codetogether-server>/sso/authorization-code/callback
Logout URI: https://<codetogether-server>/sso/logout

Application type: Web
Token endpoint: Basic
</code>```

Everything else is the defaults from OneLogin.

In the well-known configuration for our OneLogin OIDC, the offline_access scope is not in the scopes_supported attribute. CodeTogether requests this scope in the callback request when attempting to login.

The callback request is the following: https://<onelogin>/oidc/2/auth?client_id=<oidc client id>&scope=openid%20profile%20offline_access&response_type=code&redirect_uri=https%3A%2F%2F<codetogether server>%2Fsso%2Fauthorization-code%2Fcallback&state=<state>

Some information on how to enable this scope in OneLogin would be great, thanks!

答: According to OneLogin Documentation, offline_access is supported in Password Grant flow. Using it with Implicit or Authorization Code flow will cause an error.</p>

Body:
I am using an application called CodeTogether which supports SSO via OIDC. For the SSO provider, we are using OneLogin where we have set up an OIDC application with some very basic config.

Login redirect URI: https://<codetogether-server>/sso/authorization-code/callback
Logout URI: https://<codetogether-server>/sso/logout

Application type: Web
Token endpoint: Basic

Everything else is the defaults from OneLogin.

In the well-known configuration for our OneLogin OIDC, the offline_access scope is not in the scopes_supported attribute. CodeTogether requests this scope in the callback request when attempting to login.

The callback request is the following: https://<onelogin>/oidc/2/auth?client_id=<oidc client id>&scope=openid%20profile%20offline_access&response_type=code&redirect_uri=https%3A%2F%2F<codetogether server>%2Fsso%2Fauthorization-code%2Fcallback&state=<state>

Some information on how to enable this scope in OneLogin would be great, thanks!


问:
Drawing Polygon from LatLng List on mapFragment Android
I was unable to draw a polygon with latlng list!
I saved the latlang in an activity and passed it to another using sharedpref, on receiving the string and extracting the latlng it works fine, but I'm unable to plot polygon with the Arraylist of latlng.
The format of the coordinates ArrayList is also correct.
I don't know what I missed here!

```<code>    //CONVERSION
    val coordinates = ArrayList<LatLng>()

    var answer: String = points.toString()
    answer = answer.replace("lat/lng:", "")
    answer = answer.replace(")", "]")
    answer = answer.replace("(", "[")

    try {
        val jsonArray = JSONArray(answer)
        for (i in 0 until jsonArray.length()) {
            val latLong = jsonArray.getJSONArray(i)
            val lat = latLong.getDouble(0)
            val lon = latLong.getDouble(1)
            coordinates.add(LatLng(lat, lon))
        }
    } catch (e: JSONException) {
        e.printStackTrace()
    }
    val poly = PolygonOptions()
    for (latLng in coordinates) {

        poly.addAll(Collections.singleton(latLng))
        poly.add(latLng)
        gMap.addMarker(MarkerOptions().position(latLng))

    }

    val polygon: Polygon = gMap.addPolygon(poly)

    polygon.strokeColor = Color.BLUE
    polygon.fillColor = Color.BLUE
</code>```

Printing arrayList coordinates gives:

```<code>[lat/lng: (-18.062271504071017,-1.4062657579779625), lat/lng: (-18.062271504071017,-1.4062657579779625), lat/lng: (-18.062271504071017,-1.4062657579779625)]
</code>```

But I got no polygon drawn on the map!

Body:
I was unable to draw a polygon with latlng list!
I saved the latlang in an activity and passed it to another using sharedpref, on receiving the string and extracting the latlng it works fine, but I'm unable to plot polygon with the Arraylist of latlng.
The format of the coordinates ArrayList is also correct.
I don't know what I missed here!

    //CONVERSION
    val coordinates = ArrayList<LatLng>()

    var answer: String = points.toString()
    answer = answer.replace("lat/lng:", "")
    answer = answer.replace(")", "]")
    answer = answer.replace("(", "[")

    try {
        val jsonArray = JSONArray(answer)
        for (i in 0 until jsonArray.length()) {
            val latLong = jsonArray.getJSONArray(i)
            val lat = latLong.getDouble(0)
            val lon = latLong.getDouble(1)
            coordinates.add(LatLng(lat, lon))
        }
    } catch (e: JSONException) {
        e.printStackTrace()
    }
    val poly = PolygonOptions()
    for (latLng in coordinates) {

        poly.addAll(Collections.singleton(latLng))
        poly.add(latLng)
        gMap.addMarker(MarkerOptions().position(latLng))

    }

    val polygon: Polygon = gMap.addPolygon(poly)

    polygon.strokeColor = Color.BLUE
    polygon.fillColor = Color.BLUE

Printing arrayList coordinates gives:

[lat/lng: (-18.062271504071017,-1.4062657579779625), lat/lng: (-18.062271504071017,-1.4062657579779625), lat/lng: (-18.062271504071017,-1.4062657579779625)]

But I got no polygon drawn on the map!

Body:
Seems your polygone has no size - all of three vertex has same coordinates (-18.062271504071017,-1.4062657579779625):

[lat/lng: (-18.062271504071017,-1.4062657579779625), lat/lng: (-18.062271504071017,-1.4062657579779625), lat/lng: (-18.062271504071017,-1.4062657579779625)]


问:
Atlassian Bitbucket + Python
Editing to create a  minimal reproducible example:
I am importing bitbucket and Bitbucket because even though the docs indicate 'bitbucket', I get errors that there is no attribute for repo_list; see below
My code is:

```<code>
from atlassian import Bitbucket
from atlassian import bitbucket
from atlassian.bitbucket import Cloud

bitbucket_username = 'username'
scraper_token = 'token'

Bitbucket_app_pw = Cloud(
    username=bitbucket_username,
    password=scraper_token,
    cloud=True)

try:
    repo_list = bitbucket.repo_list("SOL")
    print(repo_list)
    projects = bitbucket.project_list(Bitbucket_app_pw)
    print(projects)
    data = bitbucket.project("SOL")
    print(data)
    project_info = bitbucket.project("SOL")
    print(project_info)
except AttributeError:
    project_key = "SOL"
    repo_list = Bitbucket.repo_list("SOL")
    print(repo_list)
    projects = Bitbucket.project_list(Bitbucket_app_pw)
    print(projects)
    data = Bitbucket.project("SOL")
    print(data)
    project_info = Bitbucket.project("SOL")
    print(project_info)

</code>```

My error is:

```<code>Traceback (most recent call last):
  File "C:\Users\name.name\PycharmProjects\bitbucket scraper\main.py", line 16, in <module>
    repo_list = bitbucket.repo_list("SOL")
AttributeError: module 'atlassian.bitbucket' has no attribute 'repo_list'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\name.name\PycharmProjects\bitbucket scraper\main.py", line 28, in <module>
    repo_list = Bitbucket.repo_list("SOL")
TypeError: Bitbucket.repo_list() missing 1 required positional argument: 'project_key'

</code>```

Original Question_

I am trying to log into a Atlassian BitBucket repository using the App Password, and it looks like I am in. But when I try to get a list of repositories in a project (using https://atlassian-python-api.readthedocs.io/bitbucket.html), I keep on getting an error. For example, the project key that I am trying to access is 'SOL'. So when I run:

```<code>Bitbucket.project_list('SOL')
</code>```

I get an error:

```<code>AttributeError: 'str' object has no attribute '_url_projects'
</code>```

Not sure what I am doing wrong here. Any advice?
TIA!

Editing after people left helpful comments:
So when I tried the suggestion given by AKX:

```<code>data = bitbucket.project("SOL")
print(data)
</code>```

The response was:

```<code>AttributeError: module 'atlassian.bitbucket' has no attribute 'project'
</code>```

答:
From the docs on "Manage Projects" (you linked):

```<code># Project list
bitbucket.project_list()

# Repo list
bitbucket.repo_list(project_key)

# Project info
bitbucket.project(key)
</code>```

So don't use all-in-one with Bitbucket.project_list('SOL').
Instead create a client-instance as explained by AKX and then retrieve a single specific project bitbucket.project('SOL').

Title: Atlassian Bitbucket + Python

Body:
Editing to create a  minimal reproducible example:
I am importing bitbucket and Bitbucket because even though the docs indicate 'bitbucket', I get errors that there is no attribute for repo_list; see below
My code is:

from atlassian import Bitbucket
from atlassian import bitbucket
from atlassian.bitbucket import Cloud

bitbucket_username = 'username'
scraper_token = 'token'

Bitbucket_app_pw = Cloud(
    username=bitbucket_username,
    password=scraper_token,
    cloud=True)

try:
    repo_list = bitbucket.repo_list("SOL")
    print(repo_list)
    projects = bitbucket.project_list(Bitbucket_app_pw)
    print(projects)
    data = bitbucket.project("SOL")
    print(data)
    project_info = bitbucket.project("SOL")
    print(project_info)
except AttributeError:
    project_key = "SOL"
    repo_list = Bitbucket.repo_list("SOL")
    print(repo_list)
    projects = Bitbucket.project_list(Bitbucket_app_pw)
    print(projects)
    data = Bitbucket.project("SOL")
    print(data)
    project_info = Bitbucket.project("SOL")
    print(project_info)

My error is:

Traceback (most recent call last):
  File "C:\Users\name.name\PycharmProjects\bitbucket scraper\main.py", line 16, in <module>
    repo_list = bitbucket.repo_list("SOL")
AttributeError: module 'atlassian.bitbucket' has no attribute 'repo_list'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\name.name\PycharmProjects\bitbucket scraper\main.py", line 28, in <module>
    repo_list = Bitbucket.repo_list("SOL")
TypeError: Bitbucket.repo_list() missing 1 required positional argument: 'project_key'

Original Question_

I am trying to log into a Atlassian BitBucket repository using the App Password, and it looks like I am in. But when I try to get a list of repositories in a project (using https://atlassian-python-api.readthedocs.io/bitbucket.html), I keep on getting an error. For example, the project key that I am trying to access is 'SOL'. So when I run:

Bitbucket.project_list('SOL')

I get an error:

AttributeError: 'str' object has no attribute '_url_projects'

Not sure what I am doing wrong here. Any advice?
TIA!

Editing after people left helpful comments:
So when I tried the suggestion given by AKX:

data = bitbucket.project("SOL")
print(data)

The response was:

AttributeError: module 'atlassian.bitbucket' has no attribute 'project'

Body:
From the docs on "Manage Projects" (you linked):

# Project list
bitbucket.project_list()

# Repo list
bitbucket.repo_list(project_key)

# Project info
bitbucket.project(key)

So don't use all-in-one with Bitbucket.project_list('SOL').
Instead create a client-instance as explained by AKX and then retrieve a single specific project bitbucket.project('SOL').


问:
Tab key == 4 spaces and auto-indent after curly braces in Vim
How do I make vi-Vim never use tabs (converting spaces to tabs, bad!), makes the tab key == 4 spaces, and automatically indent code after curly brace blocks like Emacs does?

Also, how do I save these settings so I never have to input them again?

I've seen other questions related to this, but it always seems to be a little off from what I want.

答:
Simplest one will be in vim file or simply edit the .vimrc</p>
```<code>set tabstop=4
</code>```

OwnerDisplayName: Simucal

Body:
Simplest one will be in vim file or simply edit the .vimrc

set tabstop=4


问:
I was trying to design an algorithm that sort a generic array with respect to a specific criteria, but every ways I thought are not efficient
I need to separate even numbers from odd numbers this way:

even numbers must be in the first half of the array.

odd numbers must be in the second half of the array.

note: I can't use a second array.

I've tried this algorithm:

if the first element is odd, then swap this element with the next element.

go to the next element.

if the second element is odd (and I know this is odd, because it's the element I've swapped), then swap again the same way. and repeat.

the problem is that it doesn't work. I think it's because I should have checked another elements. meaning, let x be the current element, x1 is the next element, and x2 is "x1 + 1". I need to check if x is odd, if x1 is odd, and if x2 is odd as well. if x2 is even, then I swap x with x2. then I increment counter by 1. repeat.

But I feel this is not an efficient algorithm, because it could be a source of confusion, and a source of errors too. To solve this, I thought of another way.

It consists of going at the middle of the array, and comparing the current element with the first element. if the current element is even and the first element is odd, then swap them together. if it's not the case, don't do anything else and increment counter by 1. repeat until the end of the array is reached (note: it's not a string, hence it's not a zero-terminated array). This could work, but there's still another problem, what have I to do if the first element and the current element are odd? there's a solution, but it'd add an extra layer of complexity. Therefore, I think I should avoid this way.

答:
I would echo the comment from @user3386109 above.

If you were using Python then sorted could be used:

```<code>In [1]: x = [5, 3, 8, 0, 2, 7, 4, 6, 9, 1]

In [2]: sorted(x, key=lambda i: i % 2)
Out[2]: [8, 0, 2, 4, 6, 5, 3, 7, 9, 1]
</code>```

Note:

i % 2 returns a lower number, zero, for all evens and one for all odds.

Comparisons are reduced as all evens compare equal as do all odds (due to the key function). Within the two partitions, numbers are not unnecessarily sorted.

It uses the C-optimised sorted function and would be more readable/maintainable than using explicit Python of dancing pointers over an array with conditions that must be just-so.

P.s. It works for negative ints too:

```<code>In [9]: x = random.sample(range(-5, 5), 10)

In [10]: x
Out[10]: [1, 2, 3, -4, -5, 4, -3, -1, 0, -2]

In [11]: sorted(x, key=lambda i: i % 2)
Out[11]: [2, -4, 4, 0, -2, 1, 3, -5, -3, -1]
</code>```

Body:
I would echo the comment from @user3386109 above.

If you were using Python then sorted could be used:

In [1]: x = [5, 3, 8, 0, 2, 7, 4, 6, 9, 1]

In [2]: sorted(x, key=lambda i: i % 2)
Out[2]: [8, 0, 2, 4, 6, 5, 3, 7, 9, 1]

Note:

i % 2 returns a lower number, zero, for all evens and one for all odds.

Comparisons are reduced as all evens compare equal as do all odds (due to the key function). Within the two partitions, numbers are not unnecessarily sorted.

It uses the C-optimised sorted function and would be more readable/maintainable than using explicit Python of dancing pointers over an array with conditions that must be just-so.

P.s. It works for negative ints too:

In [9]: x = random.sample(range(-5, 5), 10)

In [10]: x
Out[10]: [1, 2, 3, -4, -5, 4, -3, -1, 0, -2]

In [11]: sorted(x, key=lambda i: i % 2)
Out[11]: [2, -4, 4, 0, -2, 1, 3, -5, -3, -1]


问:
Efficient object storage in a file in Java
I am writing a Spotify-like app for an assignment.I have a Song and a Playlist class and I have files where I would store the data. In the constructor of the Spotify Server, the files are supposed to be read and their data transformed into Song and Playlist objects, which the client would then be able to play.
For example, when the Server is run for the first time, the files are empty and there are no songs and playlists. An administrator/user adds several songs and playlists. They are stored in those files. The application is terminated. When the Server is run again, the songs and playlists that have been added in all previous sessions (and stored in files) are loaded and a user can play them.
The question is what technique should I use to store the object data in the most efficient way.
I have considered the following options:

A database - I haven't studied how to make one and that's not the idea of the assignment.

JSON - I know that JSON is an effective way to store and send information in the network. But here, I won't be sending the information across the network. The server will read it from its local hardware. If I use JSON, I will make use of the GSON library.

Serialization - I could do it the traditional way. Make Song and Playlist implement Serializable and store the information in the files.

 The structure of the classes is as follows:

public class Song{
   private final UUID id;
   private final String artist;
   private final String name;
   private final int duration;
   private int timesListenedTo = 0;
   private final Path filePath; // a non-changing path to the .wav audio file of the song
}
```
<pre class="lang-java prettyprint-override"><code>public class Playlist{
   private List<Song> songs; // I could replace this with a List<String> or List<UUID> if considered more efficient
   private final String name;
}
</code>```

 What is the most resource-efficient approach for my task? My priorities in order are:

Minimal CPU usage

Minimal memory usage

Code complexity (the least important)

答:
You can Perst give a try.

Perst is McObject’s open source, dual license, object-oriented embedded database system (ODBMS). It is available in one edition developed as an all-Java embedded database, and another implemented in C# (for Microsoft .NET Framework applications).  Perst gives developers the ability to store, sort and retrieve objects in their applications with maximum speed and with low memory and storage overhead, while leveraging the object-oriented paradigm of Java and C#.

Body:
I am writing a Spotify-like app for an assignment.I have a Song and a Playlist class and I have files where I would store the data. In the constructor of the Spotify Server, the files are supposed to be read and their data transformed into Song and Playlist objects, which the client would then be able to play.
For example, when the Server is run for the first time, the files are empty and there are no songs and playlists. An administrator/user adds several songs and playlists. They are stored in those files. The application is terminated. When the Server is run again, the songs and playlists that have been added in all previous sessions (and stored in files) are loaded and a user can play them.
The question is what technique should I use to store the object data in the most efficient way.
I have considered the following options:

A database - I haven't studied how to make one and that's not the idea of the assignment.

JSON - I know that JSON is an effective way to store and send information in the network. But here, I won't be sending the information across the network. The server will read it from its local hardware. If I use JSON, I will make use of the GSON library.

Serialization - I could do it the traditional way. Make Song and Playlist implement Serializable and store the information in the files.

 The structure of the classes is as follows:

public class Song{
   private final UUID id;
   private final String artist;
   private final String name;
   private final int duration;
   private int timesListenedTo = 0;
   private final Path filePath; // a non-changing path to the .wav audio file of the song
}

public class Playlist{
   private List<Song> songs; // I could replace this with a List<String> or List<UUID> if considered more efficient
   private final String name;
}

 What is the most resource-efficient approach for my task? My priorities in order are:

Minimal CPU usage

Minimal memory usage

Code complexity (the least important)


问:
VueJS: How can I pass params into a component?
I am new to vueJS.
What I want to do is passing parameters to a component, depending on the selection of the routes. Here is my App.vue:

```<code><template>
  <div id="main">
    <header>
      <h1 style="color:red">{{msg}}</h1>
    </header>

    <div>
      <aside class="sidebar">
        <router-link v-for="el in this.$router.options.routes" :to="el">
          {{el.name}}
        </router-link>
      </aside>
      <SubMenu></SubMenu>

      <div class="content">
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script>
  import SubMenu from './components/SubMenu.vue'
  export default {
    components: {
      'SubMenu': SubMenu
    },
    data() {
      return {
        msg: 'Welcome to Your Vue.js App'      }
    }
  }

</script>

<style>
  @import 'style.css';
  @import 'grid.css';
</style>
</code>```

and the SubMenu component I would like to make dynamic:

```<code><template>
  <div>
    something dynamic
  </div>
</template>
</code>```

How can I pass some parameters to use in the component?
thank you

答:
Ok many thanks to both.

But what if I would like to pass something that depends on the voices in router-link? I mean, router-link prints a menu with 4 voices...what if I would like a behavior like this:

click on voice1 in router-link ---> pass this object ['input1', 'input2'] to SubMenu

click on voice2 in router-link ---> pass this other object ['input3', 'input4', 'input5'] to SubMenu

and so on.

thanks again :)

Body:
I am new to vueJS.
What I want to do is passing parameters to a component, depending on the selection of the routes. Here is my App.vue:

<template>

{{msg}}

        <router-link v-for="el in this.$router.options.routes" :to="el">
          {{el.name}}
        </router-link>

      <SubMenu></SubMenu>

        <router-view></router-view>

</template>

and the SubMenu component I would like to make dynamic:

<template>

    something dynamic

</template>

How can I pass some parameters to use in the component?
thank you


问:
Java, Calculate the number of days between two dates

Possible Duplicate:

  Calculating the Difference Between Two Java Date Instances

In Java, I want to calculate the number of days between two dates.

In my database they are stored as a DATE datatype, but in my code they are strings.

I want to calculate the no of days between those two strings.

答:
Note: this answer was written in 2011. I would recommend using java.time now instead of Joda Time.

Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.

I would recommend that you use Joda Time, which is a much better API than Date/Calendar. It sounds like you should use the LocalDate type in this case. You can then use:

```<code>int days = Days.daysBetween(date1, date2).getDays();
</code>```

Body:
Note: this answer was written in 2011. I would recommend using java.time now instead of Joda Time.

Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with.

I would recommend that you use Joda Time, which is a much better API than Date/Calendar. It sounds like you should use the LocalDate type in this case. You can then use:

int days = Days.daysBetween(date1, date2).getDays();


问:
how to set position of cursor in bottom right of textarea in textfield in flutter
I need text area cursor starting point will be bottom right
https://i.stack.imgur.com/wsS8O.jpg</p>

答:
```<code>textarea {
    text-align: right;
}
</code>```

Body:
textarea {
    text-align: right;
}


问:
Running separate infinite background thread in a python webapp (fastapi/flask/django)
How can i launch an application which does below 2 things:

Expose rest endpoint via FastAPI.

Run a seperate thread infintely (rabbitmq consumer - pika) waiting for request.

Below is the code through which i am launching the fastAPI server. But when i try to run a thread,  before execution of below line, it says coroutine was never awaited.

How can both be run parallely?

答:
```<code>import asyncio
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI
import uvicorn

app = FastAPI()

def run(corofn, *args):
    loop = asyncio.new_event_loop()
    try:
        coro = corofn(*args)
        asyncio.set_event_loop(loop)
        return loop.run_until_complete(coro)
    finally:
        loop.close()

async def sleep_forever():
    await asyncio.sleep(1000)

#
async def main():
    loop = asyncio.get_event_loop()
    executor = ThreadPoolExecutor(max_workers=2)
    futures = [loop.run_in_executor(executor, run, sleep_forever),
               loop.run_in_executor(executor, run, uvicorn.run, app)]
    print(await asyncio.gather(*futures))

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
</code>```

Note: This may hinder your FastAPI performance. Better approach would be to use a Celery Task

Body:
import asyncio
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI
import uvicorn

app = FastAPI()

def run(corofn, *args):
    loop = asyncio.new_event_loop()
    try:
        coro = corofn(*args)
        asyncio.set_event_loop(loop)
        return loop.run_until_complete(coro)
    finally:
        loop.close()

async def sleep_forever():
    await asyncio.sleep(1000)

#
async def main():
    loop = asyncio.get_event_loop()
    executor = ThreadPoolExecutor(max_workers=2)
    futures = [loop.run_in_executor(executor, run, sleep_forever),
               loop.run_in_executor(executor, run, uvicorn.run, app)]
    print(await asyncio.gather(*futures))

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Note: This may hinder your FastAPI performance. Better approach would be to use a Celery Task


问:
C memory leak after freeing string that has been realloc'd multiple times
I am trying to create a program that reads different movies from a large file and sorts them in different ways. I have run into a problem with a particularly stubborn memory leak - one that has resisted my attempts to fix it.

Without further ado, here is the function where valgrind says the memory leak happens.

```<code>static int isValidAnimatedMovie(char * genre, unsigned int votes){
    if (votes < MIN_VOTES_ANIMATED)
        return 0;

    char * line;
    char * resp = NULL;
    int c;
    unsigned long len=0;
    int flag = 0;
    line = strtok(genre,GDIV);
    for(int i = 0; i < MAX_GENRES && line != NULL; i++){
        c = strcmp("Animation", line);

        if (c != 0){
            len+= strlen(line)+1;
            if (resp == NULL){
                resp = malloc(sizeof(char)*(len+1));
                if (resp == NULL || errno == ENOMEM){
                    perror("Memory ERROR in isValidAnimatedMovie");
                }
                strcpy(resp, line);
            }

            else{
                resp = realloc(resp, (len+1)+1);
                if (resp == NULL || errno == ENOMEM){
                    perror("Memory ERROR in isValidAnimatedMovie");
                }
                resp = strcat(resp, line);
            }
            resp = strcat(resp, GDIV);
        }

        if (c<0 && flag==0){
            return 0;
        }
        else if (c==0)
            flag=1;
        line = strtok(NULL,GDIV);

    }
    resp[len-1]=0;
    strcpy(genre,resp);
    free(resp);
    return flag;
}
</code>```

The function receives a string called genres. This string has all of the movie's genres separated by GDIV (a comma) and in alphabetical order. An example would be "Action,Adventure,Animation,Comedy".

What this function is supposed to do is check whether a movie has enough votes and, if it has the word "Animation" in the string genres, it should remove it so that the final result looks like "Action,Adventure,Comedy" if I feed it the example string.

That works wonderfully. What happens here is that even though I free the pointer resp at the end of the function, valgrind still detects a memory leak, even though I've freed the pointer. It says the following.

Direct leak of 37666 byte(s) in 2042 object(s) allocated from:

Then this function, with the line in which the malloc happens highlighted. It also displays the realloc in the same way.

I have tried different things to solve this. I have tried to set resp to NULL after freeing it, and I have also tried to use strncpy instead of the final strcpy. However, none of those things have solved my problem.

I have noticed that after freeing it, resp still shows up in the debugger as "/001". Is that a clue as to what could have gone wrong? Thank you very much.

答:
The leak is here:

```<code>    if (c<0 && flag==0){
        return 0;
    }
</code>```

To fix it:

```<code>    if (c<0 && flag==0){
        free(resp);
        return 0;
    }
</code>```

Body:
I am trying to create a program that reads different movies from a large file and sorts them in different ways. I have run into a problem with a particularly stubborn memory leak - one that has resisted my attempts to fix it.

Without further ado, here is the function where valgrind says the memory leak happens.

static int isValidAnimatedMovie(char * genre, unsigned int votes){
    if (votes < MIN_VOTES_ANIMATED)
        return 0;

    char * line;
    char * resp = NULL;
    int c;
    unsigned long len=0;
    int flag = 0;
    line = strtok(genre,GDIV);
    for(int i = 0; i < MAX_GENRES && line != NULL; i++){
        c = strcmp("Animation", line);

        if (c != 0){
            len+= strlen(line)+1;
            if (resp == NULL){
                resp = malloc(sizeof(char)*(len+1));
                if (resp == NULL || errno == ENOMEM){
                    perror("Memory ERROR in isValidAnimatedMovie");
                }
                strcpy(resp, line);
            }

            else{
                resp = realloc(resp, (len+1)+1);
                if (resp == NULL || errno == ENOMEM){
                    perror("Memory ERROR in isValidAnimatedMovie");
                }
                resp = strcat(resp, line);
            }
            resp = strcat(resp, GDIV);
        }

        if (c<0 && flag==0){
            return 0;
        }
        else if (c==0)
            flag=1;
        line = strtok(NULL,GDIV);

    }
    resp[len-1]=0;
    strcpy(genre,resp);
    free(resp);
    return flag;
}

The function receives a string called genres. This string has all of the movie's genres separated by GDIV (a comma) and in alphabetical order. An example would be "Action,Adventure,Animation,Comedy".

What this function is supposed to do is check whether a movie has enough votes and, if it has the word "Animation" in the string genres, it should remove it so that the final result looks like "Action,Adventure,Comedy" if I feed it the example string.

That works wonderfully. What happens here is that even though I free the pointer resp at the end of the function, valgrind still detects a memory leak, even though I've freed the pointer. It says the following.

Direct leak of 37666 byte(s) in 2042 object(s) allocated from:

Then this function, with the line in which the malloc happens highlighted. It also displays the realloc in the same way.

I have tried different things to solve this. I have tried to set resp to NULL after freeing it, and I have also tried to use strncpy instead of the final strcpy. However, none of those things have solved my problem.

I have noticed that after freeing it, resp still shows up in the debugger as "/001". Is that a clue as to what could have gone wrong? Thank you very much.

Body:
The leak is here:

    if (c<0 && flag==0){
        return 0;
    }

To fix it:

    if (c<0 && flag==0){
        free(resp);
        return 0;
    }


问:
I've used TabBar inside bottomNavigationBar. Where do I insert content for these tabs?
I've used TabBar inside bottomNavigationBar and just wanted to know where do I insert content in these tabs.
I'm basically creating an app similar to facebook so I need to enter content in these tabs and navigate through them
here I'm attaching the code and I'm looking forward for some guidance. Is there a way I could do this without using TabBarView ?

Widget build(BuildContext context) {

```<code>Widget menu() {
  return Container(
    color: Colors.white,
    child: TabBar(
      labelColor: Color(int.parse("0xff3A5FCD")),
      unselectedLabelColor: Colors.grey,
      indicatorSize: TabBarIndicatorSize.tab,
      indicatorPadding: EdgeInsets.all(5.0),
      indicatorColor: Colors.blue,
      onTap: (index){

      },
      tabs: [

        InkWell(
          onTap: (){},
          child: Tab(
            text: "Home",
            icon: Icon(Icons.home,size: 30,),
          ),
        ),
        InkWell(
          onTap: (){
            Navigator.pushNamed(context, MyRoutes.friendsRoute);
            setState(() {
            });
          },
          child: Tab(
            text: "Friends",
            icon: Icon(Icons.people,size: 30,),
          ),
        ),
        InkWell(
          onTap: (){},
          child: Tab(
            text: "Notifications",
            icon: Icon(Icons.notifications,size: 30,),
          ),
        ),
        InkWell(
          onTap: (){},
          child: Tab(
            text: "Menu",
            icon: Icon(Icons.menu,size: 30,),
          ),
        ),
      ],
    ),
  );
}

return DefaultTabController(
  length: 4,
  child: Scaffold(
    appBar: AppBar(
      elevation: 0,
      foregroundColor: Colors.white10,
      automaticallyImplyLeading: false,
      title: Text("facebook",textScaleFactor: 1.6,style: TextStyle(
        color: Colors.indigo,
        fontWeight: FontWeight.bold
      ),),
      backgroundColor: Colors.white10,
      actions: <Widget>[
        Row(
          children: [
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(28),
                color: Color(int.parse("0xffEBEBEB"))
              ),
             // color: Colors.grey,
              child: IconButton(
                onPressed: () {},
                icon: FaIcon(FontAwesomeIcons.search),
                  color: Colors.black,
                  iconSize: 23,

              ),
            ),
            SizedBox(width: 10,),
            Container(
              width: 50,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(28),
                color: Color(int.parse("0xffEBEBEB"))
              ),
              child: IconButton(
                onPressed: (){},
                icon: FaIcon(FontAwesomeIcons.facebookMessenger),
                  color: Colors.black,
                  iconSize: 23,

              ),
            ),
            SizedBox(width: 10,height: 10,),
          ],
        ),
      ],
    ),

    bottomNavigationBar: menu(),
</code>```

答:
Set the body of the Scaffold to a TabBarView and set the children of each content like so:

```<code>Scaffold:
 body: TabBarView(
  children: [
   Container(child: Text("Home")),
   Container(child: Text("Friends")),
   Container(child: Text("Notifications),
   Container(child: Text("Menu")),
  ]
 ),
),
</code>```

Body:
I've used TabBar inside bottomNavigationBar and just wanted to know where do I insert content in these tabs.
I'm basically creating an app similar to facebook so I need to enter content in these tabs and navigate through them
here I'm attaching the code and I'm looking forward for some guidance. Is there a way I could do this without using TabBarView ?

Widget build(BuildContext context) {

Widget menu() {
  return Container(
    color: Colors.white,
    child: TabBar(
      labelColor: Color(int.parse("0xff3A5FCD")),
      unselectedLabelColor: Colors.grey,
      indicatorSize: TabBarIndicatorSize.tab,
      indicatorPadding: EdgeInsets.all(5.0),
      indicatorColor: Colors.blue,
      onTap: (index){

      },
      tabs: [

        InkWell(
          onTap: (){},
          child: Tab(
            text: "Home",
            icon: Icon(Icons.home,size: 30,),
          ),
        ),
        InkWell(
          onTap: (){
            Navigator.pushNamed(context, MyRoutes.friendsRoute);
            setState(() {
            });
          },
          child: Tab(
            text: "Friends",
            icon: Icon(Icons.people,size: 30,),
          ),
        ),
        InkWell(
          onTap: (){},
          child: Tab(
            text: "Notifications",
            icon: Icon(Icons.notifications,size: 30,),
          ),
        ),
        InkWell(
          onTap: (){},
          child: Tab(
            text: "Menu",
            icon: Icon(Icons.menu,size: 30,),
          ),
        ),
      ],
    ),
  );
}

return DefaultTabController(
  length: 4,
  child: Scaffold(
    appBar: AppBar(
      elevation: 0,
      foregroundColor: Colors.white10,
      automaticallyImplyLeading: false,
      title: Text("facebook",textScaleFactor: 1.6,style: TextStyle(
        color: Colors.indigo,
        fontWeight: FontWeight.bold
      ),),
      backgroundColor: Colors.white10,
      actions: <Widget>[
        Row(
          children: [
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(28),
                color: Color(int.parse("0xffEBEBEB"))
              ),
             // color: Colors.grey,
              child: IconButton(
                onPressed: () {},
                icon: FaIcon(FontAwesomeIcons.search),
                  color: Colors.black,
                  iconSize: 23,

              ),
            ),
            SizedBox(width: 10,),
            Container(
              width: 50,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(28),
                color: Color(int.parse("0xffEBEBEB"))
              ),
              child: IconButton(
                onPressed: (){},
                icon: FaIcon(FontAwesomeIcons.facebookMessenger),
                  color: Colors.black,
                  iconSize: 23,

              ),
            ),
            SizedBox(width: 10,height: 10,),
          ],
        ),
      ],
    ),

    bottomNavigationBar: menu(),

Body:
Set the body of the Scaffold to a TabBarView and set the children of each content like so:

Scaffold:
 body: TabBarView(
  children: [
   Container(child: Text("Home")),
   Container(child: Text("Friends")),
   Container(child: Text("Notifications),
   Container(child: Text("Menu")),
  ]
 ),
),


答:
here's a small program which may help you:</p>

```<code>import java.util.*;

public class DateDifference {
    public static void main(String args[]){
        DateDifference difference = new DateDifference();
    }

    DateDifference() {
        Calendar cal1 = new GregorianCalendar();
        Calendar cal2 = new GregorianCalendar();

        cal1.set(2010, 12, 1);
        cal2.set(2011, 9, 31);
        System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
    }

    public int daysBetween(Date d1, Date d2) {
        return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
    }
}
</code>```

Title: Java, Calculate the number of days between two dates

Body:
Possible Duplicate:

  Calculating the Difference Between Two Java Date Instances

In Java, I want to calculate the number of days between two dates.

In my database they are stored as a DATE datatype, but in my code they are strings.

I want to calculate the no of days between those two strings.

Body:
here's a small program which may help you:

import java.util.*;

public class DateDifference {
    public static void main(String args[]){
        DateDifference difference = new DateDifference();
    }

    DateDifference() {
        Calendar cal1 = new GregorianCalendar();
        Calendar cal2 = new GregorianCalendar();

        cal1.set(2010, 12, 1);
        cal2.set(2011, 9, 31);
        System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
    }

    public int daysBetween(Date d1, Date d2) {
        return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
    }
}


问:
The method 'of' isn't defined for the type 'ThemeProvider'. in Flutter
I am Beginner to Flutter just following the YouTube tutorial on building User Profile while doing everything is OK but Theme Provider gave me the error I didn't understand What's going on can You guys help me, the error is The method 'of' isn't defined for the type 'ThemeProvider', I am getting error at

```<code>@override
  Widget build(BuildContext context) {
    final user = UserPreferences.getUser();
    return ThemeProvider(
      initTheme: user.isDarkMode ?  MyThemes.darkTheme : MyThemes.lightTheme,
      child: Builder(
        builder: (context) => MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: ThemeProvider.of(context),
          title: title,
          home:  const ProfilePage(),
        ),
      ),
    );
  }
</code>```

and full code is so long so I Attaching github link for reference, Thanking You Advance.

After updating theme_provider in dependency I got 2 more errors below I attached a screenshot of it.

答:
Don't skip reading Documentation.Keep on mind your Module docs.

This is the sample of your package owner.Be careful check.

```<code>    ThemeProvider(
          initTheme: initTheme,
   ---->  builder: (context, myTheme) {
            return MaterialApp(
              title: 'Flutter Demo',
        ----> theme: myTheme,
              home: MyHomePage(),
            );
          }),
        ),
</code>```

Body:
I am Beginner to Flutter just following the YouTube tutorial on building User Profile while doing everything is OK but Theme Provider gave me the error I didn't understand What's going on can You guys help me, the error is The method 'of' isn't defined for the type 'ThemeProvider', I am getting error at

@override
  Widget build(BuildContext context) {
    final user = UserPreferences.getUser();
    return ThemeProvider(
      initTheme: user.isDarkMode ?  MyThemes.darkTheme : MyThemes.lightTheme,
      child: Builder(
        builder: (context) => MaterialApp(
          debugShowCheckedModeBanner: false,
          theme: ThemeProvider.of(context),
          title: title,
          home:  const ProfilePage(),
        ),
      ),
    );
  }

and full code is so long so I Attaching github link for reference, Thanking You Advance.

After updating theme_provider in dependency I got 2 more errors below I attached a screenshot of it.

Body:
Don't skip reading Documentation.Keep on mind your Module docs.

This is the sample of your package owner.Be careful check.

    ThemeProvider(
          initTheme: initTheme,
   ---->  builder: (context, myTheme) {
            return MaterialApp(
              title: 'Flutter Demo',
        ----> theme: myTheme,
              home: MyHomePage(),
            );
          }),
        ),


问:
C++ check if entered value is unsigned integer
I'm trying to get unsigned integer from std::cin.

When enter a char or string my program stucks

```<code>#include <iostream>
#include <climits>

using namespace std;

int main()
{
    unsigned int number;
    do
    {
        cout << "Enter a unsigned number\t";
        cin >> number;

        if (0 < number && number < 65535 && std::cin.good())
        {
            cout << "It's a number";
            break;
        }
        cout << "Not a number";
    } while (true);
}
</code>```

How to do that ?

答:
It seems that std::cin needs to be recovered when a failure happens(std::cin.clear() fails to restore input stream in a good state)

Then I think using unsigned int is not a solution to enforce positiveness because c/c++ allow implicit conversion between unsigned int and int, so if you do unsigned int x = -1 ,x will become 4294967295(assuming 32 bits int) due to underflow.

#include <iostream>

int main()
{
    int number;
    while (true)
    {
        std::cout << "Enter an unsigned number\n";
        std::cin >> number;

        if (std::cin.fail())
        {
            std::cout << "Please enter a number\n";
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
        else if (number > 0)
        {
            std::cout << "It's an unsigned number\n";
            break;
        }
        else
        {
            std::cout << "It's an negative number\n";
        }
    }
}
```

Body:
I'm trying to get unsigned integer from std::cin.

When enter a char or string my program stucks

#include <iostream>
#include <climits>

using namespace std;

int main()
{
    unsigned int number;
    do
    {
        cout << "Enter a unsigned number\t";
        cin >> number;

        if (0 < number && number < 65535 && std::cin.good())
        {
            cout << "It's a number";
            break;
        }
        cout << "Not a number";
    } while (true);
}

How to do that ?


问:
Spring i18n question
I have a question using Spring i18n. Can i pass parameters to i18ned messages from other message codes.

For eg.

```<code>YesKey=Yes
NoKey=No

Message1=This is {YesKey}
Message2=This is {NoKey}
</code>```

Is there any alternative to this if i cann't implement .

答:
As fare I know it is not possible use a message in an other message simply by using there name. -- This is not a limitation of spring, it is a limitation of java.text.MessageFormat.

But what you can do is this:

message.properties:

```<code>YesKey=Yes
NoKey=No

Message1=This is {0}
Message2=This is {0}
</code>```

java code

```<code> MessageSource messageSource =...
 String param = messageSource.getMessage("YesKey",
                      new Object[0], Locale.English);
 String message = messageSource.getMessage("Message1",
                      new Object[]{param}, Locale.English);
</code>```

or in jsp(x):

```<code> <spring:message var="param" code="YesKey" />
 <spring:message var="message" code="Message1" arguments="${param}" />
</code>```

Title: Spring i18n question

Body:
I have a question using Spring i18n. Can i pass parameters to i18ned messages from other message codes.

For eg.

YesKey=Yes
NoKey=No

Message1=This is {YesKey}
Message2=This is {NoKey}

Is there any alternative to this if i cann't implement .

Body:
As fare I know it is not possible use a message in an other message simply by using there name. -- This is not a limitation of spring, it is a limitation of java.text.MessageFormat.

But what you can do is this:

message.properties:

YesKey=Yes
NoKey=No

Message1=This is {0}
Message2=This is {0}

java code

 MessageSource messageSource =...
 String param = messageSource.getMessage("YesKey",
                      new Object[0], Locale.English);
 String message = messageSource.getMessage("Message1",
                      new Object[]{param}, Locale.English);

or in jsp(x):

 <spring:message var="param" code="YesKey" />
 <spring:message var="message" code="Message1" arguments="${param}" />


问:
How to convert two dimensional array of string into one of type int?
How can I convert a double array of type String to a double array of type int ?

```<code>    @PostMapping("/hole/coordinate")
    @ResponseBody
    public String saveCoordinate(@RequestBody Map<String, Object> params) {
        System.out.println("params = " + params);
        System.out.println("params = " + params.get("coordinate"));

        return "success";
    }
</code>```

System.out.println(params.get("coordinate")); store
[[445, 292], [585, 331], [612, 223], [205, 532]]
There are m 2 elements of the double array.
ex) [a,b],[c,d].....m
At this time, I want to receive the result in the data type of int[][], not String.

I was wondering how can I convert from String to int[][].

I tried like below

```<code>int[] arr= Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
for (int i : arr) {
    System.out.println("i = " + i);
}
</code>```

but it give me

```<code>4
4
5
2
9
2
...
</code>```

Best Regards!

答:
```<code>    Try this. It creates a matrix of coordinates.

    String str = "[[445, 292], [585, 331], [612, 223], [205, 532]]";
    List<String> numbers = List.of(str.split(",| |\\[|\\]"));
    List<String> onlyNumbers = numbers.stream()
                                      .filter(number -> !number.equals("") && !number.equals(" "))
                                      .toList();
    Integer[][] coordinates = new Integer[onlyNumbers.size()][2];
    int counter = 0;
    for(int i=0; i < onlyNumbers.size() - 1; i+=2){
        coordinates[counter][0] = Integer.valueOf(onlyNumbers.get(i));
        coordinates[counter][1] = Integer.valueOf(onlyNumbers.get(i+1));
        counter++;
    }
</code>```

Body:
How can I convert a double array of type String to a double array of type int ?

    @PostMapping("/hole/coordinate")
    @ResponseBody
    public String saveCoordinate(@RequestBody Map<String, Object> params) {
        System.out.println("params = " + params);
        System.out.println("params = " + params.get("coordinate"));

        return "success";
    }

System.out.println(params.get("coordinate")); store
[[445, 292], [585, 331], [612, 223], [205, 532]]
There are m 2 elements of the double array.
ex) [a,b],[c,d].....m
At this time, I want to receive the result in the data type of int[][], not String.

I was wondering how can I convert from String to int[][].

I tried like below

int[] arr= Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
for (int i : arr) {
    System.out.println("i = " + i);
}

but it give me

4
4
5
2
9
2
...

Best Regards!


问:
How to make a list in a web page that can be edited without reloading
Here's some low-hanging fruit for those more comfortable with Javascript than I...

I want to improve a Moodle plugin's admin UI. (Moodle is a PHP-based web app). What I need to do is take what is currently a text box, with semi-colon delimited entries and replace that with a editable list.

The HTML elements I would use is a select list, a text input field and another hidden textfield. I guess a couple of submit buttons too, one for adding, and the other for removing of entries.

The behaviour would be:

Entries can be added to the select list from the visible textbox upon some kind of submit (this cannot reload the page).

The hidden textbox would contain all the entries from the select list, just semi-colon delimited

There's a function to remove entries from the select list that also does not reload the page.

The hidden textbox is updated with add/remove actions

This seems to me like something that's easy enough. Though I'm having a hard time finding a close enough example to rip off.

This sample code is as close as I've found thus far. There's got to be some good examples of precisely this sort of thing out there. Any decent pointers will be rewarded with + votes.

答:
What you want to do is use JavaScript and manipulate with the DOM of the webpage. Basically, the HTML of a webpage is parsed and rendered by the browser into a tree of elements. Each HTML tag like <select> is an element in the tree. You use JavaScript to interact with this tree by performing operations like removing elements from this tree or adding elements to this tree. (Note that preforming operations on the tree will not refresh the page.)

The standardized API to do these sorts of manipulation in JavaScript is known as the DOM. However, many people, myself included, think that this API is very clunky and not nearly expressive enough. Doing even trivial things require tons of lines of code. For this reason, many developers do not use the DOM directly instead using more powerful libraries, such as jQuery, to make their lives easier.

Below is an example of some HTML + JavaScript that I think mimics most of your requirements. Ideally for learning purposes, this would be written purely using the standard W3C DOM API, but since your problem is not that trivial, I resorted to using jQuery instead.

The HTML:

```<code><select id="list" multiple="multiple"></select>
<input id="removeButton" type="button" value="Remove"></input>

<div>
    <input id="optionAdder" type="text"></input>
    <input id="addButton" type="button" value="Add"></input>
</div>

<br>
<input id="clearButton" type="button" value="Clear All"></input>
<div>Not So Hidden: <input id="hidden" type="text"></input></div>
</code>```

The JavaScript:

```<code>// Uses jQuery to define an on document ready  call back function
$(function(){
    // The code in this function runs when the page is loaded

    var options = []; // contains all the options

    // add new option to drop-down
   var addOption = function(optText) {

       // Create new option element and add it to the <select> tag
        $('<option></option>')
            .attr('value', optText).text(optText)
            .appendTo( $('#list') );
    };

    // writes the names of all the options in the "hidden" text box
    var fillHidden = function() {
        $('#hidden').val('');
        var hiddenText = "";
        for(var i=0; i< options.length; i++) {
           if(hiddenText) {
               hiddenText += "; ";
           }
           hiddenText += options[i];
        }
        $('#hidden').val(hiddenText);
    }

    // Bind the click event of the "Add" button to add an option on click
    $('#addButton')
        .click(function(){
            var optText = $('#optionAdder').val();

            if(optText) {
                addOption(optText);
            }
            $('#optionAdder').val('');
            options.push(optText);
            fillHidden();
        });

    // Bind the click event of the "Remove" button to remove the selected options on click
    $('#removeButton')
        .click(function(){
            $('#list option:selected').each(function(){

                var optIndex = $.inArray($(this).val(), options);
                if(optIndex > -1) {
                   options.splice(optIndex, 1);
                   $(this).remove();
                }
                fillHidden();
            });
        });

    // Bind the click event of the "Clear" button to clear all options on click
    $('#clearButton')
        .click(function(){
            $('#list').children().remove();
            options = [];
            fillHidden();
        });
});
</code>```

Here is a jsfiddle demonstrating the code

Body:
What you want to do is use JavaScript and manipulate with the DOM of the webpage. Basically, the HTML of a webpage is parsed and rendered by the browser into a tree of elements. Each HTML tag like <select> is an element in the tree. You use JavaScript to interact with this tree by performing operations like removing elements from this tree or adding elements to this tree. (Note that preforming operations on the tree will not refresh the page.)

The standardized API to do these sorts of manipulation in JavaScript is known as the DOM. However, many people, myself included, think that this API is very clunky and not nearly expressive enough. Doing even trivial things require tons of lines of code. For this reason, many developers do not use the DOM directly instead using more powerful libraries, such as jQuery, to make their lives easier.

Below is an example of some HTML + JavaScript that I think mimics most of your requirements. Ideally for learning purposes, this would be written purely using the standard W3C DOM API, but since your problem is not that trivial, I resorted to using jQuery instead.

The HTML:

<select id="list" multiple="multiple"></select>
<input id="removeButton" type="button" value="Remove"></input>

<div>
    <input id="optionAdder" type="text"></input>
    <input id="addButton" type="button" value="Add"></input>
</div>

<br>
<input id="clearButton" type="button" value="Clear All"></input>
<div>Not So Hidden: <input id="hidden" type="text"></input></div>

The JavaScript:

// Uses jQuery to define an on document ready  call back function
$(function(){
    // The code in this function runs when the page is loaded

    var options = []; // contains all the options

    // add new option to drop-down
   var addOption = function(optText) {

       // Create new option element and add it to the <select> tag
        $('<option></option>')
            .attr('value', optText).text(optText)
            .appendTo( $('#list') );
    };

    // writes the names of all the options in the "hidden" text box
    var fillHidden = function() {
        $('#hidden').val('');
        var hiddenText = "";
        for(var i=0; i< options.length; i++) {
           if(hiddenText) {
               hiddenText += "; ";
           }
           hiddenText += options[i];
        }
        $('#hidden').val(hiddenText);
    }

    // Bind the click event of the "Add" button to add an option on click
    $('#addButton')
        .click(function(){
            var optText = $('#optionAdder').val();

            if(optText) {
                addOption(optText);
            }
            $('#optionAdder').val('');
            options.push(optText);
            fillHidden();
        });

    // Bind the click event of the "Remove" button to remove the selected options on click
    $('#removeButton')
        .click(function(){
            $('#list option:selected').each(function(){

                var optIndex = $.inArray($(this).val(), options);
                if(optIndex > -1) {
                   options.splice(optIndex, 1);
                   $(this).remove();
                }
                fillHidden();
            });
        });

    // Bind the click event of the "Clear" button to clear all options on click
    $('#clearButton')
        .click(function(){
            $('#list').children().remove();
            options = [];
            fillHidden();
        });
});

Here is a jsfiddle demonstrating the code


问:
Angular + Git - How to Include a file from a package exists inside node_modules
I have ng-payment-card package and I've made some modifications in a file inside the package, and I need to include this file in the git commit in order to not reset it every time I make npm install.

I tried to write in .gitignore like this:

```<code>!/node_modules/ng-payment-card/__ivy_ngcc__/fesm2015/ng-payment-card.js
</code>```

but the same, the file hasn't been added to the commit.

答:
if you like to work with .gitignore

thats what you need to add to .gitignore

/*

!node_modules

node_modules/*

!node_modules/ng-payment-card

node_modules/ng-payment-card/*

!node_modules/ng-payment-card/ivy_ngcc

node_modules/ng-payment-card/ivy_ngcc/*

!node_modules/ng-payment-card/ivy_ngcc/fesm2015

node_modules/ng-payment-card/ivy_ngcc/fesm2015/*

!node_modules/ng-payment-card/ivy_ngcc/fesm2015/ng-payment-card.js

basically the problem is you have to allow access to all the sub directories to get to the last folder where the file is residing.

Body:
I have ng-payment-card package and I've made some modifications in a file inside the package, and I need to include this file in the git commit in order to not reset it every time I make npm install.

I tried to write in .gitignore like this:

!/node_modules/ng-payment-card/__ivy_ngcc__/fesm2015/ng-payment-card.js

but the same, the file hasn't been added to the commit.