问:
Swap Characters Using Command Prompt
Trying to write a program called SwapChars.java using command line arguments that allows any two characters to be swapped. For example if the program was called SwapChars then to swap all ‘a’s and ‘b’s in a file test.txt we would type

```<code>java SwapChars test.txt ab
</code>```

I typed the following code which kept giving me an exception error and I'm not sure where I'm going wrong...

```<code>import java.util.*;
import java.io.*;
public class SwapChars {

    public static void main(String[] args) throws IOException {
        String a = args[0]; //file name (test.txt entered into command line)
        FileReader fr = new FileReader(a);
        String b = args[1];//which characters to swap
        int t = fr.read();
        while(t!=-1)
        {
            if(t==b.charAt(0))
            {
                System.out.println(b.charAt(1));
            }
            else if(t==b.charAt(1))
            {
                System.out.println(b.charAt(0));
            }
            else
            {
                System.out.println((char)t);
            }
                    t=fr.read();
        }
        // TODO Auto-generated method stub

    }

}
</code>```

Exception error as follows:

```<code>Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at SwapChars.main(SwapChars.java:7)
</code>```

I can get the desired output when I change my code to remove the need for commands as follows:

```<code>import java.util.*;
import java.io.*;
public class SwapCharsTest {

public static void main(String[] args) throws IOException{
    FileReader fr = new FileReader("test.txt");
    String swap = "ab";
    int t = fr.read();
    while(t!=-1)
    {
        if(t==swap.charAt(0))
        {
            System.out.print(swap.charAt(1));
        }
        else if(t==swap.charAt(1))
        {
            System.out.print(swap.charAt(0));
        }
        else
        {
            System.out.print((char)t);
        }
        t=fr.read();
    }
    // TODO Auto-generated method stub

}

}
</code>```

答:
The exception is because the file cannot be found. Try to refer to the file with a full path.

Also, when the file is found, your program will loop forever. And the printout can easily be improved. Make these two changes:

```<code>        else
        {
            System.out.println((char) t);
        }
        t = fr.read();
    }
</code>```

(t = fr.read(); reads a new char for every loop, (char) casts the integer so it looks better on screen)

If you don't want to use a full path, you need to figure out where Java will look for the file. This will (most likely) show you where to put the file:

```<code>System.out.println(new File("dummy").getAbsolutePath());
</code>```

Title: Swap Characters Using Command Prompt

Body:
Trying to write a program called SwapChars.java using command line arguments that allows any two characters to be swapped. For example if the program was called SwapChars then to swap all ‘a’s and ‘b’s in a file test.txt we would type

java SwapChars test.txt ab

I typed the following code which kept giving me an exception error and I'm not sure where I'm going wrong...

import java.util.*;
import java.io.*;
public class SwapChars {

    public static void main(String[] args) throws IOException {
        String a = args[0]; //file name (test.txt entered into command line)
        FileReader fr = new FileReader(a);
        String b = args[1];//which characters to swap
        int t = fr.read();
        while(t!=-1)
        {
            if(t==b.charAt(0))
            {
                System.out.println(b.charAt(1));
            }
            else if(t==b.charAt(1))
            {
                System.out.println(b.charAt(0));
            }
            else
            {
                System.out.println((char)t);
            }
                    t=fr.read();
        }
        // TODO Auto-generated method stub

    }

}

Exception error as follows:

Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at SwapChars.main(SwapChars.java:7)

I can get the desired output when I change my code to remove the need for commands as follows:

import java.util.*;
import java.io.*;
public class SwapCharsTest {

public static void main(String[] args) throws IOException{
    FileReader fr = new FileReader("test.txt");
    String swap = "ab";
    int t = fr.read();
    while(t!=-1)
    {
        if(t==swap.charAt(0))
        {
            System.out.print(swap.charAt(1));
        }
        else if(t==swap.charAt(1))
        {
            System.out.print(swap.charAt(0));
        }
        else
        {
            System.out.print((char)t);
        }
        t=fr.read();
    }
    // TODO Auto-generated method stub

}

}

Body:
The exception is because the file cannot be found. Try to refer to the file with a full path.

Also, when the file is found, your program will loop forever. And the printout can easily be improved. Make these two changes:

        else
        {
            System.out.println((char) t);
        }
        t = fr.read();
    }

(t = fr.read(); reads a new char for every loop, (char) casts the integer so it looks better on screen)

If you don't want to use a full path, you need to figure out where Java will look for the file. This will (most likely) show you where to put the file:

System.out.println(new File("dummy").getAbsolutePath());


来源: stackexchange

问:
GitLab Two Factor Authentication: ArgumentError (must specify a key)
I'm running GitLab 10.2.2 and Two Factor Authentication (2FA) doesn't work at all. I shortly migrated and upgraded the GitLab instance. I just copied the old config/secrets.yml with the base key to its place. But even if I don't I should be able to activate 2FA.

When I try to activate 2FA, the logs says:

```<code>==> production.log <==
Started GET "/profile/two_factor_auth" for 87.138.100.36 at 2017-11-29 16:52:59 +0100
Processing by Profiles::TwoFactorAuthsController#show as HTML
Completed 500 Internal Server Error in 191ms (ActiveRecord: 4.1ms)

ArgumentError (must specify a key):
  app/controllers/profiles/two_factor_auths_controller.rb:6:in `show'
  lib/gitlab/i18n.rb:47:in `with_locale'
  lib/gitlab/i18n.rb:53:in `with_user_locale'
  app/controllers/application_controller.rb:340:in `set_locale'
  lib/gitlab/middleware/multipart.rb:93:in `call'
  lib/gitlab/request_profiler/middleware.rb:14:in `call'
  lib/gitlab/middleware/go.rb:18:in `call'
  lib/gitlab/etag_caching/middleware.rb:11:in `call'
  lib/gitlab/middleware/read_only.rb:31:in `call'
  lib/gitlab/request_context.rb:18:in `call'
  lib/gitlab/metrics/requests_rack_middleware.rb:27:in `call'
</code>```

Another user with already enabled 2FA can't login anymore with nearly the same error.

Does someone know how to fix it?

答:
The solution was not that obvious. I updated libssl and libssl-dev to 1.1.0 (by sury). I uninstalled all Gems and reinstalled them. Some parts getting compiled again against the new libssl. And after that 2FA worked without an error.

# add sury APT repo
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

# update libssl
sudo apt-get install libssl libssl-dev

# uninstall all Gems
# https://stackoverflow.com/a/21385516/3898725
bundle list | ruby -e 'ARGF.readlines[1..-1].each {|l| g = l.split(" ");  puts "Removing #{g[1]}"; `gem uninstall --force #{g[1]} -v #{g[2].gsub(/\(|\)/, "")}`; }'

# reinstall all gems (with MySQL)
sudo -u git -H bundle install --without postgres development test --deployment
```

ContentLicense: CC BY-SA 3.0

Body:
I'm running GitLab 10.2.2 and Two Factor Authentication (2FA) doesn't work at all. I shortly migrated and upgraded the GitLab instance. I just copied the old config/secrets.yml with the base key to its place. But even if I don't I should be able to activate 2FA.

When I try to activate 2FA, the logs says:

==> production.log <==
Started GET "/profile/two_factor_auth" for 87.138.100.36 at 2017-11-29 16:52:59 +0100
Processing by Profiles::TwoFactorAuthsController#show as HTML
Completed 500 Internal Server Error in 191ms (ActiveRecord: 4.1ms)

ArgumentError (must specify a key):
  app/controllers/profiles/two_factor_auths_controller.rb:6:in `show'
  lib/gitlab/i18n.rb:47:in `with_locale'
  lib/gitlab/i18n.rb:53:in `with_user_locale'
  app/controllers/application_controller.rb:340:in `set_locale'
  lib/gitlab/middleware/multipart.rb:93:in `call'
  lib/gitlab/request_profiler/middleware.rb:14:in `call'
  lib/gitlab/middleware/go.rb:18:in `call'
  lib/gitlab/etag_caching/middleware.rb:11:in `call'
  lib/gitlab/middleware/read_only.rb:31:in `call'
  lib/gitlab/request_context.rb:18:in `call'
  lib/gitlab/metrics/requests_rack_middleware.rb:27:in `call'

Another user with already enabled 2FA can't login anymore with nearly the same error.

Does someone know how to fix it?


问:
how to specify an image path when the file name is in the redux store
Hi I have a react/redux app built on create-react-app (so no webpack, sigh, i cld eject i guess wldnt be a big deal) with image file names in the redux store. In order to render the images I have to provide a path to them. This bit of code is the only thing that's worked so far <img src={require(`../../assets/${avatar}`)} /> but it seems hacky to put a require statement in the render function. Also I can't figure out how to test it (how do i get a jest/enzyme test to pass this require statement containing a path and a prop). My app currently has no routing but I will eventually add some so if I could use react-router to solve this problem then I will. The relevant code looks like:

The module

```<code>import React from 'react'
import PropTypes from 'prop-types'

const UserProfile = ({name='', avatar=''}) => {

    return (
        <section className='bg-bright padding-m'>
            <img alt='avatar' src={require(`../../assets/${avatar}`)} />
            {name}
        </section>
    )

}

UserProfile.propTypes = {
    name: PropTypes.string,
    avatar: PropTypes.string
}

export default UserProfile
</code>```

The redux store data it's using looks something like

```<code>{
    "name": "a name",
    "avatar": "name.jpg"
  }
</code>```

The line in question renders as

```<code><img alt="avatar" src="/static/media/admin.34e378b0.jpg">
</code>```

Thx!

答:
seems hacky to put a require statement in the render function

Of course, provided code works properly only because appropriate webpack plugin is enabled, and loader like image-loader is provided.

When some relative path is provided, webpack performs including all root directory in target dist build, and then in runtime performs variable reading and fetching resource from dist build https://webpack.js.org/api/module-methods/#require-context

If you want, just reconfigure webpack-config in part of media resolver: https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/config/webpack.config.dev.js#L157

Body:
Hi I have a react/redux app built on create-react-app (so no webpack, sigh, i cld eject i guess wldnt be a big deal) with image file names in the redux store. In order to render the images I have to provide a path to them. This bit of code is the only thing that's worked so far <img src={require(`../../assets/${avatar}`)} /> but it seems hacky to put a require statement in the render function. Also I can't figure out how to test it (how do i get a jest/enzyme test to pass this require statement containing a path and a prop). My app currently has no routing but I will eventually add some so if I could use react-router to solve this problem then I will. The relevant code looks like:

The module

import React from 'react'
import PropTypes from 'prop-types'

const UserProfile = ({name='', avatar=''}) => {

    return (

            <img alt='avatar' src={require(`../../assets/${avatar}`)} />
            {name}

    )

}

UserProfile.propTypes = {
    name: PropTypes.string,
    avatar: PropTypes.string
}

export default UserProfile

The redux store data it's using looks something like

{
    "name": "a name",
    "avatar": "name.jpg"
  }

The line in question renders as

Thx!


问:
Use resource file in XAML file (Xamarin)
How to use resource files in XAML (xamarin forms) like ?

答:
There is a nice article here covering this topic. It includes lot of examples.

After you implement your TranslateExtension your code will look like this:

```<code><Label x:Name="lblName" Text="{local:TranslateExtension MyString}" />
</code>```

Body:
There is a nice article here covering this topic. It includes lot of examples.

After you implement your TranslateExtension your code will look like this:

<Label x:Name="lblName" Text="{local:TranslateExtension MyString}" />


问:
'pathExtension' is unavailable: Use pathExtension on URL instead
This code gives an error 'pathExtension' is unavailable: Use pathExtension on URL instead:</p>

```<code>if originalAudioFormat == "MP2" || originalAudioFormat == "BWFMP2" {
                    SourceFileNameWithPath = decodeMp2ToWav()

                        if SourceFileNameWithPath.pathExtension != "wav" { //error at this line
                            print("save File as PCM Fehler: \(SourceFileNameWithPath)")
                            return
                            }
</code>```

答:
Basically it's highly recommended to prefer always URLs to String paths.

Alternatively you can bridge the string to NSString

```<code>(SourceFileNameWithPath as NSString).pathExtension
</code>```

Please conform to the naming convention that variable names start with a lowercase letter.

Body:
This code gives an error 'pathExtension' is unavailable: Use pathExtension on URL instead:

if originalAudioFormat == "MP2" || originalAudioFormat == "BWFMP2" {
                    SourceFileNameWithPath = decodeMp2ToWav()

                        if SourceFileNameWithPath.pathExtension != "wav" { //error at this line
                            print("save File as PCM Fehler: \(SourceFileNameWithPath)")
                            return
                            }

Body:
Basically it's highly recommended to prefer always URLs to String paths.

Alternatively you can bridge the string to NSString

(SourceFileNameWithPath as NSString).pathExtension

Please conform to the naming convention that variable names start with a lowercase letter.


问:
Horizontal FlatList React Native with different height of items

I have a little problem with the FlatList Component in react native. In the FlatList are items with different height. Here is a little example of what i have:

example FlatL

The first problem is that all items are positioned at the top. I want to position all items at the bottom.

The second problem is that the height of the FlatList is always the height of the biggest item. So you can also scroll to another item in the white area of a small item...

here my code:

```<code>    import React from "react";
import {
    Text,
    View,
    Dimensions,
    StyleSheet,
    ListView,
    TouchableOpacity,
    Animated,
    Image,
    FlatList
} from "react-native";

import glamorous, { ThemeProvider } from "glamorous-native";

import theme from "../theme";

const { height, width } = Dimensions.get("window");

const cards = [
    {
        id: 1,
        color: "red",
        height: 400
    },
    {
        id: 2,
        color: "blue",
        height: 300
    },
    {
        id: 3,
        color: "yellow",
        height: 200
    }
];

class Test extends React.Component {
    render() {
        return (
            <View style={{ bottom: 0 }}>
                <FlatList
                    ref={elm => (this.flatList = elm)}
                    showsHorizontalScrollIndicator={false}
                    data={cards}
                    pagingEnabled={true}
                    horizontal={true}
                    keyExtractor={item => item.id}
                    renderItem={({ item }) => (
                        <View
                            style={{
                                height: item.height,
                                width: width,
                                backgroundColor: item.color
                            }}
                        />
                    )}
                />
            </View>
        );
    }
}

export default Test;
</code>```

Has anyone a solution?

答: You can change the position of each item by setting the contentContainerStyle property of the FlatList itself. But the height of the FlatList will always have to be the height of the largest component inside it.

Body:
I have a little problem with the FlatList Component in react native. In the FlatList are items with different height. Here is a little example of what i have:

example FlatL

The first problem is that all items are positioned at the top. I want to position all items at the bottom.

The second problem is that the height of the FlatList is always the height of the biggest item. So you can also scroll to another item in the white area of a small item...

here my code:

    import React from "react";
import {
    Text,
    View,
    Dimensions,
    StyleSheet,
    ListView,
    TouchableOpacity,
    Animated,
    Image,
    FlatList
} from "react-native";

import glamorous, { ThemeProvider } from "glamorous-native";

import theme from "../theme";

const { height, width } = Dimensions.get("window");

const cards = [
    {
        id: 1,
        color: "red",
        height: 400
    },
    {
        id: 2,
        color: "blue",
        height: 300
    },
    {
        id: 3,
        color: "yellow",
        height: 200
    }
];

class Test extends React.Component {
    render() {
        return (
            <View style={{ bottom: 0 }}>
                <FlatList
                    ref={elm => (this.flatList = elm)}
                    showsHorizontalScrollIndicator={false}
                    data={cards}
                    pagingEnabled={true}
                    horizontal={true}
                    keyExtractor={item => item.id}
                    renderItem={({ item }) => (
                        <View
                            style={{
                                height: item.height,
                                width: width,
                                backgroundColor: item.color
                            }}
                        />
                    )}
                />
            </View>
        );
    }
}

export default Test;

Has anyone a solution?


问:
how to insert values in to a multi dimensional cell array in matlab?
I have a cell array defined as A = cell(i,8);

say i = 4. now i am trying to fill up the 4 x 8 cell array with a function present inside the loop.

Say,

```<code>A = cell(i,8);
for index=1:8
A{i,index} = zeros(C{i}, D{i}, E{i});
end
</code>```

where, the values of C{i}, D{i}, E{i} are

```<code>C{i} = [10]    [10]    [10]    [10]
D{I} = [13]    [13]    [13]    [13]
E{I} = [62]    [91]    [71]    [89]
</code>```

And the contents of the cell are obviously zeros, since i used zeros() but i need this step for some further processing.

Now, i should get the Value of A(Cell array) - 4 x 8 Dimension like below,

```<code>10x13x62 double10x13x62 double  10x13x62 double 10x13x62 double 10x13x62 double 10x13x62 double 10x13x62 double 10x13x62 double
10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double
10x13x71 double 10x13x71 double 10x13x71 double 10x13x71 double 10x13x71 double 10x13x71 double 10x13x71 double 10x13x71 double
10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double
</code>```

Instead i am getting the output like,

```<code>[]  []  []  []  []  []  []  []
[]  []  []  []  []  []  []  []
[]  []  []  []  []  []  []  []
10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double
</code>```

I hope I am missing some simple logic behind the loop and the Cell array, is my initialization of the cell array and the loop is correct? if not, please suggest me to find a solution like i mentioned above.

Thanks.

答:
Firs thing A{i,index} = zeros(C{i}, D{i}, E{i}); not correct since zero() not accept array as paramerts.

This code will solve your problem

```<code>i=4;
A = cell(i,8);

C{i} = {10,10,10,10};
D{i} = {[13]    [13]    [13]    [13]};
E{i} = {[62]    [91]    [71]    [89]};
for j=1:8
 for index=1:4
    A{index,j} = zeros(cell2mat(C{i}(index)), cell2mat(D{i}(index)), cell2mat(E{i}(index)));
 end
end
</code>```

This is the output

```<code>A =

  4×8 cell array

  Columns 1 through 6

    [10×13×62 double]    [10×13×62 double]    [10×13×62 double]    [10×13×62 double]    [10×13×62 double]    [10×13×62 double]
    [10×13×91 double]    [10×13×91 double]    [10×13×91 double]    [10×13×91 double]    [10×13×91 double]    [10×13×91 double]
    [10×13×71 double]    [10×13×71 double]    [10×13×71 double]    [10×13×71 double]    [10×13×71 double]    [10×13×71 double]
    [10×13×89 double]    [10×13×89 double]    [10×13×89 double]    [10×13×89 double]    [10×13×89 double]    [10×13×89 double]

  Columns 7 through 8

    [10×13×62 double]    [10×13×62 double]
    [10×13×91 double]    [10×13×91 double]
    [10×13×71 double]    [10×13×71 double]
    [10×13×89 double]    [10×13×89 double]
</code>```

Body:
I have a cell array defined as A = cell(i,8);

say i = 4. now i am trying to fill up the 4 x 8 cell array with a function present inside the loop.

Say,

A = cell(i,8);
for index=1:8
A{i,index} = zeros(C{i}, D{i}, E{i});
end

where, the values of C{i}, D{i}, E{i} are

C{i} = [10]    [10]    [10]    [10]
D{I} = [13]    [13]    [13]    [13]
E{I} = [62]    [91]    [71]    [89]

And the contents of the cell are obviously zeros, since i used zeros() but i need this step for some further processing.

Now, i should get the Value of A(Cell array) - 4 x 8 Dimension like below,

10x13x62 double10x13x62 double  10x13x62 double 10x13x62 double 10x13x62 double 10x13x62 double 10x13x62 double 10x13x62 double
10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double 10x13x91 double
10x13x71 double 10x13x71 double 10x13x71 double 10x13x71 double 10x13x71 double 10x13x71 double 10x13x71 double 10x13x71 double
10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double

Instead i am getting the output like,

[]  []  []  []  []  []  []  []
[]  []  []  []  []  []  []  []
[]  []  []  []  []  []  []  []
10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double 10x13x89 double

I hope I am missing some simple logic behind the loop and the Cell array, is my initialization of the cell array and the loop is correct? if not, please suggest me to find a solution like i mentioned above.

Thanks.

Body:
Firs thing A{i,index} = zeros(C{i}, D{i}, E{i}); not correct since zero() not accept array as paramerts.

This code will solve your problem

i=4;
A = cell(i,8);

C{i} = {10,10,10,10};
D{i} = {[13]    [13]    [13]    [13]};
E{i} = {[62]    [91]    [71]    [89]};
for j=1:8
 for index=1:4
    A{index,j} = zeros(cell2mat(C{i}(index)), cell2mat(D{i}(index)), cell2mat(E{i}(index)));
 end
end

This is the output

A =

  4×8 cell array

  Columns 1 through 6

    [10×13×62 double]    [10×13×62 double]    [10×13×62 double]    [10×13×62 double]    [10×13×62 double]    [10×13×62 double]
    [10×13×91 double]    [10×13×91 double]    [10×13×91 double]    [10×13×91 double]    [10×13×91 double]    [10×13×91 double]
    [10×13×71 double]    [10×13×71 double]    [10×13×71 double]    [10×13×71 double]    [10×13×71 double]    [10×13×71 double]
    [10×13×89 double]    [10×13×89 double]    [10×13×89 double]    [10×13×89 double]    [10×13×89 double]    [10×13×89 double]

  Columns 7 through 8

    [10×13×62 double]    [10×13×62 double]
    [10×13×91 double]    [10×13×91 double]
    [10×13×71 double]    [10×13×71 double]
    [10×13×89 double]    [10×13×89 double]


问:
use html5 video player only if browser is Safari
I would like to use the html5 video tag only if the users browser is Safari, and if it is not, use a flash video player.

The code below does not work (

<!--[if !Safari]>
<script src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">

  var flashvars = {};
  var params = {
      allowscriptaccess: "true",
      file:"path/to/movie.mov"
  };
  var attributes = {};

  swfobject.embedSWF("swf/player.swf", "player", "640", "480", "9.0.0", flashvars, params, attributes);

</script>
<![endif]-->
```

答:
Never use browser detection. Use feature detection instead. You can use Modernizr for that, but in this case, you don't need any JavaScript at all to fallback to Flash if the browser doesn't support HTML5's <video> element.

See this article at Nettuts+.

ContentLicense: CC BY-SA 2.5


问:
Using Custom Resource in DevExpress WPF Theme

Objective:

I have a WPF project which shall be themed using DevExpress Themes.
There is a Login-UserControl that shall have a themable background image.

Implementation

I made a custom Theme. In that theme I have a Folder "CustomResources" in which there is an Image, let's call it "Background.png" and a "Brushes.xaml" that defines an ImageBrush like this:

```<code><ResourceDictionary ...>
    <ImageBrush x:Key="{CustomThemeKeyAssembly:CustomThemeResourcesThemeKey ResourceKey=LoginBackgroundImageBrush, ThemeName=CustomTheme}" ImageSource="Background.png" />
</ResourceDictionary>
</code>```

Accordingly, I have a shared Assembly CustomThemeKeyAssembly that derives a Custom ResourceThemeKey.

In the Project, I register and set the Theme using ApplicationThemeHelper

```<code>var theme = new Theme("CustomTheme")
{
    AssemblyName = "DevExpress.Xpf.Themes.CustomTheme.v17.2"
};
Theme.RegisterTheme(theme);

ApplicationThemeHelper.ApplicationThemeName = "CustomTheme";
</code>```

and I reference the Resource through

```<code>Background="{dxci:ThemeResource ThemeKey={CustomThemeKeyAssembly:CustomThemeResourcesThemeKey ResourceKey=LoginBackgroundImageBrush}}"
</code>```

As advised by DevExpress Knowledgebase / Support.

Problem

The Resource is only found and displayed, if I add a Merged Resource Dictionary like this:

```<code>ResourceDictionary loginBackgroundDictionary = new ResourceDictionary
{
    Source = new Uri($"pack://application:,,,/{MyProject.Properties.Settings.Default.ThemeAssembly};Component/CustomResources/Brushes.xaml", UriKind.Absolute)
};

//Add LoginBackgroundImageBrush Dictionary
Resources.MergedDictionaries.Add(loginBackgroundDictionary);
</code>```

No article or example mentions having to do this, though. So my impression is that I either am doing something wrong or I am missing some simple step like merging the Brushes.xaml into some ResourceDictionary.

Without that snippet I get a warning that the resource could not be found.

Question

Has anybody an idea where I am going wrong or what I am missing to get this working without that last snippet?

FYI: I am using DevExpress 17.2.3 and the ResourceKey Assembly is targeted to .net Framework 4.0

EDIT

Meanwhile, I tried adding the Brushes.xaml to Themes/Generic.xaml in the theme assembly like this:

```<code><ResourceDictionary.MergedDictionaries>
    <dxt:ResourceDictionaryEx Source="/DevExpress.Xpf.Themes.Office2016WhiteSE.v17.2;component/Themes/ControlStyles.xaml" />
    <dxt:ResourceDictionaryEx Source="/DevExpress.Xpf.Themes.Office2016WhiteSE.v17.2;component/CustomResources/Brushes.xaml" />
</ResourceDictionary.MergedDictionaries>
</code>```

It didn't make any difference. Same behavior as before.

答:
Problem solved!

The problem was in the CustomThemeKeyAssembly

The wrong implementation was

```<code>public class CustomThemeResourcesThemeKey : ThemeKeyExtensionBase
{
    public override Assembly Assembly => TypeInTargetAssembly != null ? TypeInTargetAssembly.Assembly : GetType().Assembly;
}
</code>```

The working implementation is

```<code>public class CustomThemeResourcesThemeKey : ThemeKeyExtensionBase<ThemeResourcesThemeKeys> { }
</code>```

The breaking difference is the override of the Assembly property. The default implementation makes it work. I did that because it was done so in an example. Support told me to stick with the default implementation and it worked.

Body:
Objective:

I have a WPF project which shall be themed using DevExpress Themes.
There is a Login-UserControl that shall have a themable background image.

Implementation

I made a custom Theme. In that theme I have a Folder "CustomResources" in which there is an Image, let's call it "Background.png" and a "Brushes.xaml" that defines an ImageBrush like this:

<ResourceDictionary ...>
    <ImageBrush x:Key="{CustomThemeKeyAssembly:CustomThemeResourcesThemeKey ResourceKey=LoginBackgroundImageBrush, ThemeName=CustomTheme}" ImageSource="Background.png" />
</ResourceDictionary>

Accordingly, I have a shared Assembly CustomThemeKeyAssembly that derives a Custom ResourceThemeKey.

In the Project, I register and set the Theme using ApplicationThemeHelper

var theme = new Theme("CustomTheme")
{
    AssemblyName = "DevExpress.Xpf.Themes.CustomTheme.v17.2"
};
Theme.RegisterTheme(theme);

ApplicationThemeHelper.ApplicationThemeName = "CustomTheme";

and I reference the Resource through

Background="{dxci:ThemeResource ThemeKey={CustomThemeKeyAssembly:CustomThemeResourcesThemeKey ResourceKey=LoginBackgroundImageBrush}}"

As advised by DevExpress Knowledgebase / Support.

Problem

The Resource is only found and displayed, if I add a Merged Resource Dictionary like this:

ResourceDictionary loginBackgroundDictionary = new ResourceDictionary
{
    Source = new Uri($"pack://application:,,,/{MyProject.Properties.Settings.Default.ThemeAssembly};Component/CustomResources/Brushes.xaml", UriKind.Absolute)
};

//Add LoginBackgroundImageBrush Dictionary
Resources.MergedDictionaries.Add(loginBackgroundDictionary);

No article or example mentions having to do this, though. So my impression is that I either am doing something wrong or I am missing some simple step like merging the Brushes.xaml into some ResourceDictionary.

Without that snippet I get a warning that the resource could not be found.

Question

Has anybody an idea where I am going wrong or what I am missing to get this working without that last snippet?

FYI: I am using DevExpress 17.2.3 and the ResourceKey Assembly is targeted to .net Framework 4.0

EDIT

Meanwhile, I tried adding the Brushes.xaml to Themes/Generic.xaml in the theme assembly like this:

<ResourceDictionary.MergedDictionaries>
    <dxt:ResourceDictionaryEx Source="/DevExpress.Xpf.Themes.Office2016WhiteSE.v17.2;component/Themes/ControlStyles.xaml" />
    <dxt:ResourceDictionaryEx Source="/DevExpress.Xpf.Themes.Office2016WhiteSE.v17.2;component/CustomResources/Brushes.xaml" />
</ResourceDictionary.MergedDictionaries>

It didn't make any difference. Same behavior as before.

Body:
Problem solved!

The problem was in the CustomThemeKeyAssembly

The wrong implementation was

public class CustomThemeResourcesThemeKey : ThemeKeyExtensionBase
{
    public override Assembly Assembly => TypeInTargetAssembly != null ? TypeInTargetAssembly.Assembly : GetType().Assembly;
}

The working implementation is

public class CustomThemeResourcesThemeKey : ThemeKeyExtensionBase<ThemeResourcesThemeKeys> { }

The breaking difference is the override of the Assembly property. The default implementation makes it work. I did that because it was done so in an example. Support told me to stick with the default implementation and it worked.


问:
Docker load and save: "archive/tar: invalid tar header"
I'm trying to import a Docker image into Docker on AWS Red Hat Linux (3.10.0-514.el7.x86_64) and am having problems with the error;

```<code>Error processing tar file(exit status 1): archive/tar: invalid tar header
</code>```

This same image works fine on my local machine, and in Boot2Docker on Windows also. It's quite large (2.5 GB), but I've verified the checksum on the Red Hat Linux instance, and it's the same as from the source.

What could be wrong, or how I can resolve it?

答:
The correct way to resolve this problem is this:

When you save the image, use this instruction

```<code>Docker save --output=C:\YOUR_PATH\my_docker_image.tar e6f81ac424ae(image id)
</code>```

And when you try to load this image, use this instruction:

```<code>Docker load --input C:\YOUR_PATH\my_docker_image.tar
</code>```

After this you see your image with name <none> in Docker image, and to resolve this, use the command tag

```<code>Docker tag IMAGE_ID mydockerapplication
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to import a Docker image into Docker on AWS Red Hat Linux (3.10.0-514.el7.x86_64) and am having problems with the error;

Error processing tar file(exit status 1): archive/tar: invalid tar header

This same image works fine on my local machine, and in Boot2Docker on Windows also. It's quite large (2.5 GB), but I've verified the checksum on the Red Hat Linux instance, and it's the same as from the source.

What could be wrong, or how I can resolve it?

Body:
The correct way to resolve this problem is this:

When you save the image, use this instruction

Docker save --output=C:\YOUR_PATH\my_docker_image.tar e6f81ac424ae(image id)

And when you try to load this image, use this instruction:

Docker load --input C:\YOUR_PATH\my_docker_image.tar

After this you see your image with name <none> in Docker image, and to resolve this, use the command tag

Docker tag IMAGE_ID mydockerapplication


问:
How to pass discount amount to Authorize.Net
I would like pass discount(Coupon) amount to Authorize .net in C#,
when i pass discount amount in line items with negative value($-30), i am getting error. without discount code everything working fine

Example:

```<code>1   Item1   10  N   US $24.95   US $249.50

Discount:       US $-30.00
Total:      US $219.50

var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),   // charge the card
                amount = order.LineItems.Sum(od => od.UnitPrice * od.Quantity),
                lineItems = lineItems,
                order = new orderType { invoiceNumber = order.Orderid, description = order.OrderDescription },
                customer = new customerDataType { id = order.customerdetails.Customerid, email = order.customerdetails.CustomerEmail },
                currencyCode = order.CurrencyCode
            };
</code>```

How can i achieve this?

答:
You have a string input and must parse string to a number value :</p>

```<code>string input = "1   Item1   10  N   US $24.95   US $249.50";

string[] array = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

decimal amount = decimal.Parse(array[7], System.Globalization.NumberStyles.Currency);

decimal discount = amount - 30;
</code>```

Body:
I would like pass discount(Coupon) amount to Authorize .net in C#,
when i pass discount amount in line items with negative value($-30), i am getting error. without discount code everything working fine

Example:

1   Item1   10  N   US $24.95   US $249.50

Discount:       US $-30.00
Total:      US $219.50

var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),   // charge the card
                amount = order.LineItems.Sum(od => od.UnitPrice * od.Quantity),
                lineItems = lineItems,
                order = new orderType { invoiceNumber = order.Orderid, description = order.OrderDescription },
                customer = new customerDataType { id = order.customerdetails.Customerid, email = order.customerdetails.CustomerEmail },
                currencyCode = order.CurrencyCode
            };

How can i achieve this?

Body:
You have a string input and must parse string to a number value :

string input = "1   Item1   10  N   US $24.95   US $249.50";

string[] array = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

decimal amount = decimal.Parse(array[7], System.Globalization.NumberStyles.Currency);

decimal discount = amount - 30;


问:
ImageView selectableItemBackgroundBorderless does not render outside of view bounds
I am using selectableItemBackgroundBorderless to add a ripple to an ImageView.
My expected behaviour would be to have a circular ripple, extending the views size. Unfortunately the ripple gets cropped by the view bounds.
How can this issue be solved?

Default state:

Pressed state:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nav_instruction_container"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@drawable/nav_gradient_bg"
    android:padding="20dp">
    <ImageView
        android:id="@+id/nav_sign"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_centerVertical="true"
        android:scaleType="centerInside"
        android:adjustViewBounds="true"
        />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/nav_sign"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginEnd="24dp"
        android:textColor="@color/white"
        android:textSize="24sp"
        android:textStyle="bold"
        android:maxLines="2"
        tools:text="A644 Shudehill asdfkjasdf asdfasdf asdfsss"
        android:ellipsize="marquee"
        />

    <TextView
        android:id="@+id/subTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/nav_sign"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginEnd="24dp"
        android:textColor="@color/white"
        android:textSize="17sp"
        tools:text="via Church St"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        app:srcCompat="@drawable/ic_nav_queue_sheet_icon_light"
        android:id="@+id/nav_queue"
        android:scaleType="centerInside"
        android:foreground="?attr/selectableItemBackgroundBorderless"
        android:adjustViewBounds="true"/>
</RelativeLayout>
</code>```

答:
If you have a clickable ImageView, then most possibly it should be an ImageButton instead.

Having defined following ImageButton:

```<code><ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?attr/selectableItemBackgroundBorderless"
    app:srcCompat="@drawable/ic_navigation_black_24dp" />
</code>```

Then you'll get following output:

If you want bigger ripple effect, you have to change view's size: instead of wrap_content make it, let's say, 100dp:

Body:
I am using selectableItemBackgroundBorderless to add a ripple to an ImageView.
My expected behaviour would be to have a circular ripple, extending the views size. Unfortunately the ripple gets cropped by the view bounds.
How can this issue be solved?

Default state:

Pressed state:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nav_instruction_container"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@drawable/nav_gradient_bg"
    android:padding="20dp">
    <ImageView
        android:id="@+id/nav_sign"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_centerVertical="true"
        android:scaleType="centerInside"
        android:adjustViewBounds="true"
        />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/nav_sign"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginEnd="24dp"
        android:textColor="@color/white"
        android:textSize="24sp"
        android:textStyle="bold"
        android:maxLines="2"
        tools:text="A644 Shudehill asdfkjasdf asdfasdf asdfsss"
        android:ellipsize="marquee"
        />

    <TextView
        android:id="@+id/subTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title"
        android:layout_toRightOf="@+id/nav_sign"
        android:layout_marginLeft="24dp"
        android:layout_marginStart="24dp"
        android:layout_marginRight="24dp"
        android:layout_marginEnd="24dp"
        android:textColor="@color/white"
        android:textSize="17sp"
        tools:text="via Church St"
        />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        app:srcCompat="@drawable/ic_nav_queue_sheet_icon_light"
        android:id="@+id/nav_queue"
        android:scaleType="centerInside"
        android:foreground="?attr/selectableItemBackgroundBorderless"
        android:adjustViewBounds="true"/>
</RelativeLayout>

Body:
If you have a clickable ImageView, then most possibly it should be an ImageButton instead.

Having defined following ImageButton:

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?attr/selectableItemBackgroundBorderless"
    app:srcCompat="@drawable/ic_navigation_black_24dp" />

Then you'll get following output:

If you want bigger ripple effect, you have to change view's size: instead of wrap_content make it, let's say, 100dp:


问:
Best serialization library for .net with ability to deserialize inheritance correctly
I need a serialization library for .net with better features than the default xml serializer.
The problem is that it  is not polymorphic - say you have class B : A { }, and have serialized an type B, you should be able to call A myBaseType = Deserialize(xml) on it and be returned an instance of type B in the myBaseType variable.

I have an implementation at http://refactormycode.com/codes/710-polymorphic-xml-serializer with unit tests that the serialization library should be able to deal with. This implementation will not work if an object to be serialized has a child type which is also a polymorphic serialized type, so I need something better.

thanks!

答:
Can you use .NET's binary serializer or does it need to be XML? I had a similar list of complaints about .NET's XML handling, particularly when trying to serialize graphs as opposed to trees.

In the places that I needed XML to work properly, I ended up just rolling out my own serialization code for each class.

OwnerDisplayName: David Thomas Garcia


问:
How to manage Rails 2.3.x i18n locales programatically?
I would like to know if there is a way to insert, alter and remove i18n locale keys programatically (I guess I could use the DB, but I like Rails i18n and want to stay as close to it as possible).

Basically I want to know if there's a way (native, gem, plugin, whatever) to do things like:

```<code>I18n.add_locale_key("en", "application.messages.submit_message", "Submit message!")
I18n.add_locale_key("es", "application.messages.submit_message", "Enviar mensaje!")

I18n.remove_locale_key("en", "application.messages.submit_message")
I18n.remove_locale_key("es", "application.messages.submit_message")
</code>```

答:
As packaged, the Rails I18n API only support defining locale terms via the local .yaml or .rb files. Short of dynamically editing those files at runtime, your best bet is to use the DB functionality of a gem gem like FastGetText.

You could also roll your own solution, of course, but the DB method will likely work for your use case and will result in a smaller time investment.

Body:
I would like to know if there is a way to insert, alter and remove i18n locale keys programatically (I guess I could use the DB, but I like Rails i18n and want to stay as close to it as possible).

Basically I want to know if there's a way (native, gem, plugin, whatever) to do things like:

I18n.add_locale_key("en", "application.messages.submit_message", "Submit message!")
I18n.add_locale_key("es", "application.messages.submit_message", "Enviar mensaje!")

I18n.remove_locale_key("en", "application.messages.submit_message")
I18n.remove_locale_key("es", "application.messages.submit_message")


问:
mapping an array of objects and changing the value with on onClick in React
I'm trying to change the value of like within the cardArr objects while using a map() to list each obj.

Below is my code.
Current, it works, but every object shares the same counter since it's not calling from the object. I understand that I'm currently just calling the object property stored in state, but how do I edit the like in each object using a map function?

```<code>import React, { Component } from 'react';

const cardArr = [
{
    id: 1,
    text: "Hey this is a test.",
    img: " ",
    like: 0
},
{
    id: 2,
    text: "If this works I'll call it a day.",
    img: " ",
    like: 0
},
{
    id: 3,
    text: "I'll drink a lot of beer.",
    img: " ",
    like: 0
},
{
    id: 4,
    text: "Cheers",
    img: " ",
    like: 0

}
]

export class Card extends Component {
    constructor(props) {
    super(props);
    this.state = {
      like: 0,
      show: true
    };
     // this.handleClick = this.handleClick.bind(this);

  }

IncrementItem = () => {
    this.setState({ like: this.state.like + 1 });
}
DecreaseItem = () => {
    this.setState({ like: this.state.like - 1 });
}

// handleClick(e) {
//  e.preventDefault();
//  this.IncrementItem();
// }
// handleClick(e) {
//  e.preventDefault();
//  this.DecreaseItem();
// }

render() {

    const cardList = (cardArr.map((card) =>

        <ul>
            <li>
            <div key={card.id}>
                {card.text};
                <img src={card.img}/>
                <p>Like Button</p>
                <button onClick={this.handleClickAdd}>Like</button>
                <p>Dilike Button</p>
                <button onClick={this.DecreaseItem}>Disike</button>
                <p>Likes: {this.state.like}</p>
            </div>
            </li>
        </ul>
        ));

    return(
        <div id='card'>
            {cardList}
        </div>
    )
}
}
</code>```

答:
Move cardArr to your component's state so on each onClick (like or deslike) you will be able to change like prop as you want:

const Card = ({ card, onLike, onDeslike }) =>

    {card.text}

Likes: {card.like}

    <button onClick={() => onLike(card.id)}>Like</button>
    <button onClick={() => onDeslike(card.id)}>Deslike</button>

class CardList extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      cards: [
        {
          id: 1,
          text: 'Hey this is a test.',
          img: ' ',
          like: 0,
        },
        {
          id: 2,
          text: "If this works I'll call it a day.",
          img: ' ',
          like: 0,
        },
        {
          id: 3,
          text: "I'll drink a lot of beer.",
          img: ' ',
          like: 0,
        },
        {
          id: 4,
          text: 'Cheers',
          img: ' ',
          like: 0,
        },
      ]
    }

    this.handleLike = this.handleLike.bind(this)
    this.handleDeslike = this.handleDeslike.bind(this)
  }

  handleLike(id) {
    this.setState(prevState => ({
      ...prevState,
      cards: prevState.cards.map(card => ({
        ...card,
        like: card.id === id ? card.like + 1 : card.like
      }))
    }))
  }

  handleDeslike(id) {
    this.setState(prevState => ({
      ...prevState,
      cards: prevState.cards.map(card => ({
        ...card,
        like: card.id === id ? card.like - 1 : card.like
     }))
    }))
  }

  render() {
    return (

          {this.state.cards.map(card =>

              <Card
                card={card}
                onLike={this.handleLike}
                onDeslike={this.handleDeslike}
              />

          )}

    )
  }
}

ReactDOM.render(
  <CardList />,
  document.getElementById('root')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div></code>```

Don't forget that setState is asynchronous and, therefore, you won't have it's latest changes right away.

Body:
I'm trying to change the value of like within the cardArr objects while using a map() to list each obj.

Below is my code.
Current, it works, but every object shares the same counter since it's not calling from the object. I understand that I'm currently just calling the object property stored in state, but how do I edit the like in each object using a map function?

import React, { Component } from 'react';

const cardArr = [
{
    id: 1,
    text: "Hey this is a test.",
    img: " ",
    like: 0
},
{
    id: 2,
    text: "If this works I'll call it a day.",
    img: " ",
    like: 0
},
{
    id: 3,
    text: "I'll drink a lot of beer.",
    img: " ",
    like: 0
},
{
    id: 4,
    text: "Cheers",
    img: " ",
    like: 0

}
]

export class Card extends Component {
    constructor(props) {
    super(props);
    this.state = {
      like: 0,
      show: true
    };
     // this.handleClick = this.handleClick.bind(this);

  }

IncrementItem = () => {
    this.setState({ like: this.state.like + 1 });
}
DecreaseItem = () => {
    this.setState({ like: this.state.like - 1 });
}

// handleClick(e) {
//  e.preventDefault();
//  this.IncrementItem();
// }
// handleClick(e) {
//  e.preventDefault();
//  this.DecreaseItem();
// }

render() {

    const cardList = (cardArr.map((card) =>

                {card.text};

Like Button

                <button onClick={this.handleClickAdd}>Like</button>

Dilike Button

                <button onClick={this.DecreaseItem}>Disike</button>

Likes: {this.state.like}

        ));

    return(

            {cardList}

    )
}
}

Body:
Move cardArr to your component's state so on each onClick (like or deslike) you will be able to change like prop as you want:

const Card = ({ card, onLike, onDeslike }) =>
  <div>
    {card.text}
    <p>Likes: {card.like}</p>
    <button onClick={() => onLike(card.id)}>Like</button>
    <button onClick={() => onDeslike(card.id)}>Deslike</button>
  </div>

class CardList extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      cards: [
        {
          id: 1,
          text: 'Hey this is a test.',
          img: ' ',
          like: 0,
        },
        {
          id: 2,
          text: "If this works I'll call it a day.",
          img: ' ',
          like: 0,
        },
        {
          id: 3,
          text: "I'll drink a lot of beer.",
          img: ' ',
          like: 0,
        },
        {
          id: 4,
          text: 'Cheers',
          img: ' ',
          like: 0,
        },
      ]
    }

    this.handleLike = this.handleLike.bind(this)
    this.handleDeslike = this.handleDeslike.bind(this)
  }

  handleLike(id) {
    this.setState(prevState => ({
      ...prevState,
      cards: prevState.cards.map(card => ({
        ...card,
        like: card.id === id ? card.like + 1 : card.like
      }))
    }))
  }

  handleDeslike(id) {
    this.setState(prevState => ({
      ...prevState,
      cards: prevState.cards.map(card => ({
        ...card,
        like: card.id === id ? card.like - 1 : card.like
     }))
    }))
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.cards.map(card =>
            <li key={card.id}>
              <Card
                card={card}
                onLike={this.handleLike}
                onDeslike={this.handleDeslike}
              />
            </li>
          )}
        </ul>
      </div>
    )
  }
}

ReactDOM.render(
  <CardList />,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

Don't forget that setState is asynchronous and, therefore, you won't have it's latest changes right away.


问:
Not download/init browser driver when used webdrivermanager-x.x.x.jar (without Maven)
For my Selenium/Java project [without Maven], using webdrivermanager-1.7.2.jar in  to automate binary downloads for chromedriver but I'm getting "java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory" message.
My code:</p>

```<code>package selenium_webdriver_api;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.ChromeDriverManager;

public class Topic_29_ManageBrowserVersion {

    private WebDriver driver;

    @BeforeClass
    public static void setupClass() {
        ChromeDriverManager.getInstance().version("2.33").setup();
        // Or: ChromeDriverManager.getInstance().setup();
    }

    @Before
    public void setupTest() {
        driver = new ChromeDriver();
    }

    @After
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void test() {
        driver.get("https://github.com/bonigarcia/webdrivermanager");
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        driver.manage().window().maximize();
    }
}
</code>```

答: WebDriverManager depends on several libraries such as slf4j-api, commons-io, gson, among others (see its pom.xml for the complete list). If you are using WebDriverManager without the help of a build tool (e.g. Maven, Gradle) you need to resolve these dependencies manually. The other option is to generate a fat jar from the source, for example using the maven-assembly-plugin (info here) or maven-shade-plugin (info here).

Body:
For my Selenium/Java project [without Maven], using webdrivermanager-1.7.2.jar in  to automate binary downloads for chromedriver but I'm getting "java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory" message.
My code:

package selenium_webdriver_api;
import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.ChromeDriverManager;

public class Topic_29_ManageBrowserVersion {

    private WebDriver driver;

    @BeforeClass
    public static void setupClass() {
        ChromeDriverManager.getInstance().version("2.33").setup();
        // Or: ChromeDriverManager.getInstance().setup();
    }

    @Before
    public void setupTest() {
        driver = new ChromeDriver();
    }

    @After
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void test() {
        driver.get("https://github.com/bonigarcia/webdrivermanager");
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        driver.manage().window().maximize();
    }
}


问:
why jquery dataTable not display data
Im Getting Error as
http://localhost:47237/Home_Business/Home_Business/GetData?draw=1&columns%5B0%5D%5Bdata%5D=Emp_Id&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=EmpName&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=Email&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1512374513133

here im trying to loading data in jqueryData Table  insted of showing data in tabler Format its showing in Json Like

```<code>{"iTotalRecords":12,"aaData":[{"Emp_Id":101,"EmpName":"Hussain","Email":"Hussain@gmail.com","Psw":null,"Cnt_Id":0,"Cnt_Name":"India","Sts_Id":0,"Sts_Name":"Telangana","City_Id":0,"City_Name":"Hyd","dept_ID":null,"Date":"\/Date(1420050600000)\/","sal":15000,"Gen_Id":null,"Gen_Name":null}]}
</code>```

Mvc code

```<code> public ActionResult Index()
        {
            var x = ObjRepo.GetEmployees(1);
            int size =ObjRepo.CountEmployee();
           return Json(new { iTotalRecords = size, aaData }, JsonRequestBehavior.AllowGet);

        }
</code>```

Jquery

```<code> $(document).ready(function () {
        $('#table_id').dataTable({
//Here i Hotcoded my data Even imm not dusplay data
            "iTotalRecords":12,"aaData":[{"Emp_Id":101,"EmpName":"Hussain","Email":"Hussain@gmail.com"
            }],
            "processing": true,
            "serverSide": true,
            "Columns": [
                         { 'data': 'Emp_Id' },
                         { 'data': 'EmpName' },
                         ],
        });
    })
</code>```

答:
you can do something like this inside a function or in document ready..

```<code>     $.ajax({
        type: 'GET',
        url: '@Url.Action("GetEmployees", "ControllerName")',
        cache: false,
        success: function (result) {
            $("#table_id").DataTable({
                destroy: true,
                data: result,
                columns: [
                    { data: 'employee_id' },
                    { data: 'employee_name' }
                ]
            });
        }
    });
</code>```

then you need to have html table with thead on your #table_id

Controller:

```<code>[HttpGet]
public ActionResult GetEmployees()
{
     var x = ObjRepo.GetEmployees(1);
     int size =ObjRepo.CountEmployee();
     return Json(new { iTotalRecords = size, aaData }, JsonRequestBehavior.AllowGet);
}
</code>```

Title: why jquery dataTable not display data

Body:
you can do something like this inside a function or in document ready..

     $.ajax({
        type: 'GET',
        url: '@Url.Action("GetEmployees", "ControllerName")',
        cache: false,
        success: function (result) {
            $("#table_id").DataTable({
                destroy: true,
                data: result,
                columns: [
                    { data: 'employee_id' },
                    { data: 'employee_name' }
                ]
            });
        }
    });

then you need to have html table with thead on your #table_id

Controller:

[HttpGet]
public ActionResult GetEmployees()
{
     var x = ObjRepo.GetEmployees(1);
     int size =ObjRepo.CountEmployee();
     return Json(new { iTotalRecords = size, aaData }, JsonRequestBehavior.AllowGet);
}


问:
Android: optimal way to find shortest distance between Point and Rect?
Seems like there should be some convenient way to do this?

I couldn't find one, so I threw together the below algorithm.  Is it memory/computationally optimal?

Thanks:

Edit: Original algorithm was stupidly wrong, maybe this is better?

```<code>public static float minDistance(RectF rect, PointF point)
{
    if(rect.contains(point.x, point.y))
    {
        //North line
        float distance = point.y - rect.top;

        //East line
        distance = Math.min(distance, point.x - rect.left);

        //South line
        distance = Math.min(distance, rect.bottom - point.y);

        //West line
        distance = Math.min(distance, rect.right - point.x);

        return distance;
    }
    else
    {
        float minX, minY;

        if (point.x < rect.left)
        {
            minX = rect.left;
        }
        else if (point.x > rect.right)
        {
            minX = rect.right;
        }
        else
        {
            minX = point.x;
        }

        if (point.y < rect.top)
        {
            minY = rect.top;
        }
        else if (point.y > rect.bottom)
        {
            minY = rect.bottom;
        }
        else
        {
            minY = point.y;
        }

        float vectorX = point.x - minX;
        float vectorY = point.y - minY;

        float distance = (float) Math.sqrt((vectorX * vectorX) + (vectorY * vectorY));

        return distance;
    }
}
</code>```

答:
Just take the closest point and then get the distance to that.
Off the top of my head:</p>

```<code>    float closestX, closestY;

    if(point.x >= x1 && point.x <= x2 && point.y >= y1 && point.y <= y2)
    {
         float bestDistance = point.y - y1;
         bestDistance = Math.min(distance, y2 - point.y);
         bestDistance = Math.min(distance, point.x - x1);
         bestDistance = Math.min(distance, x2 - point.x);

         return bestDistance;
    }

    if (point.x < x1) {
        closestX = x1;
    } else if (point.x > x2) {
        closestX = x2;
    } else {
        closestX = point.x;
    }

    if (point.y < x1) {
        closestY = y1;
    } else if (point.y > y2) {
        closestY = y2;
    } else {
        closestY = point.y;
    }

    float vectorY = point.x - closestX;
    float vectorY = point.Y - closestY;

    float distance = sqrtf((vectorX * vectorX) + (vectorY * vectorY));
</code>```

Body:
Seems like there should be some convenient way to do this?

I couldn't find one, so I threw together the below algorithm.  Is it memory/computationally optimal?

Thanks:

Edit: Original algorithm was stupidly wrong, maybe this is better?

public static float minDistance(RectF rect, PointF point)
{
    if(rect.contains(point.x, point.y))
    {
        //North line
        float distance = point.y - rect.top;

        //East line
        distance = Math.min(distance, point.x - rect.left);

        //South line
        distance = Math.min(distance, rect.bottom - point.y);

        //West line
        distance = Math.min(distance, rect.right - point.x);

        return distance;
    }
    else
    {
        float minX, minY;

        if (point.x < rect.left)
        {
            minX = rect.left;
        }
        else if (point.x > rect.right)
        {
            minX = rect.right;
        }
        else
        {
            minX = point.x;
        }

        if (point.y < rect.top)
        {
            minY = rect.top;
        }
        else if (point.y > rect.bottom)
        {
            minY = rect.bottom;
        }
        else
        {
            minY = point.y;
        }

        float vectorX = point.x - minX;
        float vectorY = point.y - minY;

        float distance = (float) Math.sqrt((vectorX * vectorX) + (vectorY * vectorY));

        return distance;
    }
}

Body:
Just take the closest point and then get the distance to that.
Off the top of my head:

    float closestX, closestY;

    if(point.x >= x1 && point.x <= x2 && point.y >= y1 && point.y <= y2)
    {
         float bestDistance = point.y - y1;
         bestDistance = Math.min(distance, y2 - point.y);
         bestDistance = Math.min(distance, point.x - x1);
         bestDistance = Math.min(distance, x2 - point.x);

         return bestDistance;
    }

    if (point.x < x1) {
        closestX = x1;
    } else if (point.x > x2) {
        closestX = x2;
    } else {
        closestX = point.x;
    }

    if (point.y < x1) {
        closestY = y1;
    } else if (point.y > y2) {
        closestY = y2;
    } else {
        closestY = point.y;
    }

    float vectorY = point.x - closestX;
    float vectorY = point.Y - closestY;

    float distance = sqrtf((vectorX * vectorX) + (vectorY * vectorY));


问:
How we can handle Multiple Type UITableViewCell
I have multiple type cell to show in UITableView.

I have five type of cell in UITableView. all cell show according the different service response data, if service data nil or empty then we will not need to show the cell. so how i can check the number of row and show the cell according the service response.

答:
First receive the ResponseDataSet and call tableView.reloadData()

Then

The number of section delegate will return the number of section

```<code>func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}
</code>```

The number of rows delegate will return the number of rows in each respective section. if it returns 0 then the cell for row delegate will not be called

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

     return responseSet?.count ?? 0  // The count of response data set
}
</code>```

Here you can check the type of each cell from responseSet and then create or reuse the cell using dequeue cell function.

```<code>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

         var cell:UITableViewCell?

         if responseSet["type"] == "1" {
             cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath)
         }
         else if responseSet["type"] == "2"
         {
            cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
         }
         ..........
         ..........

         return cell
     }
</code>```

Body:
First receive the ResponseDataSet and call tableView.reloadData()

Then

The number of section delegate will return the number of section

func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

The number of rows delegate will return the number of rows in each respective section. if it returns 0 then the cell for row delegate will not be called

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

     return responseSet?.count ?? 0  // The count of response data set
}

Here you can check the type of each cell from responseSet and then create or reuse the cell using dequeue cell function.

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

         var cell:UITableViewCell?

         if responseSet["type"] == "1" {
             cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath)
         }
         else if responseSet["type"] == "2"
         {
            cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath)
         }
         ..........
         ..........

         return cell
     }


问:
Could not find method api() for arguments [project ':model'] on object of
Error:(36, 0)
Could not find method api() for arguments [project ':model'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler

Please help me.

This is my build.gradle file.

```<code>apply plugin: 'com.android.application'
//apply plugin: 'io.fabric'

android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
 applicationId "com.manafzar.mytaxi.driver"
 minSdkVersion 16
 targetSdkVersion 26
 versionCode 23
 versionName "2.0.3"
 multiDexEnabled true
 vectorDrawables.useSupportLibrary = true
 javaCompileOptions {
    annotationProcessorOptions {
    arguments = [eventBusIndex:
   'com.manafzar.mytaxi.driver.DriverEventBusIndex']
  }
 }
}
buildTypes {
 release {
   minifyEnabled false
   proguardFiles getDefaultProguardFile('proguard-android.txt'),
      'proguard-rules.pro'
  }
}
dataBinding {
  enabled = true
  }
}

dependencies {
   annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.0.1'
   api project(':model')
   api 'com.google.maps.android:android-maps-utils:0.5'
   api 'com.diogobernardino:williamchart:2.5.0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

答:
Please add "compile" instead of "api" in your dependencies tag.
And please add below code in your main build.gradle file:</p>

```<code>allprojects {
    repositories {
        jcenter()
        google()
        maven {
            url "https://maven.google.com"
        }
    }
}
</code>```

Body:
Error:(36, 0)
Could not find method api() for arguments [project ':model'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler

Please help me.

This is my build.gradle file.

apply plugin: 'com.android.application'
//apply plugin: 'io.fabric'

android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
 applicationId "com.manafzar.mytaxi.driver"
 minSdkVersion 16
 targetSdkVersion 26
 versionCode 23
 versionName "2.0.3"
 multiDexEnabled true
 vectorDrawables.useSupportLibrary = true
 javaCompileOptions {
    annotationProcessorOptions {
    arguments = [eventBusIndex:
   'com.manafzar.mytaxi.driver.DriverEventBusIndex']
  }
 }
}
buildTypes {
 release {
   minifyEnabled false
   proguardFiles getDefaultProguardFile('proguard-android.txt'),
      'proguard-rules.pro'
  }
}
dataBinding {
  enabled = true
  }
}

dependencies {
   annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.0.1'
   api project(':model')
   api 'com.google.maps.android:android-maps-utils:0.5'
   api 'com.diogobernardino:williamchart:2.5.0'
}
apply plugin: 'com.google.gms.google-services'

Body:
Please add "compile" instead of "api" in your dependencies tag.
And please add below code in your main build.gradle file:

allprojects {
    repositories {
        jcenter()
        google()
        maven {
            url "https://maven.google.com"
        }
    }
}


问:
How can I get a div to stick to the bottom of the screen and have the middle content scroll?
I'm trying to have a sticky footer, where the footer is ALWAYS visible and docked to the bottom, while the middle content will scroll as content is added to it.  I am using this method of accomplishing that:

/* Reset */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

/* Essentials */

.container {
  display: table;
}

.content {
  display: table-row;
  height: 100%;
}

.content-body {
  display: table-cell;
}

.scroller {
  max-height: 100%;
  overflow-y: auto;
}

/* Aestetics */

.container {
  width: 100%;
  height: 100%;
}

.header,
.footer {
  padding: 10px 20px;
  background: #f7f7f7;
}

.scroller {
  padding: 20px;
  background: #e7e7e7;
}

p {
  margin-top: 0;
  margin-bottom: 1rem;
}

p:last-child {
  margin-bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header class="header">
    <p>This is the header</p>
  </header>
  <section class="content">
    <div class="content-body">
      <div class="scroller">
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
      </div>
    </div>
  </section>
  <footer class="footer">
    <p>This is the footer.</p>
  </footer>
</div></code>```

This works great for Chrome and FF but does not work in IE.  Is there a simple fix for this in IE or does someone know of a better solution?

答:
```<code>.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
}
</code>```

Body:
I'm trying to have a sticky footer, where the footer is ALWAYS visible and docked to the bottom, while the middle content will scroll as content is added to it.  I am using this method of accomplishing that:

/* Reset */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

/* Essentials */

.container {
  display: table;
}

.content {
  display: table-row;
  height: 100%;
}

.content-body {
  display: table-cell;
}

.scroller {
  max-height: 100%;
  overflow-y: auto;
}

/* Aestetics */

.container {
  width: 100%;
  height: 100%;
}

.header,
.footer {
  padding: 10px 20px;
  background: #f7f7f7;
}

.scroller {
  padding: 20px;
  background: #e7e7e7;
}

p {
  margin-top: 0;
  margin-bottom: 1rem;
}

p:last-child {
  margin-bottom: 0;
}

This is the header

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the footer.

This works great for Chrome and FF but does not work in IE.  Is there a simple fix for this in IE or does someone know of a better solution?


问:
Take Unknown number of Inputs as String
Input has an unknown amount of lines of Strings of length 20 each. I am using BufferedReader to take inputs from the console. After the last input it's just waiting for the input. How can I terminate the process?

Example Input:

```<code>10100101111011111111
00000000000000000000
01011101110110101111
</code>```

Above 3 lines are given as input. But its not given there are going to be 3 line of input. That is unknown and my programme is just waiting for the next input after the last line, when it should be terminating.

There is no terminator specified in the problem.

答:
Well, you first need to logically formulate the criteria to stop executing your application.

I can suggest one: wait for X seconds -- if no input received, then terminate. If suits you, then it can be easily coded, e.g. with while (true) - break loop or with ScheduledExecutorService. Just store the last time you received the input and check (currentTime - lastTime) < X sec. in the code.

Title: Take Unknown number of Inputs as String

Body:
Input has an unknown amount of lines of Strings of length 20 each. I am using BufferedReader to take inputs from the console. After the last input it's just waiting for the input. How can I terminate the process?

Example Input:

10100101111011111111
00000000000000000000
01011101110110101111

Above 3 lines are given as input. But its not given there are going to be 3 line of input. That is unknown and my programme is just waiting for the next input after the last line, when it should be terminating.

There is no terminator specified in the problem.


问:
What is the purpose of the DEPLOYMENT qmake variable?
I am trying to get to the next level of understanding of the Qt library and qmake in particular. For that purpose I experiment with diffrent project configurations. Doing that I've stumbled upon the DEPLOYMENT variable (because of the autocomplete), which is not listed in the documentation of qmake. The search engines don't give me suitable results either. I am pretty sure there is a reason for that, but being a scientist I am used to not leaving a stone unturned. So it does bother me and I would like to find out what it is for. Is anyone familiar with this variable?

答:
DEPLOYMENT is used in Qt 4.8 to specify additional files to be deployed on Windows CE and the Symbian platform only:

This is only used on Windows CE and the Symbian platform.

Specifies which additional files will be deployed. Deployment means
  the transfer of files from the development system to the target device
  or emulator.


问:
Guava Sets intersection(HashSet1, HashSet2) compares by hash or by value?
When using Guava Sets to come up with the intersection of two HashSets, how does it determine that two elements are identical? By their value or by their hash?

== Update ==

Looking at the source code of java.util.HashSet, I realize that contains() actually calls containsKey() to do the comparison:

答:
Hashes are never, ever used to determine equality. That's not their goal. Their goal, in a hash-based collection, is to reduce the number of potentially equal candidates.

intersection() returns a view over two sets, so it completely delegates the equality tests to the underlyong two Sets.