问:
java.lang.UnsupportedClassVersionError in Dynamic Web Project (Eclipse)
I am looking to create a basic web app using eclipse and Azure. I am able to get basic print statements uploaded to the internet but when i try to reference a class in the same project, but different package, i get an error screen. I dont understand these errors and have made sure that i updated and reinstalled a new version of JDK. This only happens when calling another class. The original error was "tester/Lowercase has been compiled by a more recent version of Java Runtime (class file version 57), this version of the Runtime only recognizes class file versions up to 52.0 (unable to load class [tester.Lowercase()]". That is when i installed a different JDK, and now i am getting a different error that im having a harder time finding the solution for. The error shown in index.jsp is "The superclass "javax.servlet.http.HttpServlet" was not found on the java build path". I chose to ignore this for now, since a friend did the same exact code as me on his computer and was able to get it to work easily. This error was also resolved when i selected Tomcat under runtimes in my Project Facets, in the properties menu of my project.

This is the jsp file titled "index.jsp"

```<code><%@ page import="tester.Lowercase" %>
<html>
<body>
   <% out.println(Lowercase.makeItLower("MAKE THIS LOWERCASE")); %>
</body>
</html>
</code>```

This is the java class titled "Lowercase.java"

```<code>package tester;

public class Lowercase {
   public static String makeItLower(String data) {
      String str = data.toLowerCase();
      return str;
   }
}
</code>```

I know this is really simple code and should be a simple task, but this error i am getting is stopping me from advancing in making this webapp.

答:
You say that you have solved the UnsupportedClassVersionError problem, so I won't talk about that.

Java SE does not include javax.servlet.http.HttpServlet in its class library.  That class and related classes comes from the Java EE APIs.  So to compile your JSP in Eclipse you need to configure the build path for your project to include a JAR file containing those APIs.

You can download different versions of the APIs from Maven Central; for example, this page will give you the 3.0.1 version https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api/3.0.1.  Click on the "jar" link on that page.  Or if you are using one of the supported build tools, add the corresponding dependency information on that page to your build file.

The reason your JSP works when you deploy it to Tomcat is that Tomcat has its own copy of the servlet classes, and it automatically includes them on its build classpath when it compiles a JSP.

Body:
I am looking to create a basic web app using eclipse and Azure. I am able to get basic print statements uploaded to the internet but when i try to reference a class in the same project, but different package, i get an error screen. I dont understand these errors and have made sure that i updated and reinstalled a new version of JDK. This only happens when calling another class. The original error was "tester/Lowercase has been compiled by a more recent version of Java Runtime (class file version 57), this version of the Runtime only recognizes class file versions up to 52.0 (unable to load class [tester.Lowercase()]". That is when i installed a different JDK, and now i am getting a different error that im having a harder time finding the solution for. The error shown in index.jsp is "The superclass "javax.servlet.http.HttpServlet" was not found on the java build path". I chose to ignore this for now, since a friend did the same exact code as me on his computer and was able to get it to work easily. This error was also resolved when i selected Tomcat under runtimes in my Project Facets, in the properties menu of my project.

This is the jsp file titled "index.jsp"

<%@ page import="tester.Lowercase" %>

   <% out.println(Lowercase.makeItLower("MAKE THIS LOWERCASE")); %>

This is the java class titled "Lowercase.java"

package tester;

public class Lowercase {
   public static String makeItLower(String data) {
      String str = data.toLowerCase();
      return str;
   }
}

I know this is really simple code and should be a simple task, but this error i am getting is stopping me from advancing in making this webapp.


来源: stackexchange

问:
How to get all buttons at once?
```<code>Button button = findViewById(R.id.button1);
</code>```

That's the only way I know to get the button, but I have 45 buttons and it's too hard for me to get the buttons one by one.

Is there is any way to get all the buttons at once?

答:
as far as i understood your question i think you can find your answer on this post.
How to get all Buttons ID's in one time on Android</p>

ContentLicense: CC BY-SA 4.0

Title: How to get all buttons at once?

Body:
Button button = findViewById(R.id.button1);

That's the only way I know to get the button, but I have 45 buttons and it's too hard for me to get the buttons one by one.

Is there is any way to get all the buttons at once?


问:
Jest cannot find module 'config'
I'm using Jest to test my api calls file, when I run a simple test I've got an error Cannot find module 'config' from 'api.service.js' which is an import at the top of my api.service.js file:

```<code>//api.service.js
import config from "config"; //get data from my webpack.config.js
export const apiService = {getmyData};
function getmyData() {
  let queryString = `${config.API}/api/datacall`;

  return new Promise(
    (resolve, reject) => {
      client.get(`${config.API}/api/datacall`).then(result => {
        return resolve(result );
      });
    },
    error => {
      return reject(error);
    }
  );
}
</code>```

Test File in the same folder as the above

```<code>//api.spec.js
import getmyDatafrom "./api.service";

const domain = "http://fakeapi.com";

const mockedConsolelog = jest.spyOn(global.console, "log");
const mockedConsoleerror = jest.spyOn(global.console, "error");
</code>```

Why can't my test file get to my config like the api.service.js?

答:
You probably have to do the import with a relative path.

```<code>import config from "./config";
</code>```

Otherwise, it tries to import something from an npm module called config.

Title: Jest cannot find module 'config'

Body:
I'm using Jest to test my api calls file, when I run a simple test I've got an error Cannot find module 'config' from 'api.service.js' which is an import at the top of my api.service.js file:

//api.service.js
import config from "config"; //get data from my webpack.config.js
export const apiService = {getmyData};
function getmyData() {
  let queryString = `${config.API}/api/datacall`;

  return new Promise(
    (resolve, reject) => {
      client.get(`${config.API}/api/datacall`).then(result => {
        return resolve(result );
      });
    },
    error => {
      return reject(error);
    }
  );
}

Test File in the same folder as the above

//api.spec.js
import getmyDatafrom "./api.service";

const domain = "http://fakeapi.com";

const mockedConsolelog = jest.spyOn(global.console, "log");
const mockedConsoleerror = jest.spyOn(global.console, "error");

Why can't my test file get to my config like the api.service.js?

Body:
You probably have to do the import with a relative path.

import config from "./config";

Otherwise, it tries to import something from an npm module called config.


问:
Encrypt site_id in URL show details
I have database

```<code>site_id | site_name | site_status
1       | site A    | 1
2       | site B    | 1
3       | site C    | 1
</code>```

SiteController

```<code>public function show(site $site,$id)
{
    $site = site::where('site_id',$id)->first();
    // return $id;
    return view('master.site.show',compact('site'));
}
</code>```

User.php (Model)

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Site extends Model
{
    protected $table = "site";
    protected $primaryKey = 'site_id';

    protected $fillable = ['site_name','site_status','created_by','created_date'];
}
</code>```

Routes.

```<code>Route::get('/site_show/{id}', 'SiteController@show')->name('site_show');
</code>```

View.

```<code><a class="btn btn-info" href="{{ route('site_show',['id'=>$site->site_id]) }}"><i class="fas fa-eye"></i> Show</a>
</code>```

please help me step by step when I click Show button in show.blade, url will display http://localhost/myproject/public/site_show/asndlah9q8yasa not http://localhost/myproject/public/site_show/2

Thanks a lot for your help

答:
Hi you can use encrypt() and decrypt() Laravel helper function.

your controller

```<code>public function show(site $site,$id)
{
    $site = site::where('site_id',decrypt($id))->first();
    // return $id;
    return view('master.site.show',compact('site'));
}
</code>```

Your views

```<code><a class="btn btn-info" href="{{ route('site_show',['id'=>encrypt($site->site_id)]) }}"><i class="fas fa-eye"></i> Show</a>
</code>```

Title: Encrypt site_id in URL show details

Body:
I have database

site_id | site_name | site_status
1       | site A    | 1
2       | site B    | 1
3       | site C    | 1

SiteController

public function show(site $site,$id)
{
    $site = site::where('site_id',$id)->first();
    // return $id;
    return view('master.site.show',compact('site'));
}

User.php (Model)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Site extends Model
{
    protected $table = "site";
    protected $primaryKey = 'site_id';

    protected $fillable = ['site_name','site_status','created_by','created_date'];
}

Routes.

Route::get('/site_show/{id}', 'SiteController@show')->name('site_show');

View.

$site->site_id]) }}"> Show

please help me step by step when I click Show button in show.blade, url will display http://localhost/myproject/public/site_show/asndlah9q8yasa not http://localhost/myproject/public/site_show/2

Thanks a lot for your help

Body:
Hi you can use encrypt() and decrypt() Laravel helper function.

your controller

public function show(site $site,$id)
{
    $site = site::where('site_id',decrypt($id))->first();
    // return $id;
    return view('master.site.show',compact('site'));
}

Your views

<a class="btn btn-info" href="{{ route('site_show',['id'=>encrypt($site->site_id)]) }}"><i class="fas fa-eye"></i> Show</a>


问:
How to configure SSL in WSO2 APIM Analytic 3.0.0?
I'm using WSO2 APIM ( source am) and WSO2 APIM Analytic ( source worker and source dashboard) on Docker.

I'm searching solution to change certificate of WSO2 Analytic.

I know that this new version, we need configure deployment.yaml file. But it seems hard to understand. And I dont know which element I need to configure. There are two suspicious elements, which have keystore property:

```<code>databridge.config:
    # No of worker threads to consume events
    # THIS IS A MANDATORY FIELD
  workerThreads: 10
    # Maximum amount of messages that can be queued internally in MB
    # THIS IS A MANDATORY FIELD
  maxEventBufferCapacity: 10000000
    # Queue size; the maximum number of events that can be stored in the queue
    # THIS IS A MANDATORY FIELD
  eventBufferSize: 2000
    # Keystore file path
    # THIS IS A MANDATORY FIELD
  keyStoreLocation : ${sys:carbon.home}/resources/security/wso2carbon.jks
    # Keystore password
    # THIS IS A MANDATORY FIELD
  keyStorePassword : wso2carbon
    # Session Timeout value in mins
    # THIS IS A MANDATORY FIELD
  clientTimeoutMin: 30
    # Data receiver configurations
    # THIS IS A MANDATORY FIELD
  dataReceivers:
  -
      # Data receiver configuration
    dataReceiver:
        # Data receiver type
        # THIS IS A MANDATORY FIELD
      type: Thrift
        # Data receiver properties
      properties:
        tcpPort: '7611'
        sslPort: '7711'

  -
      # Data receiver configuration
    dataReceiver:
        # Data receiver type
        # THIS IS A MANDATORY FIELD
      type: Binary
        # Data receiver properties
      properties:
        tcpPort: '9611'
        sslPort: '9711'
        tcpReceiverThreadPoolSize: '100'
        sslReceiverThreadPoolSize: '100'
        hostName: 0.0.0.0
</code>```

and

```<code> wso2.transport.http:
  transportProperties:
    - name: "server.bootstrap.socket.timeout"
      value: 60
    - name: "client.bootstrap.socket.timeout"
      value: 60
    - name: "latency.metrics.enabled"
      value: true

  listenerConfigurations:
    - id: "default-https"
      host: "0.0.0.0"
      port: 9643
      scheme: https
      keyStoreFile: "${carbon.home}/resources/security/wso2carbon.jks"
      keyStorePassword: wso2carbon
      certPass: wso2carbon
</code>```

So what exactly should I configure?

Thank you very much.

答:
You should be able to achieve it as follows.

1) For worker profile

```<code>databridge.config:
&
listenerConfigurations :   id: "msf4j-https"
</code>```

2) For dashboard profile

```<code>listenerConfigurations: id: "default-https"
</code>```

Body:
I'm using WSO2 APIM ( source am) and WSO2 APIM Analytic ( source worker and source dashboard) on Docker.

I'm searching solution to change certificate of WSO2 Analytic.

I know that this new version, we need configure deployment.yaml file. But it seems hard to understand. And I dont know which element I need to configure. There are two suspicious elements, which have keystore property:

databridge.config:
    # No of worker threads to consume events
    # THIS IS A MANDATORY FIELD
  workerThreads: 10
    # Maximum amount of messages that can be queued internally in MB
    # THIS IS A MANDATORY FIELD
  maxEventBufferCapacity: 10000000
    # Queue size; the maximum number of events that can be stored in the queue
    # THIS IS A MANDATORY FIELD
  eventBufferSize: 2000
    # Keystore file path
    # THIS IS A MANDATORY FIELD
  keyStoreLocation : ${sys:carbon.home}/resources/security/wso2carbon.jks
    # Keystore password
    # THIS IS A MANDATORY FIELD
  keyStorePassword : wso2carbon
    # Session Timeout value in mins
    # THIS IS A MANDATORY FIELD
  clientTimeoutMin: 30
    # Data receiver configurations
    # THIS IS A MANDATORY FIELD
  dataReceivers:
  -
      # Data receiver configuration
    dataReceiver:
        # Data receiver type
        # THIS IS A MANDATORY FIELD
      type: Thrift
        # Data receiver properties
      properties:
        tcpPort: '7611'
        sslPort: '7711'

  -
      # Data receiver configuration
    dataReceiver:
        # Data receiver type
        # THIS IS A MANDATORY FIELD
      type: Binary
        # Data receiver properties
      properties:
        tcpPort: '9611'
        sslPort: '9711'
        tcpReceiverThreadPoolSize: '100'
        sslReceiverThreadPoolSize: '100'
        hostName: 0.0.0.0

and

 wso2.transport.http:
  transportProperties:
    - name: "server.bootstrap.socket.timeout"
      value: 60
    - name: "client.bootstrap.socket.timeout"
      value: 60
    - name: "latency.metrics.enabled"
      value: true

  listenerConfigurations:
    - id: "default-https"
      host: "0.0.0.0"
      port: 9643
      scheme: https
      keyStoreFile: "${carbon.home}/resources/security/wso2carbon.jks"
      keyStorePassword: wso2carbon
      certPass: wso2carbon

So what exactly should I configure?

Thank you very much.

Body:
You should be able to achieve it as follows.

1) For worker profile

databridge.config:
&
listenerConfigurations :   id: "msf4j-https"

2) For dashboard profile

listenerConfigurations: id: "default-https"


问:
SQL Group By with limit and distinct - MySQL
This is my tables and structure

Shoutbox

SID   //PK

Title //Title

shoutbox_follower

SID

UID //User ID

Shouts

SID

Text //Shouts

I want to get the last 1 (latest) shouts(Shouts.Text) for each Shoutbox, which the user is following

i tried this but it did not worked

```<code>select shoutbox_follower.SID,shoutbox.title, shouts.text from shoutbox_follower, shoutbox, shouts where shoutbox_follower.uid=1;
</code>```

But i can do the work with multiple query

```<code>SELECT SID from shoutBox_Follower where UID=5
SELECT SID,TEXT from Shouts where SID in ($boxList) order by id desc limit 1
SELECT Title from Shoutbox where SID=? limit 1
</code>```

答:
In comments you mentioned that you need fast solution. If so - then add a field latest_shout_id to the shoutbox table and maintain it with AFTER INSERT trigger of shouts table. That's all.

Here is the query that will do what you want (assuming you have shout_id as a PK in shouts table and reference to shoutbox by shoutbox_id field):

```<code>    SELECT x.*
      FROM shoutbox_follower f
INNER JOIN (SELECT MAX(shout_id) shout_id,
                   shoutbox_id
              FROM Shouts s
          GROUP BY shoutbox_id) x ON x.shoutbox_id = f.sid
     WHERE f.uid = 5
</code>```

Changing it to correlated subquery may change it in faster or slower manner, it depends on a lot of factors.

ContentLicense: CC BY-SA 3.0

Body:
This is my tables and structure

Shoutbox

SID   //PK

Title //Title

shoutbox_follower

SID

UID //User ID

Shouts

SID

Text //Shouts

I want to get the last 1 (latest) shouts(Shouts.Text) for each Shoutbox, which the user is following

i tried this but it did not worked

select shoutbox_follower.SID,shoutbox.title, shouts.text from shoutbox_follower, shoutbox, shouts where shoutbox_follower.uid=1;

But i can do the work with multiple query

SELECT SID from shoutBox_Follower where UID=5
SELECT SID,TEXT from Shouts where SID in ($boxList) order by id desc limit 1
SELECT Title from Shoutbox where SID=? limit 1

Body:
In comments you mentioned that you need fast solution. If so - then add a field latest_shout_id to the shoutbox table and maintain it with AFTER INSERT trigger of shouts table. That's all.

Here is the query that will do what you want (assuming you have shout_id as a PK in shouts table and reference to shoutbox by shoutbox_id field):

    SELECT x.*
      FROM shoutbox_follower f
INNER JOIN (SELECT MAX(shout_id) shout_id,
                   shoutbox_id
              FROM Shouts s
          GROUP BY shoutbox_id) x ON x.shoutbox_id = f.sid
     WHERE f.uid = 5

Changing it to correlated subquery may change it in faster or slower manner, it depends on a lot of factors.


问:
Elasticsearch, terms aggs according to sibling nested fields
Elasticsearch v7.5

Hello and good day!

We have 2 indices named socialmedia and influencers

Sample contents:

socialmedia:

```<code>{
    '_id' : 1001,
    'title' : "Title 1",
    'smp_id' : 1,
    "latest" : [
        {
          "soc_mm_score" : "5",
        }
    ]
},
{
    '_id' : 1002,
    'title' : "Title 2",
    'smp_id' : 2,
    "latest" : [
        {
          "soc_mm_score" : "10",
        }
    ]
},
{
    '_id' : 1003,
    'title' : "Title 3",
    'smp_id' : 3,
    "latest" : [
        {
          "soc_mm_score" : "35",
        }
    ]
},
{
    '_id' : 1004,
    'title' : "Title 4",
    'smp_id' : 2,
    "latest" : [
        {
          "soc_mm_score" : "30",
        }
    ]
}
</code>```

//omitted some other fields

influencers:

```<code>{
    '_id' : 1,
    'name' : "John",
    'smp_id' : 1
},
{
    '_id' : 2,
    'name' : "Peter",
    'smp_id' : 2
},
{
    '_id' : 3,
    'name' : "Mark",
    'smp_id' : 3
}
</code>```

Now I have this simple query that determines which documents in the socialmedia index has the most latest.soc_mm_score value, and also displaying their corresponding influencers determined by the smp_id

```<code>GET socialmedia/_search
{
  "size": 0,
  "_source": "latest",
  "query": {
    "match_all": {}
  },
  "aggs": {
    "LATEST": {
      "nested": {
        "path": "latest"
      },
      "aggs": {
        "MM_SCORE": {
          "terms": {
            "field": "latest.soc_mm_score",
            "order": {
              "_key": "desc"
            },
            "size": 3
          },
          "aggs": {
            "REVERSE": {
              "reverse_nested": {},
              "aggs": {
                "SMP_ID": {
                  "top_hits": {
                    "_source": ["smp_id"],
                    "size": 1
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

SAMPLE OUTPUT:

```<code>"aggregations" : {
    "LATEST" : {
      "doc_count" : //omitted,
      "MM_SCORE" : {
        "doc_count_error_upper_bound" : //omitted,
        "sum_other_doc_count" : //omitted,
        "buckets" : [
          {
            "key" : 35,
            "doc_count" : 1,
            "REVERSE" : {
              "doc_count" : 1,
              "SMP_ID" : {
                "hits" : {
                  "total" : {
                    "value" : 1,
                    "relation" : "eq"
                  },
                  "max_score" : 1.0,
                  "hits" : [
                    {
                      "_index" : "socialmedia",
                      "_type" : "index",
                      "_id" : "1003",
                      "_score" : 1.0,
                      "_source" : {
                        "smp_id" : "3"
                      }
                    }
                  ]
                }
              }
            }
          },
          {
            "key" : 30,
            "doc_count" : 1,
            "REVERSE" : {
              "doc_count" : 1,
              "SMP_ID" : {
                "hits" : {
                  "total" : {
                    "value" : 1,
                    "relation" : "eq"
                  },
                  "max_score" : 1.0,
                  "hits" : [
                    {
                      "_index" : "socialmedia",
                      "_type" : "index",
                      "_id" : "1004",
                      "_score" : 1.0,
                      "_source" : {
                        "smp_id" : "2"
                      }
                    }
                  ]
                }
              }
            }
          },
          {
            "key" : 10,
            "doc_count" : 1,
            "REVERSE" : {
              "doc_count" : 1,
              "SMP_ID" : {
                "hits" : {
                  "total" : {
                    "value" : 1,
                    "relation" : "eq"
                  },
                  "max_score" : 1.0,
                  "hits" : [
                    {
                      "_index" : "socialmedia",
                      "_type" : "index",
                      "_id" : "1002",
                      "_score" : 1.0,
                      "_source" : {
                        "smp_id" : "2"
                      }
                    }
                  ]
                }
              }
            }
          }
        ]
      }
    }
  }
</code>```

with the query above, I was able to successfully display which documents have the highest latest.soc_mm_score values

The sample output above only displays DOCUMENTS, telling that the influencers (a.k.a smp_id) related to them are the TOP INFLUENCERS according to latest.soc_mm_score

Ideally just by using this aggs query,

```<code>"terms" : {
    "field" : "smp_id"
}
</code>```

portrays the concept of which influencers are the top according to the doc_count

Now, displaying the terms query according to latest.soc_mm_score displays TOP DOCUMENTS

```<code>"terms" : {
    "field" : "latest.soc_mm_score"
}
</code>```

REAL OBJECTIVE:

I want to display the TOP INFLUENCERS according to the latest.soc_mm_count in the socialmedia index. If Elasticsearch can count all the documents where according to unique smp_id, is there a way for ES to sum all latest.soc_mm_score values and use it as terms?

My objective above should output these:

smp_id 2 as the Top Influencer because he has 2 posts (with soc_mm_score of 30 and 10), adding them gets him 40 soc_mm_score

smp_id 3 as the 2nd Top Influencer, he has 1 post with 35 soc_mm_score

smp_id 1 as the 3rd Top Influencer, he has 1 post with 5 soc_mm_score

Is there a proper query to meet this objective?

答:
FINALLY! FOUND AN ANSWER!!!

```<code>"aggs": {
    "INFS": {
      "terms": {
        "field": "smp_id.keyword",
        "order": {
          "LATEST > SUM_SVALUE": "desc"
        }
      },
      "aggs": {
        "LATEST": {
          "nested": {
            "path": "latest"
          },
          "aggs": {
            "SUM_SVALUE": {
              "sum" : {
                "field": "latest.soc_mm_score"
              }
            }
          }
        }
      }
    }
}
</code>```

Displays the following sample:

Body:
Elasticsearch v7.5

Hello and good day!

We have 2 indices named socialmedia and influencers

Sample contents:

socialmedia:

{
    '_id' : 1001,
    'title' : "Title 1",
    'smp_id' : 1,
    "latest" : [
        {
          "soc_mm_score" : "5",
        }
    ]
},
{
    '_id' : 1002,
    'title' : "Title 2",
    'smp_id' : 2,
    "latest" : [
        {
          "soc_mm_score" : "10",
        }
    ]
},
{
    '_id' : 1003,
    'title' : "Title 3",
    'smp_id' : 3,
    "latest" : [
        {
          "soc_mm_score" : "35",
        }
    ]
},
{
    '_id' : 1004,
    'title' : "Title 4",
    'smp_id' : 2,
    "latest" : [
        {
          "soc_mm_score" : "30",
        }
    ]
}

//omitted some other fields

influencers:

{
    '_id' : 1,
    'name' : "John",
    'smp_id' : 1
},
{
    '_id' : 2,
    'name' : "Peter",
    'smp_id' : 2
},
{
    '_id' : 3,
    'name' : "Mark",
    'smp_id' : 3
}

Now I have this simple query that determines which documents in the socialmedia index has the most latest.soc_mm_score value, and also displaying their corresponding influencers determined by the smp_id

GET socialmedia/_search
{
  "size": 0,
  "_source": "latest",
  "query": {
    "match_all": {}
  },
  "aggs": {
    "LATEST": {
      "nested": {
        "path": "latest"
      },
      "aggs": {
        "MM_SCORE": {
          "terms": {
            "field": "latest.soc_mm_score",
            "order": {
              "_key": "desc"
            },
            "size": 3
          },
          "aggs": {
            "REVERSE": {
              "reverse_nested": {},
              "aggs": {
                "SMP_ID": {
                  "top_hits": {
                    "_source": ["smp_id"],
                    "size": 1
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

SAMPLE OUTPUT:

"aggregations" : {
    "LATEST" : {
      "doc_count" : //omitted,
      "MM_SCORE" : {
        "doc_count_error_upper_bound" : //omitted,
        "sum_other_doc_count" : //omitted,
        "buckets" : [
          {
            "key" : 35,
            "doc_count" : 1,
            "REVERSE" : {
              "doc_count" : 1,
              "SMP_ID" : {
                "hits" : {
                  "total" : {
                    "value" : 1,
                    "relation" : "eq"
                  },
                  "max_score" : 1.0,
                  "hits" : [
                    {
                      "_index" : "socialmedia",
                      "_type" : "index",
                      "_id" : "1003",
                      "_score" : 1.0,
                      "_source" : {
                        "smp_id" : "3"
                      }
                    }
                  ]
                }
              }
            }
          },
          {
            "key" : 30,
            "doc_count" : 1,
            "REVERSE" : {
              "doc_count" : 1,
              "SMP_ID" : {
                "hits" : {
                  "total" : {
                    "value" : 1,
                    "relation" : "eq"
                  },
                  "max_score" : 1.0,
                  "hits" : [
                    {
                      "_index" : "socialmedia",
                      "_type" : "index",
                      "_id" : "1004",
                      "_score" : 1.0,
                      "_source" : {
                        "smp_id" : "2"
                      }
                    }
                  ]
                }
              }
            }
          },
          {
            "key" : 10,
            "doc_count" : 1,
            "REVERSE" : {
              "doc_count" : 1,
              "SMP_ID" : {
                "hits" : {
                  "total" : {
                    "value" : 1,
                    "relation" : "eq"
                  },
                  "max_score" : 1.0,
                  "hits" : [
                    {
                      "_index" : "socialmedia",
                      "_type" : "index",
                      "_id" : "1002",
                      "_score" : 1.0,
                      "_source" : {
                        "smp_id" : "2"
                      }
                    }
                  ]
                }
              }
            }
          }
        ]
      }
    }
  }

with the query above, I was able to successfully display which documents have the highest latest.soc_mm_score values

The sample output above only displays DOCUMENTS, telling that the influencers (a.k.a smp_id) related to them are the TOP INFLUENCERS according to latest.soc_mm_score

Ideally just by using this aggs query,

"terms" : {
    "field" : "smp_id"
}

portrays the concept of which influencers are the top according to the doc_count

Now, displaying the terms query according to latest.soc_mm_score displays TOP DOCUMENTS

"terms" : {
    "field" : "latest.soc_mm_score"
}

REAL OBJECTIVE:

I want to display the TOP INFLUENCERS according to the latest.soc_mm_count in the socialmedia index. If Elasticsearch can count all the documents where according to unique smp_id, is there a way for ES to sum all latest.soc_mm_score values and use it as terms?

My objective above should output these:

smp_id 2 as the Top Influencer because he has 2 posts (with soc_mm_score of 30 and 10), adding them gets him 40 soc_mm_score

smp_id 3 as the 2nd Top Influencer, he has 1 post with 35 soc_mm_score

smp_id 1 as the 3rd Top Influencer, he has 1 post with 5 soc_mm_score

Is there a proper query to meet this objective?

Body:
FINALLY! FOUND AN ANSWER!!!

"aggs": {
    "INFS": {
      "terms": {
        "field": "smp_id.keyword",
        "order": {
          "LATEST > SUM_SVALUE": "desc"
        }
      },
      "aggs": {
        "LATEST": {
          "nested": {
            "path": "latest"
          },
          "aggs": {
            "SUM_SVALUE": {
              "sum" : {
                "field": "latest.soc_mm_score"
              }
            }
          }
        }
      }
    }
}

Displays the following sample:


问:
How to save BluetoothGatt Instance on Android?
I'm currently developing an Android app which have interactions with BLE device.

I have successfully connect a BLE device with the GATT server using the connectGatt() method. Now I want to use the BluetoothGatt instance returned in another activity. Is there anyway that I can save this BluetoothGatt Instance and use it in another activity without reconnecting to the BLE device which is already connected?

答: Just like mercato has mentioned you would want to store you bluetooth logic in a controller class, since activities gets destoryed and recreated. If you are using the android architecture components you could also store you could implement you connection logic in a repository class whichyou can access from multiple activities.</p>


问:
batch copy and suppress all output
I have a batch file where I am copying files from folders to a new destination.

The folder list is generated by the batch file:

```<code>@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
@REM Set defaults
SET BASE_FLDR=.\
SET BLD_TYPE=Release
SET DST_FLDR=SC_APP
@REM Check if base folder specified, if not default to current location
IF NOT [%1] == [] SET BASE_FLDR=%1
@REM Check if build type specified, if not default to Release
IF NOT [%2] == [] SET BLD_TYPE=%2
@REM Display parameters
ECHO Base folder: %BASE_FLDR%
ECHO Build type : %BLD_TYPE%
@REM Does destination folder exist?
IF NOT EXIST %DST_FLDR% MKDIR %DST_FLDR%
@REM Create list of subfolders to search
FOR /F "delims=" %%F IN ('"DIR %BASE_FLDR% /S /B /A:D | FINDSTR /EIC:"%BLD_TYPE%" "') DO (
    @COPY /Y "%%F"\*.DLL "%DST_FLDR%" >NUL
    @COPY /Y "%%F"\*.EXE "%DST_FLDR%" >NUL
)
</code>```

During the copy process I see lots of:

```<code>The system cannot find the file specified.
</code>```

I've tried various things but have not been able to prevent this message from being displayed.

@ doesn't stop it, neither does redirecting the output to NUL, I also tried launching in another CMD, doesn't stop it happening either.

答:
Solved, see comment by Stephan.

Completed script:

```<code>    @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    @REM Set defaults
    SET BASE_FLDR=.\
    SET BLD_TYPE=Release
    @REM Check if base folder specified, if not default to current location
    IF NOT [%1] == [] SET BASE_FLDR=%1
    @REM Check if build type specified, if not default to Release
    IF NOT [%2] == [] SET BLD_TYPE=%2
    SET DST_FLDR=%BASE_FLDR%sc_app
    @REM Display parameters
    ECHO Base folder: %BASE_FLDR%
    ECHO Build type : %BLD_TYPE%
    ECHO Destination folder : %DST_FLDR%
    ECHO Please wait
    @REM Does destination folder exist?
    IF NOT EXIST %DST_FLDR% (
        ECHO Creating %DST_FLDR%
        MKDIR %DST_FLDR%
    )
    @REM Create list of subfolders to search
    ECHO Copying DLL's and EXE's to %DST_FLDR%
    FOR /F "delims=" %%F IN ('"DIR %BASE_FLDR% /S /B /A:D | FINDSTR /EIC:"%BLD_TYPE%" "') DO (
        ECHO | SET /p="."
        @COPY /Y "%%F"\*.DLL "%DST_FLDR%" >NUL 2>&1
        @COPY /Y "%%F"\*.EXE "%DST_FLDR%" >NUL 2>&1
    )
    ECHO "Copy complete"
</code>```

Title: batch copy and suppress all output

Body:
I have a batch file where I am copying files from folders to a new destination.

The folder list is generated by the batch file:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
@REM Set defaults
SET BASE_FLDR=.\
SET BLD_TYPE=Release
SET DST_FLDR=SC_APP
@REM Check if base folder specified, if not default to current location
IF NOT [%1] == [] SET BASE_FLDR=%1
@REM Check if build type specified, if not default to Release
IF NOT [%2] == [] SET BLD_TYPE=%2
@REM Display parameters
ECHO Base folder: %BASE_FLDR%
ECHO Build type : %BLD_TYPE%
@REM Does destination folder exist?
IF NOT EXIST %DST_FLDR% MKDIR %DST_FLDR%
@REM Create list of subfolders to search
FOR /F "delims=" %%F IN ('"DIR %BASE_FLDR% /S /B /A:D | FINDSTR /EIC:"%BLD_TYPE%" "') DO (
    @COPY /Y "%%F"\*.DLL "%DST_FLDR%" >NUL
    @COPY /Y "%%F"\*.EXE "%DST_FLDR%" >NUL
)

During the copy process I see lots of:

The system cannot find the file specified.

I've tried various things but have not been able to prevent this message from being displayed.

@ doesn't stop it, neither does redirecting the output to NUL, I also tried launching in another CMD, doesn't stop it happening either.

Body:
Solved, see comment by Stephan.

Completed script:

    @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    @REM Set defaults
    SET BASE_FLDR=.\
    SET BLD_TYPE=Release
    @REM Check if base folder specified, if not default to current location
    IF NOT [%1] == [] SET BASE_FLDR=%1
    @REM Check if build type specified, if not default to Release
    IF NOT [%2] == [] SET BLD_TYPE=%2
    SET DST_FLDR=%BASE_FLDR%sc_app
    @REM Display parameters
    ECHO Base folder: %BASE_FLDR%
    ECHO Build type : %BLD_TYPE%
    ECHO Destination folder : %DST_FLDR%
    ECHO Please wait
    @REM Does destination folder exist?
    IF NOT EXIST %DST_FLDR% (
        ECHO Creating %DST_FLDR%
        MKDIR %DST_FLDR%
    )
    @REM Create list of subfolders to search
    ECHO Copying DLL's and EXE's to %DST_FLDR%
    FOR /F "delims=" %%F IN ('"DIR %BASE_FLDR% /S /B /A:D | FINDSTR /EIC:"%BLD_TYPE%" "') DO (
        ECHO | SET /p="."
        @COPY /Y "%%F"\*.DLL "%DST_FLDR%" >NUL 2>&1
        @COPY /Y "%%F"\*.EXE "%DST_FLDR%" >NUL 2>&1
    )
    ECHO "Copy complete"


问:
Remove whitespaces before a character starts and before equal to(=) sign and using shell
I have one file(file1.txt)

```<code>Rahul=rahul

Vimal=vimal

   Vishal =vishal

   Rupesh =rupesh

   Aromal =aromal

   Anugrah =anugrah
</code>```

My output file should be

```<code>Rahul=rahul

Vimal=vimal

Vishal=vishal

Rupesh=rupesh

Aromal=aromal

Anugrah=anugrah
</code>```

I tried with following commands. Still not getting output as I needed.

```<code>sed 's/  */ /g' < file1.txt

sed 's/ \{1,\}/ /g' < file1.txt

sed 's/ \+ / /g' < file1.txt

sed -e "s/[[:space:]]\+/ /g" < file1.txt
</code>```

答:
You can use shell tr command if not required to use sed:

```<code>tr -d ' ' < file1.txt
</code>```

Hope this helps

Body:
I have one file(file1.txt)

Rahul=rahul

Vimal=vimal

   Vishal =vishal

   Rupesh =rupesh

   Aromal =aromal

   Anugrah =anugrah

My output file should be

Rahul=rahul

Vimal=vimal

Vishal=vishal

Rupesh=rupesh

Aromal=aromal

Anugrah=anugrah

I tried with following commands. Still not getting output as I needed.

sed 's/  */ /g' < file1.txt

sed 's/ \{1,\}/ /g' < file1.txt

sed 's/ \+ / /g' < file1.txt

sed -e "s/[[:space:]]\+/ /g" < file1.txt

Body:
You can use shell tr command if not required to use sed:

tr -d ' ' < file1.txt

Hope this helps


问:
Defining a variable using an if statement Oracle SQL Developer
I need to adapt a date range based on financial year ending in Feb.

So when the Jan-2020 report is run, it needs to calculate the 24 month window to start from 2017/12 (Feb-2018) to 2019/11 (Jan-2020). How do I get the below to calculate dynamically?

```<code>define v_report_month = 1
define v_report_year = 2020

define v_start_year = if &v_report_month > 1 then &v_report_year - 2  else &v_report_year - 3 end if
define v_start_monthno = if &v_report_month > 1 then &v_report_month - 1  else &v_report_month + 11 end if
define v_end_year = if v_report_monthno > 2 then v_report_year else v_report_year - 1 end if
define v_end_monthno = if v_report_monthno > 2 then v_report_month - 2 else v_report_monthno + 10 end if
</code>```

When I try running the following below, just get -- "ORA-00933: SQL command not properly ended"

```<code>select
&v_start_year as y
,&v_start_monthno as m
from dual;
</code>```

答:
You could use PL/SQL anonymous block which would be simpler:

```<code>SET SERVEROUTPUT ON

DECLARE
    v_report_month   NUMBER := 1;
    v_report_year    NUMBER := 2020;
    v_start_year     NUMBER;
BEGIN
    v_start_year :=
        CASE
            WHEN v_report_month > 1 THEN
                v_report_year - 2
            ELSE v_report_year - 3
        END;
    dbms_output.put_line('Start year: '||v_start_year);
END;
/

Start year: 2017

PL/SQL procedure successfully completed.
</code>```

The same CASE expression could be written using IF-THEN-ELSE:

```<code>IF v_report_month > 1 THEN
    v_start_year := v_report_year - 2;
ELSE
    v_start_year := v_report_year - 3;
END IF;
</code>```

If you want to leave the variables which you have defined in SQL*Plus, then you could do it this way:

```<code>define v_report_month = 1
define v_report_year = 2020

set serveroutput on
DECLARE
    v_report_year   NUMBER;
    v_start_year    NUMBER;
BEGIN
    v_start_year :=
        CASE
            WHEN &v_report_month > 1 THEN
                &v_report_year - 2
            ELSE &v_report_year - 3
        END;
    dbms_output.put_line(v_start_year);
END;

2017

PL/SQL procedure successfully completed.
</code>```

Body:
I need to adapt a date range based on financial year ending in Feb.

So when the Jan-2020 report is run, it needs to calculate the 24 month window to start from 2017/12 (Feb-2018) to 2019/11 (Jan-2020). How do I get the below to calculate dynamically?

define v_report_month = 1
define v_report_year = 2020

define v_start_year = if &v_report_month > 1 then &v_report_year - 2  else &v_report_year - 3 end if
define v_start_monthno = if &v_report_month > 1 then &v_report_month - 1  else &v_report_month + 11 end if
define v_end_year = if v_report_monthno > 2 then v_report_year else v_report_year - 1 end if
define v_end_monthno = if v_report_monthno > 2 then v_report_month - 2 else v_report_monthno + 10 end if

When I try running the following below, just get -- "ORA-00933: SQL command not properly ended"

select
&v_start_year as y
,&v_start_monthno as m
from dual;

Body:
You could use PL/SQL anonymous block which would be simpler:

SET SERVEROUTPUT ON

DECLARE
    v_report_month   NUMBER := 1;
    v_report_year    NUMBER := 2020;
    v_start_year     NUMBER;
BEGIN
    v_start_year :=
        CASE
            WHEN v_report_month > 1 THEN
                v_report_year - 2
            ELSE v_report_year - 3
        END;
    dbms_output.put_line('Start year: '||v_start_year);
END;
/

Start year: 2017

PL/SQL procedure successfully completed.

The same CASE expression could be written using IF-THEN-ELSE:

IF v_report_month > 1 THEN
    v_start_year := v_report_year - 2;
ELSE
    v_start_year := v_report_year - 3;
END IF;

If you want to leave the variables which you have defined in SQL*Plus, then you could do it this way:

define v_report_month = 1
define v_report_year = 2020

set serveroutput on
DECLARE
    v_report_year   NUMBER;
    v_start_year    NUMBER;
BEGIN
    v_start_year :=
        CASE
            WHEN &v_report_month > 1 THEN
                &v_report_year - 2
            ELSE &v_report_year - 3
        END;
    dbms_output.put_line(v_start_year);
END;

2017

PL/SQL procedure successfully completed.


问:
Paste special characters to function argument in R
I am building function to check if link exists on page (code bellow)

```<code>kodHTML <- read_html(stronaDoSprawdzenia)
a <- '//a[contains(@href, "https://a.pl/abc/")]'
cast6 <- html_node(kodHTML, xpath = a)
</code>```

Could I use paste function to create dynamicaly value of a?

I tried to use code bellow but this doesnt work

```<code>z <- paste("'//a[contains(@href,"," \"https://a.pl/abc/")]'")
</code>```

Is it possible to use paste function in this situation ?

答:
I think the code does not work, because you have to "escape" quotation marks.

This is your version:

```<code>z <- paste("'//a[contains(@href,"," \"https://a.pl/abc/")]'")
</code>```

and you might need this

```<code>z <- paste("'//a[contains(@href,"," \"https://a.pl/abc/\")]'")
                                                       ^
</code>```

Body:
I am building function to check if link exists on page (code bellow)

kodHTML <- read_html(stronaDoSprawdzenia)
a <- '//a[contains(@href, "https://a.pl/abc/")]'
cast6 <- html_node(kodHTML, xpath = a)

Could I use paste function to create dynamicaly value of a?

I tried to use code bellow but this doesnt work

z <- paste("'//a[contains(@href,"," \"https://a.pl/abc/")]'")

Is it possible to use paste function in this situation ?

Body:
I think the code does not work, because you have to "escape" quotation marks.

This is your version:

z <- paste("'//a[contains(@href,"," \"https://a.pl/abc/")]'")

and you might need this

z <- paste("'//a[contains(@href,"," \"https://a.pl/abc/\")]'")
                                                       ^


问:
How to create UI in angular to display m by n matrix and what should be the json format?
image preview

the matrix would be m by n having names on left and top of the matrix
note: must have column and row name

答:
Found the solution
check out my stackblitz</p>


问:
onClick with Chrome Extension not working
So I'm pretty new when it comes to java script and creating chrome extensions. So what I'm trying to do is to take two values which the user has inputted, add them together and display after the user has clicked calculate. However I can't seem to get it to work and I don't know what I'm doing wrong. I would greatly appreciate any assistance.

Here is my HTML code:

```<code><!DOCTYPE html>
    <html>
        <head>
            <h1>Simple Calculator</h1>
            <script src="script.js"></script>
        </head>
        <body>
            First Value<input type="text" id="ValueA"/><br>
            Second Value<input type="text" id="ValueB"/><br>

            Invested Cost<input type="text" id="result"/><br>
            <button id="Calc;">Calculate</button>
        </body>
    </html>
</code>```

My java script:

```<code>document.getElementById("Calc").addEventListener("click", Sum);

function Calc()
        {
            var A = document.getElementById('ValueA').value;
            var B = document.getElementById('ValueB').value;
            var C = A+B;
            document.getElementById('result').value = C;
        }
</code>```

and finally my manifest:

```<code>{
    "manifest_version": 2,
    "name": "Simple Calculator",
    "version": "1.0",
    "description":  "Simple Calculator",

    "browser_action":{
        "default_popup": "popup.html"
    }

}
</code>```

答:
You need to call Calc() function in event listener. Right now, you are invoking Sum

Also, as @Julian said in the comment, you need to remove ; from button id

Body:
So I'm pretty new when it comes to java script and creating chrome extensions. So what I'm trying to do is to take two values which the user has inputted, add them together and display after the user has clicked calculate. However I can't seem to get it to work and I don't know what I'm doing wrong. I would greatly appreciate any assistance.

Here is my HTML code:

<!DOCTYPE html>

Simple Calculator

            First Value<input type="text" id="ValueA"/>

            Second Value<input type="text" id="ValueB"/>

            Invested Cost<input type="text" id="result"/>

            <button id="Calc;">Calculate</button>

My java script:

document.getElementById("Calc").addEventListener("click", Sum);

function Calc()
        {
            var A = document.getElementById('ValueA').value;
            var B = document.getElementById('ValueB').value;
            var C = A+B;
            document.getElementById('result').value = C;
        }

and finally my manifest:

{
    "manifest_version": 2,
    "name": "Simple Calculator",
    "version": "1.0",
    "description":  "Simple Calculator",

    "browser_action":{
        "default_popup": "popup.html"
    }

}


问:
CalendarContract.Events.EVENT_TIMEZONE is not working in samsung device
I am trying to insert some events with some predefined timezone into android native calendar from my application. Somehow it is not working in Samsung devices. It is working fine in Pixel devices. Below is the code snippet for the same.

```<code>Intent intent = new Intent(Intent.ACTION_INSERT);
intent.putExtra(CalendarContract.Events.EVENT_TIMEZONE, "America/Los_Angeles");
intent.setData(CalendarContract.Events.CONTENT_URI);
intent.putExtra(CalendarContract.Events.TITLE, "test");
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, getDateTimeyyyymmddHHmm());
intent.putExtra(CalendarContract.Events.ALL_DAY, false);
intent.putExtra(CalendarContract.Events.DURATION, "PT1H");
startActivityForResult(intent, 1);

 public static Long getDateTimeyyyymmddHHmm() {
    TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles");

    DateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd, HHmm", Locale.US);
    dateFormat2.setTimeZone(timeZone);
    Date d4 = null;
    try {
        d4 = dateFormat2.parse(new StringBuilder("20200216").append(", ").append("1045").toString());
        return d4.getTime();
    } catch (ParseException e) {
        return 0L;
    }
}
</code>```

Tried many ways and din't work. Any help in resolving the device specific issue would be helpful.

答:
EVENT_TIMEZONE exists in CalendarContract.EventsColumns.

You can find here: https://developer.android.com/reference/android/provider/CalendarContract.EventsColumns.html#EVENT_TIMEZONE

Body:
I am trying to insert some events with some predefined timezone into android native calendar from my application. Somehow it is not working in Samsung devices. It is working fine in Pixel devices. Below is the code snippet for the same.

Intent intent = new Intent(Intent.ACTION_INSERT);
intent.putExtra(CalendarContract.Events.EVENT_TIMEZONE, "America/Los_Angeles");
intent.setData(CalendarContract.Events.CONTENT_URI);
intent.putExtra(CalendarContract.Events.TITLE, "test");
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, getDateTimeyyyymmddHHmm());
intent.putExtra(CalendarContract.Events.ALL_DAY, false);
intent.putExtra(CalendarContract.Events.DURATION, "PT1H");
startActivityForResult(intent, 1);

 public static Long getDateTimeyyyymmddHHmm() {
    TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles");

    DateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd, HHmm", Locale.US);
    dateFormat2.setTimeZone(timeZone);
    Date d4 = null;
    try {
        d4 = dateFormat2.parse(new StringBuilder("20200216").append(", ").append("1045").toString());
        return d4.getTime();
    } catch (ParseException e) {
        return 0L;
    }
}

Tried many ways and din't work. Any help in resolving the device specific issue would be helpful.


问:
Issue with uploading GeoLite2-City.mmdb.missing file in mautic
I have a mautic marketing automation installed on my server (I am a beginner)

However i replicated this issue when configuring GeoLite2-City IP lookup

Automatically fetching the IP lookup data failed. Download http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz, extract if necessary, and upload to /home/ol*****/public_html/mautic4/app/cache/prod/../ip_data/GeoLite2-City.mmdb.

What i attempted

i FTP into the /home/ol****/public_html/mautic4/app/cache/prod/../ip_data/GeoLite2-City.mmdb. directory

uploaded the file (the original GeoLite2-City.mmdb has '0 byte', while the newly added file is about '6000 kb'

However, once i go back into mautic to implement the lookup, the newly added file reverts back to '0byte" and i still cant get the IP lookup configured.

I have also changed the file permission to 0744, but the issue still replicates.

答:
Did you disable the cron job which looks for the file? If not, or if you clicked the button again in the dashboard, it will overwrite the file you manually placed there.

As a side note, the 2.16 release addresses this issue, please take a look at https://www.mautic.org/blog/community/announcing-mautic-2-16/.

Please ensure you take a full backup (files and database) and where possible, run the update at command line to avoid browser timeouts :)


问:
Build .NET Core 3.1.1 from git repository
I would like to build from source the .NET Core 3.1 CLR and libraries. I checked out the latest from https://github.com/dotnet/runtime. Running the build scripts will produce the next version of .net and not 3.1.1. Can you tell me how to get the .NET Core 3.1.1 source and build it? I want to be able to produce a debug version of the core so that I can add tracing and logging.</p>

答:
Go to 3.1.1 tag in dotnet/coreclr repo (https://github.com/dotnet/coreclr/tree/v3.1.1)
The entire coreclr repo has merged (along with corefx, corert and the installer) to dotnet/runtime.
The dotnet/coreclr repo is an archive currently, which still holds all the old tags.</p>


问:
How to use SEQUENCE in Apache Derby?
I'd like to use SEQUENCE support in Apache Derby 10.7. I've created the sequence with the following statement:

```<code>CREATE SEQUENCE SAMPLE_SEQ AS INT MAXVALUE 999999 CYCLE;
</code>```

How can I select next/current value from the SAMPLE_SEQ? Could you please help me out with the query?

答:
To get the current value of the sequence the following SQL should be executed:</p>

```<code>SELECT CURRENTVALUE FROM SYS.SYSSEQUENCES WHERE SEQUENCENAME='SAMPLE_SEQ'
</code>```

Title: How to use SEQUENCE in Apache Derby?

Body:
I'd like to use SEQUENCE support in Apache Derby 10.7. I've created the sequence with the following statement:

CREATE SEQUENCE SAMPLE_SEQ AS INT MAXVALUE 999999 CYCLE;

How can I select next/current value from the SAMPLE_SEQ? Could you please help me out with the query?

Body:
To get the current value of the sequence the following SQL should be executed:

SELECT CURRENTVALUE FROM SYS.SYSSEQUENCES WHERE SEQUENCENAME='SAMPLE_SEQ'


问:
Why does vue ui / npm not let me update certain packages to latest?
Im using Vue CLI, which comes with the command vue ui to allow me to update the npm packages. I got the following screen:

I would like to understand:

The reason I cannot update to the latest versions (v4.0.5)

How can I can update to a later version, which I presume will contain improvements.

答:
You can update all dependencies and plugins via VueUI, by clicking on three dot icon (highlighted in yellow)

VueUI - Project dependencies

Project plugins

If any of the dependencies or plugins fail to update, an error will be shown in the command prompt window you used to get the VueUI up and running on your machine. If you see errors, I recommend updating each one individually as it might pin point which one is giving problems.

Sorry for not embedding the images, I'm new and need to have at least 10 reputation to post an image


问:
when is exhaustive so else is redundant?
I am new to kotlin and I created a method that contains the when statement and IntelliJ suggesting me to remove the else branch.
I am not really sure why. Any idea why I need to remove the else branch here?
This is the code:</p>

```<code>    companion object{
    @Synchronized fun getDriver(
        url: String,
        desiredCapabilities: DesiredCapabilities,
        mobilePlatform: MobilePlatform)
        : AppiumDriver<WebElement> =
        when(mobilePlatform){
            MobilePlatform.ANDROID -> AndroidDriver<WebElement>(URL(url), desiredCapabilities)
            MobilePlatform.IOS -> IOSDriver<WebElement>(URL(url), desiredCapabilities)
            else -> throw RuntimeException("Cannot get the driver")
        }
}
</code>```

答: When you have exhausted all possible options of when there is no reason to have an else branch. This has the added advantage that you get a compiler error after adding elements to the enum without extending the when.

Body:
I am new to kotlin and I created a method that contains the when statement and IntelliJ suggesting me to remove the else branch.
I am not really sure why. Any idea why I need to remove the else branch here?
This is the code:

    companion object{
    @Synchronized fun getDriver(
        url: String,
        desiredCapabilities: DesiredCapabilities,
        mobilePlatform: MobilePlatform)
        : AppiumDriver<WebElement> =
        when(mobilePlatform){
            MobilePlatform.ANDROID -> AndroidDriver<WebElement>(URL(url), desiredCapabilities)
            MobilePlatform.IOS -> IOSDriver<WebElement>(URL(url), desiredCapabilities)
            else -> throw RuntimeException("Cannot get the driver")
        }
}


问:
Delete duplicate rows with an order by
I have this table:

I want to delete duplicate rows in that table based on different STATUSIN
and this is my query to duplicate rows:

```<code>;WITH CTE AS
(
   SELECT ID,NIP, ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY STATUSIN) AS RowNumber
   FROM DAILYDATAWH
), CTE2 AS
(
SELECT TOP (1000) *
    FROM CTE
    ORDER BY RowNumber DESC
    )
    DELETE FROM CTE2 WHERE RowNumber > 1
</code>```

and this is the output:

how to delete duplicate rows and show the output like this:

答:
ID, i guess is a primary key and if you want to rearrange records in your main table, it is not possible because it is stored in ascending order.

If you just want to show records like in the below picture, then after deleting the records, use

```<code>select * from DAILYDATAWH order by NIP,NAME,StatusIn
</code>```

Title: Delete duplicate rows with an order by

Body:
I have this table:

I want to delete duplicate rows in that table based on different STATUSIN
and this is my query to duplicate rows:

;WITH CTE AS
(
   SELECT ID,NIP, ROW_NUMBER()OVER(PARTITION BY STATUSIN ORDER BY STATUSIN) AS RowNumber
   FROM DAILYDATAWH
), CTE2 AS
(
SELECT TOP (1000) *
    FROM CTE
    ORDER BY RowNumber DESC
    )
    DELETE FROM CTE2 WHERE RowNumber > 1

and this is the output:

how to delete duplicate rows and show the output like this:

Body:
ID, i guess is a primary key and if you want to rearrange records in your main table, it is not possible because it is stored in ascending order.

If you just want to show records like in the below picture, then after deleting the records, use

select * from DAILYDATAWH order by NIP,NAME,StatusIn


问:
How to create a picture that fills in colours based on a matrix?
I have a cell array in MATLAB in the following format:

```<code>aa = {[1 2],[2 3],[1 2 3 4 5 6],[5],[1]}
</code>```

Is it possible to create a diagram in this style (i.e. filling in a block colour for each time a number shows up)?

答:
Here is a possible solution based on pcolor:

```<code>aa = {[1 2],[2 3],[1 2 3 4 5 6],[5],[1]};
n_rows = length(aa);
n_columns = max(cell2mat(aa));
m = zeros(n_rows + 1, n_columns + 1);
row = n_rows;
for i=1:n_rows
    m(row, aa{i}) = 1;
    row = row - 1;
end
colormap([1 1 1; 1 0.5 0]);
pcolor(m);
</code>```

it produces following result:

Body:
I have a cell array in MATLAB in the following format:

aa = {[1 2],[2 3],[1 2 3 4 5 6],[5],[1]}

Is it possible to create a diagram in this style (i.e. filling in a block colour for each time a number shows up)?

Body:
Here is a possible solution based on pcolor:

aa = {[1 2],[2 3],[1 2 3 4 5 6],[5],[1]};
n_rows = length(aa);
n_columns = max(cell2mat(aa));
m = zeros(n_rows + 1, n_columns + 1);
row = n_rows;
for i=1:n_rows
    m(row, aa{i}) = 1;
    row = row - 1;
end
colormap([1 1 1; 1 0.5 0]);
pcolor(m);

it produces following result:


问:
How to change MySQL Workbench interface font size?
How to change MySQL Workbench interface font size?

Please note: interface, not editor fonts.

Workbench 6.3 on Windows 8.1

答: Press Edit > Prefences.. >  Fonts&Colors

Body: Press Edit > Prefences.. >  Fonts&Colors


答:
In kotlin, when on a sealed class object doesn't require else if all possible inner cases are covered.

Sample sealed class:

```<code>sealed class A {
 object B: A()
 object C: A()
}
</code>```

Let the above be a sealed class then any object of class A (lets say a), can be used inside a when exhaustively(not necessarily) while returning

```<code>return when(a) {
  is A.B -> return something
  is A.C -> return something
} // no need of else here as all cases are covered.
</code>```

There is one catch here, if you just need to check for one condition, let's say is A.B you can write an else. Also, please note that, you need NOT write exhaustive conditions/else if it's just a statement.

Example below:

```<code>some code ...
when(a) {
      is A.B -> do some task
}
more code ...
</code>```

Hope this helps !!

Title: when is exhaustive so else is redundant?

Body:
In kotlin, when on a sealed class object doesn't require else if all possible inner cases are covered.

Sample sealed class:

sealed class A {
 object B: A()
 object C: A()
}

Let the above be a sealed class then any object of class A (lets say a), can be used inside a when exhaustively(not necessarily) while returning

return when(a) {
  is A.B -> return something
  is A.C -> return something
} // no need of else here as all cases are covered.

There is one catch here, if you just need to check for one condition, let's say is A.B you can write an else. Also, please note that, you need NOT write exhaustive conditions/else if it's just a statement.

Example below:

some code ...
when(a) {
      is A.B -> do some task
}
more code ...

Hope this helps !!


问:
How to get list of categories for a store
I have a Store Model that can have multiple products. Each product has a category.

What is the most optimal way to get the list of categories for products in a store?

For eg. Store A has Products A (Cat1), Product B(Cat1), Product C (Cat2)

I want Cat1, Cat2 when I pass the Store A's id.

答:
So,

Store has_many products (each product belongs_to Store): one-to-many relation

Each product has_one category (each category belongs_to a product): one-to-one relation

In your Product table, you should have store_id field, and in your Category table you should have a product_id field. Then set the has_many and belong_to relation in your Models.

```<code># beware of the use of pluralization

# Store model
class Store < ActiveRecord::Base
  has_many :products
end

# Product model
class Product < ActiveRecord::Base
  belongs_to :store
  has_one :category
end

# Category model
class Category < ActiveRecord::Base
  belongs_to :product
end

# e.g. access category of a product in your Store Controller
# or loop it in your Store view
@store = Store.find_by_id(myInt)
@firstProductCategory = @store.products[0].category.name
</code>```

Body:
So,

Store has_many products (each product belongs_to Store): one-to-many relation

Each product has_one category (each category belongs_to a product): one-to-one relation

In your Product table, you should have store_id field, and in your Category table you should have a product_id field. Then set the has_many and belong_to relation in your Models.

# beware of the use of pluralization

# Store model
class Store < ActiveRecord::Base
  has_many :products
end

# Product model
class Product < ActiveRecord::Base
  belongs_to :store
  has_one :category
end

# Category model
class Category < ActiveRecord::Base
  belongs_to :product
end

# e.g. access category of a product in your Store Controller
# or loop it in your Store view
@store = Store.find_by_id(myInt)
@firstProductCategory = @store.products[0].category.name


问:
Javascript encodeURI like function in postgresql?
Is there any function/stored procedure in PostgreSQL/plpgsql which is same as the javascripts encodeURI?

What does it mean? Javascript have a handy built in function to encode any kind of url:

encodeURI(url) -> returns the encoded url

For example:
encodeURI('http://hu.wikipedia.org/wiki/São_Paulo') -> returns a String which is "http://hu.wikipedia.org/wiki/S%C3%A3o_Paulo"

I looking for exactly the same.

I don't want to encode each parameters separately. I don't want a function like javascript encodeURIComponent which is not the same. The example above results a different output with

```<code>encodeURIComponent('http://hu.wikipedia.org/wiki/São_Paulo')
</code>```

-> "http%3A%2F%2Fhu.wikipedia.org%2Fwiki%2FS%C3%A3o_Paulo"

It's encode the whole string not just the path part. So this is not what I'm looking for. I need a plpgsql function which results equivalent output to javascript function encodeURI.

Thanks!

答:
This is a very old thread, but surprisingly none of the previously posted solutions seem to comply with the relevant RFC 3986. So here are two  PostgreSQL functions encode_uri (if you want to encode a complete URI) and encode_uri_component (if you want to encode just a component of the URI, e.g. the key or value of a query parameter) that combines Nick's buggy solution, ElDiabolo's note, and Kev's partial solution from a related thread  into a single working SQL-only solution.

How it works: first, explode the string into single characters, then hex-encode each multibyte character and and each disallowed character.

Encode URI Component:

create or replace function encode_uri_component(text) returns text as $$
    select string_agg(
        case
            when bytes > 1 or c !~ '[0-9a-zA-Z_.!~*''()-]+' then
                regexp_replace(encode(convert_to(c, 'utf-8')::bytea, 'hex'), '(..)', E'%\\1', 'g')
            else
                c
        end,
        ''
    )
    from (
        select c, octet_length(c) bytes
        from regexp_split_to_table($1, '') c
    ) q;
$$ language sql immutable strict;
```
<p><strong>Encode Complete URI:</strong></p>
<pre class="lang-sql prettyprint-override"><code>create or replace function encode_uri(text) returns text as $$
    select string_agg(
        case
            when bytes > 1 or c !~ '[0-9a-zA-Z_.!~*''();,/?:@&=+$#-]+' then
                regexp_replace(encode(convert_to(c, 'utf-8')::bytea, 'hex'), '(..)', E'%\\1', 'g')
            else
                c
        end,
        ''
    )
    from (
        select c, octet_length(c) bytes
        from regexp_split_to_table($1, '') c
    ) q;
$$ language sql immutable strict;
</code>```

Body:
Is there any function/stored procedure in PostgreSQL/plpgsql which is same as the javascripts encodeURI?

What does it mean? Javascript have a handy built in function to encode any kind of url:

encodeURI(url) -> returns the encoded url

For example:
encodeURI('http://hu.wikipedia.org/wiki/São_Paulo') -> returns a String which is "http://hu.wikipedia.org/wiki/S%C3%A3o_Paulo"

I looking for exactly the same.

I don't want to encode each parameters separately. I don't want a function like javascript encodeURIComponent which is not the same. The example above results a different output with

encodeURIComponent('http://hu.wikipedia.org/wiki/São_Paulo')

-> "http%3A%2F%2Fhu.wikipedia.org%2Fwiki%2FS%C3%A3o_Paulo"

It's encode the whole string not just the path part. So this is not what I'm looking for. I need a plpgsql function which results equivalent output to javascript function encodeURI.

Thanks!

Body:
This is a very old thread, but surprisingly none of the previously posted solutions seem to comply with the relevant RFC 3986. So here are two  PostgreSQL functions encode_uri (if you want to encode a complete URI) and encode_uri_component (if you want to encode just a component of the URI, e.g. the key or value of a query parameter) that combines Nick's buggy solution, ElDiabolo's note, and Kev's partial solution from a related thread  into a single working SQL-only solution.

How it works: first, explode the string into single characters, then hex-encode each multibyte character and and each disallowed character.

Encode URI Component:

create or replace function encode_uri_component(text) returns text as $$
    select string_agg(
        case
            when bytes > 1 or c !~ '[0-9a-zA-Z_.!~*''()-]+' then
                regexp_replace(encode(convert_to(c, 'utf-8')::bytea, 'hex'), '(..)', E'%\\1', 'g')
            else
                c
        end,
        ''
    )
    from (
        select c, octet_length(c) bytes
        from regexp_split_to_table($1, '') c
    ) q;
$$ language sql immutable strict;

Encode Complete URI:

create or replace function encode_uri(text) returns text as $$
    select string_agg(
        case
            when bytes > 1 or c !~ '[0-9a-zA-Z_.!~*''();,/?:@&=+$#-]+' then
                regexp_replace(encode(convert_to(c, 'utf-8')::bytea, 'hex'), '(..)', E'%\\1', 'g')
            else
                c
        end,
        ''
    )
    from (
        select c, octet_length(c) bytes
        from regexp_split_to_table($1, '') c
    ) q;
$$ language sql immutable strict;


问:
Can we assign a variable for looping to a value inside the loop in Java?
I would like to assign a certain value to an iteration variable inside a for loop in Java.

```<code>List<Integer> values = Arrays.asList(1,2,4,16,32,64,128);
for (Integer value: values) {
   value = value / 2;  // local value
}
</code>```

Is this assignment working in java?

答:
You can do it by hacking your way, but it is very suspicious and if you really need this, you are probably doing something wrong.

What you may need is to have another collection where you can put processed values,

```<code>List<Integer> values = Arrays.asList(1,2,4,16,32,64,128);
List<Integer> newValues = new LinkedList();

for (Integer value: values) {
  newValues.add(value / 2);
}
</code>```

Or if you ask if you can simply reassign iterator value, sure it is possible, but again is a bit suspicious. Maybe you can use it in such a case;

```<code>List<Integer> values = Arrays.asList(1,2,4,16,32,64,128);

for (Integer value: values) {
  if(value > 32)
    value = 32;
  process(value);
}
</code>```

Since i only reassign the iterator value it is safe, however editing the collection during looping over it will either result in a ConcurrentModificationException or worse(hacky way) as you cannot always determine the behavior of your list implementation.

Body:
I would like to assign a certain value to an iteration variable inside a for loop in Java.

List<Integer> values = Arrays.asList(1,2,4,16,32,64,128);
for (Integer value: values) {
   value = value / 2;  // local value
}

Is this assignment working in java?

Body:
You can do it by hacking your way, but it is very suspicious and if you really need this, you are probably doing something wrong.

What you may need is to have another collection where you can put processed values,

List<Integer> values = Arrays.asList(1,2,4,16,32,64,128);
List<Integer> newValues = new LinkedList();

for (Integer value: values) {
  newValues.add(value / 2);
}

Or if you ask if you can simply reassign iterator value, sure it is possible, but again is a bit suspicious. Maybe you can use it in such a case;

List<Integer> values = Arrays.asList(1,2,4,16,32,64,128);

for (Integer value: values) {
  if(value > 32)
    value = 32;
  process(value);
}

Since i only reassign the iterator value it is safe, however editing the collection during looping over it will either result in a ConcurrentModificationException or worse(hacky way) as you cannot always determine the behavior of your list implementation.


问:
Unable to stop the propogation of events in reactJs
I have a condition where I have simple dropdown menu

```<code>handleDropdown = (e) => {
    if (e.type === "focus") {
      console.log("inside dropdown focus");
      this.setState({ dropDownDis: "block" })
    } else if (e.type === "blur") {
      console.log("inside dropdown blur");
      this.setState({ dropDownDis: "none" })
    }
  }

 logout = (e) => {
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    console.log("inside logout")
  }
</code>```

When I click on Logout, The menu closes but logout method doesn't calls.

html

```<code>  <div className="header-user">
              <button
                type="button"
                className="dropdown-button"
                ref={this.myRef}
                onFocus={this.handleDropdown}
                onBlur={this.handleDropdown}
              >
              <img src="/img/headericon.png" alt="no header icon" />
              </button>

              <div className="dropdown-menu" style={{ display: dropDownDis }}>

              <ul className="sidebar-list">
               <li>
                <img src="../img/user.png"/> <a href="#">My Profile </a>
               </li>
               <li>
                <img src="../img/order.png"/><a href="#">Order </a>
               </li>
               <li>
                <img src="../img/account.png"/> <a href="#">My Account </a>
              </li>
              <li>
               <img src="../img/logout.png"/> <a onClick={this.logout}>Log Out </a>
              </li>
             </ul>

            </div>
   </div>
</code>```

On clicking the logout I can see the console as shown in below image

答: You should call the parent logout's function in the handleDropdownOptions's child function (in your case).</p>

Body:
I have a condition where I have simple dropdown menu

handleDropdown = (e) => {
    if (e.type === "focus") {
      console.log("inside dropdown focus");
      this.setState({ dropDownDis: "block" })
    } else if (e.type === "blur") {
      console.log("inside dropdown blur");
      this.setState({ dropDownDis: "none" })
    }
  }

 logout = (e) => {
    if (!e) var e = window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    console.log("inside logout")
  }

When I click on Logout, The menu closes but logout method doesn't calls.

html

              <button
                type="button"
                className="dropdown-button"
                ref={this.myRef}
                onFocus={this.handleDropdown}
                onBlur={this.handleDropdown}
              >

              </button>

                 My Profile

                Order

                 My Account

                Log Out

On clicking the logout I can see the console as shown in below image


问:
H2 Console throwing a error webAllowOthers in H2 database
I am using heruko to deploy my application when i am trying to load my h2 console using heruko it is throwing an error saying.

H2 Console
Sorry, remote connections ('webAllowOthers') are disabled on this server.

i am using the below settings  in my application.properties file

```<code>jdbc:h2:tcp://localhost/~/test
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:Roomy;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled = true
spring.h2.console.settings.trace=true
spring.h2.console.settings.web-allow-others=true
</code>```

I done some google and added .h2.server.properties

```<code>#H2 Server Properties
1=Generic H2 (Memory)|org.h2.Driver|jdbc:h2:mem:Roomy;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE|sa
webAllowOthers=true
tcpAllowOthers=true
webPort=8082
webSSL=false
</code>```

Please mention what i have done wrong and i am unable to view the h2 console could someone help on this.The cosole is working fine in the local and in the heroku the DB is working with no issues but unable to view the console .Any help would be greatly appreciable.

Thanks
Chaitanya

答:
for those who use application.yml format </p>

```<code>spring:
  h2:
    console:
      enabled: true
      settings:
        web-allow-others: true
</code>```

Body:
I am using heruko to deploy my application when i am trying to load my h2 console using heruko it is throwing an error saying.

H2 Console
Sorry, remote connections ('webAllowOthers') are disabled on this server.

i am using the below settings  in my application.properties file

jdbc:h2:tcp://localhost/~/test
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:Roomy;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled = true
spring.h2.console.settings.trace=true
spring.h2.console.settings.web-allow-others=true

I done some google and added .h2.server.properties

#H2 Server Properties
1=Generic H2 (Memory)|org.h2.Driver|jdbc:h2:mem:Roomy;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE|sa
webAllowOthers=true
tcpAllowOthers=true
webPort=8082
webSSL=false

Please mention what i have done wrong and i am unable to view the h2 console could someone help on this.The cosole is working fine in the local and in the heroku the DB is working with no issues but unable to view the console .Any help would be greatly appreciable.

Thanks
Chaitanya

Body:
for those who use application.yml format

spring:
  h2:
    console:
      enabled: true
      settings:
        web-allow-others: true


问:
TextFormField hidden by keyboard - Flutter
When focussing on the TextFormField, the keyboard hides over the TextFormField. I am using SingleScrollview with the Column widget. Below I attached a screenshot with coding. Please guide me in fixing this issue.

```<code>Scaffold(
  resizeToAvoidBottomInset: false,
  resizeToAvoidBottomPadding: false,
  key: _scaffoldKey,
  body: SingleChildScrollView(
  child: Padding(
    padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
    child: new Column(
      children: <Widget>[
        _tabText(),
        isSignin ? _loginContainer() : _signUpContainer(),
      ],
    ),),),);
</code>```

答:
//Add this line "resizeToAvoidBottomInset: true," to your Scaffold and put your main
    container in ScrollView.</p>

```<code>    @override
    Widget build(BuildContext context) {
   return Scaffold(
   resizeToAvoidBottomInset: true,
   key: _scaffoldKey,
   backgroundColor: Colors.white,
   body: SingleChildScrollView(
      child: Container()
    ),
   );
  }
</code>```

Body:
When focussing on the TextFormField, the keyboard hides over the TextFormField. I am using SingleScrollview with the Column widget. Below I attached a screenshot with coding. Please guide me in fixing this issue.

Scaffold(
  resizeToAvoidBottomInset: false,
  resizeToAvoidBottomPadding: false,
  key: _scaffoldKey,
  body: SingleChildScrollView(
  child: Padding(
    padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
    child: new Column(
      children: <Widget>[
        _tabText(),
        isSignin ? _loginContainer() : _signUpContainer(),
      ],
    ),),),);

Body:
//Add this line "resizeToAvoidBottomInset: true," to your Scaffold and put your main
    container in ScrollView.

    @override
    Widget build(BuildContext context) {
   return Scaffold(
   resizeToAvoidBottomInset: true,
   key: _scaffoldKey,
   backgroundColor: Colors.white,
   body: SingleChildScrollView(
      child: Container()
    ),
   );
  }


问:
Importing a typescript module to a JS module in a React app
I have a React app created with create-react-app. Recently I've added some source code for a module I need. It's in Typescript and will stay in Typescript. Not my choice.
I've installed what I needed to build Typescript and that part seems to work OK.

However, when I try importing that TS module to my regular jsx, it says module not found.

To illustrate:

```<code>shared/
    - MyTSModule/
        - index.tsx
    - OtherModule/
        - index.jsx
view/
    - MyView/
        - index.jsx
</code>```

I'm trying to import MyTSModule to MyView. The error is: Module not found: Error: Can't resolve 'shared/MyTSModule' in...

I'm importing like all the other modules from shared:

```<code>import MyTSModule from 'shared/MyTSModule ';
</code>```

What am I missing?

答:
You cannot import typescript file from javascript. You either need to:

compile typescript to javascript and then import compiled file

convert your javascript files to typescript.

I personally recommend porting all files to typescript, this way you will have more type safety.

Body:
I have a React app created with create-react-app. Recently I've added some source code for a module I need. It's in Typescript and will stay in Typescript. Not my choice.
I've installed what I needed to build Typescript and that part seems to work OK.

However, when I try importing that TS module to my regular jsx, it says module not found.

To illustrate:

shared/
    - MyTSModule/
        - index.tsx
    - OtherModule/
        - index.jsx
view/
    - MyView/
        - index.jsx

I'm trying to import MyTSModule to MyView. The error is: Module not found: Error: Can't resolve 'shared/MyTSModule' in...

I'm importing like all the other modules from shared:

import MyTSModule from 'shared/MyTSModule ';

What am I missing?


问:
How to free() an array of structs allocated by malloc()?
I've been working on a project that uses structs as storage for strings. I declared a struct consists of char type members:

```<code>struct datastore1
{
    char name[50];
    char address[50];
    char email[50];
    char number[50];
    char idnum[50];
};
</code>```

I'm aware that I can just do char *name, char *address... but let's say we specified it with max length of 50. Then on my function which uses the struct, I malloc'ed it with index size of 30:

```<code>struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));
</code>```

Supposedly I finished copying all strings into the struct by accessing each index, How should i free the allocated memory that was used after calling malloc? I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way. Should i free each indexes individually? Please enlighten me. Thank you in advance for the feedback!

答:
As far as I understand you only used malloc to allocate space for an array of datastore1 struct, so it is sufficient to just do free(dsdata).

If in the struct you would have pointers and you would use malloc to allocate each of them, only than you would need to free each of them first.

Body:
I've been working on a project that uses structs as storage for strings. I declared a struct consists of char type members:

struct datastore1
{
    char name[50];
    char address[50];
    char email[50];
    char number[50];
    char idnum[50];
};

I'm aware that I can just do char *name, char *address... but let's say we specified it with max length of 50. Then on my function which uses the struct, I malloc'ed it with index size of 30:

struct datastore1 *dsdata = malloc(30 * sizeof(struct datastore1));

Supposedly I finished copying all strings into the struct by accessing each index, How should i free the allocated memory that was used after calling malloc? I tried doing free(dsdata) on the end of the program but I am not sure if it's the right way. Should i free each indexes individually? Please enlighten me. Thank you in advance for the feedback!


问:
Unable to reset stored procedure cache in SQL Server Management Studio 2008
Workflow:

I have two stored procedures.  One stored procedure calls the other.  When I first open SQL Server Management Studio, the child/nested stored procedure has no output parameters.  Nor does my parent/calling stored procedure have an "OUTPUT" keyword on the argument when calling the child/nested stored procedure.  And of course I'm not expecting any argument to be returned as output in my parent/calling stored procedure from the child/nested stored procedure.

Then I decided I need the returned value of the id that was inserted during that child/nested stored procedure, so I decided to put an "OUTPUT" keyword onto the parameter so that I can retrieve that value in the parent/calling stored procedure.

So I altered my child/nested stored procedure after adding an "OUTPUT" keyword on the end of the parameter.  And clicked the "Execute" button in SQL Server Management Studio to save the stored procedure.

Then I added an "OUTPUT" keyword for the argument of my parent/calling stored procedure that matches up with the parameter of the child/nested stored procedure.  Then I clicked the "Execute" button in SQL Server Management Studio to save the stored procedure.

Issue:

I have red underlines under my argument in the parent/calling stored procedure.  The tooltip for the error says, "The formal parameter @donorid was not declared as an output parameter, but the actual parameter passed in requested output."

Workaround:

I can easily restart SQL Server Management Studio and it clears the cache and the red underlines go away, but I'd like to know the command that clears it without restarting.

PS: I'll post my stored procedures in separate posts so you have an example to work from.

答: This is Microsoft Connect bug 668511.</p>

Body: This is Microsoft Connect bug 668511.


问:
How does character array with single quote affects an character array without the quotes?
```<code>char a[5] = { 1, 2, 3, 4, 5 };
char a[5] = { '1','2', '3', '4', '5' };
</code>```

what is the difference? It does not raise any errors. why?

答:
In C language, the characters are represented using single quotes.
And anything that is enclosed in a single quote is a character.
Every character has an ASCII code associated with it.

ASCII abbreviated from American Standard Code for Information Interchange, is a character encoding standard for electronic communication. ASCII codes represent text in computers, telecommunications equipment, and other devices.

Example, ASCII code of 'A' is 65

```<code>char sampleChar = 'A'
char sampleASCII = 65
</code>```

Both character variables sampleChar, sampleASCII provide same value when printed.

So in your case, the compiler does not throw any error because it assumes that you want to store the characters with ASCII values 1,2,3,4 and 5.
But when you print the array,

```<code>char a[5] = { '1','2', '3', '4', '5' };
</code>```

it will provide characters 1 2 3 4 5 as output. Whereas the first array will not provide any printable output. The characters corresponding to ASCII value 1 2 3 4 5 is used for transmission control.
The ASCII values of 1, 2, 3, 4, 5 can be found here

Body:
char a[5] = { 1, 2, 3, 4, 5 };
char a[5] = { '1','2', '3', '4', '5' };

what is the difference? It does not raise any errors. why?

Body:
In C language, the characters are represented using single quotes.
And anything that is enclosed in a single quote is a character.
Every character has an ASCII code associated with it.

ASCII abbreviated from American Standard Code for Information Interchange, is a character encoding standard for electronic communication. ASCII codes represent text in computers, telecommunications equipment, and other devices.

Example, ASCII code of 'A' is 65

char sampleChar = 'A'
char sampleASCII = 65

Both character variables sampleChar, sampleASCII provide same value when printed.

So in your case, the compiler does not throw any error because it assumes that you want to store the characters with ASCII values 1,2,3,4 and 5.
But when you print the array,

char a[5] = { '1','2', '3', '4', '5' };

it will provide characters 1 2 3 4 5 as output. Whereas the first array will not provide any printable output. The characters corresponding to ASCII value 1 2 3 4 5 is used for transmission control.
The ASCII values of 1, 2, 3, 4, 5 can be found here


问:
Spatial polygon intersection - multiple resulting polygons
I am working on the intersection of polygons using the R spatial tools rgeos::gIntersection and/or raster::intersect. In my case the result of the intersection is two polygons due to the shape of one of the polygons (Lpoly) used to do the intersection. However, from the summary() function it looks it is only one feature that is created?! How can I access the two geometries resulting from the intersect process? Furthermore I'd like to select only one of the resulting polygons based on a criteria of covering a particular spatial point (coordinate pair):

```<code>A <- c(0,0)
B <- c(0,3)
C <- c(2,3)
D <- c(2,1)
E <- c(3,1)
F <- c(3,3)
G <- c(5,3)
H <- c(5,0)
Lpoly <- SpatialPolygons(list(Polygons(list(Polygon(rbind(A,B,C,D,E,F,G,H))),1)))
plot(Lpoly)

A2 <- c(1,2)
B2 <- c(1,3)
C2 <- c(4,3)
D2 <- c(4,2)
intersect_poly <-  SpatialPolygons(list(Polygons(list(Polygon(rbind(A2,B2,C2,D2))),1)))
plot(intersect_poly,col="red",add=T)

i <- intersect(Lpoly,intersect_poly)
i_rgeos <- rgeos::gIntersection(Lpoly,intersect_poly)
summary(i_rgeos)

plot(i_rgeos,add=T,col="green")
</code>```

How to select only one polygon and/or get unique features for each resulting polygon? How can I access the resulting polygon that also covers the coordinates c(1.5,2.5)?

Solution approach #1:
I found a solution based on:

```<code>i_rgeos <- disaggregate(i_rgeos)
i_rgeos <- i_rgeos[as.vector(which(over(i_rgeos,p)>0)),] #where p = spatial point of interest
</code>```

答:
Not sure in rgeos how to do it, but using the sf package, we can easily cast shapefiles to different types, in this case from MULTIPOLYGON to POLYGON, we just have to first cast i_rgeos to a simple feature.

library(sf)

st_as_sf(i_rgeos) %>% st_cast("POLYGON")
#> Simple feature collection with 2 features and 0 fields
#> geometry type:  POLYGON
#> dimension:      XY
#> bbox:           xmin: 1 ymin: 2 xmax: 4 ymax: 3
#> epsg (SRID):    NA
#> proj4string:    NA
#>                         geometry
#> 1 POLYGON ((1 3, 2 3, 2 2, 1 ...
#> 2 POLYGON ((3 2, 3 3, 4 3, 4 ...
```

Body:
I am working on the intersection of polygons using the R spatial tools rgeos::gIntersection and/or raster::intersect. In my case the result of the intersection is two polygons due to the shape of one of the polygons (Lpoly) used to do the intersection. However, from the summary() function it looks it is only one feature that is created?! How can I access the two geometries resulting from the intersect process? Furthermore I'd like to select only one of the resulting polygons based on a criteria of covering a particular spatial point (coordinate pair):

A <- c(0,0)
B <- c(0,3)
C <- c(2,3)
D <- c(2,1)
E <- c(3,1)
F <- c(3,3)
G <- c(5,3)
H <- c(5,0)
Lpoly <- SpatialPolygons(list(Polygons(list(Polygon(rbind(A,B,C,D,E,F,G,H))),1)))
plot(Lpoly)

A2 <- c(1,2)
B2 <- c(1,3)
C2 <- c(4,3)
D2 <- c(4,2)
intersect_poly <-  SpatialPolygons(list(Polygons(list(Polygon(rbind(A2,B2,C2,D2))),1)))
plot(intersect_poly,col="red",add=T)

i <- intersect(Lpoly,intersect_poly)
i_rgeos <- rgeos::gIntersection(Lpoly,intersect_poly)
summary(i_rgeos)

plot(i_rgeos,add=T,col="green")

How to select only one polygon and/or get unique features for each resulting polygon? How can I access the resulting polygon that also covers the coordinates c(1.5,2.5)?

Solution approach #1:
I found a solution based on:

i_rgeos <- disaggregate(i_rgeos)
i_rgeos <- i_rgeos[as.vector(which(over(i_rgeos,p)>0)),] #where p = spatial point of interest


问:
Why does a CSS transition not work well with another animation based on jQuery's animate method?
I have a button that I wish to move when it is clicked, and while moving it should also flip. So there are two animations that take place at the same time, and have the same duration. I also have a CSS transition set up for all the properties of the button. It seems to me that only the CSS scale transform works when I use both jQuery's animate method and the CSS transition effect. When I remove one of the animations, the other one works well.

// find elements
var button = $("button");

// handle click
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });

 // the bug: the following animation is not visible
  button.animate({
    "top": "-100px" // I tried without "px" too
  }, 0.15 * 1000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;

  position: relative;
  transition: all 0.15s;
}</code>```

Hello World

  <button>Click me</button>

```

The JSFiddle is here.

Thank you.

答:
your button position should bet set to absolute!

var button = $("button");

// handle click
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });

    // the bug: the following animation is not visible
  button.animate({top: "-100px"}, 0.15 * 1000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button{
  position:absolute;
}</code>```

Hello World

  <button>Click me</button>

```

Body:
I have a button that I wish to move when it is clicked, and while moving it should also flip. So there are two animations that take place at the same time, and have the same duration. I also have a CSS transition set up for all the properties of the button. It seems to me that only the CSS scale transform works when I use both jQuery's animate method and the CSS transition effect. When I remove one of the animations, the other one works well.

// find elements
var button = $("button");

// handle click
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });

 // the bug: the following animation is not visible
  button.animate({
    "top": "-100px" // I tried without "px" too
  }, 0.15 * 1000);
});

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;

  position: relative;
  transition: all 0.15s;
}

Hello World

  <button>Click me</button>

The JSFiddle is here.

Thank you.

Body:
your button position should bet set to absolute!

var button = $("button");

// handle click
button.on("click", function() {
  button.css({
    "transform": "scaleX(0)"
  });

    // the bug: the following animation is not visible
  button.animate({top: "-100px"}, 0.15 * 1000);
});

button{
  position:absolute;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <p>Hello World</p>
  <button>Click me</button>
</div>


问:
How to access switch argument / ID from switch?
Please forgive if my question isnt placed properly, i am new to this whole subject. In my python file i have a callback function for my switches, which i create in my .kv file.

```<code>from kivy.app import App
from kivy.uix.pagelayout import PageLayout

class PageLayout(PageLayout):
    statusMsg = 'Empty Status.'

    def switch_callback(self, switchObject, switchValue):
        #Switch values are True and False
        if(switchValue):
            statusMsg = '{0} enabled'.format(switchObject)
            print(statusMsg)
        else:
            statusMsg = '{0} disabled'.format(switchObject)
            print(statusMsg)
        return statusMsg

    def __init__(self):
        super(PageLayout, self).__init__()

class myGUI(App):
    def build(self):
        return PageLayout()

if __name__ == "__main__":
    myGUI().run()
</code>```

Kivy File (myGUI.kv):

```<code><PageLayout>:
    BoxLayout:
        BoxLayout:
        Label:
            text: 'TestLabel'
        Switch:
            id: switchCal
            active: False
            on_active: root.switch_callback(*args)
</code>```

now i can print the called object argument but not the id. Do i have to use another variable, or is id not passed with *args? My shell looks like this:

```<code><kivy.uix.switch.Switch object at 0x1111B258> enabled
</code>```

I tried switchObject.id but it doesnt work. Thanks in advance!

答:
One way to find the switch's id, is a for loop with the root's ids.

        for i_d in self.ids:
            if switchObject == self.ids[i_d]:
                print(i_d)
                break
```

<p>You have also to rename your <code>PageLayout</code> class to something else, because its name conflicts with kivy's <code>PageLayout</code>.</p>

<p>Full code for the <code>py</code> part:</p>

<pre class="lang-py prettyprint-override"><code>from kivy.app import App
from kivy.uix.pagelayout import PageLayout

class PageLayoutX(PageLayout):
    statusMsg = 'Empty Status.'

    def switch_callback(self, switchObject, switchValue):
        for i_d in self.ids:
            if switchObject == self.ids[i_d]:
                print(i_d)
                break
        # Switch values are True and False
        if (switchValue):
            statusMsg = '{0} enabled'.format(switchObject)
            print(statusMsg)
        else:
            statusMsg = '{0} disabled'.format(switchObject)
            print(statusMsg)
        return statusMsg

    def __init__(self):
        super(PageLayoutX, self).__init__()

class myGUI(App):
    def build(self):
        return PageLayoutX()

if __name__ == "__main__":
    myGUI().run()
</code>```

... and the kv part

<PageLayoutX>:
    BoxLayout:
        BoxLayout:
        Label:
            text: 'TestLabel'
        Switch:
            id: switchCal
            active: False
            on_active: root.switch_callback(*args)
```

Body:
Please forgive if my question isnt placed properly, i am new to this whole subject. In my python file i have a callback function for my switches, which i create in my .kv file.

from kivy.app import App
from kivy.uix.pagelayout import PageLayout

class PageLayout(PageLayout):
    statusMsg = 'Empty Status.'

    def switch_callback(self, switchObject, switchValue):
        #Switch values are True and False
        if(switchValue):
            statusMsg = '{0} enabled'.format(switchObject)
            print(statusMsg)
        else:
            statusMsg = '{0} disabled'.format(switchObject)
            print(statusMsg)
        return statusMsg

    def __init__(self):
        super(PageLayout, self).__init__()

class myGUI(App):
    def build(self):
        return PageLayout()

if __name__ == "__main__":
    myGUI().run()

Kivy File (myGUI.kv):

<PageLayout>:
    BoxLayout:
        BoxLayout:
        Label:
            text: 'TestLabel'
        Switch:
            id: switchCal
            active: False
            on_active: root.switch_callback(*args)

now i can print the called object argument but not the id. Do i have to use another variable, or is id not passed with *args? My shell looks like this:

<kivy.uix.switch.Switch object at 0x1111B258> enabled

I tried switchObject.id but it doesnt work. Thanks in advance!

Body:
One way to find the switch's id, is a for loop with the root's ids.

        for i_d in self.ids:
            if switchObject == self.ids[i_d]:
                print(i_d)
                break

You have also to rename your PageLayout class to something else, because its name conflicts with kivy's PageLayout.

Full code for the py part:

from kivy.app import App
from kivy.uix.pagelayout import PageLayout

class PageLayoutX(PageLayout):
    statusMsg = 'Empty Status.'

    def switch_callback(self, switchObject, switchValue):
        for i_d in self.ids:
            if switchObject == self.ids[i_d]:
                print(i_d)
                break
        # Switch values are True and False
        if (switchValue):
            statusMsg = '{0} enabled'.format(switchObject)
            print(statusMsg)
        else:
            statusMsg = '{0} disabled'.format(switchObject)
            print(statusMsg)
        return statusMsg

    def __init__(self):
        super(PageLayoutX, self).__init__()

class myGUI(App):
    def build(self):
        return PageLayoutX()

if __name__ == "__main__":
    myGUI().run()

... and the kv part

<PageLayoutX>:
    BoxLayout:
        BoxLayout:
        Label:
            text: 'TestLabel'
        Switch:
            id: switchCal
            active: False
            on_active: root.switch_callback(*args)


问:
How to write a custom powershell host
Similar to nuget

Looking for any starter material hopefully before delving into the debugger

答:
You'll find here under the blog from which I built my own PowerShell which interpret scripts without showing any windows.

Blog from Leporelo

It's really the few first lines you need and the shortcut to PowerShell SDK.

the shell responding my own need (sorry in french)

Title: How to write a custom powershell host