问:
Comparing elements of a dataframe in R
I have a very large dataframe, called recip, where each row has format recip1 recip2 num. I want to trim it down by keeping only the rows where recip1 < recip2. Attached is an image of the first 10 rows of the dataframe.

Note that recip1 corresponds to V1, and recip2 to V2. Can someone help me out? Thanks.

答:
you can use indexing for this

```<code>mtcars[ mtcars$drat > mtcars$wt , ]
</code>```

here is the dplyr way

```<code>library( dplyr )
mtcars %>% filter( wt > drat )
</code>```

Check your classes - you need numeric or integers for this

```<code>sapply( mtcars , class)
</code>```

Title: Comparing elements of a dataframe in R

Body:
you can use indexing for this

mtcars[ mtcars$drat > mtcars$wt , ]

here is the dplyr way

library( dplyr )
mtcars %>% filter( wt > drat )

Check your classes - you need numeric or integers for this

sapply( mtcars , class)


来源: stackexchange

问:
How to create an JavaScript ArrayBuffer, that is similar to the WebAuthN's ArrayBuffer?
I am currently writing a prove of concept web application for WebAuthN (FIDO U2F, FIDO2) integration.

The data type of the returned field cred.rawId is ArrayBuffer. Within Chromes' developer console, this field is shown as here:

When I try to reproduce this ArrayBuffer, I end up with this:

Pay attention to the "other representations" (e.g. [[Int8Array]]), which are all zero'ed out! And in addition, my ArrayBuffer looks like an ordinary array while the data is not shown (in that way) in the first original screenshot.

This is the source code (remember: PoC state) to retrieve the rawId from a stored Base64 repesentation:

```<code>function StringToByteArray(str) {
  var bytes = new ArrayBuffer();
  for (var i = 0; i < str.length; ++i) {
    var code = str.charCodeAt(i);
    var _bytes = new ArrayBuffer(bytes.byteLength + 1);
    for ( var j = 0; j < bytes.byteLength; j++ ) {
      _bytes[j] = bytes[j];
    }
    _bytes[bytes.byteLength] = code;
    bytes = _bytes
  }
  return bytes;
}

var x_rawId = StringToByteArray(base64.decode(cred.id.replace(/-/g, '+').replace(/_/g, '/').padRight(cred.id.length + (4 - cred.id.length % 4) % 4, '=')));
</code>```

The Base64 class is from Nick Galbreaths' Base64 for JavaScript implementation.

The current rawId may work, however I would like to reproduce it 100% so the chance that it fails in an other browser at some future browser version is minimized.

How to achieve the representation which is shown in the Chrome screenshot?

答:
Could you maybe try replacing the function with the following:

```<code>function StringToByteArray(str) {
  return Uint8Array.from(str, c => c.charCodeAt(0));
}
</code>```

It's very simple, but it does the trick in one of my projects.

ContentLicense: CC BY-SA 4.0

Body:
I am currently writing a prove of concept web application for WebAuthN (FIDO U2F, FIDO2) integration.

The data type of the returned field cred.rawId is ArrayBuffer. Within Chromes' developer console, this field is shown as here:

When I try to reproduce this ArrayBuffer, I end up with this:

Pay attention to the "other representations" (e.g. [[Int8Array]]), which are all zero'ed out! And in addition, my ArrayBuffer looks like an ordinary array while the data is not shown (in that way) in the first original screenshot.

This is the source code (remember: PoC state) to retrieve the rawId from a stored Base64 repesentation:

function StringToByteArray(str) {
  var bytes = new ArrayBuffer();
  for (var i = 0; i < str.length; ++i) {
    var code = str.charCodeAt(i);
    var _bytes = new ArrayBuffer(bytes.byteLength + 1);
    for ( var j = 0; j < bytes.byteLength; j++ ) {
      _bytes[j] = bytes[j];
    }
    _bytes[bytes.byteLength] = code;
    bytes = _bytes
  }
  return bytes;
}

var x_rawId = StringToByteArray(base64.decode(cred.id.replace(/-/g, '+').replace(/_/g, '/').padRight(cred.id.length + (4 - cred.id.length % 4) % 4, '=')));

The Base64 class is from Nick Galbreaths' Base64 for JavaScript implementation.

The current rawId may work, however I would like to reproduce it 100% so the chance that it fails in an other browser at some future browser version is minimized.

How to achieve the representation which is shown in the Chrome screenshot?

Body:
Could you maybe try replacing the function with the following:

function StringToByteArray(str) {
  return Uint8Array.from(str, c => c.charCodeAt(0));
}

It's very simple, but it does the trick in one of my projects.


问:
Can we apply check on the property field of json schema?
I want to validate my json.

If the is_dummy field exists and is set to False the fields username and password are required, if it is set to True they are not.

But it is also valid if is_dummy is not present.

```<code>{
    "type": "object",
    "properties": {
        "name": {"type": "string", "minLength": 1},
        "username": {"type": "string", "minLength": 1},
        "password": {"type": "string", "minLength": 1},
        "is_dummy": {"type": "boolean"},
    },
    "if": {"properties": {"is_dummy": {"const": False}}},
    "then": {"required": ["username", "password"]}
}
</code>```

答:
You can check if is_dummy is in your json with :

```<code>if 'is_dummy' in data['properties'].keys():
    # Do you want
</code>```

To check if the value is False you can use :

```<code>if data['properties']['is_dummy'] == False:
    # Do what you want
</code>```

You can use the same logic to check your username/password fields

Body:
I want to validate my json.

If the is_dummy field exists and is set to False the fields username and password are required, if it is set to True they are not.

But it is also valid if is_dummy is not present.

{
    "type": "object",
    "properties": {
        "name": {"type": "string", "minLength": 1},
        "username": {"type": "string", "minLength": 1},
        "password": {"type": "string", "minLength": 1},
        "is_dummy": {"type": "boolean"},
    },
    "if": {"properties": {"is_dummy": {"const": False}}},
    "then": {"required": ["username", "password"]}
}

Body:
You can check if is_dummy is in your json with :

if 'is_dummy' in data['properties'].keys():
    # Do you want

To check if the value is False you can use :

if data['properties']['is_dummy'] == False:
    # Do what you want

You can use the same logic to check your username/password fields


问:
How to change a global parameter inside a decorator and automatically reset it?
I am trying to change a config dictionary inside the decorator (So I don't have to mess with the code of the function do_something() itself). I am experiencing problems however with 'resetting' the dictionary to its old state.

How do I do this? And is there a better way going forward than this approach (without changing the do_something() code itself)?

I've tried several approaches in regards to placement of the CONFIG variable, but in the end, the global context is never reset to the original state.

import copy

CONFIG = {
    'key': 'value'
}

def alter_dictionary_decorator(function):
    def wrapper():
        old = copy.deepcopy(CONFIG)
        CONFIG['key'] = 'other_value'
        func = function()
        config = old # <- can't put 'CONFIG = old' here
        return func
    return wrapper

@alter_dictionary_decorator
def do_something():
    print(CONFIG['key'])

if __name__ == '__main__':
    print(CONFIG['key'])
    do_something()
    print(CONFIG['key'])
```

Expected results = 'value', 'other_value', 'value'

Observerd results = 'value', 'other_value', 'other_value'

答:
You need to use the global keyword in order to modify variables that have global scope. Also, config = old should have been CONFIG = old.

The following code works as you require:

```<code>import copy

CONFIG = {
    'key': 'value'
}

def alter_dictionary_decorator(function):
    def wrapper():
        global CONFIG
        old = copy.deepcopy(CONFIG)
        CONFIG['key'] = 'other_value'
        func = function()
        CONFIG = old
        return func
    return wrapper

@alter_dictionary_decorator
def do_something():
    print(CONFIG['key'])

if __name__ == '__main__':
    print(CONFIG['key'])
    do_something()
    print(CONFIG['key'])
</code>```

With the output being:

```<code>value
other_value
value
</code>```

Body:
I am trying to change a config dictionary inside the decorator (So I don't have to mess with the code of the function do_something() itself). I am experiencing problems however with 'resetting' the dictionary to its old state.

How do I do this? And is there a better way going forward than this approach (without changing the do_something() code itself)?

I've tried several approaches in regards to placement of the CONFIG variable, but in the end, the global context is never reset to the original state.

import copy

CONFIG = {
    'key': 'value'
}

def alter_dictionary_decorator(function):
    def wrapper():
        old = copy.deepcopy(CONFIG)
        CONFIG['key'] = 'other_value'
        func = function()
        config = old # <- can't put 'CONFIG = old' here
        return func
    return wrapper

@alter_dictionary_decorator
def do_something():
    print(CONFIG['key'])

if __name__ == '__main__':
    print(CONFIG['key'])
    do_something()
    print(CONFIG['key'])

Expected results = 'value', 'other_value', 'value'

Observerd results = 'value', 'other_value', 'other_value'

Body:
You need to use the global keyword in order to modify variables that have global scope. Also, config = old should have been CONFIG = old.

The following code works as you require:

import copy

CONFIG = {
    'key': 'value'
}

def alter_dictionary_decorator(function):
    def wrapper():
        global CONFIG
        old = copy.deepcopy(CONFIG)
        CONFIG['key'] = 'other_value'
        func = function()
        CONFIG = old
        return func
    return wrapper

@alter_dictionary_decorator
def do_something():
    print(CONFIG['key'])

if __name__ == '__main__':
    print(CONFIG['key'])
    do_something()
    print(CONFIG['key'])

With the output being:

value
other_value
value


问:
Find usages of task groups
We have quite a lot build and release pipelines and we are using task groups frequently. Unfortunately, there doesn't seem to be a possibility to find the pipelines that use a certain task group.

Is there any way to find all usages of a task group?

答: The taskgroup has a "References"-tab that shows where it is beeing used.

Title: Find usages of task groups


问:
_AppDomainPtr Load_3 method example?
I am trying to load a C# assembly with _AppDomainPtr Load_3 method. Do you have some example since I get error:
hr = 0x80131533 : A mismatch has occurred between the runtime type of the array and the sub type recorded in the metadata.
Here is a snippet how do I load the assembly:

```<code>static void binarray(SAFEARRAY** output, const char* data, size_t size)
{
    SAFEARRAYBOUND  Bound;
    Bound.lLbound = 0;
    Bound.cElements = size;

    *output = SafeArrayCreate(VT_R8, 1, &Bound);

    double HUGEP *pdFreq;
    HRESULT hr = SafeArrayAccessData(*output, (void HUGEP* FAR*)&pdFreq);
    if (SUCCEEDED(hr))
    {
        // copy sample values from data[] to this safearray
        for (DWORD i = 0; i < size; i++)
        {
            *pdFreq++ = data[i];
        }
        SafeArrayUnaccessData(*output);
    }
}
</code>```

And the call:

```<code>hr = spDefaultAppDomain->Load_3(output, &spAssembly);
</code>```

Anyone used that?

答:
Apparently I've found the problem. I was creating a SafeArray of Real numbers. The correct fix for anyone who needs that is:</p>

```<code>static void binarray(SAFEARRAY** output, const unsigned  char* data, size_t size)
{
    SAFEARRAYBOUND  Bound;
    Bound.lLbound = 0;
    Bound.cElements = size;
//  VT_I1
    *output = SafeArrayCreate(VT_UI1, 1, &Bound);
    //VT_R8
    unsigned char *pdFreq;
    HRESULT hr = SafeArrayAccessData(*output, (void* FAR*)&pdFreq);
    if (SUCCEEDED(hr))
    {
        // copy sample values from data[] to this safearray
        for (DWORD i = 0; i < size; i++)
        {
            *pdFreq++ = data[i];
        }
        SafeArrayUnaccessData(*output);
    }
}
</code>```

Title: _AppDomainPtr Load_3 method example?

Body:
I am trying to load a C# assembly with _AppDomainPtr Load_3 method. Do you have some example since I get error:
hr = 0x80131533 : A mismatch has occurred between the runtime type of the array and the sub type recorded in the metadata.
Here is a snippet how do I load the assembly:

static void binarray(SAFEARRAY** output, const char* data, size_t size)
{
    SAFEARRAYBOUND  Bound;
    Bound.lLbound = 0;
    Bound.cElements = size;

    *output = SafeArrayCreate(VT_R8, 1, &Bound);

    double HUGEP *pdFreq;
    HRESULT hr = SafeArrayAccessData(*output, (void HUGEP* FAR*)&pdFreq);
    if (SUCCEEDED(hr))
    {
        // copy sample values from data[] to this safearray
        for (DWORD i = 0; i < size; i++)
        {
            *pdFreq++ = data[i];
        }
        SafeArrayUnaccessData(*output);
    }
}

And the call:

hr = spDefaultAppDomain->Load_3(output, &spAssembly);

Anyone used that?

Body:
Apparently I've found the problem. I was creating a SafeArray of Real numbers. The correct fix for anyone who needs that is:

static void binarray(SAFEARRAY** output, const unsigned  char* data, size_t size)
{
    SAFEARRAYBOUND  Bound;
    Bound.lLbound = 0;
    Bound.cElements = size;
//  VT_I1
    *output = SafeArrayCreate(VT_UI1, 1, &Bound);
    //VT_R8
    unsigned char *pdFreq;
    HRESULT hr = SafeArrayAccessData(*output, (void* FAR*)&pdFreq);
    if (SUCCEEDED(hr))
    {
        // copy sample values from data[] to this safearray
        for (DWORD i = 0; i < size; i++)
        {
            *pdFreq++ = data[i];
        }
        SafeArrayUnaccessData(*output);
    }
}


问:
How can I test dynamic image content with Selenium?
I'm working on a project that generates dynamic images (like the content of the actual image changes depending on the parameters sent with the URL). Following in the TDD ways I would really like a way to test this process out. On the low end I would be okay with checking that a specific x-y pixel was a certain color. On the high end I would be happy if I could do a compare between two images and figure out if they were identical.

Any idea how I can test this with selenium? If not, is there a way to do it with HTMLUnit?

Thanks.

答:
I have the same problem over here.

I think you need to use one of the language bindings of selenium (java, perl etc) and perform some calls with your favorite image processing libraries.

Here is a perl approach by @merlyn

I set out to write a program that could find similar images, not just identical images. My selected strategy is to reduce each image to a 4-by-4 grid of RGB values, yielding a 48-number vector of values from 0 to 255.

http://www.stonehenge.com/merlyn/LinuxMag/col50.html

This does not use Selenium, maybe I'll do it and post it over here when I'm done.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
RegEx ignore letters until digit occurs and then match letters afterwards
This is intended to be used in Java.
Imagine following sample input:

```<code>WRA1007
1085808
1092650S
3901823CV
</code>```

I want to match all alphabetic characters after at least one digit.

Desired output:

```<code>S
CV
</code>```

Actual output:

```<code>0S
3CV
</code>```

My current approach looks like this:

```<code>\d[a-zA-Z]+
</code>```

The problem with this pattern is that it includes the digit beforehand too. My current solution is to remove the first character of the resulting string afterwards. And this seems quite unsatisfactory to me.

答:
You need a lookbehind:

```<code>(?<=\d)[a-zA-Z]+
</code>```

(?<=\d) means "there must be a digit before this position, but don't match it".

Demo

Alternatively, you can use a pair of () to surround the part you want to get:

```<code>\d([a-zA-Z]+)
</code>```

This is called a "group", and you can get its value by calling group(1) on your Matcher.

Body:
This is intended to be used in Java.
Imagine following sample input:

WRA1007
1085808
1092650S
3901823CV

I want to match all alphabetic characters after at least one digit.

Desired output:

S
CV

Actual output:

0S
3CV

My current approach looks like this:

\d[a-zA-Z]+

The problem with this pattern is that it includes the digit beforehand too. My current solution is to remove the first character of the resulting string afterwards. And this seems quite unsatisfactory to me.

Body:
You need a lookbehind:

(?<=\d)[a-zA-Z]+

(?<=\d) means "there must be a digit before this position, but don't match it".

Demo

Alternatively, you can use a pair of () to surround the part you want to get:

\d([a-zA-Z]+)

This is called a "group", and you can get its value by calling group(1) on your Matcher.


问:
Empty string check evaluates wrong
I have a condition checking for empty strings and it is not evaluating an empty string as expected.

I read string one char at a time:

```<code>isNumber(s: string) {
  console.log('char', s);
  if (s !== '' && !isNaN(Number(s))) {
    console.log('is a number');
    console.log('-------------');
    return true;
  }
  console.log('NOT a number');
  console.log('-------------');
}
</code>```

The string is read from a csv file:

```<code>a,b,
c,d,e
</code>```

The 3rd column 1st row is empty but if evaluates to true even though I have s !== '', I have confirmed the char is empty with console. Why is the empty string condition not working?

Update:
Could this cause a non empty string? I initialise the variable with quotes then append to it.

```<code>cellExtraction = '';
cellExtraction += s; // <- where s should be an empty string read from file
</code>```

答: The expression Number("") returns 0, which is a number. Since the s !== '' test is obviously returning true, it must be the case that s contains one or more space characters. Those also are turned into 0 by the Number() function; that is, Number(" ") is also 0.

Title: Empty string check evaluates wrong

Body:
I have a condition checking for empty strings and it is not evaluating an empty string as expected.

I read string one char at a time:

isNumber(s: string) {
  console.log('char', s);
  if (s !== '' && !isNaN(Number(s))) {
    console.log('is a number');
    console.log('-------------');
    return true;
  }
  console.log('NOT a number');
  console.log('-------------');
}

The string is read from a csv file:

a,b,
c,d,e

The 3rd column 1st row is empty but if evaluates to true even though I have s !== '', I have confirmed the char is empty with console. Why is the empty string condition not working?

Update:
Could this cause a non empty string? I initialise the variable with quotes then append to it.

cellExtraction = '';
cellExtraction += s; // <- where s should be an empty string read from file


问:
Updating/refreshing google sheets cells every minute automatically
I'm  trying to write a test script to make Google sheets update its cells automatically every minute. It's important I get this test script to work, so I can use it to do other things.

I have a google apps script function as follows:

```<code> function custom_function(id){
  return new Date().toLocaleTimeString();;
}
</code>```

Basically this correctly returns the current time, and the id parameter isn't used. If I use this function in a cell, i.e. =custom_function(B4) then it correctly computes the current time and displays it in the cell. So far so good.

But the cell doesn't update by itself. I'm trying to make it so this cell's value, i.e. the current time, is automatically updated every minute without any interaction by the person viewing the spreadsheet.

I've tried installing a trigger that calls the following function every  minute:

```<code>function private_function(){
        SpreadsheetApp.flush();
}
</code>```

My trigger does call this function every minute, but the flush does not seem to do anything. I was under the impression that flush would cause all the cell entries to be recomputed, thereby updating the values of every cell by calling the custom function again in every cell. It doesn't do what I want. Is there a simple way to do what I'm trying to do without bringing in dummy time-based parameters into all my functions?

答:
Try something like this

```<code>function updateStampInSheet(e) {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
    var stamp = new Date();
    sheet.getRange(1,1).setValue(stamp);
}
</code>```

You'll need to configure time-driven trigger to execute this every minute

Body:
I'm  trying to write a test script to make Google sheets update its cells automatically every minute. It's important I get this test script to work, so I can use it to do other things.

I have a google apps script function as follows:

 function custom_function(id){
  return new Date().toLocaleTimeString();;
}

Basically this correctly returns the current time, and the id parameter isn't used. If I use this function in a cell, i.e. =custom_function(B4) then it correctly computes the current time and displays it in the cell. So far so good.

But the cell doesn't update by itself. I'm trying to make it so this cell's value, i.e. the current time, is automatically updated every minute without any interaction by the person viewing the spreadsheet.

I've tried installing a trigger that calls the following function every  minute:

function private_function(){
        SpreadsheetApp.flush();
}

My trigger does call this function every minute, but the flush does not seem to do anything. I was under the impression that flush would cause all the cell entries to be recomputed, thereby updating the values of every cell by calling the custom function again in every cell. It doesn't do what I want. Is there a simple way to do what I'm trying to do without bringing in dummy time-based parameters into all my functions?

Body:
Try something like this

function updateStampInSheet(e) {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
    var stamp = new Date();
    sheet.getRange(1,1).setValue(stamp);
}

You'll need to configure time-driven trigger to execute this every minute


问:
jQuery Passing $(this) to a Function
I have lines of code like this:

```<code>$(this).parent().parent().children().each(function(){
    // do something
});
</code>```

It works well. But I need to run these lines multiple times.
So I have created a function and pass $(this) parameter to a function:

```<code>myFunc( $(this) );

function myFunc(thisObj) {
    thisObj.parent().parent().children().each(function(){
        // do something
    });
}
</code>```

But in this way, It didn't work.

答:
You can pass the id to the function.  With your loop inside the function.

```<code>myFunc(this.id);

function myFunc(thisid) {
    $("#" + thisid).parent().parent().children().each(function(){
        // do something
    });
}
</code>```

I would normally do the loop outside the function like below:

```<code>$(this).parent().parent().children().each(function(){
    myFunc(this.id)
});

function myFunc(thisid) {

    // do something example
   $("#" + thisid).html("Yay, i changed the html for element: " + thisid);
}
</code>```

Title: jQuery Passing $(this) to a Function

Body:
I have lines of code like this:

$(this).parent().parent().children().each(function(){
    // do something
});

It works well. But I need to run these lines multiple times.
So I have created a function and pass $(this) parameter to a function:

myFunc( $(this) );

function myFunc(thisObj) {
    thisObj.parent().parent().children().each(function(){
        // do something
    });
}

But in this way, It didn't work.

Body:
You can pass the id to the function.  With your loop inside the function.

myFunc(this.id);

function myFunc(thisid) {
    $("#" + thisid).parent().parent().children().each(function(){
        // do something
    });
}

I would normally do the loop outside the function like below:

$(this).parent().parent().children().each(function(){
    myFunc(this.id)
});

function myFunc(thisid) {

    // do something example
   $("#" + thisid).html("Yay, i changed the html for element: " + thisid);
}


问:
i need make use of environment inside main class annotated with @springbootapplication
I tried using autowired of environement variable in main method of spring bootapplication and am trying to get value from application.properties and assign it to astring variable in the main method class. when i print and check the environment object , it prints null and ends up with nullpointer exception </p>

```<code>public class App
{
    @Autowired
    private Environment env;

    public String getData(){
        System.out.println(env);
        System.out.println(env.getProperty("app.name"));
        return env.getProperty("app.name");
    }
    private  String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public static void main( String[] args )
    {

        System.out.println("name is "+new App().getData());
        SpringApplication.run(App.class, args);

    }
}
***in application.properties***

    app.name=aravind
    app.city=mumbai~

    Am getting null pointerexception if i call getProperty method, also env object is printing null
</code>```

答:
You are Autowiring inside Main class. I don't think that will work for you.

for more details see this [https://stackoverflow.com/questions/30059266/spring-autowire-inside-of-springbootapplication-class-is-behaving-differently-be ]

what you can do is create other class then mark it as @Component then retrieve Environment data.

Example

```<code>@Component
public class TestClass{
    @Autowired
    private Environment env;

    @Autowired
    TestClass(Environment env) { //this is constructor
        System.out.println("App Name: "+getData());
    }

    public String getData(){
        System.out.println(env);
        System.out.println(env.getProperty("app.name"));
        return env.getProperty("app.name");
    }
}
</code>```

also add @ComponentScan("yourpackagename") after @SpringBootApplication in Main class

Body:
I tried using autowired of environement variable in main method of spring bootapplication and am trying to get value from application.properties and assign it to astring variable in the main method class. when i print and check the environment object , it prints null and ends up with nullpointer exception

public class App
{
    @Autowired
    private Environment env;

    public String getData(){
        System.out.println(env);
        System.out.println(env.getProperty("app.name"));
        return env.getProperty("app.name");
    }
    private  String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public static void main( String[] args )
    {

        System.out.println("name is "+new App().getData());
        SpringApplication.run(App.class, args);

    }
}
***in application.properties***

    app.name=aravind
    app.city=mumbai~

    Am getting null pointerexception if i call getProperty method, also env object is printing null

Body:
You are Autowiring inside Main class. I don't think that will work for you.

for more details see this [https://stackoverflow.com/questions/30059266/spring-autowire-inside-of-springbootapplication-class-is-behaving-differently-be ]

what you can do is create other class then mark it as @Component then retrieve Environment data.

Example

@Component
public class TestClass{
    @Autowired
    private Environment env;

    @Autowired
    TestClass(Environment env) { //this is constructor
        System.out.println("App Name: "+getData());
    }

    public String getData(){
        System.out.println(env);
        System.out.println(env.getProperty("app.name"));
        return env.getProperty("app.name");
    }
}

also add @ComponentScan("yourpackagename") after @SpringBootApplication in Main class


问:
Combining columns from 2 pivot tables in order to make a chart
I am trying to combine 2 columns from a pivot table with 2 other columns from another pivot table so i can make a pivot chart. I have no clue how it is done. I can make a pivot chart for a single pivot table, but what should i do in this case?</p>

答:
You will most likely need to copy and paste the PivotTable data as values elsewhere.

Once you generate a PivotChart, or even when you insert a generic chart and select values in the pivot table as the data source, the chart permanently becomes linked to the PivotTable, and only the PivotTable. In the Select Data Source dialog, the chart data range becomes frozen as does the Series and Category, because it's now determined by how your PivotTable is arranged.

When your data is not in a pivot table, you will have much more control over the chart. You can include columns and rows from anywhere, in any combination, and control that from the ribbon: Chart Tools > Design > Select Data. Turning that range into a table (Ctrl+T) will give you a few more features and better control over the range than plain cells.


答:
If you 'add' groups you can get group 1 that contain only letters</p>

```<code>\d([a-zA-Z]+)
</code>```

Title: RegEx ignore letters until digit occurs and then match letters afterwards

Body:
If you 'add' groups you can get group 1 that contain only letters

\d([a-zA-Z]+)


问:
refactoring a class to be more efficient
i'm trying to refactor a class that i guess has several memory and runtime inefficiencies and bugs.
can you help me with that or remark my assumptions?

(for example

1.
i understand that the tostring method can use stringBuilder instead of strings concatinations...

2.also i guess it's better to use hashtable instead of list in order to getch the results from m_strings in o(1) instead of o(n) (in remove_string_method)

can you help me in approving it more??
i'm also not sure regarding those casting...
thanks

```<code>public class SomeClass
{
  private Date m_time;
  private String m_name;
  private List<Long> m_numbers;
  private List<String> m_strings;

  public MyClass(Date time, String name, List<Long> numbers, List<String> strings) {
        m_time = time; m_name = name; m_numbers = numbers; m_strings = strings;
  }

  public boolean equals(Object obj) {
     if (obj instanceof MyClass) {
        return m_name.equals(((MyClass)obj).m_name);
     }
     return false;
  }

public String toString() {
   String out = m_name;
   for (long item : m_numbers) {
      out += " " + item;
   }
   return out;
}

public void removeString(String str) {
    for (int i = 0; i < m_strings.size(); i++) {
      if (m_strings.get(i).equals(str)) {
        m_strings.remove(i);
      }
   }
}

public boolean containsNumber(long number) {
    for (long num : m_numbers) {
     if (num == number) {
       return true;
     }
    }
return false;
}

public boolean isHistoric() {
    return m_time.before(new Date());
}
}
</code>```

答:
I agree with GhostCat that you shouldn’t prepend m_ to your member variables.

But more important, you should stop reinventing the wheel.

Consider

```<code>public boolean containsNumber(long number) {
    return numbers.contains(number);
}
</code>```

Then, with

```<code>public void removeString(String str) {
    for(int i = 0; i < strings.size(); i++) {
      if(strings.get(i).equals(str)) {
        strings.remove(i);
      }
   }
}
</code>```

there’s the problem that when you remove an element at index i, the subsequent indices shift by one, so you’d miss an occurrence following the just removed one. On the other hand, if you are thinking about using a HashSet instead, you might not want to support duplicate elements, in which case you can stop after the first occurrence. You get all for free when not implementing it yourself.

```<code>public void removeString(String str) {
    strings.remove(str);
}
</code>```

will remove the first element (or only element if you don’t support duplicates)

```<code>public void removeString(String str) {
    strings.removeAll(Collections.singleton(str));
}
</code>```

will remove all occurrences of str correctly.

Whether replacing a List with a Set, like HashSet, is possible depends on how you intend to use the data, as these collection types have different semantics. Since you are not using the data at all in the shown code, we can’t say anything in that regard.

When you implement an equals method, you should also have a consistent hashCode method

```<code>@Override
public int hashCode() {
    return 1+name.hashCode();
}

@Override
public boolean equals(Object obj) {
    return obj instanceof SomeClass && name.equals(((SomeClass)obj).name);
}
</code>```

Body:
i'm trying to refactor a class that i guess has several memory and runtime inefficiencies and bugs.
can you help me with that or remark my assumptions?

(for example

1.
i understand that the tostring method can use stringBuilder instead of strings concatinations...

2.also i guess it's better to use hashtable instead of list in order to getch the results from m_strings in o(1) instead of o(n) (in remove_string_method)

can you help me in approving it more??
i'm also not sure regarding those casting...
thanks

public class SomeClass
{
  private Date m_time;
  private String m_name;
  private List<Long> m_numbers;
  private List<String> m_strings;

  public MyClass(Date time, String name, List<Long> numbers, List<String> strings) {
        m_time = time; m_name = name; m_numbers = numbers; m_strings = strings;
  }

  public boolean equals(Object obj) {
     if (obj instanceof MyClass) {
        return m_name.equals(((MyClass)obj).m_name);
     }
     return false;
  }

public String toString() {
   String out = m_name;
   for (long item : m_numbers) {
      out += " " + item;
   }
   return out;
}

public void removeString(String str) {
    for (int i = 0; i < m_strings.size(); i++) {
      if (m_strings.get(i).equals(str)) {
        m_strings.remove(i);
      }
   }
}

public boolean containsNumber(long number) {
    for (long num : m_numbers) {
     if (num == number) {
       return true;
     }
    }
return false;
}

public boolean isHistoric() {
    return m_time.before(new Date());
}
}

Body:
I agree with GhostCat that you shouldn’t prepend m_ to your member variables.

But more important, you should stop reinventing the wheel.

Consider

public boolean containsNumber(long number) {
    return numbers.contains(number);
}

Then, with

public void removeString(String str) {
    for(int i = 0; i < strings.size(); i++) {
      if(strings.get(i).equals(str)) {
        strings.remove(i);
      }
   }
}

there’s the problem that when you remove an element at index i, the subsequent indices shift by one, so you’d miss an occurrence following the just removed one. On the other hand, if you are thinking about using a HashSet instead, you might not want to support duplicate elements, in which case you can stop after the first occurrence. You get all for free when not implementing it yourself.

public void removeString(String str) {
    strings.remove(str);
}

will remove the first element (or only element if you don’t support duplicates)

public void removeString(String str) {
    strings.removeAll(Collections.singleton(str));
}

will remove all occurrences of str correctly.

Whether replacing a List with a Set, like HashSet, is possible depends on how you intend to use the data, as these collection types have different semantics. Since you are not using the data at all in the shown code, we can’t say anything in that regard.

When you implement an equals method, you should also have a consistent hashCode method

@Override
public int hashCode() {
    return 1+name.hashCode();
}

@Override
public boolean equals(Object obj) {
    return obj instanceof SomeClass && name.equals(((SomeClass)obj).name);
}


问:
Compare the columns of a dataframe in reverse order and create a new column with the index of the column which has value 0
I have imported data from a csv file into my program and then used set_index to set 'rule_id' as index. I used this code:

```<code>df = pd.read_excel('stack.xlsx')
df.set_index(['rule_id'])
</code>```

and the data looks like this:

Now I want to compare one column with another but in reverse order , for eg; I want to compare 'c' data with 'b' , then compare 'b' with 'a' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.
The result should look like this:

I am not able to write the code of how should I approach this problem, if you guys could help me , that would be great.

Edit: A minor edit. I have imported the data from an excel which looks like this , this is just a part of data , there are multiple columns:

Then I used pivot_table to manipulate the data as per my requirement using this code:

```<code>df = df.pivot_table(index = 'rule_id' , columns = ['date'], values = 'rid_fc', fill_value = 0)
</code>```

and my data looks like this now:

Now I want to compare one column with another but in reverse order , for eg; I want to compare '2019-04-25 16:36:32' data with '2019-04-25 16:29:05' , then compare '2019-04-25 16:29:05' with '2019-04-25 16:14:14' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.

答:
I suggest use numpy - compare shifted values with logical_and and set new columns by range created by np.arange with swap order and numpy.where with DatFrame constructor:

```<code>df = pd.DataFrame({
         'a':[0,0,0],
         'b':[7,0,2],
         'c':[6,1,2],
})

#change order of array
x = df.values[:, ::-1]
#compare for equal 0 and and not equal 0
a = np.logical_and(x[:, 1:] == 0, x[:, :-1] != 0)
#create range from top to 0
b = np.arange(a.shape[1]-1, -1, -1)
#new columns names
c = [f'comp{i+1}' for i in range(x.shape[1] - 1)]
#set values by boolean array a and set values
df1 = pd.DataFrame(np.where(a,  b[None, :], np.nan), columns=c, index=df.index)
print (df1)

   comp1  comp2
0    NaN    0.0
1    1.0    NaN
2    NaN    0.0
</code>```

Body:
I have imported data from a csv file into my program and then used set_index to set 'rule_id' as index. I used this code:

df = pd.read_excel('stack.xlsx')
df.set_index(['rule_id'])

and the data looks like this:

Now I want to compare one column with another but in reverse order , for eg; I want to compare 'c' data with 'b' , then compare 'b' with 'a' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.
The result should look like this:

I am not able to write the code of how should I approach this problem, if you guys could help me , that would be great.

Edit: A minor edit. I have imported the data from an excel which looks like this , this is just a part of data , there are multiple columns:

Then I used pivot_table to manipulate the data as per my requirement using this code:

df = df.pivot_table(index = 'rule_id' , columns = ['date'], values = 'rid_fc', fill_value = 0)

and my data looks like this now:

Now I want to compare one column with another but in reverse order , for eg; I want to compare '2019-04-25 16:36:32' data with '2019-04-25 16:29:05' , then compare '2019-04-25 16:29:05' with '2019-04-25 16:14:14' and so on and create another column after the comparison which contains the index of the column where the value was zero. If both the columns have value 0 , then Null should be updated in the new column and if both the comparison values are other than 0 , then also Null should be updated in the new column.

Body:
I suggest use numpy - compare shifted values with logical_and and set new columns by range created by np.arange with swap order and numpy.where with DatFrame constructor:

df = pd.DataFrame({
         'a':[0,0,0],
         'b':[7,0,2],
         'c':[6,1,2],
})

#change order of array
x = df.values[:, ::-1]
#compare for equal 0 and and not equal 0
a = np.logical_and(x[:, 1:] == 0, x[:, :-1] != 0)
#create range from top to 0
b = np.arange(a.shape[1]-1, -1, -1)
#new columns names
c = [f'comp{i+1}' for i in range(x.shape[1] - 1)]
#set values by boolean array a and set values
df1 = pd.DataFrame(np.where(a,  b[None, :], np.nan), columns=c, index=df.index)
print (df1)

   comp1  comp2
0    NaN    0.0
1    1.0    NaN
2    NaN    0.0


问:
Py_RunString Returns Only None Object
I'm using Python 3.4.3 embded in my c++ project, When I Call Py_RunString it always returns None object.
here is my code

```<code>#include <Python.h>
#include <string>
int main(){
    //Initialize the python interpreter
    Py_Initialize();
    //create new dictionary containing both global and local definitions
    PyObject *globals = PyDict_New();
    PyObject *locals = PyDict_New();

    //Set the build in definitions to the global dictionary: eg:len, str ,.. funtions
    PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
    //evaluate some python code and get the result, here is my issue, always None
    PyObject *string_result = PyRun_StringFlags(
        "1 + 1" /*or what ever python code*/
        ,
        Py_file_input, globals, locals, NULL);
    //check whether the python code caused any Exception and print it
    if (PyErr_Occurred()) {
        PyErr_Print(); PyErr_Clear(); return 1;
    }
    else {
    //if no Exceptions then try To Get string represiation of the python object, But it always None
        auto str = PyToStr(string_result);
        printf("python result is %s",str);
    }
    return 0;
}
</code>```

and here is my Function that convert any python object to c++ std::wstring

```<code>std::wstring PyToStr(PyObject*  Object)
{
    //it is equivalent to python code : str(Object)
    PyObject* objectsRepresentation = PyObject_Str(Object);
    //convert Python String Object to C++ wchar_t*
    const wchar_t* ws = PyUnicode_AsUnicode(objectsRepresentation);

    if (ws)
        return ws;
    //if ws is NULL it could not be converted implicitly to std::wstring
    return L"";
}
</code>```

答: If you just want to evaluate a single line you can use Py_eval_input instead of Py_file_input. It should then return the evaluated value.</p>

Title: Py_RunString Returns Only None Object

Body:
I'm using Python 3.4.3 embded in my c++ project, When I Call Py_RunString it always returns None object.
here is my code

#include <Python.h>
#include <string>
int main(){
    //Initialize the python interpreter
    Py_Initialize();
    //create new dictionary containing both global and local definitions
    PyObject *globals = PyDict_New();
    PyObject *locals = PyDict_New();

    //Set the build in definitions to the global dictionary: eg:len, str ,.. funtions
    PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
    //evaluate some python code and get the result, here is my issue, always None
    PyObject *string_result = PyRun_StringFlags(
        "1 + 1" /*or what ever python code*/
        ,
        Py_file_input, globals, locals, NULL);
    //check whether the python code caused any Exception and print it
    if (PyErr_Occurred()) {
        PyErr_Print(); PyErr_Clear(); return 1;
    }
    else {
    //if no Exceptions then try To Get string represiation of the python object, But it always None
        auto str = PyToStr(string_result);
        printf("python result is %s",str);
    }
    return 0;
}

and here is my Function that convert any python object to c++ std::wstring

std::wstring PyToStr(PyObject*  Object)
{
    //it is equivalent to python code : str(Object)
    PyObject* objectsRepresentation = PyObject_Str(Object);
    //convert Python String Object to C++ wchar_t*
    const wchar_t* ws = PyUnicode_AsUnicode(objectsRepresentation);

    if (ws)
        return ws;
    //if ws is NULL it could not be converted implicitly to std::wstring
    return L"";
}


问:
pip3 install PyYAML failed.(python3.7, macOS High Sierra)
Today I've upgraded python3.7 with brew upgrade command.

And I've tried to install PyYAML package with pip3.

I've got this error and have no idea..

```
% pip3 install PyYAML

    checking if libyaml is linkable
    clang build/temp.macosx-10.13-x86_64-3.7/check_libyaml.o -L/usr/local/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/sqlite/lib -lyaml -o build/temp.macosx-10.13-x86_64-3.7/check_libyaml
    building '_yaml' extension
    creating build/temp.macosx-10.13-x86_64-3.7/ext
    clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c ext/_yaml.c -o build/temp.macosx-10.13-x86_64-3.7/ext/_yaml.o
    In file included from ext/_yaml.c:271:
    ext/_yaml.h:10:9: warning: 'PyString_CheckExact' macro redefined [-Wmacro-redefined]
    #define PyString_CheckExact PyBytes_CheckExact
            ^
    ext/_yaml.c:139:11: note: previous definition is here
      #define PyString_CheckExact          PyUnicode_CheckExact
              ^
    ext/_yaml.c:1410:17: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
      __pyx_v_value = yaml_get_version_string();
                    ^ ~~~~~~~~~~~~~~~~~~~~~~~~~
    ext/_yaml.c:2577:52: warning: incompatible pointer types passing 'int (void *, char *, size_t, size_t *)' (aka 'int (void *, char *, unsigned long, unsigned long *)') to parameter of type 'yaml_read_handler_t *' (aka 'int (*)(void *, unsigned char *, unsigned long, unsigned long *)') [-Wincompatible-pointer-types]
        yaml_parser_set_input((&__pyx_v_self->parser), __pyx_f_5_yaml_input_handler, ((void *)__pyx_v_self));
                                                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /usr/local/include/yaml.h:1370:30: note: passing argument to parameter 'handler' here

.......

```

And finally

```    /usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/include/python3.7m/pystate.h:238:15: note: 'curexc_traceback' declared here
        PyObject *curexc_traceback;
                  ^
    51 warnings and 15 errors generated.
    error: command 'clang' failed with exit status 1

    ----------------------------------------
Command "/usr/local/opt/python/bin/python3.7 -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-install-exbgmayz/PyYAML/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/tmp/pip-record-n11vy5s0/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-install-exbgmayz/PyYAML/
```

I've tried solve this problem, but still have no idea.

https://github.com/yaml/pyyaml/issues/126

How do I install the yaml package for Python?

How can I resolve this issue..?

答:
yaml didnt work with python 3.7

Fix: downgrade to python2 and install yaml

brew install python@2.

brew install libyaml

sudo python -m easy_install pyyaml.

Body:
Today I've upgraded python3.7 with brew upgrade command.

And I've tried to install PyYAML package with pip3.

I've got this error and have no idea..

% pip3 install PyYAML

    checking if libyaml is linkable
    clang build/temp.macosx-10.13-x86_64-3.7/check_libyaml.o -L/usr/local/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/sqlite/lib -lyaml -o build/temp.macosx-10.13-x86_64-3.7/check_libyaml
    building '_yaml' extension
    creating build/temp.macosx-10.13-x86_64-3.7/ext
    clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/include/python3.7m -c ext/_yaml.c -o build/temp.macosx-10.13-x86_64-3.7/ext/_yaml.o
    In file included from ext/_yaml.c:271:
    ext/_yaml.h:10:9: warning: 'PyString_CheckExact' macro redefined [-Wmacro-redefined]
    #define PyString_CheckExact PyBytes_CheckExact
            ^
    ext/_yaml.c:139:11: note: previous definition is here
      #define PyString_CheckExact          PyUnicode_CheckExact
              ^
    ext/_yaml.c:1410:17: warning: assigning to 'char *' from 'const char *' discards qualifiers [-Wincompatible-pointer-types-discards-qualifiers]
      __pyx_v_value = yaml_get_version_string();
                    ^ ~~~~~~~~~~~~~~~~~~~~~~~~~
    ext/_yaml.c:2577:52: warning: incompatible pointer types passing 'int (void *, char *, size_t, size_t *)' (aka 'int (void *, char *, unsigned long, unsigned long *)') to parameter of type 'yaml_read_handler_t *' (aka 'int (*)(void *, unsigned char *, unsigned long, unsigned long *)') [-Wincompatible-pointer-types]
        yaml_parser_set_input((&__pyx_v_self->parser), __pyx_f_5_yaml_input_handler, ((void *)__pyx_v_self));
                                                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
    /usr/local/include/yaml.h:1370:30: note: passing argument to parameter 'handler' here

.......

And finally

    /usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/include/python3.7m/pystate.h:238:15: note: 'curexc_traceback' declared here
        PyObject *curexc_traceback;
                  ^
    51 warnings and 15 errors generated.
    error: command 'clang' failed with exit status 1

    ----------------------------------------
Command "/usr/local/opt/python/bin/python3.7 -u -c "import setuptools, tokenize;__file__='/private/tmp/pip-install-exbgmayz/PyYAML/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /private/tmp/pip-record-n11vy5s0/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/tmp/pip-install-exbgmayz/PyYAML/

I've tried solve this problem, but still have no idea.

https://github.com/yaml/pyyaml/issues/126

How do I install the yaml package for Python?

How can I resolve this issue..?


问:
How to find the leftmost bit of an number in one line
How to find out the leftmost bit and rightmost bit of an number in one line of code ?

Well we can traverse an loop to find out the leftmost set bit by leftshift but how to do it in one line to make an another no. whose leftmost bit / rightmost bit is set ?
Like y = x & ~(x-1) will find leftmost bit but I didn't get this how ?

Can someone give the code for that in C++ and explain ?

答:
For the rightmost bit, there is a well-known trick.

```<code>x=x & -x
</code>```

will clear all set bits in x, except the rightmost one. You will find many explanations why this works in SO (see for instance this answer)

To find its index, except by using builtins of programming languages, there is no way but doing a loop AFAIK. Note that this loop can be unrolled to have a one liner.

```<code>pos = (16*(x&0xffff0000)!=0) + (8*(x&0xff00ff00)!=0) + (4&(x&0xf0f0f0f0)!=0) + (2*(x&0x66666666)!=0)+(x&0xaaaaaaaa)!=0)
</code>```

x is the result of the previous operation (ie only the rightmost bit is set) and it works by testing is this bit is in the upper half word in which case the position will be > 16, then an even byte, even nibble, and so on.

Another solution, is to use the mathematic operator log2

```<code>pos=(int)log2((double)x)
</code>```

For the left most bit, AFAIK, there are no way to do that at the bit level, except through loops. But it is possible to use log2() to find the position of the leftmost bit.

Then, to return an int with only this bit set, one can use right shifts.

```<code>x = 1 << ((int) log2((double)x))
</code>```

This will keep only the left most bit in x.

Beware to previously check if x in non null.

Body:
For the rightmost bit, there is a well-known trick.

x=x & -x

will clear all set bits in x, except the rightmost one. You will find many explanations why this works in SO (see for instance this answer)

To find its index, except by using builtins of programming languages, there is no way but doing a loop AFAIK. Note that this loop can be unrolled to have a one liner.

pos = (16*(x&0xffff0000)!=0) + (8*(x&0xff00ff00)!=0) + (4&(x&0xf0f0f0f0)!=0) + (2*(x&0x66666666)!=0)+(x&0xaaaaaaaa)!=0)

x is the result of the previous operation (ie only the rightmost bit is set) and it works by testing is this bit is in the upper half word in which case the position will be > 16, then an even byte, even nibble, and so on.

Another solution, is to use the mathematic operator log2

pos=(int)log2((double)x)

For the left most bit, AFAIK, there are no way to do that at the bit level, except through loops. But it is possible to use log2() to find the position of the leftmost bit.

Then, to return an int with only this bit set, one can use right shifts.

x = 1 << ((int) log2((double)x))

This will keep only the left most bit in x.

Beware to previously check if x in non null.


问:
What is the most efficient way to convert list of structs to dictionary?
I have a struct that consists of multiple type elements as follows:

public struct mystruct
{
        int key;
        string value;
}
```

<p>What is the most efficient way to convert list of this struct to a dictionary that its keys are <code>mystruct.key</code> and values are list of <code>mystruct.value</code>?</p>

<p>i implement it as follows</p>

<pre class="lang-cs prettyprint-override"><code>Dictionary<int, List<string>> mydictionary = new Dictionary<int, List<string>>();
foreach (var item in mystruct_list)
            {
                if (!mydictionary.ContainsKey(item.key))
                    mydictionary.Add(item.key, new List<string>());
                mydictionary[item.key].Add(item.value);
            }
</code>```

答:
If you relax the requirement to have a IEnumerable<string> instead of a IList<string> as the values, the lookup is the thing you are looking for (internally it is materialized, so no worries about enumerating multiple times).

```<code>IEnumerable<mystruct> source = // ...

var lookup = x.ToLookup(c => c.key, c => c.value);
foreach (var g in lookup)
    Console.WriteLine($"Key: {g.Key}, Values: {string.Join(", ", g)}");
</code>```

The nice thing about lookups is that they support, well, lookup

```<code>var group3 = lookup[3];
</code>```

, and that this will give you an empty sequence when accessed with a non-existent key, instead of throwing a KeyNotFoundException at you.

Body:
I have a struct that consists of multiple type elements as follows:

public struct mystruct
{
        int key;
        string value;
}

What is the most efficient way to convert list of this struct to a dictionary that its keys are mystruct.key and values are list of mystruct.value?

i implement it as follows

Dictionary<int, List<string>> mydictionary = new Dictionary<int, List<string>>();
foreach (var item in mystruct_list)
            {
                if (!mydictionary.ContainsKey(item.key))
                    mydictionary.Add(item.key, new List<string>());
                mydictionary[item.key].Add(item.value);
            }

Body:
If you relax the requirement to have a IEnumerable<string> instead of a IList<string> as the values, the lookup is the thing you are looking for (internally it is materialized, so no worries about enumerating multiple times).

IEnumerable<mystruct> source = // ...

var lookup = x.ToLookup(c => c.key, c => c.value);
foreach (var g in lookup)
    Console.WriteLine($"Key: {g.Key}, Values: {string.Join(", ", g)}");

The nice thing about lookups is that they support, well, lookup

var group3 = lookup[3];

, and that this will give you an empty sequence when accessed with a non-existent key, instead of throwing a KeyNotFoundException at you.


问:
Subclass method signature inference
I have the following abstract class

```<code>// AbstractFiller.ts
export abstract class AbstractFiller {
   public abstract fill(data: number | string | boolean | Date, numberOfFillers: number): string;
}
</code>```

and several filler subclasses

```<code>export class WhiteSpacesFiller extends AbstractFiller {
  public fill(data: number | string | boolean | Date, numberOfFillers: number): string {
    // logic
  }
}

export class ZerosFiller extends AbstractFiller {
  public fill(data: number | string | boolean | Date,  numberOfFillers: number): string {
    // logic
  }
}

// ...etc
</code>```

Is there a way that TS would infer the method signature from the abstract class so that I have:

No type duplication in every subclass

Strict signature enforcing e.g. removing number from the type of data in a subclass will not throw an error.

答:
Typescript will not infer method parameters from base class. The way it works is that after the class is typed, the class is checked for compatibility with the base class. This mean that a parameter in a derived class can be of a derived type (this is not sound but class method parameters relate bivariantly even under strict null checks).

One thing that can be done to reduce the amount of type duplication is to use Parameters with rest parameter destructuring.

```<code>export abstract class AbstractFiller {
    public abstract fill(data: number | string | boolean | Date, numberOfFillers: number): string;
}

export class WhiteSpacesFiller extends AbstractFiller {
    public fill(...[data, numberOfFillers]: Parameters<AbstractFiller['fill']>): string {
        return ""
    }
}
</code>```

Title: Subclass method signature inference

Body:
I have the following abstract class

// AbstractFiller.ts
export abstract class AbstractFiller {
   public abstract fill(data: number | string | boolean | Date, numberOfFillers: number): string;
}

and several filler subclasses

export class WhiteSpacesFiller extends AbstractFiller {
  public fill(data: number | string | boolean | Date, numberOfFillers: number): string {
    // logic
  }
}

export class ZerosFiller extends AbstractFiller {
  public fill(data: number | string | boolean | Date,  numberOfFillers: number): string {
    // logic
  }
}

// ...etc

Is there a way that TS would infer the method signature from the abstract class so that I have:

No type duplication in every subclass

Strict signature enforcing e.g. removing number from the type of data in a subclass will not throw an error.

Body:
Typescript will not infer method parameters from base class. The way it works is that after the class is typed, the class is checked for compatibility with the base class. This mean that a parameter in a derived class can be of a derived type (this is not sound but class method parameters relate bivariantly even under strict null checks).

One thing that can be done to reduce the amount of type duplication is to use Parameters with rest parameter destructuring.

export abstract class AbstractFiller {
    public abstract fill(data: number | string | boolean | Date, numberOfFillers: number): string;
}

export class WhiteSpacesFiller extends AbstractFiller {
    public fill(...[data, numberOfFillers]: Parameters<AbstractFiller['fill']>): string {
        return ""
    }
}


答:
Excuse me if I misunderstand the question, but I think you can solve your problem with generics i.e. have your AbstractFiller class be generic.

That would look something like this:

```<code>export abstract class AbstractFiller<T> {
    public abstract fill(data: T, numberOfFillers: number): string;
}

export class WhiteSpacesFiller extends AbstractFiller<string> {
    public fill(data: string, numberOfFillers: number) {
        //logic
        return data;
    }
}

export class ZerosFiller extends AbstractFiller<number> {
    public fill(data: number, numberOfFillers: number) {
        return data.toString();
    }
}
</code>```

Title: Subclass method signature inference

Body:
Excuse me if I misunderstand the question, but I think you can solve your problem with generics i.e. have your AbstractFiller class be generic.

That would look something like this:

export abstract class AbstractFiller<T> {
    public abstract fill(data: T, numberOfFillers: number): string;
}

export class WhiteSpacesFiller extends AbstractFiller<string> {
    public fill(data: string, numberOfFillers: number) {
        //logic
        return data;
    }
}

export class ZerosFiller extends AbstractFiller<number> {
    public fill(data: number, numberOfFillers: number) {
        return data.toString();
    }
}


问:
Make WebStorm use alias for HTML tags in JSX
I need solution for WebStorm (WS); setup webpack aliases works for html attributes like src; that's my webpack.config.js for example:

```<code>const path = require('path');

module.exports = {
    resolve: {
        extensions: ['scss', 'html', 'jsx'],
        root: path.resolve(__dirname),
        alias: {
            components: path.resolve(__dirname, 'components'),
            layout: path.resolve(__dirname, 'layout'),
            static: path.resolve(__dirname, 'static'),
            js: path.resolve(__dirname, 'static/js'),
            media: path.resolve(__dirname, 'static/media'),
            sass: path.resolve(__dirname, 'static/sass'),
            vendors: path.resolve(__dirname, 'static/vendors'),
        },
    },
};
</code>```

for example look on alias settings, and I want to use it like

```<code><img src="media/logo/medium.png">
</code>```

not like

```<code><img src="static/media/logo/medium.png">
</code>```

Autocomplete for this does not work, it does not use webpack config for html attribute like src, only for import.

P.S. I already know about make folder as "resource root", but it gives autocomplete from resource directory only.

答: Webpack resolution rules only work in imports currently, path aliases in HTML/CSS are not supported. Please follow WEB-38331 for updates</p>

Body:
I need solution for WebStorm (WS); setup webpack aliases works for html attributes like src; that's my webpack.config.js for example:

const path = require('path');

module.exports = {
    resolve: {
        extensions: ['scss', 'html', 'jsx'],
        root: path.resolve(__dirname),
        alias: {
            components: path.resolve(__dirname, 'components'),
            layout: path.resolve(__dirname, 'layout'),
            static: path.resolve(__dirname, 'static'),
            js: path.resolve(__dirname, 'static/js'),
            media: path.resolve(__dirname, 'static/media'),
            sass: path.resolve(__dirname, 'static/sass'),
            vendors: path.resolve(__dirname, 'static/vendors'),
        },
    },
};

for example look on alias settings, and I want to use it like

not like

Autocomplete for this does not work, it does not use webpack config for html attribute like src, only for import.

P.S. I already know about make folder as "resource root", but it gives autocomplete from resource directory only.


问:
ASP.NET MVC: Passing items through to home page
I am currently building an application that has a to-do list function. And I am trying to pass through items to my home page through the home controller that have a due date in the next two weeks. The following code is in the HomeController.

```<code>   MembershipUser myObject = Membership.GetUser();
   Guid UserID = (Guid)myObject.ProviderUserKey;

   DateTime dateTime = new DateTime();
   dateTime = DateTime.Now;
   dateTime.AddDays(14);

   var model = db.Task.Where(n => n.UserId == UserID).Where(x => x.Due < dateTime);
   return View(model);
</code>```

The following code is in the Home Index View:

```<code>   <ul class="upcoming">
   @foreach (var item in Model)
   {
       <li>@item.Title</li>
   }
   </ul>
</code>```

However, this returns every item in the Task table in the database, even ones over 2 weeks away. How can I fix this?

Many thanks,
Dale

答:
DateTime.AddDays() returns a new DateTime object, it doesn't modify the instance. Try:

var dateTime = DateTime.Now.AddDays(14);

Body:
I am currently building an application that has a to-do list function. And I am trying to pass through items to my home page through the home controller that have a due date in the next two weeks. The following code is in the HomeController.

   MembershipUser myObject = Membership.GetUser();
   Guid UserID = (Guid)myObject.ProviderUserKey;

   DateTime dateTime = new DateTime();
   dateTime = DateTime.Now;
   dateTime.AddDays(14);

   var model = db.Task.Where(n => n.UserId == UserID).Where(x => x.Due < dateTime);
   return View(model);

The following code is in the Home Index View:

   @foreach (var item in Model)
   {

@item.Title

   }

However, this returns every item in the Task table in the database, even ones over 2 weeks away. How can I fix this?

Many thanks,
Dale


问:
How to extend my endpoint with /download/?
My code looks like this:

```<code># models.py
class Recording(models.Model):
    title = . . .
    duration = . . .

# views.py
class RecordingViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    serializer_class = RecordingSerializer
    . . .

# urls.py
router = routers.DefaultRouter()
router.register(r'recordings', RecordingViewSet, base_name='recordings')
</code>```

How can I extend my endpoint to create a /recordings/X/ endpoint? (in my case X = download)

答:
If you are using Django Rest Framework version 3.8+, you can also use @action decorator for specific endpoints and actions below viewset. For example;

```<code>from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response

# views.py
class RecordingViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    serializer_class = RecordingSerializer

    @action(detail=False, methods=["GET"])
    def download(self, request):
        # your logic here
        context = {'message': 'hi!'}
        return Response(context, status=status.HTTP_200_OK)
</code>```

and you will be able to access this endpoint as /recordings/download/.

See other usage examples and explanations from here.

Body:
My code looks like this:

# models.py
class Recording(models.Model):
    title = . . .
    duration = . . .

# views.py
class RecordingViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    serializer_class = RecordingSerializer
    . . .

# urls.py
router = routers.DefaultRouter()
router.register(r'recordings', RecordingViewSet, base_name='recordings')

How can I extend my endpoint to create a /recordings/X/ endpoint? (in my case X = download)

Body:
If you are using Django Rest Framework version 3.8+, you can also use @action decorator for specific endpoints and actions below viewset. For example;

from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response

# views.py
class RecordingViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)
    serializer_class = RecordingSerializer

    @action(detail=False, methods=["GET"])
    def download(self, request):
        # your logic here
        context = {'message': 'hi!'}
        return Response(context, status=status.HTTP_200_OK)

and you will be able to access this endpoint as /recordings/download/.

See other usage examples and explanations from here.


问:
Laravel sessions does not being stored with multiple domains
I'm using a middleware choosing the content depending on domain, but only in one of them sessions are being stored. The ideia is not share sessions between them. Each domain has to have it's sessions.

Example of problem is that CSRF tokens refresh on each reload.

I've tried set the configurations for each domain (cookie name, path, domain) and tried cookies, files and database. None of this worked.

Part of middleware code:

config([
    'session.domain' => $domain,
    'session.cookie' => $slugDomain . '_session',
    'session.path' => '/' . $slugDomain
]);
```

答:
I found the problem. Occurs that the middleware was modifying the URI, but with two bars at the end of the URI. The controllers were being executed normaly, but because of the double bars at the end of the URI sessions were not being persisted.

The new code:

//...
    $newReq = $request->duplicate();
    $newPath = '/store' . (substr($request->path(), 0, 1) === '/' ? '' : '/') . $request->path();
    $newReq->server->set('REQUEST_URI', $newPath);

    return $next($newReq);
```

<p><code>$newPath</code> before was</p>

<pre class="lang-php prettyprint-override"><code>$newPath = '/store/' . $request->path();
</code>```

Body:
I found the problem. Occurs that the middleware was modifying the URI, but with two bars at the end of the URI. The controllers were being executed normaly, but because of the double bars at the end of the URI sessions were not being persisted.

The new code:

//...
    $newReq = $request->duplicate();
    $newPath = '/store' . (substr($request->path(), 0, 1) === '/' ? '' : '/') . $request->path();
    $newReq->server->set('REQUEST_URI', $newPath);

    return $next($newReq);

$newPath before was

$newPath = '/store/' . $request->path();


答:
SQL tables represent unordered sets.  There is no ordering, unless columns specify the ordering.

If you want the first row per crop type, then in Postgres, I would recommend distinct on:

```<code>select distinct on (crop_type) t.*
from t
order by crop_type, datum;
</code>```

distinct on is Postgres extension.  It returns one row for each combination in the distinct on clause -- in this case, one per crop_type.

The row returned is the first one encountered, base don the order by clause.  The first columns in the order by should match the columns in the distinct on.  The remaining columns then define "first".

Title: how do I set up my window function properly? (PostgreSQL)

Body:
I want to get the first entry (datum, crop_type) where a specific crop is cultivated. the list I want to extract that information from is already ordered by year and month, however I have no idea, how to set up the window function properly. I think the easiest way would be to go back from each respective harvest (where yield_fm is != 0) and crop type is != 999999, but as I said, no idea how to do this.

snippet from my table:

"datum","crop_type","yield_fm"
1996-01-01,3,0
1996-02-01,3,0
1996-03-01,3,0
1996-04-01,3,0
1996-05-01,3,0
1996-06-01,3,0
1996-07-01,3,0
1996-08-01,3,9.5
1996-09-01,999999,0
1996-10-01,999999,0
1996-11-01,999999,0
1996-12-01,999999,0
1997-01-01,999999,0
1997-02-01,999999,0
1997-03-01,999999,0
1997-04-01,16,0
1997-05-01,16,0
1997-06-01,16,0
1997-07-01,16,0
1997-08-01,16,0
1997-09-01,16,53.7
1997-10-01,999999,0
1997-11-01,3,0
1997-12-01,3,0
1998-01-01,3,0
1998-02-01,3,0
1998-03-01,3,0
1998-04-01,3,0
1998-05-01,3,0
1998-06-01,3,0
1998-07-01,3,0
1998-08-01,3,8
1998-09-01,999999,0
1998-10-01,3,0
1998-11-01,3,0
1998-12-01,3,0
1999-01-01,3,0
1999-02-01,3,0
1999-03-01,3,0
1999-04-01,3,0
1999-05-01,3,0
1999-06-01,3,0
1999-07-01,3,0
1999-08-01,3,8

Body:
SQL tables represent unordered sets.  There is no ordering, unless columns specify the ordering.

If you want the first row per crop type, then in Postgres, I would recommend distinct on:

select distinct on (crop_type) t.*
from t
order by crop_type, datum;

distinct on is Postgres extension.  It returns one row for each combination in the distinct on clause -- in this case, one per crop_type.

The row returned is the first one encountered, base don the order by clause.  The first columns in the order by should match the columns in the distinct on.  The remaining columns then define "first".


问:
How may I upload file with formData to node js with express?
I want to upload the file on the server with some data, and if I'm right, I need to pass the file and all data in formData, and parse on the server side.

I'm also using Multer for parsing body and save the file on the server, but I don't know how to take my text data from my formData, because Multer takes and read-only file without formData with my data from Form.

How I may take all data in Multer or take form data without Multer?

FrontEnd

let file = file[0];
//some file from input

let data = {
  name: 'Jhon',
  job: 'Engener',
  time: 12
}
let formData = new FormData();

formData.append('formData', JSON.stringy(data))

axios.post('someURL', formData);```
</div>
</div>
</p>

<p>backend
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const multer = require('multer');
const fs = require('fs');

let storage = multer.diskStorage({
  destanation: (req, file, callback) => {
      callback(null, '/files')
  },

  filename: (req, file, callback) => {
    callback(null, 'newFile');
  }
});

let upload = multer({storage)};

api.post('/', upload.any(), (req, res) => {

});</code>```

答:
If I understood correctly, the code should treat upload and get some posted data in the same operation. A while ago I wrote this snippet of code that works very well, maybe it helps:

```<code>exports.myPostFunction = function (req, res) {
    var multer = require('multer');

    var path = require('path');
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, process.env.UPLOAD_FOLDER);
        },
        filename: function (req, file, cb) {
            cb(null, path.extname(file.originalname));
        }
    });

    // Treat posted file
    var upload = multer({ storage: storage }).fields([
        { name: 'myImage', maxCount: 1 },
    ]);

    upload(req, res, function(err) {
        if (err) {
            // ...
        }

        // Get posted data:
        var obj = {
            myField1: req.body.myField1,
            myField2: req.body.myField2
        };

        // ...
     });
};
</code>```

In front end:

```<code>var formData = new FormData();
formData.append("myField1", data.myField1);
formData.append("myField2", data.myField2);
formData.append("myImage", data.image[0]); // myInputFile.files[0]

$.ajax({
    url: 'someURL',
    type: 'put',
    processData: false,
    data: formData,
    success: function(data) {}
});
</code>```

Body:
I want to upload the file on the server with some data, and if I'm right, I need to pass the file and all data in formData, and parse on the server side.

I'm also using Multer for parsing body and save the file on the server, but I don't know how to take my text data from my formData, because Multer takes and read-only file without formData with my data from Form.

How I may take all data in Multer or take form data without Multer?

FrontEnd

let file = file[0];
//some file from input

let data = {
  name: 'Jhon',
  job: 'Engener',
  time: 12
}
let formData = new FormData();

formData.append('formData', JSON.stringy(data))

axios.post('someURL', formData);

backend

const multer = require('multer');
const fs = require('fs');

let storage = multer.diskStorage({
  destanation: (req, file, callback) => {
      callback(null, '/files')
  },

  filename: (req, file, callback) => {
    callback(null, 'newFile');
  }
});

let upload = multer({storage)};

api.post('/', upload.any(), (req, res) => {

});

Body:
If I understood correctly, the code should treat upload and get some posted data in the same operation. A while ago I wrote this snippet of code that works very well, maybe it helps:

exports.myPostFunction = function (req, res) {
    var multer = require('multer');

    var path = require('path');
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, process.env.UPLOAD_FOLDER);
        },
        filename: function (req, file, cb) {
            cb(null, path.extname(file.originalname));
        }
    });

    // Treat posted file
    var upload = multer({ storage: storage }).fields([
        { name: 'myImage', maxCount: 1 },
    ]);

    upload(req, res, function(err) {
        if (err) {
            // ...
        }

        // Get posted data:
        var obj = {
            myField1: req.body.myField1,
            myField2: req.body.myField2
        };

        // ...
     });
};

In front end:

var formData = new FormData();
formData.append("myField1", data.myField1);
formData.append("myField2", data.myField2);
formData.append("myImage", data.image[0]); // myInputFile.files[0]

$.ajax({
    url: 'someURL',
    type: 'put',
    processData: false,
    data: formData,
    success: function(data) {}
});


问:
Jackson deserialiser affected by the Deadbolt "restrict" annotation
I receiving an exception Could not resolve type id 'path.to.MyClass' as a subtype of [simple type, class java.lang.Object]: no such class found on play 2.7 server with DeadBolt (2.6.3 and 2.7.0) when I try deserialise JSON to Map<String, MyClass> inside of route action with a @Restrict annotation. All works fine if Remove this annotation.

MyClass.java

```<code>
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "class")
public class MyClass implements Serializable {
    public String name;
    public Integer age;
    public MyClass(){}
    public MyClass(String name, Integer age){
        this.name = name;
        this.age = age;
    }
}

</code>```

serialise Map<String, MyClass>

```<code>Map<String, MyClass> value = new HashMap<>();
value.put("first", new MyClass("Bob",10));
value.put("second", new MyClass("Rob",20));

ObjectMapper mapper = Json.newDefaultMapper();
        mapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE, "class");
String json = null;
try {
    json = mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

</code>```

output

```<code>{
  "first":{
    "class":"path.to.MyClass",
    "name":"Bob",
    "age":10
  },
  "second":{
    "class":"path.to.MyClass",
    "name":"Rob",
    "age":20
  }
}
</code>```

JSON format looks so because of backward compatibility with old server which use old FlexJson.

deserialise

```<code>@Restrict({@Group({"Admin"})})
public CompletionStage<Result> action(long id) {
    String json = getJsonFromStorage();
    Map<String, MyClass> result = new HashMap<>();
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE, "class");
        JsonFactory factory = mapper.getFactory();
        JsonParser parser = factory.createParser(new ByteArrayInputStream(json.getBytes(Charset.forName("UTF-8"))));
        JavaType type = mapper.getTypeFactory().constructType(result.getClass());
        t = mapper.readValue(parser, type);
        } catch (IOException e) {
            e.printStackTrace();
        }

    return ok("ok")
}
</code>```

答:
I have a temporary solution. I override class loader for current thread to class loader from play.Environment</p>

```<code>public class MyController extends Controller {

    @Inject
    private Environment environment;

    @Restrict({@Group({"Admin"})})
    public CompletionStage<Result> action(long id) {

        Thread.currentThread().setContextClassLoader(environment.classLoader());

        String json = getJsonFromStorage();
        Map<String, MyClass> result = new HashMap<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE, "class");
            JsonFactory factory = mapper.getFactory();
            JsonParser parser = factory.createParser(new ByteArrayInputStream(json.getBytes(Charset.forName("UTF-8"))));
            JavaType type = mapper.getTypeFactory().constructType(result.getClass());
            t = mapper.readValue(parser, type);
            } catch (IOException e) {
                e.printStackTrace();
            }

        return ok("ok")
    }

}
</code>```

Body:
I receiving an exception Could not resolve type id 'path.to.MyClass' as a subtype of [simple type, class java.lang.Object]: no such class found on play 2.7 server with DeadBolt (2.6.3 and 2.7.0) when I try deserialise JSON to Map<String, MyClass> inside of route action with a @Restrict annotation. All works fine if Remove this annotation.

MyClass.java

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "class")
public class MyClass implements Serializable {
    public String name;
    public Integer age;
    public MyClass(){}
    public MyClass(String name, Integer age){
        this.name = name;
        this.age = age;
    }
}

serialise Map<String, MyClass>

Map<String, MyClass> value = new HashMap<>();
value.put("first", new MyClass("Bob",10));
value.put("second", new MyClass("Rob",20));

ObjectMapper mapper = Json.newDefaultMapper();
        mapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE, "class");
String json = null;
try {
    json = mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
    e.printStackTrace();
}

output

{
  "first":{
    "class":"path.to.MyClass",
    "name":"Bob",
    "age":10
  },
  "second":{
    "class":"path.to.MyClass",
    "name":"Rob",
    "age":20
  }
}

JSON format looks so because of backward compatibility with old server which use old FlexJson.

deserialise

@Restrict({@Group({"Admin"})})
public CompletionStage<Result> action(long id) {
    String json = getJsonFromStorage();
    Map<String, MyClass> result = new HashMap<>();
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE, "class");
        JsonFactory factory = mapper.getFactory();
        JsonParser parser = factory.createParser(new ByteArrayInputStream(json.getBytes(Charset.forName("UTF-8"))));
        JavaType type = mapper.getTypeFactory().constructType(result.getClass());
        t = mapper.readValue(parser, type);
        } catch (IOException e) {
            e.printStackTrace();
        }

    return ok("ok")
}

Body:
I have a temporary solution. I override class loader for current thread to class loader from play.Environment

public class MyController extends Controller {

    @Inject
    private Environment environment;

    @Restrict({@Group({"Admin"})})
    public CompletionStage<Result> action(long id) {

        Thread.currentThread().setContextClassLoader(environment.classLoader());

        String json = getJsonFromStorage();
        Map<String, MyClass> result = new HashMap<>();
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE, "class");
            JsonFactory factory = mapper.getFactory();
            JsonParser parser = factory.createParser(new ByteArrayInputStream(json.getBytes(Charset.forName("UTF-8"))));
            JavaType type = mapper.getTypeFactory().constructType(result.getClass());
            t = mapper.readValue(parser, type);
            } catch (IOException e) {
                e.printStackTrace();
            }

        return ok("ok")
    }

}


问:
Docker stuck on "Waiting for SSH to be available..."
I'm using a docker with Windows and Hyper-v to create containers. I've added a docker machine vmachine to my docker configuration. First time the machine is created, it gets an IP (although I cannot manage nginx to access it - ERR_CONNECTION_REFUSED) and finishes the bootup.

When I turn off the machine and then try to boot it, i get stuck in this message

Waiting for SSH to be available...

And it doesn't evolve from there. The machine is booted, however, I get an IPv6 when I input the command docker-machine ip vmachine like - fe80::215:5dff:fe21:10b insted of a IPv4

What am I doing wrong?

答: If you are using Command Promt Docker will stuck at Waiting for SSH to be available..., So change to use GIT BASH as @Dave Howson said it will work. </p>


问:
Run SQL file from SQLBrowser for Sybase
I need to execute a .sql file from my local drive in the SQLBrowser client for Sybase.

Can you suggest how this can be achieved?

答:
Its on page 30 of the manual found at http://www.sqlbrowser.com/Manual.pdf

There are images showing the menu options so easier to check the manual directly.

Title: Run SQL file from SQLBrowser for Sybase


问:
Multiplying a float by -1.0 casts the number to an int
When I have a decimal and try to make it negative, it converts the number to an integer. In the test code, $myl->point_spread is 1.5.

```<code>echo "Point spread: " . ($myl->point_spread * -1.0) . " and " . $myl->point_spread . "\n";
</code>```

Here is the output:

Point spread: -1 and 1.5

I have also tried -$myl->point_spread and 0 - $myl-point_spread to no avail.

So what gives? How can I obtain the correct value of -1.5 that I am expecting?

答: As the other helpful comments pointed out, a print_r or vardump reveals it was not a primitive float as I expected. Using floatvar( $myl->point_spread ) * -1.0 gives the expected result. Thanks all.</p>

Body:
When I have a decimal and try to make it negative, it converts the number to an integer. In the test code, $myl->point_spread is 1.5.

echo "Point spread: " . ($myl->point_spread * -1.0) . " and " . $myl->point_spread . "\n";

Here is the output:

Point spread: -1 and 1.5

I have also tried -$myl->point_spread and 0 - $myl-point_spread to no avail.

So what gives? How can I obtain the correct value of -1.5 that I am expecting?


问:
Use Play! with a graph-visualization framework that relies on Servlets
I really like Play and it adresses all the problems I had when develpoing web applications. My next project involves calculations on graphs (in this case biological networks) and visualization of large graphs. All the 'backend' stuff is done with the JUNG Graph API, which can be easily integrated in a Play project.

I used to do graph visualization in web applications with yFiles AJAX from yWorks. You will most likely know yWorks if you have ever worked with graphs in Java. yFiles AJAX is basically a JAVA/JavaScript library that offers:

a) Server components that hold the graph model. They mostly extend the extend the Java Servlet API.

b) Client side components that display the graph. This is based on Dojo, which should work in Play.

The components are discribed in detail here: yFiles AJAX dev guide

I know that Play does not use the Servlet API for many good reasons. My question is more general, because I am not that experienced with Play or other frameworks:

Can I use something like yFiles AJAX, which relies on servlets, inside a Play application? Or do I have to stick to a basic JAVA EE project with servlets/jsps?

I hope you understand my question :)

答:
I'm afraid it won't be simple (possible, yes, simple, not by far). The first issue would be to encapsulate the Play application in a Servlet environment (which would somehow defeat the purpose of using Play).

The second is that Play is Stateless (one of the reasons why Servlets were dropped), which (probably) would not go nicely with your library if it relies on state (like Session).


答:
In comments you write that $myl->point_spread is an SimpleXMLElement Object.
Try cast that value to float:

```<code>echo "Point spread: " . (((float)$myl->point_spread) * -1.0) . " and " . $myl->point_spread . "\n";
</code>```

Title: Multiplying a float by -1.0 casts the number to an int

Body:
In comments you write that $myl->point_spread is an SimpleXMLElement Object.
Try cast that value to float:

echo "Point spread: " . (((float)$myl->point_spread) * -1.0) . " and " . $myl->point_spread . "\n";


问:
How to use onclick and push state to props at one time ? i have push is undef error
```<code>changeRoutePath = (e) =>{
    e.preventDefault();
    this.props.onClose();
    this.props.history.push('/company/orgStructure');
};
<Link
                to={{
                    pathname: '/company/orgStructure',
                    state: {
                        fromNotifications: true
                    }
                }}
                onClick={(e) => this.changeRoutePath(e)}>
                Prevent
            </Link>
</code>```

I  have error Uncaught TypeError: Cannot read property 'push' of undefined

I have a import of the Link

```<code>import {Link} from "react-router-dom";
</code>```

Need to go on /company/orgStructure page and take some info in state! How to do it?

If i use just link without onclick i cant use this.props.onClose for close modal. How to push info and go to orgStructure?

bgClose: false
className: ""
container: true
employeeCode: "00-005424"
escClose: false
onClose: ƒ ()
open: true
showModalEmployeeShortProfile: ƒ ()
stack: true
template: null
title: "Профиль сотрудника"
width: 960
console.log(this.props);

答:
First of all, the error you're getting is from your changeRoutePath function. The history object isn't defined in the props for that component and that's probably because your component is probably not rendered through a Route component like this.

```<code><Route path="/your-path" component={YourComponent} />
</code>```

If it isn't, you can wrap your component with the WithRouter HOC from react-router.

```<code>import { WithRouter } from "react-router";

// rest of code...

export default WithRouter(YourComponent);
</code>```

Secondly, you don't need to add an onClick function to the Link component.

You can easily do this...

```<code>changeRoutePath = (e) => {
  e.preventDefault();
  this.props.onClose();
  this.props.history.push({
    pathname: '/company/orgStructure'),
    state: {
      fromNotifications: true
    }
  });
};
</code>```

Then instead of a Link, you can do this

```<code><a href="#" onClick={e => this.changeRoutePath(e)}>Prevent</a>
</code>```

Body:
changeRoutePath = (e) =>{
    e.preventDefault();
    this.props.onClose();
    this.props.history.push('/company/orgStructure');
};
<Link
                to={{
                    pathname: '/company/orgStructure',
                    state: {
                        fromNotifications: true
                    }
                }}
                onClick={(e) => this.changeRoutePath(e)}>
                Prevent
            </Link>

I  have error Uncaught TypeError: Cannot read property 'push' of undefined

I have a import of the Link

import {Link} from "react-router-dom";

Need to go on /company/orgStructure page and take some info in state! How to do it?

If i use just link without onclick i cant use this.props.onClose for close modal. How to push info and go to orgStructure?

bgClose: false
className: ""
container: true
employeeCode: "00-005424"
escClose: false
onClose: ƒ ()
open: true
showModalEmployeeShortProfile: ƒ ()
stack: true
template: null
title: "Профиль сотрудника"
width: 960
console.log(this.props);

Body:
First of all, the error you're getting is from your changeRoutePath function. The history object isn't defined in the props for that component and that's probably because your component is probably not rendered through a Route component like this.

<Route path="/your-path" component={YourComponent} />

If it isn't, you can wrap your component with the WithRouter HOC from react-router.

import { WithRouter } from "react-router";

// rest of code...

export default WithRouter(YourComponent);

Secondly, you don't need to add an onClick function to the Link component.

You can easily do this...

changeRoutePath = (e) => {
  e.preventDefault();
  this.props.onClose();
  this.props.history.push({
    pathname: '/company/orgStructure'),
    state: {
      fromNotifications: true
    }
  });
};

Then instead of a Link, you can do this

<a href="#" onClick={e => this.changeRoutePath(e)}>Prevent</a>


问:
ClipboardEvent undefined in IE11
I have the following code in one of my Angular directives:

```<code>  @HostListener('paste', ['$event'])
  onPaste($event: ClipboardEvent) {
    setTimeout(() => {
      const input = (<HTMLInputElement>$event.target);
      input.value = input.value.replace(/\D/g, '');
    });
  }
</code>```

It fails in IE11 with an error saying that ClipboardEvent is undefined.
Luckily I could type it to just Event, but I am wondering why it breaks -
is there any lib that I could add in angular-cli.json to make it work with ClipboardEvent?

```<code>"lib": [
  "es2017",
  "dom"
],
</code>```

"dom" is where Event comes from...

答:
It seems to be an issue in IE with angulars JIT (Just-In-Time compilation) build mode. It helped to use AOT (Ahead-Of-Time). Then there's no error loading the site.

```<code>ng build --aot
</code>```

JIT makes the browser compile the code on runtime and IE seems to not compile correctly (that's guessing!).

Here's the explaination of difference bewteen AOT and JIT:
https://angular.io/guide/aot-compiler

Note:
Paste from clipboard does still not work in IE, though. Here is well explained why it's not working everywhere: Clipboard Event (Stack Overflow)

Title: ClipboardEvent undefined in IE11

Body:
I have the following code in one of my Angular directives:

  @HostListener('paste', ['$event'])
  onPaste($event: ClipboardEvent) {
    setTimeout(() => {
      const input = (<HTMLInputElement>$event.target);
      input.value = input.value.replace(/\D/g, '');
    });
  }

It fails in IE11 with an error saying that ClipboardEvent is undefined.
Luckily I could type it to just Event, but I am wondering why it breaks -
is there any lib that I could add in angular-cli.json to make it work with ClipboardEvent?

"lib": [
  "es2017",
  "dom"
],

"dom" is where Event comes from...

Body:
It seems to be an issue in IE with angulars JIT (Just-In-Time compilation) build mode. It helped to use AOT (Ahead-Of-Time). Then there's no error loading the site.

ng build --aot

JIT makes the browser compile the code on runtime and IE seems to not compile correctly (that's guessing!).

Here's the explaination of difference bewteen AOT and JIT:
https://angular.io/guide/aot-compiler

Note:
Paste from clipboard does still not work in IE, though. Here is well explained why it's not working everywhere: Clipboard Event (Stack Overflow)


问:
Avoid double search or unecessary construction with std::unordered_map (and others)
I would like to find a element with a key on a std::unordered_map, or insert it if it does not yet exist.

From cppreference.com:

std::unordered_map::emplace

Inserts a new element into the container constructed in-place with the given args if there is no element with the key in the container.

...

The element may be constructed even if there already is an element with the key in the container, in which case the newly constructed element will be destroyed immediately.

...

Returns a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place. True for Insertion, False for No Insertion.

I've tested it, for my environments, and it actually constructs the element even if the same key already exists.

This can be a major performance issue.

From c++17 there is try_emplace that avoids this construction if insertion does not take place.

I'm limited to c++14 and after looking around I find two alternatives for the same behavior:

use std::unordered_map::find first, and if the element does not exist then use std::unordered_map::emplace. If key does not exist I pay for a redundant container search.

use std::unordered_map::emplace. If key exist I pay for a unnecessary object construction and destruction.

Is my assumption correct that I have to decide on this trade-off until C++17?

答:
Is my assumption correct that I have to decide on this trade-off until C++17?

Yes.

Or, you can use a container outside of the standard library that supports a try_emplace operation or equivalent.