问:
Can't change object property for Vue component (a true anomaly)
A strange anomaly. An object/component property this.gridTiles does get set correctly when I do the "undo" action first. But then when I perform the "redo" action (see code below), I'm unable to set this.gridTiles to the new value! It seems to be holding on to the old value. this.gridTiles is an array with nested items/objects. Right before I try to set the value though, it's giving me the correct value if I assign it to a test variable. Very strange! Any help would be much appreciated!

Note : cloneDeep() is enabled by this package : [https://www.npmjs.com/package/clone-deep]

ComponentA.vue

```<code>    data() {
        return {
            gridTiles: [],
        }
    },

....

        setCurrentEntireState(historyParams) {
            let test = cloneDeep(historyParams.gridTiles); // CORRECT VALUE
            this.test = cloneDeep(historyParams.gridTiles); // we can set this arbitrary object property correctly
            //this.gridTiles = test;    // doesn't work
            //delete this.gridTiles;    // doesn't help even if we do this first
            this.gridTiles = cloneDeep(historyParams.gridTiles); // WRONG VALUE, WHY ??
        },

        getCurrentEntireState() {  // used in saving historyStack items, not shown
            return {
                gridTiles: cloneDeep(this.gridTiles)
            }
        },

....

        EventBus.$on('refreshHistoryStateForReceiptMap', (historyParams) => {
            this.setCurrentEntireState(historyParams);
            ....
        })
</code>```

ComponentB.vue

```<code>    methods: {

        ....

        undoHistoryAction() {
            let historyParams = this.$store.getters.historyStack[this.$store.getters.historyIndex - 1];
            EventBus.$emit('refreshHistoryStateForReceiptMap', historyParams);

            this.$store.commit('historyIndexDecrement');
        },

        redoHistoryAction() {
            let historyParams = this.$store.getters.historyStack[this.$store.getters.historyIndex];
            EventBus.$emit('refreshHistoryStateForReceiptMap', historyParams);

            this.$store.commit('historyIndexIncrement');
        }
    },
</code>```

答: The console.log() was showing a different value than when I actually used the Chrome JS debugger with a breakpoint. Also, I investigated further downstream and found that some other custom code was reverting the value back to the old/original one. The moral of the story, console.log() might not always be correct, or there might be some lag?</p>

Body:
A strange anomaly. An object/component property this.gridTiles does get set correctly when I do the "undo" action first. But then when I perform the "redo" action (see code below), I'm unable to set this.gridTiles to the new value! It seems to be holding on to the old value. this.gridTiles is an array with nested items/objects. Right before I try to set the value though, it's giving me the correct value if I assign it to a test variable. Very strange! Any help would be much appreciated!

Note : cloneDeep() is enabled by this package : [https://www.npmjs.com/package/clone-deep]

ComponentA.vue

    data() {
        return {
            gridTiles: [],
        }
    },

....

        setCurrentEntireState(historyParams) {
            let test = cloneDeep(historyParams.gridTiles); // CORRECT VALUE
            this.test = cloneDeep(historyParams.gridTiles); // we can set this arbitrary object property correctly
            //this.gridTiles = test;    // doesn't work
            //delete this.gridTiles;    // doesn't help even if we do this first
            this.gridTiles = cloneDeep(historyParams.gridTiles); // WRONG VALUE, WHY ??
        },

        getCurrentEntireState() {  // used in saving historyStack items, not shown
            return {
                gridTiles: cloneDeep(this.gridTiles)
            }
        },

....

        EventBus.$on('refreshHistoryStateForReceiptMap', (historyParams) => {
            this.setCurrentEntireState(historyParams);
            ....
        })

ComponentB.vue

    methods: {

        ....

        undoHistoryAction() {
            let historyParams = this.$store.getters.historyStack[this.$store.getters.historyIndex - 1];
            EventBus.$emit('refreshHistoryStateForReceiptMap', historyParams);

            this.$store.commit('historyIndexDecrement');
        },

        redoHistoryAction() {
            let historyParams = this.$store.getters.historyStack[this.$store.getters.historyIndex];
            EventBus.$emit('refreshHistoryStateForReceiptMap', historyParams);

            this.$store.commit('historyIndexIncrement');
        }
    },


来源: stackexchange

问:
MySQL queries - defining compound and single indexes across multiple queries. How to prevent the indexes from conflicting and creating slow queries?
I am struggling to work out which columns are best to put my indexes on, when it seems adding additional indexes can have a detrimental effect on the query performance.

For example, I have the following query on a table with around 5m rows;

```<code>SELECT col1, col2 FROM table WHERE col1 = 'a' AND col2 = 'b' AND col3 = 'c';
</code>```

Running this with no indexes takes 12 seconds!

I add a compound index on all 3 columns - table_col1_col2_col3_index;

My query now drops down to 2 seconds - great!

I now have another query on the same table (with no indexes on any column):

```<code>SELECT col1, col2 FROM table WHERE col1 = 'a';
</code>```

Running this on its own and the query takes 4 seconds - still pretty slow!

So now I add a single column index to col1 table_col1_index

My query reduces down to 0.2 seconds. This is great, however I now run the original query again and notice that it is using this index opposed to the one I specified earlier. The original query is now back up at 6 seconds.

I am unsure how to go about ensuring that both queries can be optimised at the same time.

答:
Turn off the query cache, or use SELECT SQL_NO_CACHE ... when doing timing.

Run each timing test twice.  The first may spend extra time fetching data and/or index blocks from disk.  The second timing is better for comparisons.  (And is closer to the way it would be in a "production" server.)

How many rows are being returned?  That could have an impact.  The 2nd query may be returning many times as many rows.

Please provide SHOW CREATE TABLE -- there could be subtle issues.  (datatypes, column sizes, collations, who-knows-what)

Please provide EXPLAIN SELECT ... -- As written, each of your examples should say "Using index", meaning that the index "covers" the query, which means that all the columns in the SELECT exist in the INDEX being used.

Do not use "index hints" -- while it may help a query today, it may hurt it more tomorrow.

All of your examples would ('should') benefit from INDEX(col1, col2, col3), in that order; I would not add any others.

ContentLicense: CC BY-SA 4.0

Body:
I am struggling to work out which columns are best to put my indexes on, when it seems adding additional indexes can have a detrimental effect on the query performance.

For example, I have the following query on a table with around 5m rows;

SELECT col1, col2 FROM table WHERE col1 = 'a' AND col2 = 'b' AND col3 = 'c';

Running this with no indexes takes 12 seconds!

I add a compound index on all 3 columns - table_col1_col2_col3_index;

My query now drops down to 2 seconds - great!

I now have another query on the same table (with no indexes on any column):

SELECT col1, col2 FROM table WHERE col1 = 'a';

Running this on its own and the query takes 4 seconds - still pretty slow!

So now I add a single column index to col1 table_col1_index

My query reduces down to 0.2 seconds. This is great, however I now run the original query again and notice that it is using this index opposed to the one I specified earlier. The original query is now back up at 6 seconds.

I am unsure how to go about ensuring that both queries can be optimised at the same time.


问:
Inheritance without default constructor?
Since the inherited class has no default constructor, I explicitly call the inherited class's constructor, and I still got the red-underline(in VScode) at   B's constructor:

no default constructor exists for class "A"

Does class A have to obtain default constructor? Is there any way to fix this?

This is simplified code:

```<code>class A
{
    public:
        int a_;

        A(int a): a_(a)
        {}
};

class B: public A
{
    public:
        A A1;
        A A2;

        B(int a1, int a2): A1(a1), A2(a2)
        {}
};

</code>```

答:
The error is about A not having a default constructor. Because it doesn't, there's no way to initialize the A part of B. You need something like:

```<code>B(int a, int a1, int a2): A(a), A1(a1), A2(a2)
{}
</code>```

Body:
Since the inherited class has no default constructor, I explicitly call the inherited class's constructor, and I still got the red-underline(in VScode) at   B's constructor:

no default constructor exists for class "A"

Does class A have to obtain default constructor? Is there any way to fix this?

This is simplified code:

class A
{
    public:
        int a_;

        A(int a): a_(a)
        {}
};

class B: public A
{
    public:
        A A1;
        A A2;

        B(int a1, int a2): A1(a1), A2(a2)
        {}
};

Body:
The error is about A not having a default constructor. Because it doesn't, there's no way to initialize the A part of B. You need something like:

B(int a, int a1, int a2): A(a), A1(a1), A2(a2)
{}


问:
Using Conditional Formatting to alter another sheet based on a string
I've been working on a dashboard in Google Sheets. When I select a text criterion from a dropdown on the dashboard (say the location Manhattan) I want to be able to highlight a row corresponding to that same text on a different sheet. The idea is that the dropdown is generated from the same sheet and I want to have this easier to read as a result.

I read from Conditional Formatting from another sheet that it's not possible (at least a few years ago) directly to reference another sheet in Conditional Formatting except by utilizing the INDIRECT function. From what I can tell, this does not work with text.

Is there a way around this or should I rethink how to make my highlighting a possibility?

I know I could just have the text in the dropdown change on a portion of the sheet and then base the conditional on that, but I was hoping to simplify this. This will affect three other sheets when I'm done with it, so less would be more. I have not experimented with add-ons at all at this point.

答:
Assuming the dropdown is in A1 and row length in other sheet is A:Z then select ColumnsA:Z in the other sheet and Format > Conditional formatting..., for Format cells if... select Custom formula is and enter:

```<code>=$A1=indirect("Dashboard!A1")
</code>```

with formatting of choice then click Done.

Body:
Assuming the dropdown is in A1 and row length in other sheet is A:Z then select ColumnsA:Z in the other sheet and Format > Conditional formatting..., for Format cells if... select Custom formula is and enter:

=$A1=indirect("Dashboard!A1")

with formatting of choice then click Done.


问:
Failed to resolve: exifinterface
When I upgrade picasso from 2.5.2 to 2.71828 and do a gradle sync I see a a
exifinterface error:

Error:

```<code>Failed to resolve: exifinterface
</code>```

Replaced

```<code>implementation 'com.squareup.picasso:picasso:2.5.2'
</code>```

with

```<code>implementation 'com.squareup.picasso:picasso:2.71828'
</code>```

答:
i use androidX and below dependency solved my problem :</p>

```<code>    implementation 'androidx.exifinterface:exifinterface:1.1.0-alpha01'
</code>```

Title: Failed to resolve: exifinterface

Body:
When I upgrade picasso from 2.5.2 to 2.71828 and do a gradle sync I see a a
exifinterface error:

Error:

Failed to resolve: exifinterface

Replaced

implementation 'com.squareup.picasso:picasso:2.5.2'

with

implementation 'com.squareup.picasso:picasso:2.71828'

Body:
i use androidX and below dependency solved my problem :

    implementation 'androidx.exifinterface:exifinterface:1.1.0-alpha01'


问:
why is method within React Component function constructor evaluating after the components have been initialized?
Sorry if the title is hard to understand, because it's definitely a weird problem.

I think this screenshot best explains what's going on, and it makes no sense to me in every sense of programming. Regardless of whether a PL is interpreted or compiled, I would expect two lines within the same function to evaluate in consecutive order.

Not in this case, however:

You can clearly see in this side-by-side screenshot that the line I would have expected to print after the first line (consecutively speaking) actually printed/evaluated first.

This is a problem for me because the entire reason I am calling the index.getObject method within the React component constructor is to use the response in the object itself. So now all the React components are just using destName = null.

Can anyone explain this behavior? (bonus points if there's a way to make sure the first line evaluates first)

additional picture to explain behavior:

答:
As @RandyCasburn has alluded to, this appears to be an issue with your index.getObject method being an asynchronous JavaScript call. This means that when calling index.getObject, the JavaScript continuous to execute code while it is waiting on the result of the index.getObject call.

Here's the canonical answer for asynchronous JavaScript questions on Stack Overflow: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference


问:
How to create Jest mock function with Promise?
I am trying to mock an axios module by create this Promise function

```<code>// __mocks__/axios.js
export default function axios() {
  return new Promise((resolve) => {
    resolve({ data: {} });
  });
}
</code>```

But when i try to call it inside my *.test.js, i got this error

```<code><PortalUploadForm /> › Submit Data correctly

expect(jest.fn())[.not].toHaveBeenCalledTimes()

Matcher error: received value must be a mock or spy function

Received has type:  function
Received has value: [Function axios]

Received has type:  function
    Received has value: [Function axios]

      87 |     await wait(() => {
      88 |       // mockAxios.mockResponse({ data: { ...uploadPortalResult } });
    > 89 |       expect(mockAxios).toHaveBeenCalledTimes(1);
         |                         ^
      90 |       expect(nameInput.value).toEqual(null);
      91 |     });
      92 |   });
</code>```

So how can i make a mock promise function using jest.fn()?

Thanks!

答:
It looks like you are trying to mock the default export for axios to be a mock function that returns a resolved Promise.

In that case you can create your mock for axios like this:

__mocks__/axios.js

```<code>export default jest.fn(() => Promise.resolve({ data: {} }));
</code>```

...and you can use it in a test like this:

```<code>import axios from 'axios';

const func = () => axios();

test('func', async () => {
  const promise = func();
  expect(axios).toHaveBeenCalledTimes(1);  // Success!
  await expect(promise).resolves.toEqual({ data: {} });  // Success!
})
</code>```

Body:
I am trying to mock an axios module by create this Promise function

// __mocks__/axios.js
export default function axios() {
  return new Promise((resolve) => {
    resolve({ data: {} });
  });
}

But when i try to call it inside my *.test.js, i got this error

<PortalUploadForm /> › Submit Data correctly

expect(jest.fn())[.not].toHaveBeenCalledTimes()

Matcher error: received value must be a mock or spy function

Received has type:  function
Received has value: [Function axios]

Received has type:  function
    Received has value: [Function axios]

      87 |     await wait(() => {
      88 |       // mockAxios.mockResponse({ data: { ...uploadPortalResult } });
    > 89 |       expect(mockAxios).toHaveBeenCalledTimes(1);
         |                         ^
      90 |       expect(nameInput.value).toEqual(null);
      91 |     });
      92 |   });

So how can i make a mock promise function using jest.fn()?

Thanks!

Body:
It looks like you are trying to mock the default export for axios to be a mock function that returns a resolved Promise.

In that case you can create your mock for axios like this:

__mocks__/axios.js

export default jest.fn(() => Promise.resolve({ data: {} }));

...and you can use it in a test like this:

import axios from 'axios';

const func = () => axios();

test('func', async () => {
  const promise = func();
  expect(axios).toHaveBeenCalledTimes(1);  // Success!
  await expect(promise).resolves.toEqual({ data: {} });  // Success!
})


问:
Count the number of times each of the symbols appears in a string - python
In this question, you are given a string s which represents a DNA string. The string s consists of symbols 'A', 'C', 'G', and 'T'. An example of a length 21 DNA string is "ATGCTTCAGAAAGGTCTTACG."

Your task is to write a code which will count the number of times each of the symbols 'A', 'C', 'G', and 'T' occur in s. Your code should generate a list of 4 integers and print it out.

```<code># Here is the DNA string:
    s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'
    # Type your code here
</code>```

Incorrectly, I wrote the string with spaces between letters.

```<code>s='A G C T T T T C A T T C T G A C T G C A A C G G G C A A T A T G T C T C T G T G T G G A T T A A A A A A A G A G T G T C T G A T A G C A G C'
list_of_symbols=s.split(sep=' ')
list_of_symbols
word_count_dictionary={}
for A in list_of_symbols:
    if A not in word_count_dictionary:
        word_count_dictionary[A]=1
    else:
        word_count_dictionary[A]+=1
</code>```

答:
You are basically on the right track but there's no need to split the string since Python already offers you the ability to loop through each character of the string.

A modified version of your attempt would be:

```<code>s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'
word_count_dictionary = {}

for c in s:
    if c not in word_count_dictionary:
        word_count_dictionary[c] = 1
    else:
        word_count_dictionary[c] += 1

print(word_count_dictionary)
</code>```

Body:
In this question, you are given a string s which represents a DNA string. The string s consists of symbols 'A', 'C', 'G', and 'T'. An example of a length 21 DNA string is "ATGCTTCAGAAAGGTCTTACG."

Your task is to write a code which will count the number of times each of the symbols 'A', 'C', 'G', and 'T' occur in s. Your code should generate a list of 4 integers and print it out.

# Here is the DNA string:
    s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'
    # Type your code here

Incorrectly, I wrote the string with spaces between letters.

s='A G C T T T T C A T T C T G A C T G C A A C G G G C A A T A T G T C T C T G T G T G G A T T A A A A A A A G A G T G T C T G A T A G C A G C'
list_of_symbols=s.split(sep=' ')
list_of_symbols
word_count_dictionary={}
for A in list_of_symbols:
    if A not in word_count_dictionary:
        word_count_dictionary[A]=1
    else:
        word_count_dictionary[A]+=1

Body:
You are basically on the right track but there's no need to split the string since Python already offers you the ability to loop through each character of the string.

A modified version of your attempt would be:

s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'
word_count_dictionary = {}

for c in s:
    if c not in word_count_dictionary:
        word_count_dictionary[c] = 1
    else:
        word_count_dictionary[c] += 1

print(word_count_dictionary)


问:
How to Send a text message from the data input on the text view fields?
I am using android studio. I made an application that allows the user to input data in different activities. The goal of the app is that what the user inputs will somehow be retrieved back to me by text message. I was wondering if there was a way to store the information input on the textfields (perhaps using a variable) and then send the variables to my phone as a text message for me to be able to see what was input on them. I’m not sure if this has been done before but I really need help with it. Thanks.</p>

答: I think, this can be achieved by using the backend services. Whatever user inputs will be stored on database or somewhere using the backend services and retrieve that data using the sms service from backend system to the specific number or phone.</p>


问:
Image compression java
I want to transfer Images via network socket(java.net).Where Can I find a sample Code for

compressing Buffered Images in java..Say for example If my Image file is around 200kb,I want

it to be converted to atleat 100kb..So that the transfer will be lil bit fast..

Thank you..

答:
To my knowledge the best compression without loss on images is done with PNG which the image libraries in Java can write.

If you need smaller images than that you need to use lossy compression.  A simple way to do that is with JPEG, where you can turn down the quality until you get the rate you want.

You could also downscale the images first to 1/2 or 1/3 of the original dimensions givning a much smaller picture and transfer that, and upscale it in the other end.  That will be usable for quick transfers, and you can then transfer a full image when the movements have settled down.

ContentLicense: CC BY-SA 3.0

Title: Image compression java


问:
Multiple findForPassport ? e.g Login with username and phone number
I have tried findForPassport. It is good if there is just one field instead of the default but I want to log in either with username or phone number. </p>

<p>For the basic login what I did is </p>

```<code>public function __construct()
    {
        $this->middleware('guest')->except('logout');

        $this->username = $this->findUsernameOrPhone();
    }

public function findUsernameOrPhone()
    {
        $login = request()->input('username');

        $fieldType = Str::startsWith($login, '07') ? 'phone' : 'username';

        request()->merge([$fieldType => $login]);

        return $fieldType;
    }

/**
     * Get phone property.
     *
     * @return string
     */
    public function phone()
    {
        return $this->username;
    }

    /**
     * Get username property.
     *
     * @return string
     */
    public function username()
    {
        return $this->username;
    }
</code>```

答:
Just add this into t=your user model. here $username can be username or email</p>

```<code>public function findForPassport($username) {
        return $this->orWhere('username', $username)
        ->orWhere('email',$username)->first();
}
</code>```

Body:
I have tried findForPassport. It is good if there is just one field instead of the default but I want to log in either with username or phone number.

For the basic login what I did is

public function __construct()
    {
        $this->middleware('guest')->except('logout');

        $this->username = $this->findUsernameOrPhone();
    }

public function findUsernameOrPhone()
    {
        $login = request()->input('username');

        $fieldType = Str::startsWith($login, '07') ? 'phone' : 'username';

        request()->merge([$fieldType => $login]);

        return $fieldType;
    }

/**
     * Get phone property.
     *
     * @return string
     */
    public function phone()
    {
        return $this->username;
    }

    /**
     * Get username property.
     *
     * @return string
     */
    public function username()
    {
        return $this->username;
    }

Body:
Just add this into t=your user model. here $username can be username or email

public function findForPassport($username) {
        return $this->orWhere('username', $username)
        ->orWhere('email',$username)->first();
}


答:
You are trying to do what collections.Counter does:

```<code>from collections import Counter

s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'

print(Counter(s))
</code>```

From there to get list of counts, use:

```<code>Counter(s).values()
</code>```

Title: Count the number of times each of the symbols appears in a string - python

Body:
You are trying to do what collections.Counter does:

from collections import Counter

s = 'AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC'

print(Counter(s))

From there to get list of counts, use:

Counter(s).values()


问:
gsutil make bucket command [gsutil mb] is not working
I am trying to create a bucket using gsutil mb command:

```<code>gsutil mb -c DRA -l US-CENTRAL1 gs://some-bucket-to-my-gs
</code>```

But I am getting this error message:

```<code>Creating gs://some-bucket-to-my-gs/...
BadRequestException: 400 Invalid argument.
</code>```

I am following the documentation from here

What is the reason for this type of error?

答:
I got the same error. I was because I used the wrong location.
The location parameter expects a region without specifying witch zone.

Eg.

```<code>sutil mb -p ${TF_ADMIN} -l europe-west1-b  gs://${TF_ADMIN}
</code>```

Should have been

```<code>sutil mb -p ${TF_ADMIN} -l europe-west1  gs://${TF_ADMIN}
</code>```

Body:
I am trying to create a bucket using gsutil mb command:

gsutil mb -c DRA -l US-CENTRAL1 gs://some-bucket-to-my-gs

But I am getting this error message:

Creating gs://some-bucket-to-my-gs/...
BadRequestException: 400 Invalid argument.

I am following the documentation from here

What is the reason for this type of error?

Body:
I got the same error. I was because I used the wrong location.
The location parameter expects a region without specifying witch zone.

Eg.

sutil mb -p ${TF_ADMIN} -l europe-west1-b  gs://${TF_ADMIN}

Should have been

sutil mb -p ${TF_ADMIN} -l europe-west1  gs://${TF_ADMIN}


问:
Windows 10 Kill EDB Postgres 8080 server
I want to kill and remove the software that uses the 8080 port that EDB Postgres localhost server so I can use the port for Jenkins.

Using tasklist it tells me the port which is processing, fine for kill the process, but where can I delete uninstall the software.

答: Just find the server named "PEM HTTPD" and turn it off.Also you can change its start mode to manual. </p>


问:
How to use an index on a list of values?
I have a query with a join on mytable unique indexed on (col1,col2)

```<code>explain
...
join mytable on col1=1 and col2=2
</code>```

shows the correct use of the index with type: eq_ref

But when using a list the index is not used anymore

```<code>join mytable on col1=1 and col2 in (2,3,4)
</code>```

Extra: Range checked for each record (index map: 0x1);

This gives the same result:

```<code>join mytable on (col1,col2) in ((1,2),(1,3),(1,4))
</code>```

Is there a way to use an index when providing a list of values?

答:
Normally one does not JOIN x ON c = constant.  The ON clause should specify how this table is related to the other table(s).  The WHERE clause should provide for filtering, such as col1=1 and col2=2.

"Row constructors" have long existed, but only recently (5.7.3) are they the least bit optimized.  What version are you running?  Even with the latest version, I would expect col1=1 and col2 in (2,3,4) to be optimized at least as well as the row-constructor approach.

OR often prevents any optimization.  And perhaps it is never faster than some alternative.

We need to see the entire query, the EXPLAIN, and SHOW CREATE TABLE; there could be other issue lurking in the shadows.

Body:
I have a query with a join on mytable unique indexed on (col1,col2)

explain
...
join mytable on col1=1 and col2=2

shows the correct use of the index with type: eq_ref

But when using a list the index is not used anymore

join mytable on col1=1 and col2 in (2,3,4)

Extra: Range checked for each record (index map: 0x1);

This gives the same result:

join mytable on (col1,col2) in ((1,2),(1,3),(1,4))

Is there a way to use an index when providing a list of values?


问:
Having trouble with this bootstrap header in react
i have bootstrap installed into my app but this video header that i am using is not showing correctly on my local server. so i guess the dependency is not working on my end.

CodePen https://codesandbox.io/s/react-hooks-counter-demo-8w7yv

I have downloaded bootstrap and it is showing in node modules it is working in sandbox but not on my server
    import React, { Component } from 'react'
    import {Link} from 'react-router-dom';

```<code>export default class Intro extends Component {
  render() {
    return (
      <header>
        <div className="overlay"></div>
        <video playsinline="playsinline" autoplay="autoplay" muted="muted" loop="loop">
          <source src="https://storage.googleapis.com/coverr-main/mp4/Mt_Baker.mp4" type="video/mp4"/>>
        </video>
        <div className="container h-100">
          <div className="d-flex h-100 text-center align-items-center">
            <div className="w-100 text-white">
              <h1 className="display-3">Video Header</h1>
              <p className="lead mb-0">With HTML5 Video and Bootstrap 4</p>
            </div>
          </div>
        </div>
      </header>
    )
  }
}
</code>```

答: Seems I didn't understand your question properly. But with your Code Pen, I replaced its content with your source code of video and see it works. Please check picture below

Body:
i have bootstrap installed into my app but this video header that i am using is not showing correctly on my local server. so i guess the dependency is not working on my end.

CodePen https://codesandbox.io/s/react-hooks-counter-demo-8w7yv

I have downloaded bootstrap and it is showing in node modules it is working in sandbox but not on my server
    import React, { Component } from 'react'
    import {Link} from 'react-router-dom';

export default class Intro extends Component {
  render() {
    return (

        <video playsinline="playsinline" autoplay="autoplay" muted="muted" loop="loop">
          <source src="https://storage.googleapis.com/coverr-main/mp4/Mt_Baker.mp4" type="video/mp4"/>>
        </video>

Video Header

With HTML5 Video and Bootstrap 4

    )
  }
}


问:
How to fit stat_summary to rectangle in ggplot?
I want to fit text from stat_summary to a rectangle in ggplot, so it adjusts automatically according to available space.

```<code>library(ggplot2)
category <- c('a','b','a','b','c','a','c')
values <- c(10,20,30,10,10,20,40)
dataset <- data.frame(category,values)
z = max(values)
stat_box_data <- function(y, upper_limit = z + 40) {
  return(
    data.frame(
      y = upper_limit,
      label = paste('Contagem =', paste(length(y)), '\n',
                    'Média =', paste(round(mean(y), 1),'horas'), '\n',
                    'Desvio =', paste(round(sd(y), 1),'horas'), '\n',
                    'Mínimo =', paste(round(min(y),1),'horas'), '\n',
                    'Máximo =', paste(round(max(y),1),'horas'), '\n',
                    'Mediana =', paste(round(median(y),1),'horas'), '\n',
                    'Total =', paste(round(sum(y),1),'horas'), '\n'
      )
    )
  )
}
ggplot(dataset,aes(x=category, y=values))+
  geom_rect(aes(x=category, y=values),xmin = 0, xmax = 10, ymin = z+10, ymax = z+50,col = 'white') +
geom_boxplot(aes(x=category, y=values))+
stat_summary(fun.data = stat_box_data, geom = "text", hjust = 0.5,vjust = 0.85) +

geom_point(aes(x=category, y=values))+
facet_grid(. ~ category, space = "free", scales="free", margins=TRUE)
</code>```

Is there a way for me to it?

There's this package: https://github.com/wilkox/ggfittext, but I can't make it work with stat_summary!

答:
The most recent version of ggfittext (version 0.8.1) makes this a lot easier. Once this is installed, it becomes quite straightforward to have the text automatically sized the way you want:

library(ggplot2)
library(ggfittext)
packageVersion("ggfittext")
#> [1] '0.8.1'

category <- c('a','b','a','b','c','a','c')
values <- c(10,20,30,10,10,20,40)
dataset <- data.frame(category,values)
z = max(values)
stat_box_data <- function(y, upper_limit = z + 40) {
  return(
    data.frame(
      y = upper_limit,
      label = paste('Contagem =', paste(length(y)), '\n',
                    'Média =', paste(round(mean(y), 1),'horas'), '\n',
                    'Desvio =', paste(round(sd(y), 1),'horas'), '\n',
                    'Mínimo =', paste(round(min(y),1),'horas'), '\n',
                    'Máximo =', paste(round(max(y),1),'horas'), '\n',
                    'Mediana =', paste(round(median(y),1),'horas'), '\n',
                    'Total =', paste(round(sum(y),1),'horas'), '\n'
      )
    )
  )
}

ggplot(dataset,aes(x = category, y = values))+
  geom_rect(xmin = 0, xmax = 10, ymin = 50, ymax = 80, col = "white") +
  geom_boxplot() +
  geom_fit_text(stat = "summary", fun.data = "stat_box_data", ymin = 50, ymax = 80) +
  geom_point() +
  facet_grid(. ~ category, space = "free", scales = "free", margins = TRUE)
```

Created on 2019-07-20 by the reprex package (v0.3.0)

Body:
I want to fit text from stat_summary to a rectangle in ggplot, so it adjusts automatically according to available space.

library(ggplot2)
category <- c('a','b','a','b','c','a','c')
values <- c(10,20,30,10,10,20,40)
dataset <- data.frame(category,values)
z = max(values)
stat_box_data <- function(y, upper_limit = z + 40) {
  return(
    data.frame(
      y = upper_limit,
      label = paste('Contagem =', paste(length(y)), '\n',
                    'Média =', paste(round(mean(y), 1),'horas'), '\n',
                    'Desvio =', paste(round(sd(y), 1),'horas'), '\n',
                    'Mínimo =', paste(round(min(y),1),'horas'), '\n',
                    'Máximo =', paste(round(max(y),1),'horas'), '\n',
                    'Mediana =', paste(round(median(y),1),'horas'), '\n',
                    'Total =', paste(round(sum(y),1),'horas'), '\n'
      )
    )
  )
}
ggplot(dataset,aes(x=category, y=values))+
  geom_rect(aes(x=category, y=values),xmin = 0, xmax = 10, ymin = z+10, ymax = z+50,col = 'white') +
geom_boxplot(aes(x=category, y=values))+
stat_summary(fun.data = stat_box_data, geom = "text", hjust = 0.5,vjust = 0.85) +

geom_point(aes(x=category, y=values))+
facet_grid(. ~ category, space = "free", scales="free", margins=TRUE)

Is there a way for me to it?

There's this package: https://github.com/wilkox/ggfittext, but I can't make it work with stat_summary!

Body:
The most recent version of ggfittext (version 0.8.1) makes this a lot easier. Once this is installed, it becomes quite straightforward to have the text automatically sized the way you want:

library(ggplot2)
library(ggfittext)
packageVersion("ggfittext")
#> [1] '0.8.1'

category <- c('a','b','a','b','c','a','c')
values <- c(10,20,30,10,10,20,40)
dataset <- data.frame(category,values)
z = max(values)
stat_box_data <- function(y, upper_limit = z + 40) {
  return(
    data.frame(
      y = upper_limit,
      label = paste('Contagem =', paste(length(y)), '\n',
                    'Média =', paste(round(mean(y), 1),'horas'), '\n',
                    'Desvio =', paste(round(sd(y), 1),'horas'), '\n',
                    'Mínimo =', paste(round(min(y),1),'horas'), '\n',
                    'Máximo =', paste(round(max(y),1),'horas'), '\n',
                    'Mediana =', paste(round(median(y),1),'horas'), '\n',
                    'Total =', paste(round(sum(y),1),'horas'), '\n'
      )
    )
  )
}

ggplot(dataset,aes(x = category, y = values))+
  geom_rect(xmin = 0, xmax = 10, ymin = 50, ymax = 80, col = "white") +
  geom_boxplot() +
  geom_fit_text(stat = "summary", fun.data = "stat_box_data", ymin = 50, ymax = 80) +
  geom_point() +
  facet_grid(. ~ category, space = "free", scales = "free", margins = TRUE)

Created on 2019-07-20 by the reprex package (v0.3.0)


问:
Pandas - Groupby and aggregate over multiple columns
I am trying to aggregate values in a groupby over multiple columns. I come from the R/dplyr world and what I want is usually achievable in a single line using group_by/summarize. I am trying to find an equivalently elegant way of achieving this using pandas.

Consider the below Input Dataset. I would like to aggregate by state and calculate the column v1 as v1 = sum(n1)/sum(d1) by state.

The r-code for this using dplyr is as follows:

input %>% group_by(state) %>%
  summarise(v1=sum(n1)/sum(d1),
            v2=sum(n2)/sum(d2))
```

<p>Is there an elegant way of doing this in Python? I found a slightly verbose way of getting what I want in on a stack overflow answer here.
Copying over modified <strong>python-code</strong> from the link</p>

<pre class="lang-py prettyprint-override"><code>In [14]: s = mn.groupby('state', as_index=False).sum()

In [15]: s['v1'] = s['n1'] / s['d1']

In [16]: s['v2'] = s['n2'] / s['d2']
In [17]: s[['state', 'v1', 'v2']]
</code>```

INPUT DATASET

```<code>state n1    n2     d1  d2
CA   100   1000    1   2
FL   200   2000    2   4
CA   300   3000    3   6
AL   400   4000    4   8
FL   500   5000    5   2
NY   600   6000    6   4
CA   700   7000    7   6
</code>```

OUTPUT

```<code>state   v1           v2
AL      100   500.000000
CA      100   500.000000
NY      100  1500.000000
CA      100  1166.666667
FL      100  1166.666667
</code>```

Body:
I am trying to aggregate values in a groupby over multiple columns. I come from the R/dplyr world and what I want is usually achievable in a single line using group_by/summarize. I am trying to find an equivalently elegant way of achieving this using pandas.

Consider the below Input Dataset. I would like to aggregate by state and calculate the column v1 as v1 = sum(n1)/sum(d1) by state.

The r-code for this using dplyr is as follows:

input %>% group_by(state) %>%
  summarise(v1=sum(n1)/sum(d1),
            v2=sum(n2)/sum(d2))

Is there an elegant way of doing this in Python? I found a slightly verbose way of getting what I want in on a stack overflow answer here.
Copying over modified python-code from the link

In [14]: s = mn.groupby('state', as_index=False).sum()

In [15]: s['v1'] = s['n1'] / s['d1']

In [16]: s['v2'] = s['n2'] / s['d2']
In [17]: s[['state', 'v1', 'v2']]

INPUT DATASET

state n1    n2     d1  d2
CA   100   1000    1   2
FL   200   2000    2   4
CA   300   3000    3   6
AL   400   4000    4   8
FL   500   5000    5   2
NY   600   6000    6   4
CA   700   7000    7   6

OUTPUT

state   v1           v2
AL      100   500.000000
CA      100   500.000000
NY      100  1500.000000
CA      100  1166.666667
FL      100  1166.666667

Body:
Another solution:

def func(x):
    u = x.sum()
    return pd.Series({'v1':u['n1']/u['d1'],
                      'v2':u['n2']/u['d2']})

df.groupby('state').apply(func)

Output:

         v1     v2
state
AL      100.0   500.000000
CA      100.0   785.714286
FL      100.0   1166.666667
NY      100.0   1500.000000


问:
What is the proper way to config multimaster on postgresql db's via SymmetricDS?
I'm tryig to config multimaster replication between separated postgresql db's. The best non-commercial solution I found is SymmetricDS, but I can't figure out how to config it. Its documentation says alot about abstract concepts, but after reading it I still don't understand what I actually have to do. Maybe there are someone who had had the same probleme and could tell me in general steps how I can make this thing work?</p>

答: Download the latest version. Then follow the step-by-step quick guide from the first chapter http://www.symmetricds.org/doc/3.10/html/tutorials.html#_demo on how to establish a two node replication. When it started working add a column to one of the tables, recreate the triggers and see how it gets synced. Then create a new table, declare a new trigger for it, associate it to an existing router, restart and enjoy it gets syncing.</p>


问:
SVGPanZoom discards original viewBox
I am using SVGPanZoom to manage the zooming of an SVG image in my hybrid Android (for all intents and purposes the same behavior as in Chrome) app.  While zooming works well I have found a strange issue.  My original inline SVG element goes like this

```<code> <svg id='puzzle' viewBox='0 0 1600 770' preserveAspectRatio='none'
  width='100vw' height='85.5vh' fill-rule='evenodd' clip-rule='evenodd'
  stroke-linejoin='round' stroke-miterlimit='1.414'
  xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://
  www.w3.org/1999/xlink'>
</code>```

Initially this SVG element is empty and gets populated programmatically from JavaScript at run time after which I initiate SVGPanZoom as follows

```<code>var panZoom = svgPanZoom('#puzzle',
{panEnabled:false,controlIconsEnabled:false,
zoomEnabled:true,dblClickZoomEnabled:true,onZoom:postZoom});

panZoom.refreshRate = 10;
panZoom.zoomScaleSensitivity = 0.02;
</code>```

The problem I have run into is this - I want my SVG image to fill the available area, 100vw x 85.5vhcompletely to do which I instruct it via the preserveAspectRatio="none"attribute above along with the viewBox="0 0 1600 770" attribute.  I have found that this works - so long as I don't use SVGPanZoom. As soon as I initiate panZoom thezoomBox`attribute gets stripped out and I end up with an image that does not quite behave in terms of its default stretching/filling behavior.

SVGPanZoom is widely used so I assume that this behavior is down to me not quite setting it up properly.  Dipping into the code I have found SVGPanZoom creates a cacheViewBoxand then proceeds to remove the original zoomBox attribute.

Which is fine if after that zooming works and the original behavior of the application does not change which is not what I find.  What am I doing wrong here?

答:
A note for anyone running into this thread.  In the end I abandoned SVGPanZoom and decided to eschew the route of using any pan/zoom library at all.  At the same time I decided to completely stop using the SVG viewBox and handle all zooming/panning entirely on my own through SVG transforms.  The core steps involved

Wrap the entire SVG contents in a group to make it easier to manage the transform. I use the id attribute gOuter for this group

Set an initial scale for the SVG to occupy the desired client rectangle.  In my case I had an original viewBox of 0 0 1600 770 intended to occupy 100% of screen width and 85% of screen height.  So my scaling was scaleX = 1600/window.innerWidth and scaleY = 770/)0.85*window.innerHeight).

Apply this initial transform to the wrapping outer group, gOuter.setAttribute('transform','0 0 scaleX,scaleY)

Now in order to zoom to a an object whose virtual top left hand coordinates in the original viewBox were Ox,Oy you would use the transform

gOuter.setAttribute('transform',

 scale(scaleX,scaleY) translate(-Ox,-Oy) scale(2*scaleX,2*scaleY) translate(Ox,Oy))

to zoom in by a factor of x 2.  The important things to understand here

In SVG transformations are applied right to left.

Here we are translating the zoom point to the top l.h.s. scaling and then translating it back to its original location.

The problem is that we also need to allow for the original level of zoom through the initial scaling so we tag that on as one last transform

This leaves you in complete control of the zooming process and as a fringe benefit the operation becomes considerably more smooth than when using a pan/zoom library.

Title: SVGPanZoom discards original viewBox

Body:
I am using SVGPanZoom to manage the zooming of an SVG image in my hybrid Android (for all intents and purposes the same behavior as in Chrome) app.  While zooming works well I have found a strange issue.  My original inline SVG element goes like this

 <svg id='puzzle' viewBox='0 0 1600 770' preserveAspectRatio='none'
  width='100vw' height='85.5vh' fill-rule='evenodd' clip-rule='evenodd'
  stroke-linejoin='round' stroke-miterlimit='1.414'
  xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://
  www.w3.org/1999/xlink'>

Initially this SVG element is empty and gets populated programmatically from JavaScript at run time after which I initiate SVGPanZoom as follows

var panZoom = svgPanZoom('#puzzle',
{panEnabled:false,controlIconsEnabled:false,
zoomEnabled:true,dblClickZoomEnabled:true,onZoom:postZoom});

panZoom.refreshRate = 10;
panZoom.zoomScaleSensitivity = 0.02;

The problem I have run into is this - I want my SVG image to fill the available area, 100vw x 85.5vhcompletely to do which I instruct it via the preserveAspectRatio="none"attribute above along with the viewBox="0 0 1600 770" attribute.  I have found that this works - so long as I don't use SVGPanZoom. As soon as I initiate panZoom thezoomBox`attribute gets stripped out and I end up with an image that does not quite behave in terms of its default stretching/filling behavior.

SVGPanZoom is widely used so I assume that this behavior is down to me not quite setting it up properly.  Dipping into the code I have found SVGPanZoom creates a cacheViewBoxand then proceeds to remove the original zoomBox attribute.

Which is fine if after that zooming works and the original behavior of the application does not change which is not what I find.  What am I doing wrong here?


问:
How to convert a Gregorian date to an Islamic (Hijri) date without the time?
See SO 15728744 and SO 51058875.

How can the following be correct:

LocalDate gregorianDate = LocalDate.parse(gregorianString, dateFormatter);
HijrahDate islamicDate = HijrahDate.from(gregorianDate);
```

I thought that the Hijri day ends at sunset, not at midnight, so a gregorianDateTime should have been required.

答:
You are right that the Hijri calendar starts days at sunset on previous western day. You are also right to say that standard Java does not support it.

Why?

I have searched in old Threeten-archives but found nothing. However, the main developer and architect of java.time-API has once stated in the documentation of the ancestor Joda-Time following sentence:

This implementation defines a day as midnight to midnight exactly as
  per the ISO chronology. This correct start of day is at sunset on the
  previous day, however this cannot readily be modelled and has been
  ignored.

My speculation is: The same motivation was also responsible why java.time does not take into account the time of day in conversions to or from islamic calendar. It is difficult to implement mainly because it requires astronomical calculations.

How to handle this deficiency?

In the scope of standard Java, users are advised to ignore the time of day as much as possible. So please keep in mind that such conversions are time-free abstractions. Of course, if you want to determine the CURRENT day (which indirectly involves the time of day and civil time zone) then such conversions are more or less faulty!

If you don't want to ignore sunset as start of day...

... then you can use my library Time4J (and I don't know any other lib which can handle sunset as start of day). Watch out the documentation of class HijriCalendar. Example for a generic conversion from a moment/instant to a Hijri calendar date:

```<code>// the geographic location
SolarTime meccaTime = SolarTime.ofLocation(21.4225, 39.826111);
// or even simple: meccaTime = SolarTime.ofMecca()

// the moment to be converted
Moment now = SystemClock.currentTime();
// alternative using an explicit gregorian date:
//   now = PlainDate.of(2019, 5, 26).atTime(18, 45).inStdTimezone();
// alternative using modern Java:
//   now = Moment.from(Instant.now());
// alternative using outdated old API:
//   java.util.Date instant = new java.util.Date();
//   now = TemporalType.JAVA_UTIL_DATE.translate(instant);

// the conversion
HijriCalendar hcal = now.toGeneralTimestamp(
  HijriCalendar.family(),
  HijriCalendar.VARIANT_UMALQURA, // attention: there is no single islamic calendar
  Timezone.ofSystem().getID(), // or use something like: ()-> "Europe/London"
  StartOfDay.definedBy(meccaTime.sunset()));
</code>```

Time4J also contains a format engine which is capable of parsing either gregorian dates or Hijri calendar date-times in many ways. The start of day at sunset can be taken into account also during formatting and parsing based on ChronoFormatter.

The reverse conversion from a Hijri calendar date to a moment is also supported. Example:

```<code>HijriCalendar hcal = ...;
Moment m =
  hcal.atTime(18, 45).in(Timezone.ofSystem(), StartOfDay.definedBy(meccaTime.sunset()));
</code>```

Body:
See SO 15728744 and SO 51058875.

How can the following be correct:

LocalDate gregorianDate = LocalDate.parse(gregorianString, dateFormatter);
HijrahDate islamicDate = HijrahDate.from(gregorianDate);

I thought that the Hijri day ends at sunset, not at midnight, so a gregorianDateTime should have been required.

Body:
You are right that the Hijri calendar starts days at sunset on previous western day. You are also right to say that standard Java does not support it.

Why?

I have searched in old Threeten-archives but found nothing. However, the main developer and architect of java.time-API has once stated in the documentation of the ancestor Joda-Time following sentence:

This implementation defines a day as midnight to midnight exactly as
  per the ISO chronology. This correct start of day is at sunset on the
  previous day, however this cannot readily be modelled and has been
  ignored.

My speculation is: The same motivation was also responsible why java.time does not take into account the time of day in conversions to or from islamic calendar. It is difficult to implement mainly because it requires astronomical calculations.

How to handle this deficiency?

In the scope of standard Java, users are advised to ignore the time of day as much as possible. So please keep in mind that such conversions are time-free abstractions. Of course, if you want to determine the CURRENT day (which indirectly involves the time of day and civil time zone) then such conversions are more or less faulty!

If you don't want to ignore sunset as start of day...

... then you can use my library Time4J (and I don't know any other lib which can handle sunset as start of day). Watch out the documentation of class HijriCalendar. Example for a generic conversion from a moment/instant to a Hijri calendar date:

// the geographic location
SolarTime meccaTime = SolarTime.ofLocation(21.4225, 39.826111);
// or even simple: meccaTime = SolarTime.ofMecca()

// the moment to be converted
Moment now = SystemClock.currentTime();
// alternative using an explicit gregorian date:
//   now = PlainDate.of(2019, 5, 26).atTime(18, 45).inStdTimezone();
// alternative using modern Java:
//   now = Moment.from(Instant.now());
// alternative using outdated old API:
//   java.util.Date instant = new java.util.Date();
//   now = TemporalType.JAVA_UTIL_DATE.translate(instant);

// the conversion
HijriCalendar hcal = now.toGeneralTimestamp(
  HijriCalendar.family(),
  HijriCalendar.VARIANT_UMALQURA, // attention: there is no single islamic calendar
  Timezone.ofSystem().getID(), // or use something like: ()-> "Europe/London"
  StartOfDay.definedBy(meccaTime.sunset()));

Time4J also contains a format engine which is capable of parsing either gregorian dates or Hijri calendar date-times in many ways. The start of day at sunset can be taken into account also during formatting and parsing based on ChronoFormatter.

The reverse conversion from a Hijri calendar date to a moment is also supported. Example:

HijriCalendar hcal = ...;
Moment m =
  hcal.atTime(18, 45).in(Timezone.ofSystem(), StartOfDay.definedBy(meccaTime.sunset()));


问:
It is currently in use by another Gradle instance
I want to do some basic functions. I'm running/building it in command line. I am referring User guide. And, doing some simple tasks.

When I start to run simple tasks, it was build successfully. But, After some times, it is showing "It is currently in use by another Gradle instance" and becomes BUILD FAILED. I'm using a terminal for run the task. I didn't run anything at that time.

If I closed the terminal which generate the error, this problem would be solved. But, I know that it is not the solution for that.

Why is this error coming frequently?

How to solve it?

And, Please refer any link to improve my knowledge on Gradle Build system in Android.

答:
Sometimes fast way comes in a non-elegant deal, there we go:

Find first the # of all gradle process running on

```<code>ps -A | grep gradle
</code>```

After that, get the IDs, Kill 'em all one by one

```<code>sudo kill -9 <process ID>
</code>```

Now you're good ;-)

Body:
Sometimes fast way comes in a non-elegant deal, there we go:

Find first the # of all gradle process running on

ps -A | grep gradle

After that, get the IDs, Kill 'em all one by one

sudo kill -9 <process ID>

Now you're good ;-)


问:
What does hg copy do?
We recently did a hg copy of a directory in our repository. We thought it
does something like cp -a and hg add and maybe flag somehow that
this file has been copied from another file inside the repo (so hg
annotate shows the original committer). But it now seems that hg
copy does more or different stuff than that. I couldn't really find
much on how exactly copy works. So:

What exactly does hg copy do and what special treatment does this
cause in the future?

If it turns out to do "the wrong thing(tm)" for our case, how do I
unflag the file as beeing a copy of another file?

(This question was asked on the Mercurial mailinglist, you may want to follow the original thread too.)

答:
How do I unflag the file as being a copy of another file?

If you revert a hg copy, the copied-to file remains in your working directory afterwards, untracked. You just have to add it normally.
The copied-from file isn't affected at all.

```<code>% hg copy file new-file
% hg status -C
A new-file
__file
% hg revert new-file
% hg add new-file
% hg status -C
A new-file
</code>```

Reference: Mercurial: The definitive guide

Title: What does hg copy do?

Body:
How do I unflag the file as being a copy of another file?

If you revert a hg copy, the copied-to file remains in your working directory afterwards, untracked. You just have to add it normally.
The copied-from file isn't affected at all.

% hg copy file new-file
% hg status -C
A new-file
__file
% hg revert new-file
% hg add new-file
% hg status -C
A new-file

Reference: Mercurial: The definitive guide


问:
Updating Ember.js environment variables do not take effect using in-repo addon config() method on ember serve
My goal here is to create an auto-increment build number that updates both on ember build and ember serve.  In the end, if I can only use this on build, that's totally ok.

I originally asked this question:
In-repo addon writing public files on build causes endless build loop on serve
In that I was attempting to solve this problem by writing out JSON files. The problem was mostly solved, but not using ember serve.

Instead of doing that, I'm now trying to update the local environment. But this is having a similar problem with ember serve. I've got the build number incrementing fine.  I can use the config() method to set custom/dynamic variables in the environment.  The problem I'm having is that the even though I can log the change in terminal when config() is called, and I can see it run on serve when files change, I don't see the changes in browser when I output Ember's ENV using ember serve.  Here's my addon's methods so far.

Note: the appNumberSetup() function is just reading a local json file in the project root and updating the build number.  That's working fine.  Anything about pubSettingsFile can be ignored, I won't be using that moving forward.

```<code>init(parent, project) {
    this._super.init && this._super.init.apply(this, arguments);
    // we need to setup env in init() so config() and prebuild()
    // will see update immediately
    this.settingsFile = path.resolve(this.appDir,  this.settingsFileName);
    this.addonPubDataPath = path.resolve(this.appDir, 'lib', this.name, 'inc', 'public', 'build-data-output');
    this.pubSettingsFile = path.resolve(this.addonPubDataPath,  this.pubSettingsFileName);
    // this only checks for .env variables and sets defaults
    this.dotEnvSetup();
    // must set this so prebuild skips processing a build number on build
    // else we get build number incremented twice on first run
    // then appNumberSetup() disables so subsequent serve preBuild() will run.
    this.skipPreBuild = true;
    this.appNumberSetup();

},
// this sends our created settings data to ENV.localBuildSettings in app
config(environment, appConfig){
    // this 'buildme' is just an experiment
    let x = `buildme${this.buildNumber}`;
    let r = {
        localBuildSettings: this.settings
    };
    r[`buildme${this.buildNumber}`] = this.buildNumber;
    this.dlog("Config ran...");
    this.dlog(JSON.stringify(r, null, 4));
    return r;
},
preBuild: function(result){
    // init() disables preBuild() here, but subsequent builds with serve still
    // run appNumberSetup() to update this.settings for env and JSON
    if(this.skipPreBuild === true){
        this.skipPreBuild = false;
    }
    else {
        // only run here after init runs
        this.appNumberSetup();
    }
    // don't do this... write file makes endless loop on serve
    // this.saveSettingsFile(this.pubSettingsFile, this.settings);

},
</code>```

this.settings is a local variable in addon and it updated on build/serve, the JSON looks like this:

```<code>{
"appVersion": 911,
"appBuildNumber": 7117
}
</code>```

Is there a way to update Ember's ENV with dynamic data? (like a new build number)

The addon config() appears to run on each change in ember serve, and it shows the build number in terminal output. But it looks like that runs after postBuild().  Maybe that's why I don't see the changes.  Is there a way to update that environment during preBuild()?

答: I'm not sure of the specifics but ember-cli-new-version does this. During the build stage they create a VERSION.txt file, might even do what you need already without needing to write it yourself.</p>

Body:
My goal here is to create an auto-increment build number that updates both on ember build and ember serve.  In the end, if I can only use this on build, that's totally ok.

I originally asked this question:
In-repo addon writing public files on build causes endless build loop on serve
In that I was attempting to solve this problem by writing out JSON files. The problem was mostly solved, but not using ember serve.

Instead of doing that, I'm now trying to update the local environment. But this is having a similar problem with ember serve. I've got the build number incrementing fine.  I can use the config() method to set custom/dynamic variables in the environment.  The problem I'm having is that the even though I can log the change in terminal when config() is called, and I can see it run on serve when files change, I don't see the changes in browser when I output Ember's ENV using ember serve.  Here's my addon's methods so far.

Note: the appNumberSetup() function is just reading a local json file in the project root and updating the build number.  That's working fine.  Anything about pubSettingsFile can be ignored, I won't be using that moving forward.

init(parent, project) {
    this._super.init && this._super.init.apply(this, arguments);
    // we need to setup env in init() so config() and prebuild()
    // will see update immediately
    this.settingsFile = path.resolve(this.appDir,  this.settingsFileName);
    this.addonPubDataPath = path.resolve(this.appDir, 'lib', this.name, 'inc', 'public', 'build-data-output');
    this.pubSettingsFile = path.resolve(this.addonPubDataPath,  this.pubSettingsFileName);
    // this only checks for .env variables and sets defaults
    this.dotEnvSetup();
    // must set this so prebuild skips processing a build number on build
    // else we get build number incremented twice on first run
    // then appNumberSetup() disables so subsequent serve preBuild() will run.
    this.skipPreBuild = true;
    this.appNumberSetup();

},
// this sends our created settings data to ENV.localBuildSettings in app
config(environment, appConfig){
    // this 'buildme' is just an experiment
    let x = `buildme${this.buildNumber}`;
    let r = {
        localBuildSettings: this.settings
    };
    r[`buildme${this.buildNumber}`] = this.buildNumber;
    this.dlog("Config ran...");
    this.dlog(JSON.stringify(r, null, 4));
    return r;
},
preBuild: function(result){
    // init() disables preBuild() here, but subsequent builds with serve still
    // run appNumberSetup() to update this.settings for env and JSON
    if(this.skipPreBuild === true){
        this.skipPreBuild = false;
    }
    else {
        // only run here after init runs
        this.appNumberSetup();
    }
    // don't do this... write file makes endless loop on serve
    // this.saveSettingsFile(this.pubSettingsFile, this.settings);

},

this.settings is a local variable in addon and it updated on build/serve, the JSON looks like this:

{
"appVersion": 911,
"appBuildNumber": 7117
}

Is there a way to update Ember's ENV with dynamic data? (like a new build number)

The addon config() appears to run on each change in ember serve, and it shows the build number in terminal output. But it looks like that runs after postBuild().  Maybe that's why I don't see the changes.  Is there a way to update that environment during preBuild()?


问:
UI5 Message box customize Button
I need help to update button (OK) text on Message box I am using library sap.ca.ui.message

```<code>sap.ca.ui.message.showMessageBox({
    type: sap.ca.ui.message.Type.ERROR,
    message: "Erro Text Message",
}, function(){});
</code>```

How can I access the button in the message box. Basically I'm looking from a translation perspective. Here in this message box I am able to translate title and message text, but I am unable to translate the OK button text.

答:
the translation texts are in a resource bundle and you can alter the value accordingly. like this

```<code>sap.ui.define(["sap/m/Button", "sap/m/MessageBox"], function(Button, MessageBox) {
  var rb = sap.ui.getCore().getLibraryResourceBundle("sap.m");
  rb.aPropertyFiles[0].mProperties["MSGBOX_YES"] = "OOO";
  rb.aPropertyFiles[0].mProperties["MSGBOX_CANCEL"] = "Katkesta";

  var oButton = new Button({
    text: "Press",
    press: function() {

      MessageBox.show("This message should appear in the message box.", {
        icon: MessageBox.Icon.INFORMATION,
        title: "My message box title",
        actions: [MessageBox.Action.YES, MessageBox.Action.CANCEL],
        onClose: function(oAction) {
        }
      });
    }
  });
  oButton.placeAt("content");
});
</code>```

https://jsbin.com/qumiweg/edit?js,output

Title: UI5 Message box customize Button

Body:
I need help to update button (OK) text on Message box I am using library sap.ca.ui.message

sap.ca.ui.message.showMessageBox({
    type: sap.ca.ui.message.Type.ERROR,
    message: "Erro Text Message",
}, function(){});

How can I access the button in the message box. Basically I'm looking from a translation perspective. Here in this message box I am able to translate title and message text, but I am unable to translate the OK button text.

Body:
the translation texts are in a resource bundle and you can alter the value accordingly. like this

sap.ui.define(["sap/m/Button", "sap/m/MessageBox"], function(Button, MessageBox) {
  var rb = sap.ui.getCore().getLibraryResourceBundle("sap.m");
  rb.aPropertyFiles[0].mProperties["MSGBOX_YES"] = "OOO";
  rb.aPropertyFiles[0].mProperties["MSGBOX_CANCEL"] = "Katkesta";

  var oButton = new Button({
    text: "Press",
    press: function() {

      MessageBox.show("This message should appear in the message box.", {
        icon: MessageBox.Icon.INFORMATION,
        title: "My message box title",
        actions: [MessageBox.Action.YES, MessageBox.Action.CANCEL],
        onClose: function(oAction) {
        }
      });
    }
  });
  oButton.placeAt("content");
});

https://jsbin.com/qumiweg/edit?js,output


问:
Is there any method to make computeds columns have 2 parameters as range?
I'm trying to create a procedure where, declared the variables initialized and having created a computed column, the average value has the variables @ efinal1 and @ efinal2 as ranges

create proc sppromediorango

@efinal1 int=0,--min value
@efinal2 int=10--max value
as
begin
--here i make a computed column for getting the average score
select ([ScoreEParcial]*0.4+[ScoreEFinal]*0.6)as averagescore
from [dbo].[tbAlumnos] a inner join [dbo].[tbScore] c
on (a.aluID=c.ScoreAluID)
--here i´m looking for a correct method
where  averagescore between @efinal1 and @efinal2

end
go
```

I´m expecting an output having @efinal1 and @efinal2 as range

答:
You can't use aliases from the select clause in the where clause.

You need to either use a derived table or a common table expression. (the only difference in this case is readability):

```<code>create proc sppromediorango

    @efinal1 int=0,--min value
    @efinal2 int=10--max value
as
begin

    select averagescore
    from
    (
        select ([ScoreEParcial]*0.4+[ScoreEFinal]*0.6)as averagescore
        from [dbo].[tbAlumnos] a
        inner join [dbo].[tbScore] c
        on (a.aluID=c.ScoreAluID)
    ) As derived
    where  averagescore between @efinal1 and @efinal2

end
go
</code>```

Body:
I'm trying to create a procedure where, declared the variables initialized and having created a computed column, the average value has the variables @ efinal1 and @ efinal2 as ranges

create proc sppromediorango

@efinal1 int=0,--min value
@efinal2 int=10--max value
as
begin
--here i make a computed column for getting the average score
select ([ScoreEParcial]*0.4+[ScoreEFinal]*0.6)as averagescore
from [dbo].[tbAlumnos] a inner join [dbo].[tbScore] c
on (a.aluID=c.ScoreAluID)
--here i´m looking for a correct method
where  averagescore between @efinal1 and @efinal2

end
go

I´m expecting an output having @efinal1 and @efinal2 as range

Body:
You can't use aliases from the select clause in the where clause.

You need to either use a derived table or a common table expression. (the only difference in this case is readability):

create proc sppromediorango

    @efinal1 int=0,--min value
    @efinal2 int=10--max value
as
begin

    select averagescore
    from
    (
        select ([ScoreEParcial]*0.4+[ScoreEFinal]*0.6)as averagescore
        from [dbo].[tbAlumnos] a
        inner join [dbo].[tbScore] c
        on (a.aluID=c.ScoreAluID)
    ) As derived
    where  averagescore between @efinal1 and @efinal2

end
go


问:
HttpErrorResponse in Ionic Angular
I'm trying to work with Ionic (first attempt) and somehow I'm not able to get my data in my view

Code

Service (posts.service.ts)

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class PostsService {

  apiUrl = 'https://example.com/api/posts/';
  url: any;

  constructor(private http: HttpClient) { }

  getPosts(): Observable<any> {
    return this.http.get(`${this.apiUrl}`).pipe(
      map(posts => posts)
    );
  }

  getDetails(url) {
    return this.http.get(`${this.url}?i=${url}&plot=full`);
  }
}
</code>```

Controller (posts.page.ts)

```<code>import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { PostsService } from './../../services/posts.service';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.page.html',
  styleUrls: ['./posts.page.scss'],
})
export class PostsPage implements OnInit {

  posts: Observable<any>;

  constructor(private postsService: PostsService) {}

  ngOnInit() {
  }

}
</code>```

view (posts.page.html)

```<code><ion-list>
  <ion-item *ngFor="let post of posts">
    <div slot="start"></div>
    <img [src]="post.image" />
    {{post.title}}
    <div class="item-note" slot="end">
      {{post.body}}
    </div>
  </ion-item>
</ion-list>
</code>```

Output

Live API

My APP

Any idea where I did mistake?

答:
SOLVED

Please refer to my other question which solved this problem.

Ionic can't get open cors

Title: HttpErrorResponse in Ionic Angular

Body:
I'm trying to work with Ionic (first attempt) and somehow I'm not able to get my data in my view

Code

Service (posts.service.ts)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class PostsService {

  apiUrl = 'https://example.com/api/posts/';
  url: any;

  constructor(private http: HttpClient) { }

  getPosts(): Observable<any> {
    return this.http.get(`${this.apiUrl}`).pipe(
      map(posts => posts)
    );
  }

  getDetails(url) {
    return this.http.get(`${this.url}?i=${url}&plot=full`);
  }
}

Controller (posts.page.ts)

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { PostsService } from './../../services/posts.service';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.page.html',
  styleUrls: ['./posts.page.scss'],
})
export class PostsPage implements OnInit {

  posts: Observable<any>;

  constructor(private postsService: PostsService) {}

  ngOnInit() {
  }

}

view (posts.page.html)

<ion-list>
  <ion-item *ngFor="let post of posts">

    {{post.title}}

      {{post.body}}

  </ion-item>
</ion-list>

Output

Live API

My APP

Any idea where I did mistake?


问:
how to calculate entropy on float numbers over a tensor in python keras
I have been struggling on this and could not get it to work. hope someone can help me with this.

I want to calculate the entropy on each row of the tensor. Because my data are float numbers not integers I think I need to use bin_histogram.

For example a sample of my data is tensor =[[0.2, -0.1, 1],[2.09,-1.4,0.9]]

Just for information My model is seq2seq and written in keras with tensorflow backend.

This is my code so far: I need to correct rev_entropy

```<code>class entropy_measure(Layer):

    def __init__(self, beta,batch, **kwargs):
        self.beta = beta
        self.batch = batch
        self.uses_learning_phase = True
        self.supports_masking = True
        super(entropy_measure, self).__init__(**kwargs)

    def call(self, x):
        return K.in_train_phase(self.rev_entropy(x, self.beta,self.batch), x)

    def get_config(self):
        config = {'beta': self.beta}
        base_config = super(entropy_measure, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

    def rev_entropy(self, x, beta,batch):

        for i in x:
            i = pd.Series(i)
            p_data = i.value_counts()  # counts occurrence of each value
            entropy = entropy(p_data)  # get entropy from counts
            rev = 1/(1+entropy)
            return rev

        new_f_w_t = x * (rev.reshape(rev.shape[0], 1))*beta

        return new_f_w_t
</code>```

Any input is much appreciated:)

答:
It looks like you have a series of questions that come together on this issue. I'll settle it here.

You calculate entropy in the following form of scipy.stats.entropy according to your code:

scipy.stats.entropy(pk, qk=None, base=None)

Calculate the entropy of a distribution for given probability values.

If only probabilities pk are given, the entropy is calculated as S =
  -sum(pk * log(pk), axis=0).

Tensorflow does not provide a direct API to calculate entropy on each row of the tensor. What we need to do is to implement the above formula.

```<code>import tensorflow as tf
import pandas as pd
from scipy.stats import entropy

a = [1.1,2.2,3.3,4.4,2.2,3.3]
res = entropy(pd.value_counts(a))

_, _, count = tf.unique_with_counts(tf.constant(a))
# [1 2 2 1]
prob = count / tf.reduce_sum(count)
# [0.16666667 0.33333333 0.33333333 0.16666667]
tf_res = -tf.reduce_sum(prob * tf.log(prob))

with tf.Session() as sess:
    print('scipy version: \n',res)
    print('tensorflow version: \n',sess.run(tf_res))

scipy version:
 1.329661348854758
tensorflow version:
 1.3296613488547582
</code>```

Then we need to define a function and achieve for loop through tf.map_fn in your custom layer according to above code.

```<code>def rev_entropy(self, x, beta,batch):
    def row_entropy(row):
        _, _, count = tf.unique_with_counts(row)
        prob = count / tf.reduce_sum(count)
        return -tf.reduce_sum(prob * tf.log(prob))

    value_ranges = [-10.0, 100.0]
    nbins = 50
    new_f_w_t = tf.histogram_fixed_width_bins(x, value_ranges, nbins)
    rev = tf.map_fn(row_entropy, new_f_w_t,dtype=tf.float32)

    new_f_w_t = x * 1/(1+rev)*beta

    return new_f_w_t
</code>```

Notes that the hidden layer will not produce a gradient that cannot propagate backwards since entropy is calculated on the basis of statistical probabilistic values. Maybe you need to rethink your hidden layer structure.

Body:
I have been struggling on this and could not get it to work. hope someone can help me with this.

I want to calculate the entropy on each row of the tensor. Because my data are float numbers not integers I think I need to use bin_histogram.

For example a sample of my data is tensor =[[0.2, -0.1, 1],[2.09,-1.4,0.9]]

Just for information My model is seq2seq and written in keras with tensorflow backend.

This is my code so far: I need to correct rev_entropy

class entropy_measure(Layer):

    def __init__(self, beta,batch, **kwargs):
        self.beta = beta
        self.batch = batch
        self.uses_learning_phase = True
        self.supports_masking = True
        super(entropy_measure, self).__init__(**kwargs)

    def call(self, x):
        return K.in_train_phase(self.rev_entropy(x, self.beta,self.batch), x)

    def get_config(self):
        config = {'beta': self.beta}
        base_config = super(entropy_measure, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

    def rev_entropy(self, x, beta,batch):

        for i in x:
            i = pd.Series(i)
            p_data = i.value_counts()  # counts occurrence of each value
            entropy = entropy(p_data)  # get entropy from counts
            rev = 1/(1+entropy)
            return rev

        new_f_w_t = x * (rev.reshape(rev.shape[0], 1))*beta

        return new_f_w_t

Any input is much appreciated:)

Body:
It looks like you have a series of questions that come together on this issue. I'll settle it here.

You calculate entropy in the following form of scipy.stats.entropy according to your code:

scipy.stats.entropy(pk, qk=None, base=None)

Calculate the entropy of a distribution for given probability values.

If only probabilities pk are given, the entropy is calculated as S =
  -sum(pk * log(pk), axis=0).

Tensorflow does not provide a direct API to calculate entropy on each row of the tensor. What we need to do is to implement the above formula.

import tensorflow as tf
import pandas as pd
from scipy.stats import entropy

a = [1.1,2.2,3.3,4.4,2.2,3.3]
res = entropy(pd.value_counts(a))

_, _, count = tf.unique_with_counts(tf.constant(a))
# [1 2 2 1]
prob = count / tf.reduce_sum(count)
# [0.16666667 0.33333333 0.33333333 0.16666667]
tf_res = -tf.reduce_sum(prob * tf.log(prob))

with tf.Session() as sess:
    print('scipy version: \n',res)
    print('tensorflow version: \n',sess.run(tf_res))

scipy version:
 1.329661348854758
tensorflow version:
 1.3296613488547582

Then we need to define a function and achieve for loop through tf.map_fn in your custom layer according to above code.

def rev_entropy(self, x, beta,batch):
    def row_entropy(row):
        _, _, count = tf.unique_with_counts(row)
        prob = count / tf.reduce_sum(count)
        return -tf.reduce_sum(prob * tf.log(prob))

    value_ranges = [-10.0, 100.0]
    nbins = 50
    new_f_w_t = tf.histogram_fixed_width_bins(x, value_ranges, nbins)
    rev = tf.map_fn(row_entropy, new_f_w_t,dtype=tf.float32)

    new_f_w_t = x * 1/(1+rev)*beta

    return new_f_w_t

Notes that the hidden layer will not produce a gradient that cannot propagate backwards since entropy is calculated on the basis of statistical probabilistic values. Maybe you need to rethink your hidden layer structure.


问:
how to update Bidirectional @OneToMany relationship
I have Employee and Functions, Bank classes
Employee and Function have @OneToMany relationship and
Employee and Bank have also @OneToMany relationship.
if the user edits the form and change the function and/or bank
I want to update the relationship. but when I change the relationship
I get Duplicate entry  exception due to the uniqueness of a column because
the Employee object persisted as a new entity

I tried to remove the employee from the function and set the employee's function to null and get a new function and add the employee to it
and set the new function but it doesn't work. any idea, please

```<code>@Entity
public class Employee extends GeneratedIdEntity<Long> {
   @ManyToOne(optional = false)
   private Functions function;

   @ManyToOne(optional = false)
   private Bank bank;

   @OneToMany(
           mappedBy = "employee",
           fetch = LAZY,
           cascade = ALL,
           orphanRemoval = true
   )
   private List<RubricValue> rubricsValues = new ArrayList<>();

   @OneToMany(
           mappedBy = "employee",
           fetch = LAZY,
           cascade = ALL,
           orphanRemoval = true
   )
   List<EmployeeStatus> employeesStatus=new ArrayList<>();
}
</code>```

```<code>@Entity
public class Functions extends GeneratedIdEntity<Long>{
    @OneToMany(
            mappedBy = "function",
            fetch = LAZY,
            cascade = ALL,
            orphanRemoval = true
    )
    private List<Employee> employees=new ArrayList<>();

    public void addEmployee(Employee employee ){
        employees.add(employee);
    }
    public void removeEmployee(Employee employee){
        employees.remove(employee);
    }
}
</code>```

```<code>@Entity
public class Bank extends GeneratedIdEntity<Long> {
   @OneToMany(
           mappedBy = "bamk",
           fetch = LAZY,
           cascade = ALL,
           orphanRemoval = true
   )
   private List<Employee> employees = new ArrayList<>();

   public void addEmployee(Employee employee ){
       employees.add(employee);
   }
   public void removeEmployee(Employee employee){
       employees.remove(employee);
   }
}
</code>```

```<code>@Stateless
public class EmployeeService extends BaseEntityService<Long, Employee> {
    @Inject
    FunctionService functionService;

    @Inject
    BankService bankService;

    public void update(Employee employee, String newFunctionName, String newBankName) {
        if (!employee.getBank().getName().equals(newBankName)) {
            employee.getBank().removeEmployee(employee);
            employee.setBank(null);
            Bank newBank = bankService.getByName(newBankName);
            newBank.addEmployee(employee);
            employee.setBank(newBank);

        }
        if (!employee.getFunction().getName().equals(newFunctionName)) {
            employee.getFunction().removeEmployee(employee);
            employee.setFunction(null);
            Functions newFunction = functionService.getByName(newFunctionName);
            newFunction.addEmployee(employee);
            employee.setFunction(newFunction);

        }
    }
}

</code>```

the exception stack trace Caused by:
  java.sql.SQLIntegrityConstraintViolationException: Duplicate entry
  'dkfhks32' for key 'REGISTRATIONNUMBER'   at
  com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:115)
    at
  com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
    at
  com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at
  com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
    at
  com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1116)
    at
  com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1066)
    at
  com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1396)
    at
  com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1051)
    at
  com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:127)
    at sun.reflect.GeneratedMethodAccessor54.invoke(Unknown Source)     at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  com.sun.gjc.spi.jdbc40.ProfiledConnectionWrapper40$1.invoke(ProfiledConnectionWrapper40.java:437)
    at com.sun.proxy.$Proxy268.executeUpdate(Unknown Source)    at
  org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:898)

答:
You don't have to change the bank for an employee by removing the reference of existing bank first. You can simply go:

```<code>if (!employee.getBank().getName().equals(newBankName)) {
    Bank newBank = bankService.getByName(newBankName);
    //You must also do an entity validation/null check here. The newBank might not be present after all.
    employee.setBank(newBank);
}
</code>```

This will update the mappings correctly. Same goes for updating function of an employee

Body:
I have Employee and Functions, Bank classes
Employee and Function have @OneToMany relationship and
Employee and Bank have also @OneToMany relationship.
if the user edits the form and change the function and/or bank
I want to update the relationship. but when I change the relationship
I get Duplicate entry  exception due to the uniqueness of a column because
the Employee object persisted as a new entity

I tried to remove the employee from the function and set the employee's function to null and get a new function and add the employee to it
and set the new function but it doesn't work. any idea, please

@Entity
public class Employee extends GeneratedIdEntity<Long> {
   @ManyToOne(optional = false)
   private Functions function;

   @ManyToOne(optional = false)
   private Bank bank;

   @OneToMany(
           mappedBy = "employee",
           fetch = LAZY,
           cascade = ALL,
           orphanRemoval = true
   )
   private List<RubricValue> rubricsValues = new ArrayList<>();

   @OneToMany(
           mappedBy = "employee",
           fetch = LAZY,
           cascade = ALL,
           orphanRemoval = true
   )
   List<EmployeeStatus> employeesStatus=new ArrayList<>();
}

@Entity
public class Functions extends GeneratedIdEntity<Long>{
    @OneToMany(
            mappedBy = "function",
            fetch = LAZY,
            cascade = ALL,
            orphanRemoval = true
    )
    private List<Employee> employees=new ArrayList<>();

    public void addEmployee(Employee employee ){
        employees.add(employee);
    }
    public void removeEmployee(Employee employee){
        employees.remove(employee);
    }
}

@Entity
public class Bank extends GeneratedIdEntity<Long> {
   @OneToMany(
           mappedBy = "bamk",
           fetch = LAZY,
           cascade = ALL,
           orphanRemoval = true
   )
   private List<Employee> employees = new ArrayList<>();

   public void addEmployee(Employee employee ){
       employees.add(employee);
   }
   public void removeEmployee(Employee employee){
       employees.remove(employee);
   }
}

@Stateless
public class EmployeeService extends BaseEntityService<Long, Employee> {
    @Inject
    FunctionService functionService;

    @Inject
    BankService bankService;

    public void update(Employee employee, String newFunctionName, String newBankName) {
        if (!employee.getBank().getName().equals(newBankName)) {
            employee.getBank().removeEmployee(employee);
            employee.setBank(null);
            Bank newBank = bankService.getByName(newBankName);
            newBank.addEmployee(employee);
            employee.setBank(newBank);

        }
        if (!employee.getFunction().getName().equals(newFunctionName)) {
            employee.getFunction().removeEmployee(employee);
            employee.setFunction(null);
            Functions newFunction = functionService.getByName(newFunctionName);
            newFunction.addEmployee(employee);
            employee.setFunction(newFunction);

        }
    }
}

the exception stack trace Caused by:
  java.sql.SQLIntegrityConstraintViolationException: Duplicate entry
  'dkfhks32' for key 'REGISTRATIONNUMBER'   at
  com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:115)
    at
  com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
    at
  com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at
  com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:960)
    at
  com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1116)
    at
  com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1066)
    at
  com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1396)
    at
  com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1051)
    at
  com.sun.gjc.spi.base.PreparedStatementWrapper.executeUpdate(PreparedStatementWrapper.java:127)
    at sun.reflect.GeneratedMethodAccessor54.invoke(Unknown Source)     at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  com.sun.gjc.spi.jdbc40.ProfiledConnectionWrapper40$1.invoke(ProfiledConnectionWrapper40.java:437)
    at com.sun.proxy.$Proxy268.executeUpdate(Unknown Source)    at
  org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeDirectNoSelect(DatabaseAccessor.java:898)

Body:
You don't have to change the bank for an employee by removing the reference of existing bank first. You can simply go:

if (!employee.getBank().getName().equals(newBankName)) {
    Bank newBank = bankService.getByName(newBankName);
    //You must also do an entity validation/null check here. The newBank might not be present after all.
    employee.setBank(newBank);
}

This will update the mappings correctly. Same goes for updating function of an employee


问:
How to tell a typescript that value is an empty object?
Here is my code.

```<code>function DD(x: { y: string } | {}) {
  if (x.y) {//error
   console.log("DD jingo");
  }
}
</code>```

I get this error  The property "y" does not exist in the type "{} | {y: string;}".The property "y" does not exist in the type "{}".

I am new to typescript. How to say that X can accept an empty object and {y: string}.

答:
You can mark the y property as optional, using ?:

```<code>function DD(x: { y?: string }) {
  if (x.y) {
   console.log("DD jingo");
  }
}
</code>```

Body:
Here is my code.

function DD(x: { y: string } | {}) {
  if (x.y) {//error
   console.log("DD jingo");
  }
}

I get this error  The property "y" does not exist in the type "{} | {y: string;}".The property "y" does not exist in the type "{}".

I am new to typescript. How to say that X can accept an empty object and {y: string}.

Body:
You can mark the y property as optional, using ?:

function DD(x: { y?: string }) {
  if (x.y) {
   console.log("DD jingo");
  }
}


问:
working of charindex,cross apply and substring in single query of sql
I have a query as follows to display @prodid= ''1,2,10,4,5,6,7,8,13,16,17,3'' from the string 'dbo.proudction @prodid= ''1,2,10,4,5,6,7,8,13,16,17,3'' ,@stock= 0':

```<code>declare @T table(Col1 varchar(100))
insert into @T values ('dbo.proudction @prodid= ''1,2,10,4,5,6,7,8,13,16,17,3'' ,@stock= 0')

select
  substring(Col1, Start, Stop-Start)
from @T
  cross apply
    (select charindex('''', Col1)+1) c1(Start)
  cross apply
    (select charindex('''', Col1, Start)) c2(Stop)
</code>```

Can you help me to understand the working  of this query, please ?

答:
The first cross apply use charindex locate the first quote in the string. The second cross apply locates the second quote in the string. Then substring will extract the text between the first quote and the second quote.

Result

```<code>1,2,10,4,5,6,7,8,13,16,17,3
</code>```

Body:
I have a query as follows to display @prodid= ''1,2,10,4,5,6,7,8,13,16,17,3'' from the string 'dbo.proudction @prodid= ''1,2,10,4,5,6,7,8,13,16,17,3'' ,@stock= 0':

declare @T table(Col1 varchar(100))
insert into @T values ('dbo.proudction @prodid= ''1,2,10,4,5,6,7,8,13,16,17,3'' ,@stock= 0')

select
  substring(Col1, Start, Stop-Start)
from @T
  cross apply
    (select charindex('''', Col1)+1) c1(Start)
  cross apply
    (select charindex('''', Col1, Start)) c2(Stop)

Can you help me to understand the working  of this query, please ?

Body:
The first cross apply use charindex locate the first quote in the string. The second cross apply locates the second quote in the string. Then substring will extract the text between the first quote and the second quote.

Result

1,2,10,4,5,6,7,8,13,16,17,3


问:
How to read a .bib file in c++?
I have a .bib file and i want to read its content in c++ through code. Basically i am writting the code so what ever .bib file i give it. It could extract data as an text content or something from it.

I know how to read, write the .txt file, And I have used the same method for the .bib file but that's not working. Following is the Code i tried.

```<code>  ofstream myfile;
  myfile.open ("example.txt");
</code>```

I expect to read the .bib file as an text content or something so i can extract data from it and also do some searching. Any help would be really appreciated thanks.

答:
Standard C++ doesn't care about file extensions. If the .bib files are text files, just open them like any other text file specifying the full name (which includes the .bib extension):

```<code>ofstream myfile("example.bib");
</code>```

std::ofstream is in text mode by default so your file would be treated as a text file.

If .bib files aren't text files, you would have to read the documentation about its format and learn how to read binary files.

Title: How to read a .bib file in c++?

Body:
I have a .bib file and i want to read its content in c++ through code. Basically i am writting the code so what ever .bib file i give it. It could extract data as an text content or something from it.

I know how to read, write the .txt file, And I have used the same method for the .bib file but that's not working. Following is the Code i tried.

  ofstream myfile;
  myfile.open ("example.txt");

I expect to read the .bib file as an text content or something so i can extract data from it and also do some searching. Any help would be really appreciated thanks.

Body:
Standard C++ doesn't care about file extensions. If the .bib files are text files, just open them like any other text file specifying the full name (which includes the .bib extension):

ofstream myfile("example.bib");

std::ofstream is in text mode by default so your file would be treated as a text file.

If .bib files aren't text files, you would have to read the documentation about its format and learn how to read binary files.


问:
Exception in thread "AWT-EventQueue-0" java.lang.InternalError: The current process has used all of its system allowance of handles
We have numerous users that use our DSS OWC Application and one of the users is getting the error below:

Exception in thread "AWT-EventQueue-0" java.lang.InternalError: The current process has used all of its system allowance of handles for Window Manager objects.

Attached the error and also Windows Task Manager showing the max 10,000 user objects. The confusing thing is that many other users at her site are using the same program without issue, so a handle leak did not seem to fit with this particular issue. Tried upgrading and then downgrading Java versions to match other users.

答: This exception is resulted because of some memory leak. Try going through again and find what is causing this. I'm sure you can fix it.</p>


问:
Convert list of pandas series to pandas dataframe
I have a list of rows that I want to convert to a data frame. Each element of a list is of type pandas Series. How can I convert it?

The sample data is like this:

```<code>GROUP_NUM                                                      61
PID_LOCATION    [(-111.58903, 33.252235), (-111.59659, 33.2470...)]
PROJECT_KEYS    224033,20542,224037,224039,224040,224041,16610...
PROJECT_NAME    name1...
ZIPCODE         xxxxx
DEFAULT_GEOM    MULTIPOLYGON (((-111.645291932 33.215893723,-1...
Name: 8468, dtype: object, aoi_attr_type_id
aoi_id                       ffeaac-cb85-447f-a367-b37558e452
GROUP_NUM                                                      60
PID_LOCATION                      [(u'-117.40181', u'34.542542')]
PROJECT_KEYS                                               204222
PROJECT_NAME                                          xyz
ZIPCODE                                                     92xxx
DEFAULT_GEOM    MULTIPOLYGON(((-117.416929337 34.557322993,-11...)))
Name: 8469, dtype: object, aoi_attr_type_id
aoi_id                       ff69ae-d61a-4776-af1d-5da73eb05a
GROUP_NUM                                                      63
PID_LOCATION    [(-97.348755, 32.587357), (-97.33046, 32.57823...)]
PROJECT_KEYS                     218461,181794,209575,59540,15239
PROJECT_NAME    some_name2
ZIPCODE                                               yyyyy
DEFAULT_GEOM    MULTIPOLYGON (((-97.332423163 32.571877745,-97...)))
Name: 8470, dtype: object]```

I tried this and get the following error:

    ipdb> res_df=pd.DataFrame.from_items(merged_polygons)
    *** ValueError: too many values to unpack

FYI
ipdb> type(merged_polygons[0])
<class 'pandas.core.series.Series'>
```

答:
Found this from here: https://github.com/pandas-dev/pandas/issues/1494

df = pd.DataFrame.from_items([(s.name, s) for s in merged_polygons]).T

Body:
I have a list of rows that I want to convert to a data frame. Each element of a list is of type pandas Series. How can I convert it?

The sample data is like this:

GROUP_NUM                                                      61
PID_LOCATION    [(-111.58903, 33.252235), (-111.59659, 33.2470...)]
PROJECT_KEYS    224033,20542,224037,224039,224040,224041,16610...
PROJECT_NAME    name1...
ZIPCODE         xxxxx
DEFAULT_GEOM    MULTIPOLYGON (((-111.645291932 33.215893723,-1...
Name: 8468, dtype: object, aoi_attr_type_id
aoi_id                       ffeaac-cb85-447f-a367-b37558e452
GROUP_NUM                                                      60
PID_LOCATION                      [(u'-117.40181', u'34.542542')]
PROJECT_KEYS                                               204222
PROJECT_NAME                                          xyz
ZIPCODE                                                     92xxx
DEFAULT_GEOM    MULTIPOLYGON(((-117.416929337 34.557322993,-11...)))
Name: 8469, dtype: object, aoi_attr_type_id
aoi_id                       ff69ae-d61a-4776-af1d-5da73eb05a
GROUP_NUM                                                      63
PID_LOCATION    [(-97.348755, 32.587357), (-97.33046, 32.57823...)]
PROJECT_KEYS                     218461,181794,209575,59540,15239
PROJECT_NAME    some_name2
ZIPCODE                                               yyyyy
DEFAULT_GEOM    MULTIPOLYGON (((-97.332423163 32.571877745,-97...)))
Name: 8470, dtype: object]```

I tried this and get the following error:

    ipdb> res_df=pd.DataFrame.from_items(merged_polygons)
    *** ValueError: too many values to unpack

FYI
ipdb> type(merged_polygons[0])
<class 'pandas.core.series.Series'>


问:
str_replace function not able to replace multiple values
I have set of strings and need to replace them using str)replace as we loop through the query as the query is success need to replace each value in PHP.

```<code><?php

include_once("con.php");
$db = new Da();

$con = $db->con();

$lclString = "{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}";

 $lclCount = 1;
 if(preg_match_all("/\{\{[^{}]+\}\}/", $lclString, $matches)) {

    foreach ($matches[0] as $match) {

        $lclQuery = "SELECT link, link_value FROM student WHERE link_value = '".$match."'";

        $lclResult = $connString->query($lclQuery);

        while($row = $lclResult->fetch(PDO::FETCH_ASSOC)) {

            $lclNewValue = str_replace($match, $row['link'], $lclString);

            }

        }

        echo json_encode($NewValue);

 }

?>
</code>```

Here only second replacement is happening.

答:
```<code><?php

include_once("con.php");
$db = new Da();

$con = $db->con();

$lclString = "{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}";

 $lclCount = 1;
 if(preg_match_all("/\{\{[^{}]+\}\}/", $lclString, $matches)) {
 $lclNewValue = $lclString;
foreach ($matches[0] as $match) {

    $lclQuery = "SELECT link, link_value FROM student WHERE link_value = '".$match."'";

    $lclResult = $connString->query($lclQuery);

    while($row = $lclResult->fetch(PDO::FETCH_ASSOC)) {

        $lclNewValue = str_replace($match, $row['link'], $lclNewValue);

        }

    }

    echo json_encode($NewValue);

 }

?>
</code>```

Body:
I have set of strings and need to replace them using str)replace as we loop through the query as the query is success need to replace each value in PHP.

<?php

include_once("con.php");
$db = new Da();

$con = $db->con();

$lclString = "{{ONE}} {{TWO}} {{THREE}} {{FOUR}} {{FIVE}} {{SIX}}";

 $lclCount = 1;
 if(preg_match_all("/\{\{[^{}]+\}\}/", $lclString, $matches)) {

    foreach ($matches[0] as $match) {

        $lclQuery = "SELECT link, link_value FROM student WHERE link_value = '".$match."'";

        $lclResult = $connString->query($lclQuery);

        while($row = $lclResult->fetch(PDO::FETCH_ASSOC)) {

            $lclNewValue = str_replace($match, $row['link'], $lclString);

            }

        }

        echo json_encode($NewValue);

 }

?>

Here only second replacement is happening.


问:
How to specify height of waveform in Modelsim/Questasim?
I'm using QuestaSim 70.7b;
And I can not change the height of waveform signal..
I've tried many options, like this:

```<code>add wave -radix hex -format analog-step -scale 100 -height 100 -color gold /bin_top_tb/clk
</code>```

But nothing happen, just height of the name signal is changed, like shown below

*thanks to dave_59, to change the height you should go to Tools -> Edit Preferences and change WaveFont and then footerFont exactly at such sequence, then click apply and ok.

答: There's no way to change the height of individual digital signal. You use the main preferences to select a larger Wave Window text font, and the size of the waveform gets scaled to match the wave label. </p>

Body:
I'm using QuestaSim 70.7b;
And I can not change the height of waveform signal..
I've tried many options, like this:

add wave -radix hex -format analog-step -scale 100 -height 100 -color gold /bin_top_tb/clk

But nothing happen, just height of the name signal is changed, like shown below

*thanks to dave_59, to change the height you should go to Tools -> Edit Preferences and change WaveFont and then footerFont exactly at such sequence, then click apply and ok.