问:
How to define a type when I only know the pattern for that object's keys?
I have a function expecting an object with keys like 'mykey-0', 'myotherkey-0', 'mykey-1', 'myotherkey-1', etc.

The thing is that I don't know if there will be any of these two keys, and I don't know what the number will be (it increases)

How can I express a TS type for these optional keys? Something like { 'mykey-*'?: string, 'myotherkey-*'?: string, otherprop: string }.

答:
Ok this is not an answer for your direct question as your data structure is just wrongly made. Fact that you have iterator in the end of every key means it probably should be an array. Consider how I would model such:

```<code>type MyData = {
  mykey: string,
  myotherkey: string
}
type ArrMyData = MyData[]

function f(arr: ArrMyData) {
    return arr.map(el => el.mykey) // example transformation
}
</code>```

Such structure also fixes your issue with optionally, as just the element will not be in the array. Done.

In summary - lets try to use proper data structures instead of inventing the wheel.
I wrote more info about how we should think about state modeling, consider reading maybe it will help - State modeling is your responsibility

If such kind of data is forced by the server we need to transform it instead of propagating invalid structure and deal with it. Popular pattern for such is Decoder, BTW - its the one and only why to deal with server side data in Elm architecture. Such decoder will be typed as WrongDataStructure -> CorrectDataStructure. So lets write such decoder:

```<code>type ApiResponse = Record<string, string>

type WantedData = {
  mykey: string,
  myotherkey: string
}
type ArrMyData = WantedData[]

function decoder(data: ApiResponse): ArrMyData {
    const keys = Object.keys(data);
    return keys.reduce((acc, key) => {
        let i: string | number = key.match(/-([0-9])$/)?.[1] ?? '0';
        i = parseInt(i)
        const cleanKey = key.replace(/-([0-9])$/, '') // remove the index
        if (!acc[i]) {
            acc.push({[cleanKey]: data[key]} as WantedData)
        } else {
            acc[i] = {...acc[i], [cleanKey]: data[key]}
        }
        return acc;
    } ,[] as ArrMyData)
}

const response = { 'mykey-0': 'a', 'myotherkey-0': 'b', 'mykey-1': 'c', 'myotherkey-1': 'd' };
const data = decoder(response);
</code>```

Playground

What we are doing is kinda a gate when we take the structure and make it more approachable. My implementation is only example.

Body:
Ok this is not an answer for your direct question as your data structure is just wrongly made. Fact that you have iterator in the end of every key means it probably should be an array. Consider how I would model such:

type MyData = {
  mykey: string,
  myotherkey: string
}
type ArrMyData = MyData[]

function f(arr: ArrMyData) {
    return arr.map(el => el.mykey) // example transformation
}

Such structure also fixes your issue with optionally, as just the element will not be in the array. Done.

In summary - lets try to use proper data structures instead of inventing the wheel.
I wrote more info about how we should think about state modeling, consider reading maybe it will help - State modeling is your responsibility

If such kind of data is forced by the server we need to transform it instead of propagating invalid structure and deal with it. Popular pattern for such is Decoder, BTW - its the one and only why to deal with server side data in Elm architecture. Such decoder will be typed as WrongDataStructure -> CorrectDataStructure. So lets write such decoder:

type ApiResponse = Record<string, string>

type WantedData = {
  mykey: string,
  myotherkey: string
}
type ArrMyData = WantedData[]

function decoder(data: ApiResponse): ArrMyData {
    const keys = Object.keys(data);
    return keys.reduce((acc, key) => {
        let i: string | number = key.match(/-([0-9])$/)?.[1] ?? '0';
        i = parseInt(i)
        const cleanKey = key.replace(/-([0-9])$/, '') // remove the index
        if (!acc[i]) {
            acc.push({[cleanKey]: data[key]} as WantedData)
        } else {
            acc[i] = {...acc[i], [cleanKey]: data[key]}
        }
        return acc;
    } ,[] as ArrMyData)
}

const response = { 'mykey-0': 'a', 'myotherkey-0': 'b', 'mykey-1': 'c', 'myotherkey-1': 'd' };
const data = decoder(response);

<a href="https://www.typescriptlang.org/play/index.html?ssl=25&ssc=32&pln=1&pc=1#code/C4TwDgpgBAgmCWAlCBnMB7Adi6BeKyAxugE4AmAPCsCfJgOYA0U1tDAfAFCeiRQDqAQ0zAIZACKDggqPgDenKFAC2IANYQQALhY06TRSpDpgACwgkN23W3qcAvj3DQYJEgFkQk6bIHDRElKCANoAutwAZgCumITA8FhQZBDEySQAFGRBOnBIqBjYEACUOW6e3jIKSkrE2MBQVii%20APIARgBWKcAAdI2ZQUUA3IZKJBDAUSSYDZoo3WNkUYQQ6emChITMVkWy7FBV1YcANuNQ8Dqs%20lAAPlCYUcqtFr5W3cpShKbpAPQAtOnBAAMvwAnKEigASb5FAD83WCAEZQlAYTCoAByQHo4aHQ7wXxgQQkHAASRE6XgRRGuNq1CghBOwgA0poXpp5hAwEd1is-gDgWDId9mOj0Ttvt8oGNlOgAG7QMzQOjJAAe1LxESg6QAhOtCMF4OD9urcUo9d0wFEUF85MEGRBmZpQjostJglZQvYoIImkIRGIKlTTUovRAjjhjcHcXqDcj5N0EzHDcw7YzMCyQM6kkF3U7HFH88GxhMpt6Njjql7GGFvU1XB4vAMHNxafUxmgsBH5BjVFZflidOjBOiRaoTOZLJp%20%20jB60Rz31FOETOMYR5%20ix4rJyBfsvB2R0VB7MNW9mfPhkqkLOl2wUcEMgA" rel="nofollow noreferrer">Playground

What we are doing is kinda a gate when we take the structure and make it more approachable. My implementation is only example.


来源: stackexchange

问:
How to display a different field than `id` in many-to-many relationship?
I would like to implement tags in strapi. — a project can have multiple tags, but I would also like to be able to find projects by tag.

so I created:

but in my projects, it displays the tag ids. how can I make it so that it shows the tag name instead?

答: You can change this by "configure the view" under the pulldown on the page where you create the content. This is feature since the last view releases.</p>

ContentLicense: CC BY-SA 4.0


答:
You could add a check for value it has the sign bit at the first bit and take either

the delta of the parsed value and 256, or

the parsed number.

function getSignedInteger(bits) {
    var value = parseInt(bits, 2);
    return value & (1 << 7)
        ? value - (1 << 8)
        : value;
}
console.log(...['10100100', '11100001', '11001', '100000', '100001', '101010', '1000111', '11011000', '1010011', '1011000', '10111011', '10000110', '10111010', '1110101', '1111', '110111'].map(getSignedInteger));```

Title: Getting decimal from binary's signed 2's complement

Body:
I am trying to get decimal number for binary's signed 2's complement if it is available for the same.

Here is how am i trying to do it.

    function getSignedInteger(bits) {
        for (var i = 0; i < bits.length; i++) {
            bits[i]
        }
        let negative = (bits[0] === '1');
        console.log(bits[0] === '1')
        if (negative) {
            let inverse = '';
            for (let i = 0; i < bits.length; i++) {
                inverse += (bits[i] === '0' ? '1' : '0');
            }
            console.log(inverse)
            return (parseInt(inverse, 2) + 1) * -1;
        } else {
            return parseInt(bits, 2);
        }
    }

Input : ['10100100','11100001','11001','100000','100001','101010','1000111','11011000','1010011','1011000','10111011','10000110','10111010','1110101','1111','110111']

Output :
[-92, -31, 25, 32, 33, 42, 71, -40, 83, 88, -69, -122, -70, 117, 15, 55]

What actually i am getting
[-92,  -31,  -7, -32, -31, -22, -57, -40, -45, -40, -69, -122, -70, -11, -1, -9]


问:
plt.show() does not show the 3d scatter image
community,

I tried to create the 3d scatter by using matplotlib Axes3D on jupyter notebook.
However, it is not showing the image once I execute 'plt.show()'.

```<code>#pip install matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure()
ax =fig.add_subplot(111, projection = '3d')
x = dframe['CTR']
y = dframe['Clicks']
z = dframe['Avg. CPC']
ax.scatter(x, y, z, c='r', marker='o')
plt.show()
</code>```

答:
Your code works fine like this:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")

# dummy data (your actual data should go here)
x = [1, 2, 3, 4]
y = x
z = x
ax.scatter(x, y, z, c="r", marker="o")
plt.show()
```

This shows:

May be something is wrong with your data. Also, since you are using plt.show() anyway, you can remove the %matplotlib inline line.

Body:
community,

I tried to create the 3d scatter by using matplotlib Axes3D on jupyter notebook.
However, it is not showing the image once I execute 'plt.show()'.

#pip install matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
%matplotlib inline
fig = plt.figure()
ax =fig.add_subplot(111, projection = '3d')
x = dframe['CTR']
y = dframe['Clicks']
z = dframe['Avg. CPC']
ax.scatter(x, y, z, c='r', marker='o')
plt.show()

Body:
Your code works fine like this:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")

# dummy data (your actual data should go here)
x = [1, 2, 3, 4]
y = x
z = x
ax.scatter(x, y, z, c="r", marker="o")
plt.show()

This shows:

May be something is wrong with your data. Also, since you are using plt.show() anyway, you can remove the %matplotlib inline line.


问:
Cron job issue Magento 2
trying to run custom cron in magento 2 giving below error in system.log file

main.WARNING: Could not acquire lock for cron group: default, skipping run [] []

答:
Please check below code for custom cron

Create crontab.xml in app/code/Vendor/Module/etc/ folder

```<code><?xml version="1.0"?>
   <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
     <group id="default">
       <job name="bestseller_cronjob" instance="Test\Customcron\Cron\Bestseller" method="execute">
         <schedule>0 1 * * *</schedule>
       </job>
     </group>
   </config>
</code>```

And create on instance file for cron execute
app/code/Test/Customcron/Cron/Bestseller.php

```<code><?php
  namespace CP\Coreoverride\Cron;
  use Magento\Framework\App\Bootstrap;
  class Bestseller {
    public function execute()
    {
       //your code goes here
    }
  }
</code>```

You can execute cron by below command

php bin/magento cron:run (for all cron execute)

    php bin/magento cron:run --group="bestseller_cronjob" (particular cron group)

Title: Cron job issue Magento 2

Body:
Please check below code for custom cron

Create crontab.xml in app/code/Vendor/Module/etc/ folder

<?xml version="1.0"?>
   <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
     <group id="default">
       <job name="bestseller_cronjob" instance="Test\Customcron\Cron\Bestseller" method="execute">
         <schedule>0 1 * * *</schedule>
       </job>
     </group>
   </config>

And create on instance file for cron execute
app/code/Test/Customcron/Cron/Bestseller.php

<?php
  namespace CP\Coreoverride\Cron;
  use Magento\Framework\App\Bootstrap;
  class Bestseller {
    public function execute()
    {
       //your code goes here
    }
  }

You can execute cron by below command

php bin/magento cron:run (for all cron execute)

    php bin/magento cron:run --group="bestseller_cronjob" (particular cron group)


问:
Convert moment.Duration into string
I have a moment.Duration object which I need to convert to string format HH:mm:ss (without any timezone conversion). I know we can do like

```<code>foobar.hours + ":" + foobar.minutes + ":" + foobar.seconds
</code>```

But honestly I was hoping to have a better solution that just string manipulations.

答:
moment().format('HH:mm:ss');
if u have already moment object use like this

object.format('HH:mm:ss');

Title: Convert moment.Duration into string

Body:
I have a moment.Duration object which I need to convert to string format HH:mm:ss (without any timezone conversion). I know we can do like

foobar.hours + ":" + foobar.minutes + ":" + foobar.seconds

But honestly I was hoping to have a better solution that just string manipulations.


问:
ERROR in bundle.js from UglifyJs
I've completed a project and now it's time to build it. I'm using a boilerplate project and still don't fully understand all the npm/webpack stuff going on under the hood. When running "npm start", I'm receiving the error:

```<code>ERROR in bundle.js from UglifyJs
SyntaxError: Unexpected token: punc ()) [bundle.js:848,29]
</code>```

After an hour of searching the internet on this issue, I'm still unable to resolve it. From my understanding, this issue is happening because Uglify doesn't like ES2016 yet. However, the solutions I found on the internet don't seem to be working or don't make enough sense for me to implement.

I found this stackoverflow question and changed the webpack line in my project's package.json file to:

```<code>"webpack": "fulls1z3/webpack#v2.1.0-beta.27-harmony"
</code>```

But this didn't work. The other suggestion of forking webpack is beyond my understanding at the moment.

I also tried running babel on my src folder per another suggestion but that didn't seem to do anything or I ran it incorrectly.

Does anyone have a nice solution to this issue? I'm pretty stuck at the moment and haven't had time to learn npm/webpack from the ground up to fully grasp what's going on.

Much appreciated!

答:
In my case i did changed  sourceMap:false So error came like

```<code>ERROR in index.bundle.js from UglifyJs

TypeError: Cannot read property 'sections' of null.
</code>```

Now when i change  sourceMap:true.

It worked fine.

```<code>new webpack.optimize.UglifyJsPlugin({ sourceMap: true}),
</code>```

ContentLicense: CC BY-SA 3.0

Title: ERROR in bundle.js from UglifyJs

Body:
I've completed a project and now it's time to build it. I'm using a boilerplate project and still don't fully understand all the npm/webpack stuff going on under the hood. When running "npm start", I'm receiving the error:

ERROR in bundle.js from UglifyJs
SyntaxError: Unexpected token: punc ()) [bundle.js:848,29]

After an hour of searching the internet on this issue, I'm still unable to resolve it. From my understanding, this issue is happening because Uglify doesn't like ES2016 yet. However, the solutions I found on the internet don't seem to be working or don't make enough sense for me to implement.

I found this stackoverflow question and changed the webpack line in my project's package.json file to:

"webpack": "fulls1z3/webpack#v2.1.0-beta.27-harmony"

But this didn't work. The other suggestion of forking webpack is beyond my understanding at the moment.

I also tried running babel on my src folder per another suggestion but that didn't seem to do anything or I ran it incorrectly.

Does anyone have a nice solution to this issue? I'm pretty stuck at the moment and haven't had time to learn npm/webpack from the ground up to fully grasp what's going on.

Much appreciated!

Body:
In my case i did changed  sourceMap:false So error came like

ERROR in index.bundle.js from UglifyJs

TypeError: Cannot read property 'sections' of null.

Now when i change  sourceMap:true.

It worked fine.

new webpack.optimize.UglifyJsPlugin({ sourceMap: true}),


问:
How to append data to a file?
I trying to write into the txt file.

But with out losing the data that is already stored in the file.

But my problem that when I put string in the txt file, the new string overwrite on the old string that i put it before.

My code is:

```<code>public void addWorker(Worker worker){
        workers.put(worker.getId(), worker);

    }

    public void printWorker (String id){
    Worker work = (Worker) workers.get( id );

    if (work == null) {
        System.out.println("Worker NOT found");
    }

    else {
         work.printText();
     }
    }
       public void printWorkers() {
           if (workers.size() == 0) {
               System.out.println("No workres");
                return;
           }

           Collection<Worker> c = workers.values();
           Iterator<Worker> itr = c.iterator();
           System.out.println("Workers in division "+dName+ ":");
           while (itr.hasNext()) {
                  Worker wo = itr.next();
                  wo.printText();
           }
       }

       public void writeToFile(){
           PrintWriter pw = null;
           try{
               pw = new PrintWriter(new File("d:\\stam\\stam.txt"));
               Collection<Worker> c = workers.values();
               Iterator<Worker> itr = c.iterator();
               while (itr.hasNext()) {
                   Worker wo = itr.next();
                   pw.write("worker: "+wo.getId()+", "+wo.getName()+", "+wo.getAddress()+", "+wo.getSex());
                   pw.println();
               }
            }
            catch(Exception e) {
                System.out.println(e);
            }
            finally {
                if (pw != null) {
                    pw.close();
                }
            }

        }

}
</code>```

Can you help me?

答:
Use a FileWriter with second argument 'true' and a BufferedWriter:</p>

```<code>FileWriter writer = new FileWriter("outFile.txt", true);
BufferedWriter out = new BufferedWriter(writer);
</code>```

Title: How to append data to a file?

Body:
I trying to write into the txt file.

But with out losing the data that is already stored in the file.

But my problem that when I put string in the txt file, the new string overwrite on the old string that i put it before.

My code is:

public void addWorker(Worker worker){
        workers.put(worker.getId(), worker);

    }

    public void printWorker (String id){
    Worker work = (Worker) workers.get( id );

    if (work == null) {
        System.out.println("Worker NOT found");
    }

    else {
         work.printText();
     }
    }
       public void printWorkers() {
           if (workers.size() == 0) {
               System.out.println("No workres");
                return;
           }

           Collection<Worker> c = workers.values();
           Iterator<Worker> itr = c.iterator();
           System.out.println("Workers in division "+dName+ ":");
           while (itr.hasNext()) {
                  Worker wo = itr.next();
                  wo.printText();
           }
       }

       public void writeToFile(){
           PrintWriter pw = null;
           try{
               pw = new PrintWriter(new File("d:\\stam\\stam.txt"));
               Collection<Worker> c = workers.values();
               Iterator<Worker> itr = c.iterator();
               while (itr.hasNext()) {
                   Worker wo = itr.next();
                   pw.write("worker: "+wo.getId()+", "+wo.getName()+", "+wo.getAddress()+", "+wo.getSex());
                   pw.println();
               }
            }
            catch(Exception e) {
                System.out.println(e);
            }
            finally {
                if (pw != null) {
                    pw.close();
                }
            }

        }

}

Can you help me?

Body:
Use a FileWriter with second argument 'true' and a BufferedWriter:

FileWriter writer = new FileWriter("outFile.txt", true);
BufferedWriter out = new BufferedWriter(writer);


问:
How can I do route configuration in ASP.NET MVC?
How can I do route configuration as below?

My current url is: http://localhost:4815/Home/ByCategory/1

But I want it to be: http://localhost:4815/CategoryTitle

```<code>public ActionResult ByCategory(int? id)
{
    ...
}

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "ByCategory", id = UrlParameter.Optional }
        );
</code>```

答:
Thank you for your suggestions. I have added the following code to routeconfig. I used <code> </code> on the view page to go to the relevant controller</p>

```<code>public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               name: "AddQuestion",
               url: "AddQuestion",
               defaults: new { controller = "Question", action = "Create" }
           );

</code>```

Body:
How can I do route configuration as below?

My current url is: http://localhost:4815/Home/ByCategory/1

But I want it to be: http://localhost:4815/CategoryTitle

public ActionResult ByCategory(int? id)
{
    ...
}

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "ByCategory", id = UrlParameter.Optional }
        );

Body:
Thank you for your suggestions. I have added the following code to routeconfig. I used <a href="/question"> </a> on the view page to go to the relevant controller

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
               name: "AddQuestion",
               url: "AddQuestion",
               defaults: new { controller = "Question", action = "Create" }
           );


问:
Accessing element in table (Selenium, C#)
I am trying to automatize a task at work and this required i access an element inside a nested table. i managed to get the XPath through Chrome but getting an error that it cannot locate the element.

Error message:

答:
Do not use absolute xpath from chrome as this would likely to be failed. When you deal with tables the best practice is to accessing table>tr>td. Below is the example that would help you. This can be your starting point and then based on cell text you can click on the element.</p>

```<code>//find table.
WebElement mytable = driver.findElement(By.xpath("html/body/table/tbody"));

//find rows of table.
List < WebElement > rows_table = mytable.findElements(By.tagName("tr"));

//calculate no of rows In table.
int rows_count = rows_table.size();

//Loop will execute for all the rows of the table
for (int row = 0; row < rows_count; row++) {

//find columns(cells) of that specific row.
List < WebElement > Columns_row = rows_table.get(row).findElements(By.tagName("td"));
//calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row " + row + " are " + columns_count);

//Loop will execute till the last cell of that specific row.
for (int column = 0; column < columns_count; column++) {
    //To retrieve text from the cells.
    String celltext = Columns_row.get(column).getText();
    System.out.println("Cell Value Of row number " + row + " and column number " + column + " Is " + celltext);
}
}
</code>```

Body:
Do not use absolute xpath from chrome as this would likely to be failed. When you deal with tables the best practice is to accessing table>tr>td. Below is the example that would help you. This can be your starting point and then based on cell text you can click on the element.

//find table.
WebElement mytable = driver.findElement(By.xpath("html/body/table/tbody"));

//find rows of table.
List < WebElement > rows_table = mytable.findElements(By.tagName("tr"));

//calculate no of rows In table.
int rows_count = rows_table.size();

//Loop will execute for all the rows of the table
for (int row = 0; row < rows_count; row++) {

//find columns(cells) of that specific row.
List < WebElement > Columns_row = rows_table.get(row).findElements(By.tagName("td"));
//calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row " + row + " are " + columns_count);

//Loop will execute till the last cell of that specific row.
for (int column = 0; column < columns_count; column++) {
    //To retrieve text from the cells.
    String celltext = Columns_row.get(column).getText();
    System.out.println("Cell Value Of row number " + row + " and column number " + column + " Is " + celltext);
}
}


问:
Vue.js - Is Chaining Form Input Modifiers Allowed?
The Vue.js ecosystem comes with some handy modifiers for use with form inputs.

```<code><input v-model.lazy="msg">

<input v-model.trim="msg">

<input v-model.number="msg">
</code>```

I was wondering if it were possible to chain such modifiers, perhaps something like this:

```<code><input v-model.lazy.trim="msg">
</code>```

If not, has anyone any experience of making their own modifiers?

答:
Unfortunately it doesn't look like you can make custom modifiers the moment, there's some desire for the feature here. Your best option IMO is to make a custom component and then emit the modified value based on what you need.

I made a quick app (included below) to test chaining modifiers and it does work.

new Vue({
   el: '#app',
   data: {
      message: 'Hello Vue.js!',
   },
   computed: {
      len: function() {
         return this.message.length;
      }
   }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="text" v-model.lazy.trim="message" />
  <span style="background:yellow">{{ message }}</span>
  <span>{{len}}</span>
</div></code>```

Body:
The Vue.js ecosystem comes with some handy modifiers for use with form inputs.

<input v-model.lazy="msg">

<input v-model.trim="msg">

<input v-model.number="msg">

I was wondering if it were possible to chain such modifiers, perhaps something like this:

<input v-model.lazy.trim="msg">

If not, has anyone any experience of making their own modifiers?

Body:
Unfortunately it doesn't look like you can make custom modifiers the moment, there's some desire for the feature here. Your best option IMO is to make a custom component and then emit the modified value based on what you need.

I made a quick app (included below) to test chaining modifiers and it does work.

new Vue({
   el: '#app',
   data: {
      message: 'Hello Vue.js!',
   },
   computed: {
      len: function() {
         return this.message.length;
      }
   }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="text" v-model.lazy.trim="message" />
  <span style="background:yellow">{{ message }}</span>
  <span>{{len}}</span>
</div>


问:
How to remove property when window size is scaled to lower or higher
I have a table component here from antd

Basically I wanted to remove the scroll={{ x:1000 }} when I make the browser window bigger, say than 1200px. How can I achieve this in React?

Booking function()

```<code>function booking() {

    return (

        <div className="booking">
            <Navbar bg="" variant="dark" id="mainHeader">
                <Nav className="mr-auto">
                    <img
                        src={logo}
                        width="110"
                        height="50"
                        className="d-inline-block align-top ml-4 mt-3 mb-2"
                        alt="logo"
                    />
                </Nav>
                <Nav.Link a href="/" className="ml-sm-4 text-dark">Home</Nav.Link>
                <Nav.Link a href="/bookings" className=" text-dark">Bookings</Nav.Link>
                <Nav.Link a href="/signout" className="mr-sm-4 text-dark">Sign Out</Nav.Link>
            </Navbar>

            {/* My Booking Table */}
            <header className="App-header text-dark">
                    <Card border="light" className="bookingCard" id="bookingCard" >
                        <h1 className="mt-4 ml-4" id="cardTitle">Upcoming Bookings</h1>
                        <Card.Body>
                            <Table columns={columns} dataSource={data} {...!!this.state.scroll && { scroll: { x: 1000 }}} pagination={{ pageSize: 4 }} />
                        </Card.Body>
                    </Card>
            </header>
        </div>
    );
}
</code>```

I wanted to change the Table there.

答:
You can add an event that fires on window resize. Small sample code:

```<code>import React from "react";
import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      resized: window.innerWidth < 1200
    };
    this.onResize = this.onResize.bind(this);
  }

  onResize() {
    if (window.innerWidth < 1200) {
      this.setState({ resized: true });
    } else {
      this.setState({ resized: false });
    }
  }

  componentDidMount() {
    window.addEventListener("resize", this.onResize);
  }
}
</code>```

And in return statement:

```<code><Table columns={columns} dataSource={data} scroll={{x: this.state.resized ?  1000 : 0}} pagination={{ pageSize: 4 }} />
</code>```

Body:
I have a table component here from antd

Basically I wanted to remove the scroll={{ x:1000 }} when I make the browser window bigger, say than 1200px. How can I achieve this in React?

Booking function()

function booking() {

    return (

            <Navbar bg="" variant="dark" id="mainHeader">

                Home
                Bookings
                Sign Out
            </Navbar>

            {/* My Booking Table */}

                    <Card border="light" className="bookingCard" id="bookingCard" >

Upcoming Bookings

                        <Card.Body>

                        </Card.Body>
                    </Card>

    );
}

I wanted to change the Table there.

Body:
You can add an event that fires on window resize. Small sample code:

import React from "react";
import "./styles.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      resized: window.innerWidth < 1200
    };
    this.onResize = this.onResize.bind(this);
  }

  onResize() {
    if (window.innerWidth < 1200) {
      this.setState({ resized: true });
    } else {
      this.setState({ resized: false });
    }
  }

  componentDidMount() {
    window.addEventListener("resize", this.onResize);
  }
}

And in return statement:

<Table columns={columns} dataSource={data} scroll={{x: this.state.resized ?  1000 : 0}} pagination={{ pageSize: 4 }} />


问:
How to make Clojure tests stop tests running in case one of them failed?
I just would like to make the command lein test fail right once the first one test case fails.

答:
I use eftest as a better alternative to default clojure.test runner:

How to use?

From the REPL https://github.com/weavejester/eftest#fast-failure

```<code>user=> (run-tests (find-tests "test") {:fail-fast? true})
</code>```

or using lein plugin https://github.com/weavejester/eftest#plugin

Body:
I use eftest as a better alternative to default clojure.test runner:

How to use?

From the REPL https://github.com/weavejester/eftest#fast-failure

user=> (run-tests (find-tests "test") {:fail-fast? true})

or using lein plugin https://github.com/weavejester/eftest#plugin


问:
Why i am getting errors while passing array of pointer to struct node to createHash() function?
Recently i have learned separate chaining technique of hashing and trying to write a C program which will print a Binary Tree in vertical order,when i am passing hash array which is array of pointers to struct node to createHash() function i am getting following errors.
Thanks in advance,to let me know what actually i am  doing wrong.

```<code>#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node* next;
};
struct BTnode
{
    int data;
    struct BTnode* Lchild;
    struct BTnode* Rchild;
};
void findmin_max(struct BTnode* root,int *min,int *max,int hd)
{
    if(root==NULL)
    return;
    if(hd<*min)
    {
        *min=hd;
    }
    else if(hd>*max)
    {
        *max=hd;
    }
    findmin_max(root->Lchild,min,max,hd-1);
    findmin_max(root->Rchild,min,max,hd+1);
}
struct BTnode* newNode(int data)
{
    struct BTnode* newnode=(struct BTnode*)malloc(sizeof(struct BTnode));
    newnode->data=data;
    newnode->Lchild=NULL;
    newnode->Rchild=NULL;
    return newnode;
}
struct node* insertnode(struct BTnode* root,int ln,int hd)
{
    if(root==NULL);
    return root;
        else if(hd==ln)
    {
        struct node* nw=(struct node*)malloc(sizeof(struct node));
        nw->data=root->data;
        nw->next=NULL;
        return nw;
    }
    insertnode(root,ln,hd-1);
    insertnode(root,ln,hd+1);
}
void createHash(struct BTnode* root,struct node* hash,int min,int max,int hd)
{
    int key=0;
    for(int line_no=min;line_no<=max;line_no++)
    {
         key=line_no+abs(min);
         if((hash[key])==NULL)
             (hash[key])=insertnode(root,line_no,0);
         else
         {
             struct node* temp=(hash[key]);
             while(temp->next!=NULL)
             {
                 temp=temp->next;
             }
             temp->next=insertnode(root,line_no,0);
         }
    }
}
int main()
{
    struct BTnode* root;
    int min=0;
    int max=0;
        root = newNode(1);
        root->Lchild = newNode(2);
        root->Rchild = newNode(3);
        root->Lchild->Rchild = newNode(4);
        root->Lchild->Rchild = newNode(5);
        root->Rchild->Lchild = newNode(6);
        root->Rchild->Rchild = newNode(7);
        root->Rchild->Lchild->Rchild = newNode(8);
        root->Rchild->Rchild->Rchild = newNode(9);
    findmin_max(root,&min,&max,0);
    int N=abs(min-max);

    struct node* hash[N];

        for(int i=0;i<N;i++)
        hash[i]=NULL;
    createHash(root,hash,min,max,0);
    return 0;
}
</code>```

Currently my program does not contain print function which will print hash table,and i was compiling
it to see have i written the above code correctly or not.

These are the errors which i am getting while compiling in Linux terminal.

```<code>BT_vertical.c: In function ‘insertnode’:
BT_vertical.c:40:9: warning: returning ‘struct BTnode *’ from a function with incompatible return type ‘struct node *’ [-Wincompatible-pointer-types]
  return root;
         ^~~~
BT_vertical.c:41:9: error: ‘else’ without a previous ‘if’
         else if(hd==ln)
         ^~~~
BT_vertical.c: In function ‘createHash’:
BT_vertical.c:57:18: error: invalid operands to binary == (have ‘struct node’ and ‘void *’)
    if((hash[key])==NULL)
       ~~~~~~~~~~~^~
BT_vertical.c:58:19: error: incompatible types when assigning to type ‘struct node’ from type ‘struct node *’
        (hash[key])=insertnode(root,line_no,0);
                   ^
BT_vertical.c:61:23: error: incompatible types when initializing type ‘struct node *’ using type ‘struct node’
     struct node* temp=(hash[key]);
                       ^
BT_vertical.c: In function ‘main’:
BT_vertical.c:91:18: warning: passing argument 2 of ‘createHash’ from incompatible pointer type [-Wincompatible-pointer-types]
  createHash(root,hash,min,max,0);
                  ^~~~
BT_vertical.c:51:50: note: expected ‘struct node *’ but argument is of type ‘struct node **’
 void createHash(struct BTnode* root,struct node* hash,int min,int max,int hd)
                                     ~~~~~~~~~~~~~^~~~
</code>```

答:
struct node* insertnode(struct BTnode* root,int ln,int hd) returns value of type struct node* but return root; will return variable of type struct BTnode* - so you could simply change that to return NULL;

Also within insertnode: When neither the condition root == NULL nor hd == ln is true, the return value for this function is completely missing

Further you are passing hash (array of type struct node*) to void createHash(struct BTnode* root,struct node* hash,int min,int max,int hd) - in order to make it compile you need to change your function argument to struct node** hash or struct node* hash[]

But you should really look into what the compiler is telling you and try to understand what you made wrong - these failures are quite obvious

Body:
Recently i have learned separate chaining technique of hashing and trying to write a C program which will print a Binary Tree in vertical order,when i am passing hash array which is array of pointers to struct node to createHash() function i am getting following errors.
Thanks in advance,to let me know what actually i am  doing wrong.

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node* next;
};
struct BTnode
{
    int data;
    struct BTnode* Lchild;
    struct BTnode* Rchild;
};
void findmin_max(struct BTnode* root,int *min,int *max,int hd)
{
    if(root==NULL)
    return;
    if(hd<*min)
    {
        *min=hd;
    }
    else if(hd>*max)
    {
        *max=hd;
    }
    findmin_max(root->Lchild,min,max,hd-1);
    findmin_max(root->Rchild,min,max,hd+1);
}
struct BTnode* newNode(int data)
{
    struct BTnode* newnode=(struct BTnode*)malloc(sizeof(struct BTnode));
    newnode->data=data;
    newnode->Lchild=NULL;
    newnode->Rchild=NULL;
    return newnode;
}
struct node* insertnode(struct BTnode* root,int ln,int hd)
{
    if(root==NULL);
    return root;
        else if(hd==ln)
    {
        struct node* nw=(struct node*)malloc(sizeof(struct node));
        nw->data=root->data;
        nw->next=NULL;
        return nw;
    }
    insertnode(root,ln,hd-1);
    insertnode(root,ln,hd+1);
}
void createHash(struct BTnode* root,struct node* hash,int min,int max,int hd)
{
    int key=0;
    for(int line_no=min;line_no<=max;line_no++)
    {
         key=line_no+abs(min);
         if((hash[key])==NULL)
             (hash[key])=insertnode(root,line_no,0);
         else
         {
             struct node* temp=(hash[key]);
             while(temp->next!=NULL)
             {
                 temp=temp->next;
             }
             temp->next=insertnode(root,line_no,0);
         }
    }
}
int main()
{
    struct BTnode* root;
    int min=0;
    int max=0;
        root = newNode(1);
        root->Lchild = newNode(2);
        root->Rchild = newNode(3);
        root->Lchild->Rchild = newNode(4);
        root->Lchild->Rchild = newNode(5);
        root->Rchild->Lchild = newNode(6);
        root->Rchild->Rchild = newNode(7);
        root->Rchild->Lchild->Rchild = newNode(8);
        root->Rchild->Rchild->Rchild = newNode(9);
    findmin_max(root,&min,&max,0);
    int N=abs(min-max);

    struct node* hash[N];

        for(int i=0;i<N;i++)
        hash[i]=NULL;
    createHash(root,hash,min,max,0);
    return 0;
}

Currently my program does not contain print function which will print hash table,and i was compiling
it to see have i written the above code correctly or not.

These are the errors which i am getting while compiling in Linux terminal.

BT_vertical.c: In function ‘insertnode’:
BT_vertical.c:40:9: warning: returning ‘struct BTnode *’ from a function with incompatible return type ‘struct node *’ [-Wincompatible-pointer-types]
  return root;
         ^~~~
BT_vertical.c:41:9: error: ‘else’ without a previous ‘if’
         else if(hd==ln)
         ^~~~
BT_vertical.c: In function ‘createHash’:
BT_vertical.c:57:18: error: invalid operands to binary == (have ‘struct node’ and ‘void *’)
    if((hash[key])==NULL)
       ~~~~~~~~~~~^~
BT_vertical.c:58:19: error: incompatible types when assigning to type ‘struct node’ from type ‘struct node *’
        (hash[key])=insertnode(root,line_no,0);
                   ^
BT_vertical.c:61:23: error: incompatible types when initializing type ‘struct node *’ using type ‘struct node’
     struct node* temp=(hash[key]);
                       ^
BT_vertical.c: In function ‘main’:
BT_vertical.c:91:18: warning: passing argument 2 of ‘createHash’ from incompatible pointer type [-Wincompatible-pointer-types]
  createHash(root,hash,min,max,0);
                  ^~~~
BT_vertical.c:51:50: note: expected ‘struct node *’ but argument is of type ‘struct node **’
 void createHash(struct BTnode* root,struct node* hash,int min,int max,int hd)
                                     ~~~~~~~~~~~~~^~~~


问:
Why does the Rust compiler complain that I use a moved value when I've replaced it with a new value?
I am working on two singly linked lists, named longer and shorter. The length of the longer one is guaranteed to be no less than the shorter one.

I pair the lists element-wise and do something to each pair. If the longer list has more unpaired elements, process the rest of them:

struct List {
    next: Option<Box<List>>,
}

fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    while let (Some(node1), Some(node2)) = (shorter, longer) {
        // Actual work elided.
        shorter = node1.next;
        longer = node2.next;
    }
    // Process the rest in the longer list.
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}
```

<p>However, the compiler complains on the second while loop that</p>

```error[E0382]: use of moved value
  --> src/lib.rs:13:20
   |
5  | fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
   |                                                ---------- move occurs because `longer` has type `std::option::Option<std::boxed::Box<List>>`, which does not implement the `Copy` trait
6  |     // Pair the elements in the two lists.
7  |     while let (Some(node1), Some(node2)) = (shorter, longer) {
   |                                                      ------ value moved here
...
13 |     while let Some(node) = longer {
   |                    ^^^^ value used here after move
```

However, I do set a new value for shorter and longer at the end of the loop, so that I will never use a moved value of them.

How should I cater to the compiler?

答:
One solution is to avoid the tuple and consequently the move of longer into the tuple. </p>

```<code>fn actual_work(node1: &Box<List>, node2: &Box<List>) {
    // Actual work elided
}

fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
    while let Some(node1) = shorter {

        if let Some(node2) = longer.as_ref() {
            actual_work(&node1, node2);
        }

        shorter = node1.next;
        longer = longer.map_or(None, move |l| {
            l.next
        });
    }
    // Process the rest in the longer list.

    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }

}
</code>```

Body:
I am working on two singly linked lists, named longer and shorter. The length of the longer one is guaranteed to be no less than the shorter one.

I pair the lists element-wise and do something to each pair. If the longer list has more unpaired elements, process the rest of them:

struct List {
    next: Option<Box<List>>,
}

fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
    // Pair the elements in the two lists.
    while let (Some(node1), Some(node2)) = (shorter, longer) {
        // Actual work elided.
        shorter = node1.next;
        longer = node2.next;
    }
    // Process the rest in the longer list.
    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }
}

However, the compiler complains on the second while loop that

error[E0382]: use of moved value
  --> src/lib.rs:13:20
   |
5  | fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
   |                                                ---------- move occurs because `longer` has type `std::option::Option<std::boxed::Box<List>>`, which does not implement the `Copy` trait
6  |     // Pair the elements in the two lists.
7  |     while let (Some(node1), Some(node2)) = (shorter, longer) {
   |                                                      ------ value moved here
...
13 |     while let Some(node) = longer {
   |                    ^^^^ value used here after move

However, I do set a new value for shorter and longer at the end of the loop, so that I will never use a moved value of them.

How should I cater to the compiler?

Body:
One solution is to avoid the tuple and consequently the move of longer into the tuple.

fn actual_work(node1: &Box<List>, node2: &Box<List>) {
    // Actual work elided
}

fn drain_lists(mut shorter: Option<Box<List>>, mut longer: Option<Box<List>>) {
    while let Some(node1) = shorter {

        if let Some(node2) = longer.as_ref() {
            actual_work(&node1, node2);
        }

        shorter = node1.next;
        longer = longer.map_or(None, move |l| {
            l.next
        });
    }
    // Process the rest in the longer list.

    while let Some(node) = longer {
        // Actual work elided.
        longer = node.next;
    }

}


问:
Search muliple columns for the most common value
excuse the basic nature of this question but I have searched for hours for an answer and they all seem to over complicate what I need.

I have a dataframe like the following: -

```<code>id food_item_1   food_item_2   food_item_3

1  nuts          bread         coffee
2  potatoes      coffee        cake
3  fish          beer          coffee
4  bread         coffee        coffee
</code>```

What I want to do is search all the 'food_item_*' columns (so in this case there are 3) and have returned back to me the single most common value such as e.g. 'coffee' across all 3 columns.

Could someone please recommend the best way to do this?

Many thanks

md

答:
Use DataFrame.filter, reshape by DataFrame.stack and then use Series.mode, last select first value by position with Series.iat:

```<code>a = df.filter(like='food_item_').stack().mode().iat[0]
print (a)
coffee
</code>```

Another idea is with Series.value_counts and selecting first value of index:

```<code>a = df.filter(like='food_item_').stack().value_counts().index[0]
</code>```

Body:
excuse the basic nature of this question but I have searched for hours for an answer and they all seem to over complicate what I need.

I have a dataframe like the following: -

id food_item_1   food_item_2   food_item_3

1  nuts          bread         coffee
2  potatoes      coffee        cake
3  fish          beer          coffee
4  bread         coffee        coffee

What I want to do is search all the 'food_item_*' columns (so in this case there are 3) and have returned back to me the single most common value such as e.g. 'coffee' across all 3 columns.

Could someone please recommend the best way to do this?

Many thanks

md

Body:
Use DataFrame.filter, reshape by DataFrame.stack and then use Series.mode, last select first value by position with Series.iat:

a = df.filter(like='food_item_').stack().mode().iat[0]
print (a)
coffee

Another idea is with Series.value_counts and selecting first value of index:

a = df.filter(like='food_item_').stack().value_counts().index[0]


问:
jQuery postcode validation does not work
I am trying to validate postcode field using jQuery but it does not work.

Here is my code:

```<code>if (postcod.val().match ('~^([1-9]{1}[0-9]{3}\s[A-Z]{2})$~')){
         }else{
            postcod.addClass("needsfilled");
            postcod.val(postcoderror);
        }
</code>```

Here is html:

```<code>PostCode<br /><input id="postcod" type="text" value="" name="postcod" />
</code>```

Could you help plz

答:
There are a few issues...

Regexs are not quoted in JavaScript, unless you need to create a RegExp object via its constructor. In this circumstance, you don't. I only use them if I need to concatenate an outside string. While you can pass a string to match() and it will be implicitly converted, it's not recommended over passing a RegExp literal.

You need to use / as the delimiters in a regex literal. When using the RegExp, you don't pass any delimiters. So ~ are never correct. Perhaps you are thinking PHP.

Whilst not necessary, some of your regex could be improved. The {1} quantifier is implicit, and the [0-9] character class can be substituted with \d.

Instead of having an empty block and an else, just negate the condition with the bang operator (!).

Here is how I might use it...

```<code>if ( ! postcod.val().match(/^([1-9]\d{3}\s[A-Z]{2})$/)){
   ...
}
</code>```

Body:
I am trying to validate postcode field using jQuery but it does not work.

Here is my code:

if (postcod.val().match ('~^([1-9]{1}[0-9]{3}\s[A-Z]{2})$~')){
         }else{
            postcod.addClass("needsfilled");
            postcod.val(postcoderror);
        }

Here is html:

PostCode
<input id="postcod" type="text" value="" name="postcod" />

Could you help plz

Body:
There are a few issues...

Regexs are not quoted in JavaScript, unless you need to create a RegExp object via its constructor. In this circumstance, you don't. I only use them if I need to concatenate an outside string. While you can pass a string to match() and it will be implicitly converted, it's not recommended over passing a RegExp literal.

You need to use / as the delimiters in a regex literal. When using the RegExp, you don't pass any delimiters. So ~ are never correct. Perhaps you are thinking PHP.

Whilst not necessary, some of your regex could be improved. The {1} quantifier is implicit, and the [0-9] character class can be substituted with \d.

Instead of having an empty block and an else, just negate the condition with the bang operator (!).

Here is how I might use it...

if ( ! postcod.val().match(/^([1-9]\d{3}\s[A-Z]{2})$/)){
   ...
}


问:
creating orderer genesis block without cryptogen
I am currently trying to build a production hyperledger-fabric setup. Therefore I am using a CA instead of cryptogen.
My structure looks like this:

orderer

org1

peer0.org1

peer1.org1

org2

peer0.org2

peer1.org2

and I have 2 CAs (1 for every org).
I have registered and enrolled orderer, peer0.org1, peer1.org1 and Org1Admin @CA1
and peer0.org2, peer1.org2 and Org2Admin @CA2.
The orderer has ROOT_CERTS of both CAs.

But how can I create the orderer genesis block based of those MSPs?
The configtx.yaml asks for an 'MSPDir' when describing the organizations, but I don't have an MSP directory for the organization itself, I only got the MSPs of the identites. Do I have to set up a specific folder structure for this?

答:
you should create a msp directory for each of the organizations, including admincerts and cacerts.

if your tls is enable, you need tlscacerts.

if you have Intermediate CA, you need intermediatecerts too.

you can read this document for complete information.


问:
Extract part of string in multiple places
How can I extract part of this string

```<code>declare @string varchar(1024)
set @string = 'Total # of bytes             : 128270200832 (119.46GB)'
select Substring (@string, Charindex( ':', @string )+2 , Len(@string))
</code>```

I only need the numbers after: and without the (119.46GB)

答:
Use replace() :

```<code>select replace(replace(Substring (@string, Charindex( ':', @string )+2 , Len(@string)), '(', ''), ')', '');
</code>```

EDIT : If you don't want  values inside () then you can do :

```<code>select left(col, charindex('(', col) - 1)
from ( values (Substring (@string, Charindex( ':', @string )+2 , Len(@string)))
     ) t(col);
</code>```

Body:
How can I extract part of this string

declare @string varchar(1024)
set @string = 'Total # of bytes             : 128270200832 (119.46GB)'
select Substring (@string, Charindex( ':', @string )+2 , Len(@string))

I only need the numbers after: and without the (119.46GB)

Body:
Use replace() :

select replace(replace(Substring (@string, Charindex( ':', @string )+2 , Len(@string)), '(', ''), ')', '');

EDIT : If you don't want  values inside () then you can do :

select left(col, charindex('(', col) - 1)
from ( values (Substring (@string, Charindex( ':', @string )+2 , Len(@string)))
     ) t(col);


问:
Is there a way to list keys in context.Context?
So, I have a context.Context(https://golang.org/pkg/context/) variable with me, is there a way I can list all the keys this variable holds?</p>

答:
It is possible to list the internals of context.Context using unsafe reflection and using that information to figure out the keys and/or see if the information you want is in the context.

There are some pitfall such as if the context implementation returns a hardcoded value for a key it wont show up here, and it can be quite unclear on how to actually access the values using keys.

This is nothing I run in production. But in my case I needed to be able to inspect the context.Context to understand better what information it contains.

```<code>func printContextInternals(ctx interface{}, inner bool) {
    contextValues := reflect.ValueOf(ctx).Elem()
    contextKeys := reflect.TypeOf(ctx).Elem()

    if !inner {
        fmt.Printf("\nFields for %s.%s\n", contextKeys.PkgPath(), contextKeys.Name())
    }

    if contextKeys.Kind() == reflect.Struct {
        for i := 0; i < contextValues.NumField(); i++ {
            reflectValue := contextValues.Field(i)
            reflectValue = reflect.NewAt(reflectValue.Type(), unsafe.Pointer(reflectValue.UnsafeAddr())).Elem()

            reflectField := contextKeys.Field(i)

            if reflectField.Name == "Context" {
                printContextInternals(reflectValue.Interface(), true)
            } else {
                fmt.Printf("field name: %+v\n", reflectField.Name)
                fmt.Printf("value: %+v\n", reflectValue.Interface())
            }
        }
    } else {
        fmt.Printf("context is empty (int)\n")
    }
}
</code>```

Examples:

```<code>func Ping(w http.ResponseWriter, r *http.Request) {
    printContextInternals(r.Context(), false)
    /* Prints
        Fields for context.valueCtx
        context is empty (int)
        field name: key
        value: net/http context value http-server
        field name: val
        value: &{Addr::20885 Handler:0xc00001c000 TLSConfig:0xc000001c80 ReadTimeout:0s ReadHeaderTimeout:0s WriteTimeout:0s IdleTimeout:0s MaxHeaderBytes:0 TLSNextProto:map[h2:0x12db010] ConnState:<nil> ErrorLog:<nil> BaseContext:<nil> ConnContext:<nil> disableKeepAlives:0 inShutdown:0 nextProtoOnce:{done:1 m:{state:0 sema:0}} nextProtoErr:<nil> mu:{state:0 sema:0} listeners:map[0xc00015a840:{}] activeConn:map[0xc000556fa0:{}] doneChan:<nil> onShutdown:[0x12e9670]}
        field name: key
        value: net/http context value local-addr
        field name: val
        value: [::1]:20885
        field name: mu
        value: {state:0 sema:0}
        field name: done
        value: 0xc00003c2a0
        field name: children
        value: map[context.Background.WithValue(type *http.contextKey, val <not Stringer>).WithValue(type *http.contextKey, val [::1]:20885).WithCancel.WithCancel:{}]
        field name: err
        value: <nil>
        field name: mu
        value: {state:0 sema:0}
        field name: done
        value: <nil>
        field name: children
        value: map[]
        field name: err
        value: <nil>
        field name: key
        value: 0
        field name: val
        value: map[]
        field name: key
        value: 1
        field name: val
        value: &{handler:0x151cf50 buildOnly:false name: err:<nil> namedRoutes:map[] routeConf:{useEncodedPath:false strictSlash:false skipClean:false regexp:{host:<nil> path:0xc0003d78f0 queries:[]} matchers:[0xc0003d78f0 [GET POST]] buildScheme: buildVarsFunc:<nil>}}

    */

    printContextInternals(context.Background(), false)
    /* Prints
        Fields for context.emptyCtx
        context is empty (int)
    */
}
</code>```

Body:
It is possible to list the internals of context.Context using unsafe reflection and using that information to figure out the keys and/or see if the information you want is in the context.

There are some pitfall such as if the context implementation returns a hardcoded value for a key it wont show up here, and it can be quite unclear on how to actually access the values using keys.

This is nothing I run in production. But in my case I needed to be able to inspect the context.Context to understand better what information it contains.

func printContextInternals(ctx interface{}, inner bool) {
    contextValues := reflect.ValueOf(ctx).Elem()
    contextKeys := reflect.TypeOf(ctx).Elem()

    if !inner {
        fmt.Printf("\nFields for %s.%s\n", contextKeys.PkgPath(), contextKeys.Name())
    }

    if contextKeys.Kind() == reflect.Struct {
        for i := 0; i < contextValues.NumField(); i++ {
            reflectValue := contextValues.Field(i)
            reflectValue = reflect.NewAt(reflectValue.Type(), unsafe.Pointer(reflectValue.UnsafeAddr())).Elem()

            reflectField := contextKeys.Field(i)

            if reflectField.Name == "Context" {
                printContextInternals(reflectValue.Interface(), true)
            } else {
                fmt.Printf("field name: %+v\n", reflectField.Name)
                fmt.Printf("value: %+v\n", reflectValue.Interface())
            }
        }
    } else {
        fmt.Printf("context is empty (int)\n")
    }
}

Examples:

func Ping(w http.ResponseWriter, r *http.Request) {
    printContextInternals(r.Context(), false)
    /* Prints
        Fields for context.valueCtx
        context is empty (int)
        field name: key
        value: net/http context value http-server
        field name: val
        value: &{Addr::20885 Handler:0xc00001c000 TLSConfig:0xc000001c80 ReadTimeout:0s ReadHeaderTimeout:0s WriteTimeout:0s IdleTimeout:0s MaxHeaderBytes:0 TLSNextProto:map[h2:0x12db010] ConnState:<nil> ErrorLog:<nil> BaseContext:<nil> ConnContext:<nil> disableKeepAlives:0 inShutdown:0 nextProtoOnce:{done:1 m:{state:0 sema:0}} nextProtoErr:<nil> mu:{state:0 sema:0} listeners:map[0xc00015a840:{}] activeConn:map[0xc000556fa0:{}] doneChan:<nil> onShutdown:[0x12e9670]}
        field name: key
        value: net/http context value local-addr
        field name: val
        value: [::1]:20885
        field name: mu
        value: {state:0 sema:0}
        field name: done
        value: 0xc00003c2a0
        field name: children
        value: map[context.Background.WithValue(type *http.contextKey, val <not Stringer>).WithValue(type *http.contextKey, val [::1]:20885).WithCancel.WithCancel:{}]
        field name: err
        value: <nil>
        field name: mu
        value: {state:0 sema:0}
        field name: done
        value: <nil>
        field name: children
        value: map[]
        field name: err
        value: <nil>
        field name: key
        value: 0
        field name: val
        value: map[]
        field name: key
        value: 1
        field name: val
        value: &{handler:0x151cf50 buildOnly:false name: err:<nil> namedRoutes:map[] routeConf:{useEncodedPath:false strictSlash:false skipClean:false regexp:{host:<nil> path:0xc0003d78f0 queries:[]} matchers:[0xc0003d78f0 [GET POST]] buildScheme: buildVarsFunc:<nil>}}

    */

    printContextInternals(context.Background(), false)
    /* Prints
        Fields for context.emptyCtx
        context is empty (int)
    */
}


问:
Table view cells lose their data when leaving view using navigation bar
I have a table view which has custom cells. My table view cell get populated through the values inserted in an SQLite database.

The database values are shown in my table view cells, but the problem is, when I navigate from my table view to the previous view, and back to the tableview through the navigation bar, the table view becomes empty. What might be the problem?

答:
Edited to suggest a more likely solution based on comments to this answer

Assuming you're adding the login view as a modal viewController, you need to refresh the table after each additional login. In your viewWillAppear method reload your tableView:

```<code>[tableView reloadData];
</code>```

Or, if your table takes a while to reload, you can send a notification to the viewController to reload the tableView from the login view before you dismiss it.

<s>Currently-not-visible views can be unloaded at-will by the OS if memory gets tight. A common iOS development mistake is to assume that the code in a viewController's viewDidLoad and viewDidUnload methods will only be called when the view is first loaded and later unloaded. Check to make sure that your viewDidLoad method isn't making any assumptions about the availability of data and that your viewDidUnload method isn't accidentally deleting data that the newly re-called viewDidLoad will need.

Similarly, ensure that your viewWillAppear method isn't being thwarted by something in your viewDidUnload method.

Lastly, and in the same vein, understand that if your view gets dumped by the OS for memory reasons, it will sometimes call your viewDidUnload method as it clears it out, but sometimes seems to not call it, perhaps because the memory used by the view was so great that a failure to clear things out in its didReceiveMemoryWarning method made it decide to just dump the view immediately and completely, without really allowing it to clean itself up.</s>

Body:
Edited to suggest a more likely solution based on comments to this answer

Assuming you're adding the login view as a modal viewController, you need to refresh the table after each additional login. In your viewWillAppear method reload your tableView:

[tableView reloadData];

Or, if your table takes a while to reload, you can send a notification to the viewController to reload the tableView from the login view before you dismiss it.

<s>Currently-not-visible views can be unloaded at-will by the OS if memory gets tight. A common iOS development mistake is to assume that the code in a viewController's viewDidLoad and viewDidUnload methods will only be called when the view is first loaded and later unloaded. Check to make sure that your viewDidLoad method isn't making any assumptions about the availability of data and that your viewDidUnload method isn't accidentally deleting data that the newly re-called viewDidLoad will need.

Similarly, ensure that your viewWillAppear method isn't being thwarted by something in your viewDidUnload method.

Lastly, and in the same vein, understand that if your view gets dumped by the OS for memory reasons, it will sometimes call your viewDidUnload method as it clears it out, but sometimes seems to not call it, perhaps because the memory used by the view was so great that a failure to clear things out in its didReceiveMemoryWarning method made it decide to just dump the view immediately and completely, without really allowing it to clean itself up.</s>


问:
Xcode couldn't find any iOS App Store Provisioning Profiles
I'm using a beta of Xcode 9. I've archived my iOS Project and whenever I try to validate it, I get this error for every one of the targets in my app:

And I'm getting this error for every target like I said. The provisioning profile for each of the targets is an Xcode Managed Profile. What am I doing wrong?

答: It happened to me when I wanted to make an enterprise build but I accidentally selected to upload build to App Store.</p>


问:
R dplyr::Filter dataframe by group and numeric vector?
I have dataframe df1 containing data and groups, and df2 which stores the same groups, and one value per group.

I want to filter rows of df1 by df2 where lag by group is higher than indicated value.

Dummy example:

```<code>  # identify the first year of disturbance by lag by group
df1 <- data.frame(year = c(1:4, 1:4),
                 mort = c(5,16,40,4,5,6,10,108),
                 distance = rep(c("a", "b"), each = 4))

df2 = data.frame(distance = c("a", "b"),
                       my.median = c(12,1))
</code>```

Now calculate the lag between values (creates new column) and filter df1 based on column values of df2:

```<code># calculate lag between years
df1 %>%
  group_by(distance) %>%
  dplyr::mutate(yearLag  = mort - lag(mort, default = 0)) %>%
  filter(yearLag > df2$my.median)  ##
</code>```

This however does not produce expected results:

```<code># A tibble: 3 x 4
# Groups:   distance [2]
   year  mort distance yearLag
  <int> <dbl> <fct>      <dbl>
1     2    16 a             11
2     3    40 a             24
3     4   108 b             98
</code>```

Instead, I expect to get:

```<code># A tibble: 3 x 4
# Groups:   distance [2]
   year  mort distance yearLag
  <int> <dbl> <fct>      <dbl>
1     3    40 a             24
2     1     5 b              5
3     3    10 b              4
</code>```

The filter works great while applied to single value, but how to adapt it to vector, and especially vector of groups (as the order of elements can potentially change?)

答:
Is this what you're trying to do?

```<code>df1 %>%
  group_by(distance) %>%
  dplyr::mutate(yearLag  = mort - lag(mort, default = 0)) %>%
  left_join(df2) %>%
  filter(yearLag > my.median)
</code>```

Result:

```<code># A tibble: 4 x 5
# Groups:   distance [2]
   year  mort distance yearLag my.median
  <int> <dbl> <fct>      <dbl>     <dbl>
1     3    40 a             24        12
2     1     5 b              5         1
3     3    10 b              4         1
4     4   108 b             98         1
</code>```

Body:
I have dataframe df1 containing data and groups, and df2 which stores the same groups, and one value per group.

I want to filter rows of df1 by df2 where lag by group is higher than indicated value.

Dummy example:

  # identify the first year of disturbance by lag by group
df1 <- data.frame(year = c(1:4, 1:4),
                 mort = c(5,16,40,4,5,6,10,108),
                 distance = rep(c("a", "b"), each = 4))

df2 = data.frame(distance = c("a", "b"),
                       my.median = c(12,1))

Now calculate the lag between values (creates new column) and filter df1 based on column values of df2:

# calculate lag between years
df1 %>%
  group_by(distance) %>%
  dplyr::mutate(yearLag  = mort - lag(mort, default = 0)) %>%
  filter(yearLag > df2$my.median)  ##

This however does not produce expected results:

# A tibble: 3 x 4
# Groups:   distance [2]
   year  mort distance yearLag
  <int> <dbl> <fct>      <dbl>
1     2    16 a             11
2     3    40 a             24
3     4   108 b             98

Instead, I expect to get:

# A tibble: 3 x 4
# Groups:   distance [2]
   year  mort distance yearLag
  <int> <dbl> <fct>      <dbl>
1     3    40 a             24
2     1     5 b              5
3     3    10 b              4

The filter works great while applied to single value, but how to adapt it to vector, and especially vector of groups (as the order of elements can potentially change?)

Body:
Is this what you're trying to do?

df1 %>%
  group_by(distance) %>%
  dplyr::mutate(yearLag  = mort - lag(mort, default = 0)) %>%
  left_join(df2) %>%
  filter(yearLag > my.median)

Result:

# A tibble: 4 x 5
# Groups:   distance [2]
   year  mort distance yearLag my.median
  <int> <dbl> <fct>      <dbl>     <dbl>
1     3    40 a             24        12
2     1     5 b              5         1
3     3    10 b              4         1
4     4   108 b             98         1


问:
Check if pandas column contains only 0's or 1's
I want to know if there is a way to check whether a pandas column contains only 0's or 1's. This can be done using df.groupby('col').count() and then verifying that there are only two indices and checking if 0 and 1 are part of the index. Is there a better way?

答:
Use Series.isin with test if all values are Trues by Series.all:

It returns True or False flag. See it in action here.Let's consider this dataframe:

```<code>df = pd.DataFrame({'col1':[0,1,0],
                   'col2':[2,3,1]})
print (df)
   col1  col2
0     0     2
1     1     3
2     0     1

test = df['col1'].isin([0,1]).all()
True

test = df['col2'].isin([0,1]).all()
False
</code>```

Body:
Use Series.isin with test if all values are Trues by Series.all:

It returns True or False flag. See it in action here.Let's consider this dataframe:

df = pd.DataFrame({'col1':[0,1,0],
                   'col2':[2,3,1]})
print (df)
   col1  col2
0     0     2
1     1     3
2     0     1

test = df['col1'].isin([0,1]).all()
True

test = df['col2'].isin([0,1]).all()
False


问:
how to display product detail description on product listing page?
I want to show a detailed product description after a short description on the product listing page.

I'm doing this

```<code><?
echo $_product->getDescription();
?>
</code>```

but nothing shows up.

I also tried this

```<code>Mage::getModel('catalog/product')->load($_product->getProductId())->getDescription();
</code>```

but to no success.

答:
$_product->getProductId() is not the function call you want, it is $_product->getId() :)

I advice you to take a look at the template in .../template/catalog/product/view/description.phtml. That template prints the description for the product view page, so you'll want a similar thing on the list page.

Body:
I want to show a detailed product description after a short description on the product listing page.

I'm doing this

<?
echo $_product->getDescription();
?>

but nothing shows up.

I also tried this

Mage::getModel('catalog/product')->load($_product->getProductId())->getDescription();

but to no success.


答:
Seems like STUFF with CHARINDEX and a couple of replaces does the job:

```<code>DECLARE @string varchar(1024);
SET @string = 'Total # of bytes             : 128270200832 (119.46GB)';
SELECT REPLACE(REPLACE(STUFF(@string,1,CHARINDEX(':',@string)+1,''),'(',''),')','');
</code>```

Edit: Based on the new logic you have defined:

```<code>SELECT SUBSTRING(@String,V.CI,CHARINDEX('(',@String,V.CI) - V.CI)
FROM (VALUES(CHARINDEX(':',@string)+1))V(CI);
</code>```

Title: Extract part of string in multiple places

Body:
Seems like STUFF with CHARINDEX and a couple of replaces does the job:

DECLARE @string varchar(1024);
SET @string = 'Total # of bytes             : 128270200832 (119.46GB)';
SELECT REPLACE(REPLACE(STUFF(@string,1,CHARINDEX(':',@string)+1,''),'(',''),')','');

Edit: Based on the new logic you have defined:

SELECT SUBSTRING(@String,V.CI,CHARINDEX('(',@String,V.CI) - V.CI)
FROM (VALUES(CHARINDEX(':',@string)+1))V(CI);


问:
(NLP) Natural Language Processing Dependancy Libraries issue
I am trying to create a NLP demo and when i am creating dependency parsing i am getting this error.

My Code:

```<code>from nltk.grammar import DependencyGrammar
from nltk.parse import (DependencyGraph,ProjectiveDependencyParser, NonprojectiveDependencyParser)
    dg = DependencyGraph(text)
    dg.tree().pprint()
    for head,dep,rel in     dg.triples():
        print('({h[0]}, {h[1]}), {r}, ({d[0]}, {d[1]})'.format(h=head, r=rel, d=dep))
</code>```

And Error:

```<code>Traceback (most recent call last):
  File "/home/indianic/anaconda3/lib/python3.7/site-packages/nltk/parse/dependencygraph.py", line 351, in _parse
    cell_extractor = extractors[cell_number]
KeyError: 111

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "demo.py", line 77, in <module>
    dependency(text)
  File "demo.py", line 69, in dependency
    dg = DependencyGraph(text)
  File "/home/indianic/anaconda3/lib/python3.7/site-packages/nltk/parse/dependencygraph.py", line 90, in __init__
    top_relation_label=top_relation_label,
  File "/home/indianic/anaconda3/lib/python3.7/site-packages/nltk/parse/dependencygraph.py", line 355, in _parse
    'CoNLL(10) or Malt-Tab(4) format'.format(cell_number)
ValueError: Number of tab-delimited fields (111) not supported by CoNLL(10) or Malt-Tab(4) format.
</code>```

Anyone can help me?

答:
tl;dr you need to be careful with your input text.

Providing plain text will indeed fail:

```<code>>> DependencyGraph("random sentence")
 ...
 ValueError: Number of tab-delimited fields (2) not supported by CoNLL(10) or Malt-Tab(4) format
</code>```

As you may see from its documentation, DependencyGraph is taking as input a string with Malt-TAB format or CoNLL format.

Some examples are shown here. Find one below:

```<code>>>> treebank_data = """Pierre  NNP     2       NMOD
... Vinken  NNP     8       SUB
... ,       ,       2       P
... 61      CD      5       NMOD
... years   NNS     6       AMOD
... old     JJ      2       NMOD
... ,       ,       2       P
... will    MD      0       ROOT
... join    VB      8       VC
... the     DT      11      NMOD
... board   NN      9       OBJ
... as      IN      9       VMOD
... a       DT      15      NMOD
... nonexecutive    JJ      15      NMOD
... director        NN      12      PMOD
... Nov.    NNP     9       VMOD
... 29      CD      16      NMOD
... .       .       9       VMOD
... """
>>> dg = DependencyGraph(treebank_data)
</code>```

So your input text should contain tab separated values such as CoNLL or Malt-Tab format, as is requested from the error message you get.

Body:
I am trying to create a NLP demo and when i am creating dependency parsing i am getting this error.

My Code:

from nltk.grammar import DependencyGrammar
from nltk.parse import (DependencyGraph,ProjectiveDependencyParser, NonprojectiveDependencyParser)
    dg = DependencyGraph(text)
    dg.tree().pprint()
    for head,dep,rel in     dg.triples():
        print('({h[0]}, {h[1]}), {r}, ({d[0]}, {d[1]})'.format(h=head, r=rel, d=dep))

And Error:

Traceback (most recent call last):
  File "/home/indianic/anaconda3/lib/python3.7/site-packages/nltk/parse/dependencygraph.py", line 351, in _parse
    cell_extractor = extractors[cell_number]
KeyError: 111

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "demo.py", line 77, in <module>
    dependency(text)
  File "demo.py", line 69, in dependency
    dg = DependencyGraph(text)
  File "/home/indianic/anaconda3/lib/python3.7/site-packages/nltk/parse/dependencygraph.py", line 90, in __init__
    top_relation_label=top_relation_label,
  File "/home/indianic/anaconda3/lib/python3.7/site-packages/nltk/parse/dependencygraph.py", line 355, in _parse
    'CoNLL(10) or Malt-Tab(4) format'.format(cell_number)
ValueError: Number of tab-delimited fields (111) not supported by CoNLL(10) or Malt-Tab(4) format.

Anyone can help me?

Body:
tl;dr you need to be careful with your input text.

Providing plain text will indeed fail:

>> DependencyGraph("random sentence")
 ...
 ValueError: Number of tab-delimited fields (2) not supported by CoNLL(10) or Malt-Tab(4) format

As you may see from its documentation, DependencyGraph is taking as input a string with Malt-TAB format or CoNLL format.

Some examples are shown here. Find one below:

>>> treebank_data = """Pierre  NNP     2       NMOD
... Vinken  NNP     8       SUB
... ,       ,       2       P
... 61      CD      5       NMOD
... years   NNS     6       AMOD
... old     JJ      2       NMOD
... ,       ,       2       P
... will    MD      0       ROOT
... join    VB      8       VC
... the     DT      11      NMOD
... board   NN      9       OBJ
... as      IN      9       VMOD
... a       DT      15      NMOD
... nonexecutive    JJ      15      NMOD
... director        NN      12      PMOD
... Nov.    NNP     9       VMOD
... 29      CD      16      NMOD
... .       .       9       VMOD
... """
>>> dg = DependencyGraph(treebank_data)

So your input text should contain tab separated values such as CoNLL or Malt-Tab format, as is requested from the error message you get.


问:
Java: How to save a date into MySQL without timezone conversion?
I'm saving a birthday with Java8 + MyBatis + MySQL5.7. My code is like this:

// 'birthday' is a DATE column
@Insert("insert into MyTable (id, birthday) values (#{id"}, #{date})")
void saveDate(int id, LocalDate date);

@Select("select birthday from MyTable where id=#{id"}")
LocalDate loadDate(@Param("id") int id);
```

<p>And the code to save and load a date.</p>

<pre class="lang-java prettyprint-override"><code>final int id = 1;
final LocalDate date = LocalDate.of(2020, 1, 3);

repo.saveDate(id, date);
LocalDate dateFromDB = repo.loadDate(id);

System.out.println(date);        // 2020-1-3
System.out.println(dateFromDB);  // 2020-1-2
</code>```

I noticed that the value of "dateFromDB" is always one day before the "date". I think it's caused by the timezone conversion. Since my application is at UTC+8, while DB is using UTC. By using DATETIME instead of DATE, I can see the date '2020-1-3' is saved as '2020-1-2 16:0:0'.

So the question is how to avoid timezone conversion when saving a date like a birthday?

----------------- Updated 2020-02-20 ------------------------------------

So far, I found 4 ways to do it:

Add a parameter noTzConversionForDateType=true to avoid the conversion only for date type. This is the best way but it only applies to version 5.1. I really don't understand why it's removed from version 8.0... (document)

Add a parameter serverTimezone=GMT%2B8 use the client timezone (UTC+8) as the server timezone. The conversion still happens but it changes nothing. The problem is TIMESTAMP columns would also be affected.

Add a parameter -Duser.timezone=UTC to JVM. The problem is similar to #2.

Send LocalDate value as String. Update the saveDate function as below (only change the type from LocalDate to String):

@Insert("insert into MyTable (id, birthday) values (#{id"}, #{date})")
void saveDate(int id, String date);
```

<p>Then convert the date to a <code>String</code> before calling <code>saveDate</code>:</p>

```String dateString = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
repo.saveDate(id, dateString);
```

Note that the data type in DB is still DATE. The benefit of this way is only the birthday column will be affected. The problem is that the code is not elegant and it might lead to performance issues for a large data set.

答:
Assuming you are connecting to MySQL using a connection string like the following

jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false&serverTimezone=YOUR_TZ

Should do some conversion for you

Body:
I'm saving a birthday with Java8 + MyBatis + MySQL5.7. My code is like this:

// 'birthday' is a DATE column
@Insert("insert into MyTable (id, birthday) values (#{id"}, #{date})")
void saveDate(int id, LocalDate date);

@Select("select birthday from MyTable where id=#{id"}")
LocalDate loadDate(@Param("id") int id);

And the code to save and load a date.

final int id = 1;
final LocalDate date = LocalDate.of(2020, 1, 3);

repo.saveDate(id, date);
LocalDate dateFromDB = repo.loadDate(id);

System.out.println(date);        // 2020-1-3
System.out.println(dateFromDB);  // 2020-1-2

I noticed that the value of "dateFromDB" is always one day before the "date". I think it's caused by the timezone conversion. Since my application is at UTC+8, while DB is using UTC. By using DATETIME instead of DATE, I can see the date '2020-1-3' is saved as '2020-1-2 16:0:0'.

So the question is how to avoid timezone conversion when saving a date like a birthday?

----------------- Updated 2020-02-20 ------------------------------------

So far, I found 4 ways to do it:

Add a parameter noTzConversionForDateType=true to avoid the conversion only for date type. This is the best way but it only applies to version 5.1. I really don't understand why it's removed from version 8.0... (document)

Add a parameter serverTimezone=GMT%2B8 use the client timezone (UTC+8) as the server timezone. The conversion still happens but it changes nothing. The problem is TIMESTAMP columns would also be affected.

Add a parameter -Duser.timezone=UTC to JVM. The problem is similar to #2.

Send LocalDate value as String. Update the saveDate function as below (only change the type from LocalDate to String):

@Insert("insert into MyTable (id, birthday) values (#{id"}, #{date})")
void saveDate(int id, String date);

Then convert the date to a String before calling saveDate:

String dateString = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
repo.saveDate(id, dateString);

Note that the data type in DB is still DATE. The benefit of this way is only the birthday column will be affected. The problem is that the code is not elegant and it might lead to performance issues for a large data set.


问:
How do I run two isolated instances of firefox?
For testing purposes, I want to install two different instances of firefox on ubuntu - so that they don't share cookies.
(I want to simultaneously login with both instances as different users to our website).
How do I do that?
I do it with Firefox & Opera, but I prefer Firefox (because of firebug).</p>

答:
In linux terminal run,

firefox -new-instance -P "Another Profile"

Then create new profile > start firefox.

It opens new instance, not a new window in running instance, which allows multiple copies of application to be open at a time.

From next time firefox -new-instance -P <Profile name>

Source:  mozilla website

OwnerDisplayName: andy

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: leppie


问:
how to show PDF from mobile storage in xamarin android c# app?
I am working in a xmarin android app in c#. I want to open a pdf file which is in a custom folder of internal storage "TESTFOLDER". code is given below, every time it is going to the catch section whiche it is going to start the activity. how to open it?

code

```<code>var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/TESTFOLDER";
                Java.IO.File file = new Java.IO.File(externalPath, "qdummy.pdf");
                if(file.Exists())
                {
                    try
                    {
                        file.SetReadable(true);
                        Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
                        Intent intent = new Intent(Intent.ActionView);
                        intent.SetDataAndType(uri, "application/pdf");
                        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
                        intent.SetFlags(ActivityFlags.NoHistory);
                        StartActivity(intent);
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(Application.Context, "problem", ToastLength.Long).Show();
                    }
                }
                else
                {
                    Toast.MakeText(Application.Context, "No exx", ToastLength.Long).Show();
                }
</code>```

答:
issue has been resolved,

** please follow all the steps written in this blog, just replace the try catch block to resolve the issue.

```<code>try
                    {
                        string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
                        string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                        Intent intent = new Intent(Intent.ActionView);
                        intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
                        Android.Net.Uri path = FileProvider.GetUriForFile(Application.Context, Android.App.Application.Context.PackageName + ".provider", file);
                        intent.SetDataAndType(path, mimeType);
                        intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                        Application.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(Application.Context, "problem", ToastLength.Long).Show();
                    }
</code>```

Body:
I am working in a xmarin android app in c#. I want to open a pdf file which is in a custom folder of internal storage "TESTFOLDER". code is given below, every time it is going to the catch section whiche it is going to start the activity. how to open it?

code

var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/TESTFOLDER";
                Java.IO.File file = new Java.IO.File(externalPath, "qdummy.pdf");
                if(file.Exists())
                {
                    try
                    {
                        file.SetReadable(true);
                        Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
                        Intent intent = new Intent(Intent.ActionView);
                        intent.SetDataAndType(uri, "application/pdf");
                        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
                        intent.SetFlags(ActivityFlags.NoHistory);
                        StartActivity(intent);
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(Application.Context, "problem", ToastLength.Long).Show();
                    }
                }
                else
                {
                    Toast.MakeText(Application.Context, "No exx", ToastLength.Long).Show();
                }

Body:
issue has been resolved,

** please follow all the steps written in this blog, just replace the try catch block to resolve the issue.

try
                    {
                        string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
                        string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                        Intent intent = new Intent(Intent.ActionView);
                        intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
                        Android.Net.Uri path = FileProvider.GetUriForFile(Application.Context, Android.App.Application.Context.PackageName + ".provider", file);
                        intent.SetDataAndType(path, mimeType);
                        intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                        Application.Context.StartActivity(Intent.CreateChooser(intent, "Choose App"));
                    }
                    catch (Exception ex)
                    {
                        Toast.MakeText(Application.Context, "problem", ToastLength.Long).Show();
                    }


问:
How to find c++ include file names when Microsoft documentation only includes C# examples
When MSDN only contains C# examples, and I am trying to code C++, how can I find the names of the required include files?  For example, I want to write some C++ code that uses the TextPointer class, how do I find the #include statements that are required?

答:
TextPointer is a .NET class. C++Builder does not support .NET development, which is why its compiler  can't find any .NET related C++ header files - they don't exist in C++Builder's runtime libraries.

The only way you can use .NET classes in C++Builder projects is if either:

the .NET classes are COM compatible (ie, have the [ComVisible(true)] attribute), then C++Builder code can create instances of the appropriate COM objects.

you wrap your .NET code in a DLL written in Visual Studio, and have it export a C compatible interface so C++Builder code can then use it.

you use a 3rd party framework, like CrossTalk or Hydra, that allows C++Builder code to host the .NET runtime and use .NET assemblies and types as-is.


答:
You can also melt your columns and value_counts:

```<code>print (df.melt(id_vars="id", value_vars=df.columns[1:])["value"].value_counts())

coffee      5
bread       2
nuts        1
potatoes    1
cake        1
beer        1
fish        1
</code>```

Title: Search muliple columns for the most common value

Body:
excuse the basic nature of this question but I have searched for hours for an answer and they all seem to over complicate what I need.

I have a dataframe like the following: -

id food_item_1   food_item_2   food_item_3

1  nuts          bread         coffee
2  potatoes      coffee        cake
3  fish          beer          coffee
4  bread         coffee        coffee

What I want to do is search all the 'food_item_*' columns (so in this case there are 3) and have returned back to me the single most common value such as e.g. 'coffee' across all 3 columns.

Could someone please recommend the best way to do this?

Many thanks

md

Body:
You can also melt your columns and value_counts:

print (df.melt(id_vars="id", value_vars=df.columns[1:])["value"].value_counts())

coffee      5
bread       2
nuts        1
potatoes    1
cake        1
beer        1
fish        1


问:
How to Display few Labels in One Line and Few in the next line with Python Tkinter?
I have a Program that displays Labels on the GUI screen but all in one Line. I want to display all Labels in first Loop in one Line and all Labels in second Loop in another line. Code is Below:

```<code>from tkinter import *
import tkinter as tk

win = Tk()
win.title("Labels")
win.geometry("800x600+50+50")
win.config(bg='white')

label1=Label(win, text="All Labels", font=("Calibri",24,"bold"), bg='white', borderwidth=1, relief="solid")
label1.pack(pady=15)

for a in range(10):
    pre1=Label(win, text=("PIN",a), font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
    pre1.pack(side=tk.LEFT)

for b in range(10):

    if (b%2==0):
        pre2=Label(win, text="OFF", font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
        pre2.pack(side=tk.LEFT)
    else:
        pre3=Label(win, text="ON", font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
        pre3.pack(side=tk.LEFT)

win.mainloop()
</code>```

Output:

答:
This should work:

```<code>from tkinter import *
import tkinter as tk

win = Tk()
win.title("Labels")
win.geometry("800x600+50+50")
win.config(bg='white')

label1=Label(win, text="All Labels", font=("Calibri",24,"bold"), bg='white', borderwidth=1, relief="solid")
label1.pack(pady=15)

lblframe = tk.Frame(win)
for a in range(10):
    pre1=Label(lblframe, text=("PIN",a), font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
    pre1.grid(row=0, column=a)

for b in range(10):

    if (b%2==0):
        pre2=Label(lblframe, text="OFF", font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
        pre2.grid(row=1, column=b)
    else:
        pre3=Label(lblframe, text="ON", font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
        pre3.grid(row=1, column=b)

lblframe.pack()

win.mainloop()
</code>```

Body:
I have a Program that displays Labels on the GUI screen but all in one Line. I want to display all Labels in first Loop in one Line and all Labels in second Loop in another line. Code is Below:

from tkinter import *
import tkinter as tk

win = Tk()
win.title("Labels")
win.geometry("800x600+50+50")
win.config(bg='white')

label1=Label(win, text="All Labels", font=("Calibri",24,"bold"), bg='white', borderwidth=1, relief="solid")
label1.pack(pady=15)

for a in range(10):
    pre1=Label(win, text=("PIN",a), font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
    pre1.pack(side=tk.LEFT)

for b in range(10):

    if (b%2==0):
        pre2=Label(win, text="OFF", font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
        pre2.pack(side=tk.LEFT)
    else:
        pre3=Label(win, text="ON", font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
        pre3.pack(side=tk.LEFT)

win.mainloop()

Output:

Body:
This should work:

from tkinter import *
import tkinter as tk

win = Tk()
win.title("Labels")
win.geometry("800x600+50+50")
win.config(bg='white')

label1=Label(win, text="All Labels", font=("Calibri",24,"bold"), bg='white', borderwidth=1, relief="solid")
label1.pack(pady=15)

lblframe = tk.Frame(win)
for a in range(10):
    pre1=Label(lblframe, text=("PIN",a), font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
    pre1.grid(row=0, column=a)

for b in range(10):

    if (b%2==0):
        pre2=Label(lblframe, text="OFF", font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
        pre2.grid(row=1, column=b)
    else:
        pre3=Label(lblframe, text="ON", font=("Calibri",12), bg="white", borderwidth=1, relief="solid")
        pre3.grid(row=1, column=b)

lblframe.pack()

win.mainloop()


问:
Difference between Openzeppelin SDK and Truffle?
For smart contract development, what is the difference between Openzeppelin SDK and Truffle? When should I use one or another, or both together? </p>

答:
OpenZeppelin Contracts: library of SmartContracts, that can be inherited and used to develop upon;

OpenZeppelin SDK: is former ZeppelinOS, it is SDK to help development process;

Truffle SDK: is well-known SDK to help development process as well. Besides SDK Truffle has other great projects as Ganache.

Spend some time to read documentation - it is very clear documented.

PS: ZeppelinOS was first SDK, that allowed to develop Upgradable Smart Contracts - really cool (https://medium.com/coinmonks/how-to-create-an-upgradeable-smart-contract-using-openzeppelin-sdk-example-of-fixing-smart-260dfbfd5bae)


问:
Convert moment.Duration into string
I have a moment.Duration object which I need to convert to string format HH:mm:ss (without any timezone conversion). I know we can do like

```<code>foobar.hours + ":" + foobar.minutes + ":" + foobar.seconds
</code>```

But honestly I was hoping to have a better solution that just string manipulations.

答:
```<code>var now = moment()
var then = moment().subtract(3, 'hours').subtract(20, 'minutes')

const duration = now.subtract(then)

duration.format("HH:mm:ss")

>> 03:20:00
</code>```

Title: Convert moment.Duration into string

Body:
I have a moment.Duration object which I need to convert to string format HH:mm:ss (without any timezone conversion). I know we can do like

foobar.hours + ":" + foobar.minutes + ":" + foobar.seconds

But honestly I was hoping to have a better solution that just string manipulations.


问:
Keras sequential model with multiple inputs, Tensorflow 1.9.0
I try creating a neural network, having two inputs of a particular size (here four) each and one output of the same size size (so also four). Unfortunately, I always get this error when running my code:

```<code>ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not
the size the model expected. Expected to see 2 array(s), but instead got the following list of 1 arrays:
[array([[[-1.07920336,  1.16782929,  1.40131554, -0.30052492],
         [-0.50067655,  0.54517916, -0.87033621, -0.22922157]],

        [[-0.53766128, -0.03527806, -0.14637072,  2.32319071],
         [ 0...
</code>```

I think, the problem lies in the fact, that once I pass the data for training, the input shape is either incorrect or I have a datatype issue. Hence, there is an extra list bracket around the array.

I'm using Tensorflow 1.9.0 (due to project restrictions). I already checked the search function and tried solutions provided here. Following is an example code for reproducting the error of mine:

```<code>import numpy as np
import tensorflow as tf
from tensorflow import keras
import keras.backend as K
from tensorflow.keras import layers, models

def main():

    ip1 = keras.layers.Input(shape=(4,))
    ip2 = keras.layers.Input(shape=(4,))
    dense = layers.Dense(3, activation='sigmoid', input_dim=4)  # Passing the value in a weighted manner
    merge_layer = layers.Concatenate()([ip1, ip2])  # Concatenating the outputs of the first network
    y = layers.Dense(6, activation='sigmoid')(merge_layer)  # Three fully connected layers
    y = layers.Dense(4, activation='sigmoid')(y)
    model = keras.Model(inputs=[ip1, ip2], outputs=y)

    model.compile(optimizer='adam',
                  loss='mean_squared_error')
    model.summary()

    # dataset shape: 800 samples, 2 inputs for sequential model, 4 input size
    X_train = np.random.randn(800, 2, 4)
    y_train = np.random.randn(800, 4)
    X_test = np.random.randn(200, 2, 4)
    y_test = np.random.randn(200, 4)

    history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=1000, batch_size=32)

 if __name__ == '__main__':
     main()
</code>```

答:
When there is multiple inputs keras expects list of multiple arrays. The size of the list corresponds to number of inputs you have for the model. </p>

<p>So basically you need to pass a list of 2 array each with shape (X,4) </p>

```<code>X_train1 = np.random.randn(800, 4)
X_train2=np.random.randn(800,4)
y_train = np.random.randn(800, 4)
X_test1 = np.random.randn(200, 4)
X_test2 = np.random.randn(200, 4)
y_test = np.random.randn(200, 4)

history = model.fit([X_train1,X_train2], y_train, validation_data=([X_test1,X_test2], y_test), epochs=1000, batch_size=32)
</code>```

Body:
I try creating a neural network, having two inputs of a particular size (here four) each and one output of the same size size (so also four). Unfortunately, I always get this error when running my code:

ValueError: Error when checking model input: the list of Numpy arrays that you are passing to your model is not
the size the model expected. Expected to see 2 array(s), but instead got the following list of 1 arrays:
[array([[[-1.07920336,  1.16782929,  1.40131554, -0.30052492],
         [-0.50067655,  0.54517916, -0.87033621, -0.22922157]],

        [[-0.53766128, -0.03527806, -0.14637072,  2.32319071],
         [ 0...

I think, the problem lies in the fact, that once I pass the data for training, the input shape is either incorrect or I have a datatype issue. Hence, there is an extra list bracket around the array.

I'm using Tensorflow 1.9.0 (due to project restrictions). I already checked the search function and tried solutions provided here. Following is an example code for reproducting the error of mine:

import numpy as np
import tensorflow as tf
from tensorflow import keras
import keras.backend as K
from tensorflow.keras import layers, models

def main():

    ip1 = keras.layers.Input(shape=(4,))
    ip2 = keras.layers.Input(shape=(4,))
    dense = layers.Dense(3, activation='sigmoid', input_dim=4)  # Passing the value in a weighted manner
    merge_layer = layers.Concatenate()([ip1, ip2])  # Concatenating the outputs of the first network
    y = layers.Dense(6, activation='sigmoid')(merge_layer)  # Three fully connected layers
    y = layers.Dense(4, activation='sigmoid')(y)
    model = keras.Model(inputs=[ip1, ip2], outputs=y)

    model.compile(optimizer='adam',
                  loss='mean_squared_error')
    model.summary()

    # dataset shape: 800 samples, 2 inputs for sequential model, 4 input size
    X_train = np.random.randn(800, 2, 4)
    y_train = np.random.randn(800, 4)
    X_test = np.random.randn(200, 2, 4)
    y_test = np.random.randn(200, 4)

    history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=1000, batch_size=32)

 if __name__ == '__main__':
     main()

Body:
When there is multiple inputs keras expects list of multiple arrays. The size of the list corresponds to number of inputs you have for the model.

So basically you need to pass a list of 2 array each with shape (X,4)

X_train1 = np.random.randn(800, 4)
X_train2=np.random.randn(800,4)
y_train = np.random.randn(800, 4)
X_test1 = np.random.randn(200, 4)
X_test2 = np.random.randn(200, 4)
y_test = np.random.randn(200, 4)

history = model.fit([X_train1,X_train2], y_train, validation_data=([X_test1,X_test2], y_test), epochs=1000, batch_size=32)