问:
Error When Deserializing a JSON String to a Java Object with Interface Data Member
I have a JSON String and I want to deserialize it to a Java object with a interface data member.  The Java object looks like this:

```<code>public class Person {
     private String id;
     private String name;
     private AddressInterface addr;
}
</code>```

Both the Person and the AddressInterface are third party classes, so I can't make any changes to them.

When I used the following to deserialize the JSON string,

```<code> objectMapper.readValue(json_file, Person.class)
</code>```

I got the following exception.  It's because the object mapper doesn't know how to deserialize the AddressInterface  field.  Can someone let me know how to deserialize the string into an Person object in this case?  Many Thanks.

```<code> abstract types either need to be mapped to
 concrete types, have custom deserializer,
 or be instantiated with additional type information
</code>```

答:
AddressInterface is an interface and is considered abstract. Both classes Foo and Bar could implement AddressInterface, but it would be unable to tell which one the data should be deserialized as.

Random idea which might work:

Put the interface in a wrapper. I'm just guessing since I don't know the library context, but maybe something like this. Also there's probably a few typos in here, but it shows the general idea.

    public class AbstractSerializable<T> implements Deserialize {
        private final String className;
        private T obj;

        public AbstractSerializable(T obj) {
              this.obj = obj;
              this.className = obj.getClass().getCardinalName();
        }

        @Override
        public AbstractSerializable deserialize(ObjectMapper objectMapper) {
             String clazz = input.readNext(String.class);
             return objectMapper.readNext(Class.forName(clazz));
        }

    }

```

Edit: This would probably break if you tried to put a lambda in it.

Edit 2: @Hadi Note is correct that Gson would make some things easier, however it would run into the same issues. I did find this article which explains how to fix it when using Gson. It uses a similar approach to my answer, but they have a much better explanation.

Body:
I have a JSON String and I want to deserialize it to a Java object with a interface data member.  The Java object looks like this:

public class Person {
     private String id;
     private String name;
     private AddressInterface addr;
}

Both the Person and the AddressInterface are third party classes, so I can't make any changes to them.

When I used the following to deserialize the JSON string,

 objectMapper.readValue(json_file, Person.class)

I got the following exception.  It's because the object mapper doesn't know how to deserialize the AddressInterface  field.  Can someone let me know how to deserialize the string into an Person object in this case?  Many Thanks.

 abstract types either need to be mapped to
 concrete types, have custom deserializer,
 or be instantiated with additional type information

Body:
AddressInterface is an interface and is considered abstract. Both classes Foo and Bar could implement AddressInterface, but it would be unable to tell which one the data should be deserialized as.

Random idea which might work:

Put the interface in a wrapper. I'm just guessing since I don't know the library context, but maybe something like this. Also there's probably a few typos in here, but it shows the general idea.

    public class AbstractSerializable<T> implements Deserialize {
        private final String className;
        private T obj;

        public AbstractSerializable(T obj) {
              this.obj = obj;
              this.className = obj.getClass().getCardinalName();
        }

        @Override
        public AbstractSerializable deserialize(ObjectMapper objectMapper) {
             String clazz = input.readNext(String.class);
             return objectMapper.readNext(Class.forName(clazz));
        }

    }

Edit: This would probably break if you tried to put a lambda in it.

Edit 2: @Hadi Note is correct that Gson would make some things easier, however it would run into the same issues. I did find this article which explains how to fix it when using Gson. It uses a similar approach to my answer, but they have a much better explanation.


来源: stackexchange

问:
How to set session attributes in Spring Boot?
I want to set a session attribute with the name that is send by user. User will first login in. And when he logged in I want that his username will set as session attribute.

What should I do?

This is my controller:

```<code>@GetMapping("/login")
public String login() {
    return "Login";
}

@PostMapping("/loginCheck")
public String checkLogin(@ModelAttribute("users") Users user) {
    if (userService.checkUser(user)) {
        return "redirect:/"+user.getUsername()+"/";
    } else {
        return "Login";
    }
}

@PostMapping("/signup")
public ModelAndView createuser(@ModelAttribute("users") Users user) {
    if (userService.checkUser(user)) {
        return new ModelAndView("Login");
    } else {
        userService.adduser(user);
        return new ModelAndView("Login");
    }
}
</code>```

Now how I set the username as session which I am getting in user.getUsername()?

答:
```<code>@Autowired
ObjectFactory<HttpSession> httpSessionFactory;
.
.
.
HttpSession session = httpSessionFactory.getObject();
</code>```

Works good. Thanks to this post.

ContentLicense: CC BY-SA 4.0

Body:
I want to set a session attribute with the name that is send by user. User will first login in. And when he logged in I want that his username will set as session attribute.

What should I do?

This is my controller:

@GetMapping("/login")
public String login() {
    return "Login";
}

@PostMapping("/loginCheck")
public String checkLogin(@ModelAttribute("users") Users user) {
    if (userService.checkUser(user)) {
        return "redirect:/"+user.getUsername()+"/";
    } else {
        return "Login";
    }
}

@PostMapping("/signup")
public ModelAndView createuser(@ModelAttribute("users") Users user) {
    if (userService.checkUser(user)) {
        return new ModelAndView("Login");
    } else {
        userService.adduser(user);
        return new ModelAndView("Login");
    }
}

Now how I set the username as session which I am getting in user.getUsername()?

Body:
@Autowired
ObjectFactory<HttpSession> httpSessionFactory;
.
.
.
HttpSession session = httpSessionFactory.getObject();

Works good. Thanks to this post.


问:
How do you balance working for a living and contributing to open source projects?
I have been a working programmer since the turn of the century and I have always been fascinated by the open source world. I have wanted to contribute to these projects but I find it difficult to find the time that I think these projects would require.

I find professional software development to be a huge time sink. Almost every project I have worked on has a familiar litany inflexible deadlines and inevitable round the clock last minute pushes that eat up your nights and weekends and everything else in sight. Even in the project that don't have this - the typical work day is 10 to 12 hours and after that one has errands and chores, reading up on the latest stuff, etc...

Since this happens with a fair amount of regularity - I am hesitant to join projects since I can't promise to devote a regular number of hours every week.

My question is how do you people do it?

Do you work at open source companies? Am I exaggerating the amount of time I need to spend (I am thinking a couple of hours everyday)? Am I way off base and simply not managing my time efficiently? How do you manage your time?

答: Stop working 12 hour days, for a start. (grin)  You don't need to pre-commit any particular amount of time to start working on some open source project that interests you -- even an hour a week can be of benefit to you and the project.  You'll find that your desire to spend time on a project will increase over time as you get more interested in something, and you'll reprioritise things in your life, as you would with any other hobby you enjoy doing.</p>

OwnerDisplayName: Nikhil

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: womble


问:
Regular expression to replace content between parentheses ()
I tried this code:

```<code>string.replaceAll("\\(.*?)","");
</code>```

But it returns null. What am I missing?

答:
string.replaceAll("\\([^\\)]*\\)","");
This way you are saying match a bracket, then all non-closing bracket chars, and then a closing bracket. This is usually faster than reluctant or greedy .* matchers.

ContentLicense: CC BY-SA 3.0

Body:
I tried this code:

string.replaceAll("\\(.*?)","");

But it returns null. What am I missing?


问:
How to fix ‘Trying to get property of non-object ’ notice in Previous Post Thumbnail
I added a thumbnail for next and previous post in my Wordpress theme specifically inside the single.php file.

It works as require but it is displaying the notice:

Notice: Trying to get property of non-object in \wp-content\themes\theme\template-parts\content-footer.php on line 27

I have tried out some of the examples from similar answers in this website but they do not work for me.
I removed both $prevPost->ID and $nextPost->ID but it then displays the current post thumbnail instead.

The code causing the error is below:
The line of code causing the notice is the 3rd and 4th lines below:

```<code><?php
    $prevPost = get_previous_post();
    $nextPost = get_next_post();
    $prevthumbnail = get_the_post_thumbnail($prevPost->ID, array(50,50) );
    $nextthumbnail = get_the_post_thumbnail($nextPost->ID, array(50,50) );
?>
</code>```

The thumbnails were called using the codes below:

<?php echo $prevthumbnail; ?>
 and
<?php echo $nextthumbnail; ?>
 which both works.

The error is just a notice so it does not break the website or even appear unless wordpress debug is enabled. However, I would prefer not getting this notice so as not to cause some concern for my client.

Any idea on how to resolve this?

答:
So, in WordPress - the first post in the database is NOT going to have a "previous" post, and the last post is not going to have a "next" - so this behavior is perfectly normal.

To prevent the notice, you just need to check if it exists first - I typically like to use empty to perform the check - like so:

```<code>$prevPost = get_previous_post();
$nextPost = get_next_post();
if ( ! empty( $prevPost->ID ) ) {
    $prevthumbnail = get_the_post_thumbnail($prevPost->ID, array(50,50) );
}

if ( ! empty( $nextPost->ID ) ) {
    $nextthumbnail = get_the_post_thumbnail($nextPost->ID, array(50,50) );
}
</code>```

Note that this may have the undesirable effect of leaving $nextthumbnail and / or $prevthumbnail as undefined variables, so to combat that, I'd recommend modifying the code even further:

```<code>$prevPost = get_previous_post();
$nextPost = get_next_post();
// use a ternary to set the thumbnail if not empty, or empty string if empty
$prevthumbnail = ( empty( $prevPost->ID ) ) ? '' : get_the_post_thumbnail($prevPost->ID, array(50,50) );
// use a ternary to set the thumbnail if not empty, or empty string if empty
$nextthumbnail = ( empty( $nextPost->ID ) ) ? '' : get_the_post_thumbnail($nextPost->ID, array(50,50) );
</code>```

Body:
I added a thumbnail for next and previous post in my Wordpress theme specifically inside the single.php file.

It works as require but it is displaying the notice:

Notice: Trying to get property of non-object in \wp-content\themes\theme\template-parts\content-footer.php on line 27

I have tried out some of the examples from similar answers in this website but they do not work for me.
I removed both $prevPost->ID and $nextPost->ID but it then displays the current post thumbnail instead.

The code causing the error is below:
The line of code causing the notice is the 3rd and 4th lines below:

<?php
    $prevPost = get_previous_post();
    $nextPost = get_next_post();
    $prevthumbnail = get_the_post_thumbnail($prevPost->ID, array(50,50) );
    $nextthumbnail = get_the_post_thumbnail($nextPost->ID, array(50,50) );
?>

The thumbnails were called using the codes below:

<?php echo $prevthumbnail; ?>
 and
<?php echo $nextthumbnail; ?>
 which both works.

The error is just a notice so it does not break the website or even appear unless wordpress debug is enabled. However, I would prefer not getting this notice so as not to cause some concern for my client.

Any idea on how to resolve this?

Body:
So, in WordPress - the first post in the database is NOT going to have a "previous" post, and the last post is not going to have a "next" - so this behavior is perfectly normal.

To prevent the notice, you just need to check if it exists first - I typically like to use empty to perform the check - like so:

$prevPost = get_previous_post();
$nextPost = get_next_post();
if ( ! empty( $prevPost->ID ) ) {
    $prevthumbnail = get_the_post_thumbnail($prevPost->ID, array(50,50) );
}

if ( ! empty( $nextPost->ID ) ) {
    $nextthumbnail = get_the_post_thumbnail($nextPost->ID, array(50,50) );
}

Note that this may have the undesirable effect of leaving $nextthumbnail and / or $prevthumbnail as undefined variables, so to combat that, I'd recommend modifying the code even further:

$prevPost = get_previous_post();
$nextPost = get_next_post();
// use a ternary to set the thumbnail if not empty, or empty string if empty
$prevthumbnail = ( empty( $prevPost->ID ) ) ? '' : get_the_post_thumbnail($prevPost->ID, array(50,50) );
// use a ternary to set the thumbnail if not empty, or empty string if empty
$nextthumbnail = ( empty( $nextPost->ID ) ) ? '' : get_the_post_thumbnail($nextPost->ID, array(50,50) );


问:
How to specify generic key constraint in function argument
I might be going about this the wrong way, I just wanted to have a little bit of fun in code today. I'm sure a library already does this as well.

I am creating a generic pushUnique function that determines if a new object being pushed to an array is unique based on a key, and if so, push it.

So far I have little more than pseudo-code that doesn't work for obvious reasons:

```<code>  pushUnique<T, U>(arr: T[], obj: T, key: U = null) {
    if (key !== null) {
      const index = arr.findIndex(o => o.key === obj.key);
    }
  }
</code>```

How can I get the object name of the key and specify it for the findIndex function?

EDIT:

With help from Titian Cernicova-Dragomir this is my final solution for now that works great for my POC needs!

```<code>export class Utils {
  pushUnique<T, U>(arr: T[], obj: T, key: (o: T) => U = null, logVerbose: boolean = false): void {
    if (logVerbose === true) {
      console.log('pushUnique called');
    }

    if (typeof obj === 'object' && key === null) {
      console.warn('Object defined in pushUnique is complex, but a key was not specified.');
    } else if (typeof obj !== 'object' && key !== null) {
      console.warn('Object is not complex, but a key was specified');
    }

    const index = key !== null ? arr.findIndex(o => key(o) === key(obj)) : arr.indexOf(obj);
    if (index === -1) {
      arr.push(obj);
    } else {
      if (logVerbose === true) {
        console.log('Duplicate object, not added');
      }
    }
  }
}
</code>```

答:
You can pass in the key typed as keyof T meaning it must be a key of whatever T is passed in and then you can just use index access to get the value:

```<code>class Util {
    pushUnique<T>(arr: T[], obj: T, key: keyof T) {
        if (key !== null) {
            const index = arr.findIndex(o => o[key] === obj[key]);
        }
    }
}

new Util().pushUnique([{a: 1}], {a :2 }, "a")
new Util().pushUnique([{a: 1}], {a :2 }, "b") //err
</code>```

You can also use a function instead of keyof but this is the JS/TS way of doing things:

```<code>class Util {
    pushUnique<T, U>(arr: T[], obj: T, key: (o: T) => U) {
        if (key !== null) {
            const index = arr.findIndex(o => key(o) === key(o));
        }
    }
}

new Util().pushUnique([{a: 1}], {a :2 }, o => o.a)
new Util().pushUnique([{a: 1}], {a :2 }, o => o.b) //err
</code>```

Body:
I might be going about this the wrong way, I just wanted to have a little bit of fun in code today. I'm sure a library already does this as well.

I am creating a generic pushUnique function that determines if a new object being pushed to an array is unique based on a key, and if so, push it.

So far I have little more than pseudo-code that doesn't work for obvious reasons:

  pushUnique<T, U>(arr: T[], obj: T, key: U = null) {
    if (key !== null) {
      const index = arr.findIndex(o => o.key === obj.key);
    }
  }

How can I get the object name of the key and specify it for the findIndex function?

EDIT:

With help from Titian Cernicova-Dragomir this is my final solution for now that works great for my POC needs!

export class Utils {
  pushUnique<T, U>(arr: T[], obj: T, key: (o: T) => U = null, logVerbose: boolean = false): void {
    if (logVerbose === true) {
      console.log('pushUnique called');
    }

    if (typeof obj === 'object' && key === null) {
      console.warn('Object defined in pushUnique is complex, but a key was not specified.');
    } else if (typeof obj !== 'object' && key !== null) {
      console.warn('Object is not complex, but a key was specified');
    }

    const index = key !== null ? arr.findIndex(o => key(o) === key(obj)) : arr.indexOf(obj);
    if (index === -1) {
      arr.push(obj);
    } else {
      if (logVerbose === true) {
        console.log('Duplicate object, not added');
      }
    }
  }
}

Body:
You can pass in the key typed as keyof T meaning it must be a key of whatever T is passed in and then you can just use index access to get the value:

class Util {
    pushUnique<T>(arr: T[], obj: T, key: keyof T) {
        if (key !== null) {
            const index = arr.findIndex(o => o[key] === obj[key]);
        }
    }
}

new Util().pushUnique([{a: 1}], {a :2 }, "a")
new Util().pushUnique([{a: 1}], {a :2 }, "b") //err

You can also use a function instead of keyof but this is the JS/TS way of doing things:

class Util {
    pushUnique<T, U>(arr: T[], obj: T, key: (o: T) => U) {
        if (key !== null) {
            const index = arr.findIndex(o => key(o) === key(o));
        }
    }
}

new Util().pushUnique([{a: 1}], {a :2 }, o => o.a)
new Util().pushUnique([{a: 1}], {a :2 }, o => o.b) //err


问:
CMD batch file to delete a file if not found in list from text txt file
I need a bat to delete all files with the RELATIVE name that are NOT contained in a text file

In the text file list.txt i have this:

```<code>C:\S-ATLANTICO-1\MEDIA\Innplay-Logo.mp4
C:\S-ATLANTICO-1\MEDIA\logo-FB_sep.png
C:\S-ATLANTICO-1\MEDIA\logo-news_sa.png
</code>```

and the in the same folder have this files:

```<code>Innplay-Logo.mp4
logo-FB_sep.png
logo-news_sa.png
Carlos.jpg
Sapo.png
list.txt
</code>```

So i need to delete the next files because not exist in list.txt

```<code>Carlos.jpg
Sapo.png
</code>```

but i also MUST KEEP the LIST.TXT

i have tried this but without sucess

```<code>@echo off
setlocal
set "folder=C:\S-ATLANTICO-1\MEDIA"
set "excludeFile=C:\S-ATLANTICO-1\MEDIA\list.txt"
for /f "eol=: delims=" %%F in ('dir /b /a-d "%folder%" ^| findstr  /vig:"%excludeFile%" ^| findstr /v /i "\list.txt"') do del "%folder%\%%F"
</code>```

any one can help me with this.

Thanks

答:
Give this a try. It iterates over the contents of $thedir and deletes files that are not in list.txt and are not scripts. Put these two (2) files in the same directory. It would be best not to put them in the same directory as the files being deleted. Run the .bat file from a cmd.exe shell.

When you are satisfied that the correct files will be removed, remove the -WhatIf from the Remove-Item cmdlet.

=== Remove-Except.ps1

```<code>$thedir = 'C:\src\t\delexcept'
$precious = (Get-Content -Path (Join-Path -Path $thedir -ChildPath 'list.txt')) +
    @(Join-Path -Path $thedir -ChildPath 'list.txt')

Get-ChildItem -Path $thedir -Exclude 'list.txt','*.ps1','*.bat' |
    Where-Object { (-not $_.PSIsContainer) -and
        ($precious -notcontains $_.FullName) -and
        $_.FullName.StartsWith($thedir) } |
    ForEach-Object { Remove-Item -Path $_.FullName -WhatIf }
</code>```

=== Remove-Except.bat

```<code>powershell -NoLogo -NoProfile -File "%~dpn0.ps1"
</code>```

Body:
I need a bat to delete all files with the RELATIVE name that are NOT contained in a text file

In the text file list.txt i have this:

C:\S-ATLANTICO-1\MEDIA\Innplay-Logo.mp4
C:\S-ATLANTICO-1\MEDIA\logo-FB_sep.png
C:\S-ATLANTICO-1\MEDIA\logo-news_sa.png

and the in the same folder have this files:

Innplay-Logo.mp4
logo-FB_sep.png
logo-news_sa.png
Carlos.jpg
Sapo.png
list.txt

So i need to delete the next files because not exist in list.txt

Carlos.jpg
Sapo.png

but i also MUST KEEP the LIST.TXT

i have tried this but without sucess

@echo off
setlocal
set "folder=C:\S-ATLANTICO-1\MEDIA"
set "excludeFile=C:\S-ATLANTICO-1\MEDIA\list.txt"
for /f "eol=: delims=" %%F in ('dir /b /a-d "%folder%" ^| findstr  /vig:"%excludeFile%" ^| findstr /v /i "\list.txt"') do del "%folder%\%%F"

any one can help me with this.

Thanks

Body:
Give this a try. It iterates over the contents of $thedir and deletes files that are not in list.txt and are not scripts. Put these two (2) files in the same directory. It would be best not to put them in the same directory as the files being deleted. Run the .bat file from a cmd.exe shell.

When you are satisfied that the correct files will be removed, remove the -WhatIf from the Remove-Item cmdlet.

=== Remove-Except.ps1

$thedir = 'C:\src\t\delexcept'
$precious = (Get-Content -Path (Join-Path -Path $thedir -ChildPath 'list.txt')) +
    @(Join-Path -Path $thedir -ChildPath 'list.txt')

Get-ChildItem -Path $thedir -Exclude 'list.txt','*.ps1','*.bat' |
    Where-Object { (-not $_.PSIsContainer) -and
        ($precious -notcontains $_.FullName) -and
        $_.FullName.StartsWith($thedir) } |
    ForEach-Object { Remove-Item -Path $_.FullName -WhatIf }

=== Remove-Except.bat

powershell -NoLogo -NoProfile -File "%~dpn0.ps1"


问:
Recursion to print number by using return statement
I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.

```<code>class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num<=2){
            rec(++num);
        }
        System.out.println(num);
    }
}
</code>```

but I want to do this with the following way.

```<code>class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num==2){
            return;
        }
        rec(++num);
        System.out.println(num);
    }
}
</code>```

Expected output:

```<code>2,1,0
</code>```

but it shows:

```<code>2,1
</code>```

Why does it happen?

答:
++num increments num, which (as here) makes the code harder to understand.

Try calling rec(num + 1); instead.

You may find your terminating condition needs to be modified to:

```<code>if (num > 2)
</code>```

Terminating conditions are usually the “do nothing” case, which is the case here.

Body:
I'm using recursion to print numbers until 2(number), and I'm passing zero(0) as input and recursively calling it until the number reaches 2.
I have tried this code, and it shows the correct output.

class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num<=2){
            rec(++num);
        }
        System.out.println(num);
    }
}

but I want to do this with the following way.

class Test{
    public static void main(String[] args) {
        rec(0);
    }
    private static void rec(int num){
        if(num==2){
            return;
        }
        rec(++num);
        System.out.println(num);
    }
}

Expected output:

2,1,0

but it shows:

2,1

Why does it happen?

Body:
++num increments num, which (as here) makes the code harder to understand.

Try calling rec(num + 1); instead.

You may find your terminating condition needs to be modified to:

if (num > 2)

Terminating conditions are usually the “do nothing” case, which is the case here.


问:
Deserialization of interfaces using Jackson, where the interface implementation is specified in the serialized object
I have the following sort of structure (simplified to hopefully make the problem clearer):

```<code>interface Settings {
    ...
}

interface Component {
    ...
}

class Container {
    Class<? extends Component> component;
    Settings settings;
}

@SettingsClass(MySettings.class)
class MyComponent implements Component{
    ...
}

class MySettings implements Settings{
    ...
}
</code>```

If I serialize an instance of Container using Jackson, I get a JSON that looks a bit like:

```<code>{
    component: "my.package.MyComponent"
    settings: { ... }
}
</code>```

This is exactly what I want.

But I can't deserialize that JSON because Jackson doesn't know which implementation of Settings to use. At run time, I can retrieve the SettingsClass annotation and identify which class the settings field should be deserialized to.

Is there a way for me to get Jackson to partially deserialize the JSON, and then have it deserialize the rest (i.e. the settings) once I've been able to inspect the component and determine which Settings class to use?

答:
Not really. I had to do something similar recently. I parsed into JsonNode and checked the property manually.

```<code>final JsonNode jsonRoot = new ObjectMapper().readTree(jsonString);
//...
Optional.ofNullable(jsonRoot.get("component")).map(JsonNode::textValue) ...
</code>```

Then serialized the tree into the POJO.

```<code>new ObjectMapper().readerFor(theClass).readValue(jsonRoot)
</code>```

Not amazing, but saves parsing the entire string twice at least.

Body:
I have the following sort of structure (simplified to hopefully make the problem clearer):

interface Settings {
    ...
}

interface Component {
    ...
}

class Container {
    Class<? extends Component> component;
    Settings settings;
}

@SettingsClass(MySettings.class)
class MyComponent implements Component{
    ...
}

class MySettings implements Settings{
    ...
}

If I serialize an instance of Container using Jackson, I get a JSON that looks a bit like:

{
    component: "my.package.MyComponent"
    settings: { ... }
}

This is exactly what I want.

But I can't deserialize that JSON because Jackson doesn't know which implementation of Settings to use. At run time, I can retrieve the SettingsClass annotation and identify which class the settings field should be deserialized to.

Is there a way for me to get Jackson to partially deserialize the JSON, and then have it deserialize the rest (i.e. the settings) once I've been able to inspect the component and determine which Settings class to use?

Body:
Not really. I had to do something similar recently. I parsed into JsonNode and checked the property manually.

final JsonNode jsonRoot = new ObjectMapper().readTree(jsonString);
//...
Optional.ofNullable(jsonRoot.get("component")).map(JsonNode::textValue) ...

Then serialized the tree into the POJO.

new ObjectMapper().readerFor(theClass).readValue(jsonRoot)

Not amazing, but saves parsing the entire string twice at least.


问:
Difference between two lists
I Have two generic list filled with CustomsObjects.

I need to retrieve the difference between those two lists(Items who are in the first without the items in the second one)  in a third one.

I was thinking using .Except() was a good idea but I don't see how to use this..
Help!

答:
You could do something like this:</p>

```<code>var result = customlist.Where(p => !otherlist.Any(l => p.someproperty == l.someproperty));
</code>```

Title: Difference between two lists

Body:
You could do something like this:

var result = customlist.Where(p => !otherlist.Any(l => p.someproperty == l.someproperty));


问:
What is the point of making separate public functions for getting/setting a private value?
Let me just preface this by saying that I know this is probably a newbie quesion, I tried searching for it and I can't find a proper anwser for it (probbably asking it wrong).

So usually when I want to use another value outisde of its class, I just make it public and access it lik.

Yet often I see other code use private values in their class and then make separate functions for getting and setting the value like so:

private bool fooBar;

public void SetFooBar(bool boolean)
{
   fooBar = boolean;
}

public bool GetFooBar()
{
   return fooBar;
}
```

Excuse my ignorance but what exactly is the point of it? They both do essentially the same thing (by my newbie logic atleast). I know that private variables are useful in that it ensures you can't break the functionality of a program by modifying them elsewhere in the code, but you're modifying them elsewhere in the code anyway, so what gives? Why do I see people do this?

答:
Because directly modifying the state of an object is a no-no in OOP

Because you can't put fields into an interface (and once you get far enough, you usually end up accessing most other objects through interfaces)

Because it allows additional logic (like raising events) when another object wants to interact with the field

Because certain things (like WPF bindings) only work with properties, not fields

Because you may want to change how the value is retrieved/stored (not just in-memory) later

(Note that in C# you usually do this as a property, not methods, like public bool Foo {get; set;})

Body:
Let me just preface this by saying that I know this is probably a newbie quesion, I tried searching for it and I can't find a proper anwser for it (probbably asking it wrong).

So usually when I want to use another value outisde of its class, I just make it public and access it lik.

Yet often I see other code use private values in their class and then make separate functions for getting and setting the value like so:

private bool fooBar;

public void SetFooBar(bool boolean)
{
   fooBar = boolean;
}

public bool GetFooBar()
{
   return fooBar;
}

Excuse my ignorance but what exactly is the point of it? They both do essentially the same thing (by my newbie logic atleast). I know that private variables are useful in that it ensures you can't break the functionality of a program by modifying them elsewhere in the code, but you're modifying them elsewhere in the code anyway, so what gives? Why do I see people do this?


问:
How to fix "The SELECT would examine more than MAX_JOIN_SIZE rows" problem?
I am using MySQLi Procedural to run query from a MYSQL database. I have only seen how this is done using MySQLi Object-Oriented code.

It runs perfectly on localhost, but on the remote server I get an error message saying that I have more than MAX_JOIN_SIZE rows.  What code do I use to fix this error?

I have looked at all the pages concerned with this error and although I know what the problem is, I can't work out how to fix it. All of the examples I have seen use MySQLi Object-Oriented code. I have tried limiting (LIMIT 30) the number of records returned, but this made no difference.

```<code><?php
$con=mysqli_connect("localhost","******","******","ps10");
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_rs4 = "SELECT * FROM  student_data INNER JOIN users ON student_data.class = users.class INNER JOIN ext_writing_tbl ON student_data.id = ext_writing_tbl.id";

$rs4 = mysqli_query($con, $query_rs4)or die( mysqli_error($con) );
$row = mysqli_num_rows($rs4);
echo "There are " . $row . " students in this class";
?>
</code>```

This is the complete error message.

The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay.

It should output to a table.

答: I am sure now that this is something set on the server and is beyond my control. How then to write a query that does not use three tables (uses INNER JOIN twice)? </p>

Body:
I am using MySQLi Procedural to run query from a MYSQL database. I have only seen how this is done using MySQLi Object-Oriented code.

It runs perfectly on localhost, but on the remote server I get an error message saying that I have more than MAX_JOIN_SIZE rows.  What code do I use to fix this error?

I have looked at all the pages concerned with this error and although I know what the problem is, I can't work out how to fix it. All of the examples I have seen use MySQLi Object-Oriented code. I have tried limiting (LIMIT 30) the number of records returned, but this made no difference.

<?php
$con=mysqli_connect("localhost","******","******","ps10");
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_rs4 = "SELECT * FROM  student_data INNER JOIN users ON student_data.class = users.class INNER JOIN ext_writing_tbl ON student_data.id = ext_writing_tbl.id";

$rs4 = mysqli_query($con, $query_rs4)or die( mysqli_error($con) );
$row = mysqli_num_rows($rs4);
echo "There are " . $row . " students in this class";
?>

This is the complete error message.

The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET MAX_JOIN_SIZE=# if the SELECT is okay.

It should output to a table.


答:
When you are calling rec(++num);, you are incrementing num before printing it out. So when you use 0 as input, by the time it prints num will have changed to 1. When num = 2 at the start of rec(), the print does not execute.

rec(0) prints rec(1),1

rec(1) prints rec(2),2

rec(2) prints nothing

Total output: 2,1

Title: Recursion to print number by using return statement


问:
Sending an Intent from Google Assistant to my smartphone
I would like to do the following:

give a command to (the Google Assistant in) Google Home

from there, send an Intent to my Android smartphone starting an application (on a specific Activity)

Is that possible with Google actions?

I've scanned https://developers.google.com/actions/ but it is not clear to me whether I can send Intents to my phone.  If so, can you provide a pointer?

Thanks in advance,

Marc

答:
There is no direct way to do this. Here are a few ways to get close to the desired behavior:

When an intent is triggered on your Assistant surface, send a push notification to your phone (will require account linking). This push notification can then start an intent.

You can use a helper in the Action to request a new surface with a screen capability. This will not send an intent for your app, but will move the conversation over to a new surface which may make more sense. (This new surface may be able to present a Card with a deeplink into your app)


问:
How to listen to mousemove inside angular material dialog component?
In my app Ineed to track the mouse movment all the time.

At the app.component.ts file I have placed the following code:

```<code>ngOnInit() {
document.addEventListener("mousemove", (e) => {
  //foo()
 });
})
</code>```

Everything works as expected besides inside the dialog.

The dialog is an Angular Material Dialog component and the code of creating it like this:

```<code>openModal() {
    const dialogRef = this.dialog.open(ModalComponent, {
      panelClass: 'generic-dialog-container',
      data: {
        header: 'Leave session',
        content:
          'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
        isInfo: false,
      },
    });

    this.dialogSub = dialogRef.componentInstance.isApprove.subscribe(
      isApprove => {
        if (isApprove) {
          this.navigateBack();
        }
      },
    );
  }
</code>```

I have tried adding an event listener inside the modal's OnInit - didn't work, Plus I saw that when I add It at the app.component.ts to the document than the listener is added to the body element and wraps the whole app, like this:

While the dialog is open the Event Listener listens to mouse events at the component in the background (the component who called to open the dialog), but not in the dialog itself.

After closing the dialog and then reopen it, the Event Listener listens to mouse events also inside the dialog as expected.

答:
You can use HostListener to listen for mousemove events inside your ModalComponent:

```<code>import { Component, Inject, HostListener } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

// ...

export class ModalComponent {

  constructor(
    public dialogRef: MatDialogRef<ModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) { }

  @HostListener('mousemove', ['$event'])
  handleMousemove(event) {
    console.log(`x: ${event.clientX}, y: ${event.clientY}`);
  }
}
</code>```

From within the mousemove event handler you can look to emit data as needed perhaps via a shared service, taking advantage of RxJS subjects such as BehaviorSubjects that other components/services such as subscribe to.

Here is an example in action. Notice that the mousemove event is only triggering when the mouse is in the confines of the modal.

Hopefully that helps!

Body:
In my app Ineed to track the mouse movment all the time.

At the app.component.ts file I have placed the following code:

ngOnInit() {
document.addEventListener("mousemove", (e) => {
  //foo()
 });
})

Everything works as expected besides inside the dialog.

The dialog is an Angular Material Dialog component and the code of creating it like this:

openModal() {
    const dialogRef = this.dialog.open(ModalComponent, {
      panelClass: 'generic-dialog-container',
      data: {
        header: 'Leave session',
        content:
          'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
        isInfo: false,
      },
    });

    this.dialogSub = dialogRef.componentInstance.isApprove.subscribe(
      isApprove => {
        if (isApprove) {
          this.navigateBack();
        }
      },
    );
  }

I have tried adding an event listener inside the modal's OnInit - didn't work, Plus I saw that when I add It at the app.component.ts to the document than the listener is added to the body element and wraps the whole app, like this:

While the dialog is open the Event Listener listens to mouse events at the component in the background (the component who called to open the dialog), but not in the dialog itself.

After closing the dialog and then reopen it, the Event Listener listens to mouse events also inside the dialog as expected.

Body:
You can use HostListener to listen for mousemove events inside your ModalComponent:

import { Component, Inject, HostListener } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

// ...

export class ModalComponent {

  constructor(
    public dialogRef: MatDialogRef<ModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) { }

  @HostListener('mousemove', ['$event'])
  handleMousemove(event) {
    console.log(`x: ${event.clientX}, y: ${event.clientY}`);
  }
}

From within the mousemove event handler you can look to emit data as needed perhaps via a shared service, taking advantage of RxJS subjects such as BehaviorSubjects that other components/services such as subscribe to.

Here is an example in action. Notice that the mousemove event is only triggering when the mouse is in the confines of the modal.

Hopefully that helps!


答:
This allows you to change the way the value is stored regardless of how external users access it.

Using Getter and Setter functions, you could request the data from a local cache or pull it from a database.

C# supports Getter Setter functionality implementations using a property style accessor.

```<code>private bool _fooBar
public bool FooBar
{
 get { return _fooBar; }
 set {  _fooBar = value; }
}
</code>```

As BradleyDotNET mentioned in the comments, you can write these in a way that resembles lambdas starting with C# 7.0

```<code>private bool _fooBar
public bool FooBar
{
    get => _fooBar;
    set => _fooBar = value;
}
</code>```

As BradleyDotNET mentioned you can write this exact implementation as

```<code>public bool FooBar { get; set; }
</code>```

Which will act the same way.

You can also expand upon this by making the value only public to get, but only settable in the class.

```<code>public bool FooBar { get; protected set; }
</code>```

Title: What is the point of making separate public functions for getting/setting a private value?

Body:
This allows you to change the way the value is stored regardless of how external users access it.

Using Getter and Setter functions, you could request the data from a local cache or pull it from a database.

C# supports Getter Setter functionality implementations using a property style accessor.

private bool _fooBar
public bool FooBar
{
 get { return _fooBar; }
 set {  _fooBar = value; }
}

As BradleyDotNET mentioned in the comments, you can write these in a way that resembles lambdas starting with C# 7.0

private bool _fooBar
public bool FooBar
{
    get => _fooBar;
    set => _fooBar = value;
}

As BradleyDotNET mentioned you can write this exact implementation as

public bool FooBar { get; set; }

Which will act the same way.

You can also expand upon this by making the value only public to get, but only settable in the class.

public bool FooBar { get; protected set; }


问:
add automatic failover to my existing cluster?
I need help with Automatic Fail-over in Hadoop. The requirement is to transfer the control from one node to another during the failure. I already have running cluster and want to add this to the existing cluster.

hdfs dfsadmin -report
Configured Capacity: 4393174024192 (4.00 TB)
Present Capacity: 4101312667648 (3.73 TB)
DFS Remaining: 4100850401280 (3.73 TB)
DFS Used: 462266368 (440.85 MB)
DFS Used%: 0.01%
Replicated Blocks:
    Under replicated blocks: 20
    Blocks with corrupt replicas: 0
    Missing blocks: 0
    Missing blocks (with replication factor 1): 0
    Low redundancy blocks with highest priority to recover: 0
    Pending deletion blocks: 0
Erasure Coded Block Groups:
    Low redundancy block groups: 0
    Block groups with corrupt internal blocks: 0
    Missing block groups: 0
    Low redundancy blocks with highest priority to recover: 0
    Pending deletion blocks: 0

Live datanodes (4):

Name: 192.168.5.250:9866 (odin)
Hostname: odin
Decommission Status : Normal
Configured Capacity: 1098293506048 (1022.87 GB)
DFS Used: 222879744 (212.55 MB)
Non DFS Used: 16838836224 (15.68 GB)
DFS Remaining: 1025325965312 (954.91 GB)
DFS Used%: 0.02%
DFS Remaining%: 93.36%
Configured Cache Capacity: 0 (0 B)
Cache Used: 0 (0 B)
Cache Remaining: 0 (0 B)
Cache Used%: 100.00%
Cache Remaining%: 0.00%
Xceivers: 1
Last contact: Mon May 20 10:44:50 IST 2019
Last Block Report: Mon May 20 09:12:14 IST 2019
Num of Blocks: 129

Name: 192.168.5.251:9866 (loki)
Hostname: loki
Decommission Status : Normal
Configured Capacity: 1098293506048 (1022.87 GB)
DFS Used: 145424384 (138.69 MB)
Non DFS Used: 15433760768 (14.37 GB)
DFS Remaining: 1026808496128 (956.29 GB)
DFS Used%: 0.01%
DFS Remaining%: 93.49%
Configured Cache Capacity: 0 (0 B)
Cache Used: 0 (0 B)
Cache Remaining: 0 (0 B)
Cache Used%: 100.00%
Cache Remaining%: 0.00%
Xceivers: 1
Last contact: Mon May 20 10:44:50 IST 2019
Last Block Report: Mon May 20 09:12:14 IST 2019
Num of Blocks: 106

Name: 192.168.5.252:9866 (thor)
Hostname: thor
Decommission Status : Normal
Configured Capacity: 1098293506048 (1022.87 GB)
DFS Used: 8003584 (7.63 MB)
Non DFS Used: 16954404864 (15.79 GB)
DFS Remaining: 1025425272832 (955.00 GB)
DFS Used%: 0.00%
DFS Remaining%: 93.37%
Configured Cache Capacity: 0 (0 B)
Cache Used: 0 (0 B)
Cache Remaining: 0 (0 B)
Cache Used%: 100.00%
Cache Remaining%: 0.00%
Xceivers: 1
Last contact: Mon May 20 10:44:50 IST 2019
Last Block Report: Mon May 20 10:08:38 IST 2019
Num of Blocks: 102

Name: 192.168.5.253:9866 (hela)
Hostname: hela
Decommission Status : Normal
Configured Capacity: 1098293506048 (1022.87 GB)
DFS Used: 85958656 (81.98 MB)
Non DFS Used: 19011055616 (17.71 GB)
DFS Remaining: 1023290667008 (953.01 GB)
DFS Used%: 0.01%
DFS Remaining%: 93.17%
Configured Cache Capacity: 0 (0 B)
Cache Used: 0 (0 B)
Cache Remaining: 0 (0 B)
Cache Used%: 100.00%
Cache Remaining%: 0.00%
Xceivers: 1
Last contact: Mon May 20 10:44:50 IST 2019
Last Block Report: Mon May 20 09:12:14 IST 2019
Num of Blocks: 109

答:
```<code>[https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/HDFSHighAvailabilityWithNFS.html][1] , I found this link and [https://www.edureka.co/blog/how-to-set-up-hadoop-cluster-with-hdfs-high-availability/][1]
Both will helps for setting this environment.
</code>```


问:
Combining Radio button values into a hidden form element using jquery or javascript
I have form where people search for a profile match on two values. In this case their role Specialist, Doctor or Nurse and their ranking - Gold, Silver or Bronze.

I need to be able to join these values and send to a hidden input which is submitted with the form. For example <input name="Icon" type="hidden" value="NurseSilver" />  is then used to determine which icon can be represented on a map that's returned. My code is looking something like this...

```<code><input type="radio" name="role" value="Specialist" id="role1" />
<input type="radio" name="role" value="Doctor" id="role2" />
<input type="radio" name="role" value="Nurse" id="role3" />

<input type="radio" name="rank" value="Gold" id="rank1" />
<input type="radio" name="rank" value="Silver" id="rank2" />
<input type="radio" name="rank" value="Bronze" id="rank3" />

<input name="Icon" type="hidden" value="" />
</code>```

Thanks for looking...

答:
You can do something like this:</p>

```<code>var selRole = $(":radio[name=role] :checked").val();
var selRank = $(":radio[name=rank] :checked").val();
$(":hidden[name=Icon]").val(selRole + selRank);
</code>```

Body:
I have form where people search for a profile match on two values. In this case their role Specialist, Doctor or Nurse and their ranking - Gold, Silver or Bronze.

I need to be able to join these values and send to a hidden input which is submitted with the form. For example <input name="Icon" type="hidden" value="NurseSilver" />  is then used to determine which icon can be represented on a map that's returned. My code is looking something like this...

<input type="radio" name="role" value="Specialist" id="role1" />
<input type="radio" name="role" value="Doctor" id="role2" />
<input type="radio" name="role" value="Nurse" id="role3" />

<input type="radio" name="rank" value="Gold" id="rank1" />
<input type="radio" name="rank" value="Silver" id="rank2" />
<input type="radio" name="rank" value="Bronze" id="rank3" />

<input name="Icon" type="hidden" value="" />

Thanks for looking...

Body:
You can do something like this:

var selRole = $(":radio[name=role] :checked").val();
var selRank = $(":radio[name=rank] :checked").val();
$(":hidden[name=Icon]").val(selRole + selRank);


问:
I save a DataFrame in Hbase and I get: java.lang.NoClassDefFoundError: org/apache/hadoop/hbase/client/TableDescriptor
I created a project on Apache Spark.

Version:

scala 2.11.8

apache spark 2.3.0

apache hbase 1.2.0

hortonworks shc 1.1.0.3.1.2.0-4 (the hortonworks connector)

I need to save a simple DataFrame in an HBase table. For this I started HBase 1.2.0 in Docker container (https://github.com/zhao-y/docker-hbase-pseudo) and created the following table:

```<code>$ hbase(main):002:0> create "table1", "cf1", "cf2", "cf3", "cf4", "cf5", "cf6", "cf7", "cf8"
$ 0 row (s) in 1.4440 seconds
</code>```

To save a DataFrame in Hbase I use: https://github.com/hortonworks-spark/shc

I declared the catalog exactly as in the example

I created a catalog-based dataframe

I tried to save dataframe in hbase as in example:

```<code>dataFrame.write.options(
  Map(HBaseTableCatalog.tableCatalog -> catalog, HBaseTableCatalog.newTable -> "5"))
  .format("org.apache.spark.sql.execution.datasources.hbase")
  .save()
</code>```

Code:

```<code>import org.apache.spark.sql.execution.datasources.hbase.HBaseTableCatalog
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.junit.Test

class SparkTest {
  case class HBaseRecord(
                          col0: String,
                          col1: Boolean,
                          col2: Double,
                          col3: Float,
                          col4: Int,
                          col5: Long,
                          col6: Short,
                          col7: String,
                          col8: Byte)

  object HBaseRecord {
    def apply(i: Int, t: String): HBaseRecord = {
      val s = s"""row${"%03d".format(i)}"""
      HBaseRecord(s,
        i % 2 == 0,
        i.toDouble,
        i.toFloat,
        i,
        i.toLong,
        i.toShort,
        s"String$i: $t",
        i.toByte)
    }
  }

  @Test
  def bar(): Unit = {
    val sparkSession = SparkSession.builder
      .appName("SparkTest")
      .master("local[*]")
      .config("spark.testing.memory", 2147480000)
      .getOrCreate()

    val data = (0 to 255).map { i => HBaseRecord(i, "extra") }

    val dataFrame = sparkSession.createDataFrame(data)
    dataFrame.show

    dataFrame.write.options(
      Map(HBaseTableCatalog.tableCatalog -> catalog, HBaseTableCatalog.newTable -> "5"))
      .format("org.apache.spark.sql.execution.datasources.hbase")
      .save()
  }
}

</code>```

Error:

```<code>java.lang.NoClassDefFoundError: org/apache/hadoop/hbase/client/TableDescriptor

    at org.apache.spark.sql.execution.datasources.hbase.DefaultSource.createRelation(HBaseRelation.scala:63)
    at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:46)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:70)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:68)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:86)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:80)
    at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:80)
    at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:654)
    at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:654)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:77)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:654)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:273)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:267)
    at SparkTest.bar(SparkTest.scala:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
    at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
    at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMethod(JUnit4ClassRunner.java:88)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:130)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.hbase.client.TableDescriptor
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 41 more
</code>```

答:
```<code>val sparkSession = SparkSession.builder
      .appName("SparkTest")
      .master("local[*]")
      .config("spark.testing.memory", 2147480000)
      .getOrCreate()
</code>```

means you are running that in local and your hbase client jar is missing. (if its there in classpath then you can change the scope to runtime rather than compile)

```<code><!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-client -->
<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-client</artifactId>
    <version>2.1.4</version>
</dependency>
</code>```

if you are using intellij to run locally, you can see hbase client jar is present in the .iml file.

normal way of runnning in cluster or client modes(not local)  would be hbase claasspath add it to

```  export HBASE_CLASSPATH=$HBASE_CLASSPATH:`hbase classpath` ```

which will add all the hbase jars in to the classpath

to see/print all the jars in classpath below will be helpful to understand which jars in your classpath.

```<code> def urlsinclasspath(cl: ClassLoader): Array[java.net.URL] = cl match {
    case null => Array()
    case u: java.net.URLClassLoader => u.getURLs() ++ urlsinclasspath(cl.getParent)
    case _ => urlsinclasspath(cl.getParent)
  }
</code>```

Caller would be...

```<code>  val  urls = urlsinclasspath(getClass.getClassLoader).foreach(println)
</code>```

Body:
I created a project on Apache Spark.

Version:

scala 2.11.8

apache spark 2.3.0

apache hbase 1.2.0

hortonworks shc 1.1.0.3.1.2.0-4 (the hortonworks connector)

I need to save a simple DataFrame in an HBase table. For this I started HBase 1.2.0 in Docker container (https://github.com/zhao-y/docker-hbase-pseudo) and created the following table:

$ hbase(main):002:0> create "table1", "cf1", "cf2", "cf3", "cf4", "cf5", "cf6", "cf7", "cf8"
$ 0 row (s) in 1.4440 seconds

To save a DataFrame in Hbase I use: https://github.com/hortonworks-spark/shc

I declared the catalog exactly as in the example

I created a catalog-based dataframe

I tried to save dataframe in hbase as in example:

dataFrame.write.options(
  Map(HBaseTableCatalog.tableCatalog -> catalog, HBaseTableCatalog.newTable -> "5"))
  .format("org.apache.spark.sql.execution.datasources.hbase")
  .save()

Code:

import org.apache.spark.sql.execution.datasources.hbase.HBaseTableCatalog
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.junit.Test

class SparkTest {
  case class HBaseRecord(
                          col0: String,
                          col1: Boolean,
                          col2: Double,
                          col3: Float,
                          col4: Int,
                          col5: Long,
                          col6: Short,
                          col7: String,
                          col8: Byte)

  object HBaseRecord {
    def apply(i: Int, t: String): HBaseRecord = {
      val s = s"""row${"%03d".format(i)}"""
      HBaseRecord(s,
        i % 2 == 0,
        i.toDouble,
        i.toFloat,
        i,
        i.toLong,
        i.toShort,
        s"String$i: $t",
        i.toByte)
    }
  }

  @Test
  def bar(): Unit = {
    val sparkSession = SparkSession.builder
      .appName("SparkTest")
      .master("local[*]")
      .config("spark.testing.memory", 2147480000)
      .getOrCreate()

    val data = (0 to 255).map { i => HBaseRecord(i, "extra") }

    val dataFrame = sparkSession.createDataFrame(data)
    dataFrame.show

    dataFrame.write.options(
      Map(HBaseTableCatalog.tableCatalog -> catalog, HBaseTableCatalog.newTable -> "5"))
      .format("org.apache.spark.sql.execution.datasources.hbase")
      .save()
  }
}

Error:

java.lang.NoClassDefFoundError: org/apache/hadoop/hbase/client/TableDescriptor

    at org.apache.spark.sql.execution.datasources.hbase.DefaultSource.createRelation(HBaseRelation.scala:63)
    at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:46)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:70)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:68)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:86)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:131)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:155)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:152)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:127)
    at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:80)
    at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:80)
    at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:654)
    at org.apache.spark.sql.DataFrameWriter$$anonfun$runCommand$1.apply(DataFrameWriter.scala:654)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:77)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:654)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:273)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:267)
    at SparkTest.bar(SparkTest.scala:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
    at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:98)
    at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
    at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
    at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMethod(JUnit4ClassRunner.java:88)
    at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
    at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
    at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
    at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:130)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.hbase.client.TableDescriptor
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 41 more

Body:
val sparkSession = SparkSession.builder
      .appName("SparkTest")
      .master("local[*]")
      .config("spark.testing.memory", 2147480000)
      .getOrCreate()

means you are running that in local and your hbase client jar is missing. (if its there in classpath then you can change the scope to runtime rather than compile)

<!-- https://mvnrepository.com/artifact/org.apache.hbase/hbase-client -->
<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-client</artifactId>
    <version>2.1.4</version>
</dependency>

if you are using intellij to run locally, you can see hbase client jar is present in the .iml file.

normal way of runnning in cluster or client modes(not local)  would be hbase claasspath add it to

  export HBASE_CLASSPATH=$HBASE_CLASSPATH:`hbase classpath`

which will add all the hbase jars in to the classpath

to see/print all the jars in classpath below will be helpful to understand which jars in your classpath.

 def urlsinclasspath(cl: ClassLoader): Array[java.net.URL] = cl match {
    case null => Array()
    case u: java.net.URLClassLoader => u.getURLs() ++ urlsinclasspath(cl.getParent)
    case _ => urlsinclasspath(cl.getParent)
  }

Caller would be...

  val  urls = urlsinclasspath(getClass.getClassLoader).foreach(println)


问:
How can I receive combinations of two/one finger and single/double taps in hammer.js
I'm attempting to receive three types of tap events using hammer.js

single tap with one finger

double tap with one finger

double tap with two fingers

How can I set this up correctly in hammer.js

Here is what I currently have:

```<code>  if (mc == null) {
    mc = new Hammer.Manager(el);
  }
  mc.set({ touchAction: "none" });
  //mc.get("swipe").set({direction: Hammer.DIRECTION_ALL, pointers: 2});'
  //mc.get('tap').set({enable: false});
  var singletap = new Hammer.Tap({
    event: "singletap",
    taps: 1,
    pointers: 1
  });

  var doubletap = new Hammer.Tap({
    event: "doubletap",
    taps: 2,
    pointers: 1
  });
  var twodoubletap = new Hammer.Tap({
    event: "twodoubletap",
    taps: 2,
    pointers: 2
  });

  mc.add([twodoubletap, doubletap,singletap]);//, twotap, threetap]);

  twodoubletap.recognizeWith([doubletap,singletap])
  doubletap.recognizeWith([singletap,twodoubletap])

  //doubletap.requireFailure(twodoubletap);

  singletap.requireFailure([doubletap,twodoubletap]);

  mc.on("twodoubletap doubletap singletap", binding.value);
</code>```

I can get a single tap to fire consistently and a one finger double tap sometimes.

The two-finger double tap either does not fire, or fires along with a one other taps following it immediately.

Ideally, I would like each type of tap to fire consistently.

答:
I was able to get this to work by doing three things.
1. I added dropRequireFailure to the two-fingerdouble tap for the other taps
2. I made the thresholds larger in the events.
3. I added a time-based filter in the event handler that rejects taps too close to each other. I know this isn't ideal but it works for now.

```<code>          if (mc == null) {
            mc = new Hammer.Manager(el);
          }
          mc.set({ touchAction: "none" });
          //mc.get("swipe").set({direction: Hammer.DIRECTION_ALL, pointers: 2});'
          //mc.get('tap').set({enable: false});
          var singletap = new Hammer.Tap({
            event: "singletap",
            taps: 1,
            pointers: 1,
            interval: 500,
            threshold: 200,
            posThreshold: 200
          });

          var doubletap = new Hammer.Tap({
            event: "doubletap",
            taps: 2,
            pointers: 1,
            interval: 300,
            threshold: 200,
            posThreshold: 200
          });
          var twodoubletap = new Hammer.Tap({
            event: "twodoubletap",
            taps: 2,
            pointers: 2,
            interval: 400,
            threshold: 500,
            posThreshold: 200
          });

          mc.add([twodoubletap, doubletap,singletap]);//, twotap, threetap]);

          twodoubletap.recognizeWith([doubletap,singletap])
          doubletap.recognizeWith([twodoubletap])

          doubletap.requireFailure(twodoubletap);
          singletap.requireFailure([doubletap,twodoubletap]);
          twodoubletap.dropRequireFailure(doubletap);
          twodoubletap.dropRequireFailure(singletap);

          mc.on("twodoubletap doubletap singletap", handler);
</code>```

Then at the top of the event handler:

```<code>      let now = Date.now();
      if((now - lastTap)<500){
        return;
      }
      lastTap = now;
</code>```

Body:
I'm attempting to receive three types of tap events using hammer.js

single tap with one finger

double tap with one finger

double tap with two fingers

How can I set this up correctly in hammer.js

Here is what I currently have:

  if (mc == null) {
    mc = new Hammer.Manager(el);
  }
  mc.set({ touchAction: "none" });
  //mc.get("swipe").set({direction: Hammer.DIRECTION_ALL, pointers: 2});'
  //mc.get('tap').set({enable: false});
  var singletap = new Hammer.Tap({
    event: "singletap",
    taps: 1,
    pointers: 1
  });

  var doubletap = new Hammer.Tap({
    event: "doubletap",
    taps: 2,
    pointers: 1
  });
  var twodoubletap = new Hammer.Tap({
    event: "twodoubletap",
    taps: 2,
    pointers: 2
  });

  mc.add([twodoubletap, doubletap,singletap]);//, twotap, threetap]);

  twodoubletap.recognizeWith([doubletap,singletap])
  doubletap.recognizeWith([singletap,twodoubletap])

  //doubletap.requireFailure(twodoubletap);

  singletap.requireFailure([doubletap,twodoubletap]);

  mc.on("twodoubletap doubletap singletap", binding.value);

I can get a single tap to fire consistently and a one finger double tap sometimes.

The two-finger double tap either does not fire, or fires along with a one other taps following it immediately.

Ideally, I would like each type of tap to fire consistently.

Body:
I was able to get this to work by doing three things.
1. I added dropRequireFailure to the two-fingerdouble tap for the other taps
2. I made the thresholds larger in the events.
3. I added a time-based filter in the event handler that rejects taps too close to each other. I know this isn't ideal but it works for now.

          if (mc == null) {
            mc = new Hammer.Manager(el);
          }
          mc.set({ touchAction: "none" });
          //mc.get("swipe").set({direction: Hammer.DIRECTION_ALL, pointers: 2});'
          //mc.get('tap').set({enable: false});
          var singletap = new Hammer.Tap({
            event: "singletap",
            taps: 1,
            pointers: 1,
            interval: 500,
            threshold: 200,
            posThreshold: 200
          });

          var doubletap = new Hammer.Tap({
            event: "doubletap",
            taps: 2,
            pointers: 1,
            interval: 300,
            threshold: 200,
            posThreshold: 200
          });
          var twodoubletap = new Hammer.Tap({
            event: "twodoubletap",
            taps: 2,
            pointers: 2,
            interval: 400,
            threshold: 500,
            posThreshold: 200
          });

          mc.add([twodoubletap, doubletap,singletap]);//, twotap, threetap]);

          twodoubletap.recognizeWith([doubletap,singletap])
          doubletap.recognizeWith([twodoubletap])

          doubletap.requireFailure(twodoubletap);
          singletap.requireFailure([doubletap,twodoubletap]);
          twodoubletap.dropRequireFailure(doubletap);
          twodoubletap.dropRequireFailure(singletap);

          mc.on("twodoubletap doubletap singletap", handler);

Then at the top of the event handler:

      let now = Date.now();
      if((now - lastTap)<500){
        return;
      }
      lastTap = now;


问:
diff() excluding the first row of each group
I am trying to get the difference between the consecutive values in a data frame (which I have already grouped). When I used the below code, all the first-row "Value" fields are changing to NAN's which I will be needing. I want to exclude the first row from the diff operation. Can somebody help me, please? </p>

```<code>SNo  Var %    Value
1000    0    1.2
1000    1    2.2
1000    2    3.2
1000    3    4.2
1000    4    5.2
1000    4    6.2
1000    5    7.2
1000    5    8.2
1001    0    0.5
1001    1    1.5
1001    2    2.5
1001    2    3.5
</code>```

```<code>x['value_diff'] = x.groupby('SNo').value.diff()
</code>```

```<code>SNo  Var %    Value
1000    0    NAN
1000    1    1
1000    2    1
1000    3    1
1000    4    1
1000    4    1
1000    5    1
1000    5    1
1001    0    NAN
1001    1    1
1001    2    1
1001    2    1
</code>```

答:
the first-row "Value" fields are changing to NAN's which I will be needing.

As mentioned in the comments, you need:

```<code>df.groupby('SNo').Value.diff().fillna(df.Value)
</code>```

This will fill the NaN in the same index from Value column

```<code>0     1.2
1     1.0
2     1.0
3     1.0
4     1.0
5     1.0
6     1.0
7     1.0
8     0.5
9     1.0
10    1.0
11    1.0
</code>```

Body:
I am trying to get the difference between the consecutive values in a data frame (which I have already grouped). When I used the below code, all the first-row "Value" fields are changing to NAN's which I will be needing. I want to exclude the first row from the diff operation. Can somebody help me, please?

SNo  Var %    Value
1000    0    1.2
1000    1    2.2
1000    2    3.2
1000    3    4.2
1000    4    5.2
1000    4    6.2
1000    5    7.2
1000    5    8.2
1001    0    0.5
1001    1    1.5
1001    2    2.5
1001    2    3.5

x['value_diff'] = x.groupby('SNo').value.diff()

SNo  Var %    Value
1000    0    NAN
1000    1    1
1000    2    1
1000    3    1
1000    4    1
1000    4    1
1000    5    1
1000    5    1
1001    0    NAN
1001    1    1
1001    2    1
1001    2    1

Body:
the first-row "Value" fields are changing to NAN's which I will be needing.

As mentioned in the comments, you need:

df.groupby('SNo').Value.diff().fillna(df.Value)

This will fill the NaN in the same index from Value column

0     1.2
1     1.0
2     1.0
3     1.0
4     1.0
5     1.0
6     1.0
7     1.0
8     0.5
9     1.0
10    1.0
11    1.0


问:
Is there a way to store a file in a React state?
I'm working on a project where I need to store an image in my components state, so that I can send the file and accompanying data to a different component that uploads the data to my Firebase Database and the image to my Firestore.

I've tried doing it by setting the state the normal way, using a functions that is called when an image is submitted. But the state in which I want to pass on the file remains empty.

The initial state:

```<code>state = {
    title: '',
    description: '',
    date: '',
    ticket: '',
    price: '',
    image: []
}
</code>```

The input:

```<code><input type="file" id="image" accept="image/*" onChange={this.handleChangeImage} />
</code>```

The function that is supposed to handle my problem:

```<code>handleChangeImage = (e) => {
    const file = e.target.files[0];
    this.setState({
        [e.target.id]: file
    });
}
</code>```

If I console log the variable "file" I get the file, but console logging state.image will just show me an empty array.

答:
This problem is now resolved. I am an idiot. My problem wasn't that the state wasn't updated with the file, the problem was that the console log output happened before the state was updated with the file.

The state was always updated with the file, I just never realised.

The issue was in other words not an issue, just a plain dumb rookie mistake.

Body:
I'm working on a project where I need to store an image in my components state, so that I can send the file and accompanying data to a different component that uploads the data to my Firebase Database and the image to my Firestore.

I've tried doing it by setting the state the normal way, using a functions that is called when an image is submitted. But the state in which I want to pass on the file remains empty.

The initial state:

state = {
    title: '',
    description: '',
    date: '',
    ticket: '',
    price: '',
    image: []
}

The input:

<input type="file" id="image" accept="image/*" onChange={this.handleChangeImage} />

The function that is supposed to handle my problem:

handleChangeImage = (e) => {
    const file = e.target.files[0];
    this.setState({
        [e.target.id]: file
    });
}

If I console log the variable "file" I get the file, but console logging state.image will just show me an empty array.


问:
How to get the count of elements in each unordered HTML list on a page with multiple lists present?
I can count the no of individual elements, particularly
 on a web page that I am trying to scrape .

But I want it to count
 elements for each
 on the page.

This is what I tried to count all
 on a page, a simple one

```<code>list = driver.find_elements_by_tag_name("li")
print(len(list))
</code>```

I have a page with lot of list like below, exactly the same class name, everything same except the text inside
 tags.

```<code><ul class="tags">
  <li class="tag"><a rel="tag" class="term" href="/site1">Flight</a></li>
  <li class="tag"><a rel="tag" class="term" href="/site2">Action</a></li>
  <li class="tag"><a rel="tag" class="term" href="/site3">Gravity</a></li>
</ul>
</code>```

I want to count number of elements inside each  tag on the page.

答:
Try the following code.It will first find all
 tag and then find linked
 tag

```<code> elements=driver.find_elements_by_tag_name('ul')
    #print(len(elements))
    for ele in elements:
        print(len(ele.find_elements_by_xpath("./li")))
</code>```

Output:

```<code>2
3
4
</code>```

Body:
I can count the no of individual elements, particularly
 on a web page that I am trying to scrape .

But I want it to count
 elements for each
 on the page.

This is what I tried to count all
 on a page, a simple one

list = driver.find_elements_by_tag_name("li")
print(len(list))

I have a page with lot of list like below, exactly the same class name, everything same except the text inside
 tags.

Flight

Action

Gravity

I want to count number of elements inside each  tag on the page.

Body:
Try the following code.It will first find all <ul> tag and then find linked <li> tag

 elements=driver.find_elements_by_tag_name('ul')
    #print(len(elements))
    for ele in elements:
        print(len(ele.find_elements_by_xpath("./li")))

Output:

2
3
4


问:
Kendo autocomplete truncates selected value

I am trying to use the Kendo autocomplete component and I keep getting this grey bar that obscures part of the answer when it is selected.

Does anyone know who to fix this issue?

See my code below:

```<code><link href="~/Scripts/Kendo/styles/kendo.common.min.css" rel="stylesheet" />
<link href="~/Scripts/Kendo/styles/kendo.bootstrap.min.css" rel="stylesheet" />

<script src="~/Scripts/Kendo/js/kendo.ui.core.min.js"></script>
<script src="~/Scripts/Kendo/js/kendo.combobox.min.js"></script>

<div class="k-content">
<input id="siteItem" placeholder="Select site..." style="width:100%"   />
</code>```

```<code>$.getJSON("/FormReport/GetSites/" + org + "/" + e.dataItem.Value,
        function (data) {

            $("#siteItem").kendoComboBox({
                autoWidth: true,

                dataTextField: "Text",
                dataValueField: "Value",
                dataSource: data,
                filter: "contains",
                suggest: true
            });
        });
</code>```

答: The fix to remove the issue was style="min-width=100%". The textbox started off on page load with no data attached to it and therefore wasn't actually using the correct width. When data was added later, it doesn't recompensate to the correct width. Using min-width makes the textbox draw correctly before data gets attached dynamically and therefore removes the phantom grey box (which I believe is the X or clear button).</p>

Body:
I am trying to use the Kendo autocomplete component and I keep getting this grey bar that obscures part of the answer when it is selected.

Does anyone know who to fix this issue?

See my code below:

<link href="~/Scripts/Kendo/styles/kendo.common.min.css" rel="stylesheet" />
<link href="~/Scripts/Kendo/styles/kendo.bootstrap.min.css" rel="stylesheet" />

<input id="siteItem" placeholder="Select site..." style="width:100%"   />

$.getJSON("/FormReport/GetSites/" + org + "/" + e.dataItem.Value,
        function (data) {

            $("#siteItem").kendoComboBox({
                autoWidth: true,

                dataTextField: "Text",
                dataValueField: "Value",
                dataSource: data,
                filter: "contains",
                suggest: true
            });
        });


问:
How to pass data from one class to another in flutter?
I am passing some data from one class to another. I have a button which upon being tapped passed the data to another stateful class without Route or Navigator.

How to pass the data 'onTap' of button from one class to another in flutter ???

Thanks in Advance.

This is link where is whole code: https://dpaste.de/mfyz#L456

i have this button on stateful class, i want to pass a flag ontap of this button.

```<code> new Expanded(child: Center(
                            child: !_canShowButton ? new MaterialButton(onPressed: (){
                              TabApp tab= new TabApp(valueReview);

                            },
                              child: new Text("Review For Submit",style: TextStyle(
                                  fontSize: 21.0,
                                  fontWeight: FontWeight.bold
                              ),),
                              color: Colors.greenAccent,
                              height: 43.0,
                              textColor: Colors.blue,
                              splashColor: Colors.red,):SizedBox()
                          )),
</code>```

i have this stateful class where i wants a flag to pass:

```<code>class TabApp extends StatefulWidget {

   TabApp(int valueReview);

  @override
  _TabAppState createState() => _TabAppState();
  }

  class _TabAppState extends State<TabApp> with TickerProviderStateMixin{

   }
</code>```

答:
To pass data between classes like the way it seems you're trying to do you should look into architectural patterns such as BLoC or ScopedModel (or one of the many other options available). ScopedModel is pretty simple and straightforward.  If you want to use the standard library and not involve another package then you could use a plain vanilla InheritedWidget. Personally I'd recommend ScopedModel since it's really simple. If you do end up passing data between routes later on then be sure you place the model above the MaterialApp widget (or CupertinoApp).

```<code>class TabApp extends StatefulWidget {

   TabApp(int valueReview);

   final int valueReview;

  @override
  _TabAppState createState() => _TabAppState();
  }

  class _TabAppState extends State<TabApp> with TickerProviderStateMixin{

   }
</code>```

Then call your variable in the State by using widget.valueReview

Body:
I am passing some data from one class to another. I have a button which upon being tapped passed the data to another stateful class without Route or Navigator.

How to pass the data 'onTap' of button from one class to another in flutter ???

Thanks in Advance.

This is link where is whole code: https://dpaste.de/mfyz#L456

i have this button on stateful class, i want to pass a flag ontap of this button.

 new Expanded(child: Center(
                            child: !_canShowButton ? new MaterialButton(onPressed: (){
                              TabApp tab= new TabApp(valueReview);

                            },
                              child: new Text("Review For Submit",style: TextStyle(
                                  fontSize: 21.0,
                                  fontWeight: FontWeight.bold
                              ),),
                              color: Colors.greenAccent,
                              height: 43.0,
                              textColor: Colors.blue,
                              splashColor: Colors.red,):SizedBox()
                          )),

i have this stateful class where i wants a flag to pass:

class TabApp extends StatefulWidget {

   TabApp(int valueReview);

  @override
  _TabAppState createState() => _TabAppState();
  }

  class _TabAppState extends State<TabApp> with TickerProviderStateMixin{

   }

Body:
To pass data between classes like the way it seems you're trying to do you should look into architectural patterns such as BLoC or ScopedModel (or one of the many other options available). ScopedModel is pretty simple and straightforward.  If you want to use the standard library and not involve another package then you could use a plain vanilla InheritedWidget. Personally I'd recommend ScopedModel since it's really simple. If you do end up passing data between routes later on then be sure you place the model above the MaterialApp widget (or CupertinoApp).

class TabApp extends StatefulWidget {

   TabApp(int valueReview);

   final int valueReview;

  @override
  _TabAppState createState() => _TabAppState();
  }

  class _TabAppState extends State<TabApp> with TickerProviderStateMixin{

   }

Then call your variable in the State by using widget.valueReview


问:
CodeIgniter cannot use session data after redirect()
I was trying to build an application but I faced a problem with the session data. So I downloaded a new fresh CodeIgniter project and tried to work with the session but still failed. Here's what I did:

application/config/autoload.php:

$autoload['libraries'] = array('session');

$autoload['helper'] = array('url');
```

<p><strong>application/config/config.php:</strong></p>

<pre class="lang-php prettyprint-override"><code>$config['sess_save_path'] = 'D:\Projects\CodeIgnter-fresh\application\cache\session';
</code>```

After that I created a controller called User.php

User.php

<?php

class User extends CI_Controller {

    public function index() {
        $this->session->set_userdata('somedata', 'somevalue');
        redirect('user/dashboard', 'refresh');
    }

    public function dashboard() {
        var_dump($this->session->userdata);
    }
}
```

The controller contains two simple methods. The index method sets some user data and after that redirects to the other method, which dumps the userdata. Unfortunately here's what I see:

It seems the only data I am able to see is some CodeIgniter data, but for sure the data I am trying to set is gone. Interesting thing I noticed was that in application/cache/session folder I can see some files with my data in it. So I guess it has to be some permission problem, but I cannot figure it out. Any suggestions?

I'm using:

OS: Windows 10 Education

PHP version: 7.2.11

CodeIgniter version: 3.1.10

答:
I see 2 issues in this question:

not being able to write the session information to the disk using CI
file driver

and

not being able to retrieve the session information

1. write the session information to the disk

The config.php at around line 344 says

'sess_save_path'

The location to save sessions to, driver dependent.

For the 'files' driver, it's a path to a writable directory.
    WARNING: Only absolute paths are supported!

IMPORTANT: You are REQUIRED to set a valid save path!

Therefore you need to set it either to false (nothing is saved) or use an absolute path. In order to make this work for development and production alike, you can use the PHP $_SERVER array and use it in your config.php like:

```<code>$config['sess_save_path'] = $_SERVER['DOCUMENT_ROOT'].'/application/cache/session/';
</code>```

finally you need to make sure, that above directory is writable, but only you have access to that directory (on production server).

P.S.: you see what's in $_SERVER using this line:

```<code><?php echo'```';print_r($_SERVER); ?>
```

<p><strong>2. retrieve the session information</strong></p>

<ul>
<li>make sure that you don't destroy the session in a previous function</li>
<li>keep in mind changing $config['cookie_domain'], $config['cookie_path'],
$config['cookie_secure'] can affect sessions:</li>
</ul>

<p>this setting works on my setup:</p>

```$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = $_SERVER['DOCUMENT_ROOT'].'/application/cache/session/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

$config['cookie_prefix']    = '';
$config['cookie_domain']    = '';
$config['cookie_path']      = '/';
$config['cookie_secure']    = FALSE;
$config['cookie_httponly']  = FALSE;
```

<p>If none of this works, you can still try to override autoload, putting this constructor into your <code>User</code> controller:</p>

```public function __construct(){
  parent::__construct();
  $this->load->library('session');
}
```

Body:
I was trying to build an application but I faced a problem with the session data. So I downloaded a new fresh CodeIgniter project and tried to work with the session but still failed. Here's what I did:

application/config/autoload.php:

$autoload['libraries'] = array('session');

$autoload['helper'] = array('url');

application/config/config.php:

$config['sess_save_path'] = 'D:\Projects\CodeIgnter-fresh\application\cache\session';

After that I created a controller called User.php

User.php

<?php

class User extends CI_Controller {

    public function index() {
        $this->session->set_userdata('somedata', 'somevalue');
        redirect('user/dashboard', 'refresh');
    }

    public function dashboard() {
        var_dump($this->session->userdata);
    }
}

The controller contains two simple methods. The index method sets some user data and after that redirects to the other method, which dumps the userdata. Unfortunately here's what I see:

It seems the only data I am able to see is some CodeIgniter data, but for sure the data I am trying to set is gone. Interesting thing I noticed was that in application/cache/session folder I can see some files with my data in it. So I guess it has to be some permission problem, but I cannot figure it out. Any suggestions?

I'm using:

OS: Windows 10 Education

PHP version: 7.2.11

CodeIgniter version: 3.1.10

Body:
I see 2 issues in this question:

not being able to write the session information to the disk using CI
file driver

and

not being able to retrieve the session information

1. write the session information to the disk

The config.php at around line 344 says

'sess_save_path'

The location to save sessions to, driver dependent.

For the 'files' driver, it's a path to a writable directory.
    WARNING: Only absolute paths are supported!

IMPORTANT: You are REQUIRED to set a valid save path!

Therefore you need to set it either to false (nothing is saved) or use an absolute path. In order to make this work for development and production alike, you can use the PHP $_SERVER array and use it in your config.php like:

$config['sess_save_path'] = $_SERVER['DOCUMENT_ROOT'].'/application/cache/session/';

finally you need to make sure, that above directory is writable, but only you have access to that directory (on production server).

P.S.: you see what's in $_SERVER using this line:

<?php echo'<pre>';print_r($_SERVER); ?>

2. retrieve the session information

make sure that you don't destroy the session in a previous function

keep in mind changing $config['cookie_domain'], $config['cookie_path'],
$config['cookie_secure'] can affect sessions:

this setting works on my setup:

$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = $_SERVER['DOCUMENT_ROOT'].'/application/cache/session/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

$config['cookie_prefix']    = '';
$config['cookie_domain']    = '';
$config['cookie_path']      = '/';
$config['cookie_secure']    = FALSE;
$config['cookie_httponly']  = FALSE;

If none of this works, you can still try to override autoload, putting this constructor into your User controller:

public function __construct(){
  parent::__construct();
  $this->load->library('session');
}


问:
How to make Dllimport correctly in c#?
ive had some problems building a correct .dll from a c++-project to my c#-project.
I played around with the c++-project-properties and got a .dll file which i can add and refer to in my c# web-project. I use Dllimport to make a function call to the .dll like this:

```<code>[DllImport("Filename.dll", CharSet = CharSet.Ansi)]
static extern void Function1([MarshalAs(UnmanagedType.LPStr)] string src,
                             int srcLen,
                             [MarshalAs(UnmanagedType.LPWStr)] StringBuilder dst,
                             int dstLen)
</code>```

The c++ function header is:

```<code>__declspec(dllimport) void Function1(unsigned char *src,
                     unsigned long srclen,
                     unsigned char *dst,
                     unsigned long dstlen);
</code>```

Im calling Function1 in c# with this:

```<code>string strSrc = "Something";
StringBuilder strDest = new StringBuilder(kryptlen-1);
int l = strSrc.Length();
Function1(strSrc, l, strDest, l);
</code>```

No exceptions or errors are occuring, though im not getting the output im expecting. The function is a decrypting method that takes an encrypted string(src) and returns the decrypted version of this (dst).

Is it the way ive generated the .dll file or is it the wrong way im calling the function? Im running out of ideas ive tried most combinations.

Thanks in advice!

答:
C++ by default unless changed uses a caller( Cdecl ) calling convention.  Your C++ code does not change the calling convention.  Your C# code by default ( unless you change it ) will use a callee convention ( StdCall ).

While this might not be exactly the problem your having it still is technically incorrect.  Even if you were to fix your current problem you likely will end up having a problem because of the calling convention.

No exceptions or errors are occuring,
  though im not getting the output im
  expecting. The function is a
  decrypting method that takes an
  encrypted string(src) and returns the
  decrypted version of this (dst).

What exactly are you getting?

The solution to the calling convention problem is to declare the calling convention.

```<code>[DllImport("Filename.dll", CharSet = CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] static extern void Function1([MarshalAs(UnmanagedType.LPStr)] string src,                               int srcLen,                               [MarshalAs(UnmanagedType.LPWStr)] StringBuilder dst,                              int dstLen)
</code>```

Title: How to make Dllimport correctly in c#?

Body:
ive had some problems building a correct .dll from a c++-project to my c#-project.
I played around with the c++-project-properties and got a .dll file which i can add and refer to in my c# web-project. I use Dllimport to make a function call to the .dll like this:

[DllImport("Filename.dll", CharSet = CharSet.Ansi)]
static extern void Function1([MarshalAs(UnmanagedType.LPStr)] string src,
                             int srcLen,
                             [MarshalAs(UnmanagedType.LPWStr)] StringBuilder dst,
                             int dstLen)

The c++ function header is:

__declspec(dllimport) void Function1(unsigned char *src,
                     unsigned long srclen,
                     unsigned char *dst,
                     unsigned long dstlen);

Im calling Function1 in c# with this:

string strSrc = "Something";
StringBuilder strDest = new StringBuilder(kryptlen-1);
int l = strSrc.Length();
Function1(strSrc, l, strDest, l);

No exceptions or errors are occuring, though im not getting the output im expecting. The function is a decrypting method that takes an encrypted string(src) and returns the decrypted version of this (dst).

Is it the way ive generated the .dll file or is it the wrong way im calling the function? Im running out of ideas ive tried most combinations.

Thanks in advice!

Body:
C++ by default unless changed uses a caller( Cdecl ) calling convention.  Your C++ code does not change the calling convention.  Your C# code by default ( unless you change it ) will use a callee convention ( StdCall ).

While this might not be exactly the problem your having it still is technically incorrect.  Even if you were to fix your current problem you likely will end up having a problem because of the calling convention.

No exceptions or errors are occuring,
  though im not getting the output im
  expecting. The function is a
  decrypting method that takes an
  encrypted string(src) and returns the
  decrypted version of this (dst).

What exactly are you getting?

The solution to the calling convention problem is to declare the calling convention.

[DllImport("Filename.dll", CharSet = CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)] static extern void Function1([MarshalAs(UnmanagedType.LPStr)] string src,                               int srcLen,                               [MarshalAs(UnmanagedType.LPWStr)] StringBuilder dst,                              int dstLen)


问:
RegEx for quantifying and finding a character
Considering a string with 12 characters, I want to split the string in three groups of four characters and find a character in group 1 and 3.

For example:

```<code>AAAABBBBAAAA  -> B not found (they are in group 2)
ABAABBBBAAAA  -> B found in the first 4 characters (group 1)
AAAABBBBABAA  -> B found in the last 4 characteres (group 2)
</code>```

I only managed to create group 1 and 3, but I don't know how to find the 'B' on them:

```<code>(^.{0,4})|(.{0,4}$)
</code>```

Thanks

Body:
Considering a string with 12 characters, I want to split the string in three groups of four characters and find a character in group 1 and 3.

For example:

AAAABBBBAAAA  -> B not found (they are in group 2)
ABAABBBBAAAA  -> B found in the first 4 characters (group 1)
AAAABBBBABAA  -> B found in the last 4 characteres (group 2)

I only managed to create group 1 and 3, but I don't know how to find the 'B' on them:

(^.{0,4})|(.{0,4}$)

Thanks

Body:
You could try this. This finds a 'B' in any group of 4.

Perl version:

^(?:(?=.{0,3}(B))?....)(?:(?=.{0,3}(B))?....)(?:(?=.{0,3}(B))?....)$

PCRE version:

^(?:(?:(?=.{0,3}(B)))?....)(?:(?:(?=.{0,3}(B)))?....)(?:(?:(?=.{0,3}(B)))?....)$

https://regex101.com/r/yV72s2/1

Explained

 ^
 (?:
      (?=
           .{0,3}
           ( B )                         # (1), B in first group of 4
      )?
      . . . .
 )

 (?:
      (?=
           .{0,3}
           ( B )                         # (2), B in second group of 4
      )?
      . . . .
 )

 (?:
      (?=
           .{0,3}
           ( B )                         # (3), B in third group of 4
      )?
      . . . .
 )
 $

If you just want to find out if a 'B' matches in the first or last 4, it would be this

(?:^(?=.{12}$)(?:(?=.{0,3}?(B))....)|(?<=^.{8})(?:(?=.{0,3}?(B))....)$)

https://regex101.com/r/wEdTCU/1

Explained

 (?:
      ^
      (?= .{12} $ )
      (?:
           (?=
                .{0,3}?
                ( B )                         # (1), B in first group of 4
           )
           . . . .
      )
   |
      (?<= ^ .{8} )
      (?:
           (?=
                .{0,3}?
                ( B )                         # (2), B in third group of 4
           )
           . . . .
      )
      $
 )


问:
How can I write a python code for this question?
A snail falls at the bottom of a 125 cm well. Each day the snail rises 30 cm. But at night, while sleeping, slides 20 cm because the walls are wet. How many days does it take to escape from the well?</p>

答:
```<code>well = 125
cmPerDay = 30
cmPerNight = -20
snailHasNotEscaped = True
days = 0
totalCMs = 0

cmPerWholeDay = cmPerDay + cmPerNight

while snailHasNotEscaped:
   totalCMs += cmPerWholeDay
   days += 1
   print(days)
   if totalCMs >= well:
      snailHasNotEscaped = False

print("Congratulations! the snail escaped in", days, "days")

</code>```