问:
Map activity does not show up in my phone because I have many activities
I created new activity which is map activity. I think I have problem in AndroidManofest.xml.
My phone works perfectly if I create new project with just map activity. If I add it to my project, which has a lot of activities, it does not work. I do not know why.

the problem is about the activities
  AndroidManofest.xml

I checked every thing APU is enable

AndroidManofest.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.abdullahalhajri.smarttutor">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activities.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.RegisterActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.HomePage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchPage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchRating"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchSubject"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.MathTutor"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.ReviewComment"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.TutorProfile"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.UsersActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".activities.MapsActivity"
            android:label="@string/title_activity_maps">

        </activity>
    </application>

</manifest>
</code>```

Error

```<code>12-04 04:31:22.639 25820-26431/com.example.abdullahalhajri.smarttutor E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
                                                                                Ensure that the "Google Maps Android API v2" is enabled.
                                                                                Ensure that the following Android Key exists:
                                                                                API Key: <<redacted>>
</code>```

答:
Go to the Google Developer console then click on the 'Enable API's and Services' option along with plus icon on the top of the Dashboard tab.Then there is a 'Google Maps Api' option under the Maps Category,select that then there is 'Manage' option which will enable your google maps apis.

After then you can create the map key for your project using your package name and then use it in your manifest.

Note- After using key please reinstall your app ones to reflect the map changes.

Body:
I created new activity which is map activity. I think I have problem in AndroidManofest.xml.
My phone works perfectly if I create new project with just map activity. If I add it to my project, which has a lot of activities, it does not work. I do not know why.

the problem is about the activities
  AndroidManofest.xml

I checked every thing APU is enable

AndroidManofest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.abdullahalhajri.smarttutor">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".activities.LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.RegisterActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.HomePage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchPage"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchRating"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.SearchSubject"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.MathTutor"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.ReviewComment"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.TutorProfile"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.UsersActivity"
            android:screenOrientation="portrait" />
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".activities.MapsActivity"
            android:label="@string/title_activity_maps">

        </activity>
    </application>

</manifest>

Error

12-04 04:31:22.639 25820-26431/com.example.abdullahalhajri.smarttutor E/Google Maps Android API: In the Google Developer Console (https://console.developers.google.com)
                                                                                Ensure that the "Google Maps Android API v2" is enabled.
                                                                                Ensure that the following Android Key exists:
                                                                                API Key: <<redacted>>


来源: stackexchange

问:
Comparing two [String: Any] dictionaries in Swift 4
I have two dictionaries that work as text attributes of type [String: Any] and in order to toggle ON or OFF the desired attributes I need to check if two dictionaries are the same.

I tried the following:

```<code>let current = inputTextView.typingAttributes

let undo = current.elementsEqual(attributes, by: { (arg0, arg1) -> Bool in
    return ((arg0.key == arg1.key) && (arg0.value == arg1.value))
})
</code>```

But on the second evaluation I get the error:

Binary operator '==' cannot be applied to two 'Any' operands

What's the best approach here to compare two dictionaries of type [String: Any] ??

Thank you

答:
Any does not conform to Equatable protocol. It is a must-have for a type if the == operator will be used. Therefore, you need to compare your Any objects using a function that takes a type parameter as mentioned in this answer:

```<code>func isEqual<T: Equatable>(type: T.Type, a: Any, b: Any) -> Bool? {
    guard let a = a as? T, let b = b as? T else { return nil }
    return a == b
}
</code>```

However, to use this function, you should know the exact type of each value in typingAttributes. You can achieve this using the Mirror struct as follows:

```<code>let lilAny: Any = "What's my type? :("
print(Mirror(reflecting: lilAny).subjectType) // String
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two dictionaries that work as text attributes of type [String: Any] and in order to toggle ON or OFF the desired attributes I need to check if two dictionaries are the same.

I tried the following:

let current = inputTextView.typingAttributes

let undo = current.elementsEqual(attributes, by: { (arg0, arg1) -> Bool in
    return ((arg0.key == arg1.key) && (arg0.value == arg1.value))
})

But on the second evaluation I get the error:

Binary operator '==' cannot be applied to two 'Any' operands

What's the best approach here to compare two dictionaries of type [String: Any] ??

Thank you

Body:
Any does not conform to Equatable protocol. It is a must-have for a type if the == operator will be used. Therefore, you need to compare your Any objects using a function that takes a type parameter as mentioned in this answer:

func isEqual<T: Equatable>(type: T.Type, a: Any, b: Any) -> Bool? {
    guard let a = a as? T, let b = b as? T else { return nil }
    return a == b
}

However, to use this function, you should know the exact type of each value in typingAttributes. You can achieve this using the Mirror struct as follows:

let lilAny: Any = "What's my type? :("
print(Mirror(reflecting: lilAny).subjectType) // String

ContentLicense: CC BY-SA 4.0


问:
Adding APIT in NS2.35 Ubuntu 16.04
Dear ns2 user after I edit cmu-trace.cc file in ns2.35 to add APIT many errors were generated. some of them are the following.
 please help me. thank you in advance.</p>

```<code> trace/cmu-trace.cc: In member function ‘void CMUTrace::format_apit(Packet*, int)’:
trace/cmu-trace.cc:1077:45: error: ‘HDR_APIT’ was not declared in this scope
             struct hdr_apit *wd = HDR_APIT(p);
                                             ^
trace/cmu-trace.cc:1078:60: error: ‘HDR_APIT_BEACON’ was not declared in this scope
             struct hdr_apit_beacon *bcn = HDR_APIT_BEACON(p);
                                                            ^
trace/cmu-trace.cc:1079:57: error: ‘HDR_APIT_RSSI’ was not declared in this scope
             struct hdr_apit_rssi *rssi = HDR_APIT_RSSI(p);
                                                         ^
.....
</code>```

答:
The three "missing" definitions are done in apit_packet.h, line 41 .. 43

```<code>#define HDR_APIT(p)             ((struct hdr_apit*)hdr_apit::access(p))
#define HDR_APIT_BEACON(p)      ((struct hdr_apit_beacon*)hdr_apit::access(p))
#define HDR_APIT_RSSI(p)        ((struct hdr_apit_rssi*)hdr_apit::access(p))
</code>```

... So all you have to do is to add a line (66) to cmu-trace.cc :

```<code>#include <apit/apit_packet.h>
</code>```

Title: Adding APIT in NS2.35 Ubuntu 16.04

Body:
Dear ns2 user after I edit cmu-trace.cc file in ns2.35 to add APIT many errors were generated. some of them are the following.
 please help me. thank you in advance.

 trace/cmu-trace.cc: In member function ‘void CMUTrace::format_apit(Packet*, int)’:
trace/cmu-trace.cc:1077:45: error: ‘HDR_APIT’ was not declared in this scope
             struct hdr_apit *wd = HDR_APIT(p);
                                             ^
trace/cmu-trace.cc:1078:60: error: ‘HDR_APIT_BEACON’ was not declared in this scope
             struct hdr_apit_beacon *bcn = HDR_APIT_BEACON(p);
                                                            ^
trace/cmu-trace.cc:1079:57: error: ‘HDR_APIT_RSSI’ was not declared in this scope
             struct hdr_apit_rssi *rssi = HDR_APIT_RSSI(p);
                                                         ^
.....

Body:
The three "missing" definitions are done in apit_packet.h, line 41 .. 43

#define HDR_APIT(p)             ((struct hdr_apit*)hdr_apit::access(p))
#define HDR_APIT_BEACON(p)      ((struct hdr_apit_beacon*)hdr_apit::access(p))
#define HDR_APIT_RSSI(p)        ((struct hdr_apit_rssi*)hdr_apit::access(p))

... So all you have to do is to add a line (66) to cmu-trace.cc :

#include <apit/apit_packet.h>


问:
Is it necessary to close the file in json.load?
It's clear that a file object should be closed to delete it from memory:

```<code>file = open('data.txt', 'r')
#more code here
file.close()
</code>```

Is it also necessary to close a file object served to the json.load method?

```<code>data = json.load(open('data.json','r'))
</code>```

I guess no since the file object not stored in a variable, but if yes, how can it be done?

答:
Don't rely on the GC to clean/close the file descriptor.
Use a context manager instead.

You also don't need to provide the mode 'r' since it is the default for open.

```<code>with open('data.json') as f:
    data = json.load(f)
</code>```

Body:
It's clear that a file object should be closed to delete it from memory:

file = open('data.txt', 'r')
#more code here
file.close()

Is it also necessary to close a file object served to the json.load method?

data = json.load(open('data.json','r'))

I guess no since the file object not stored in a variable, but if yes, how can it be done?

Body:
Don't rely on the GC to clean/close the file descriptor.
Use a context manager instead.

You also don't need to provide the mode 'r' since it is the default for open.

with open('data.json') as f:
    data = json.load(f)


问:
How do I get the App version and build number using Swift?
I have an IOS app with an Azure back-end, and would like to log certain events, like logins and which versions of the app users are running.

How can I return the version and build number using Swift?

答:
Swift 4

```<code>func getAppVersion() -> String {
    return "\(Bundle.main.infoDictionary!["CFBundleShortVersionString"] ?? "")"
}
</code>```

Bundle.main.infoDictionary!["CFBundleShortVersionString"]

Swift old syntax

```<code>let appVer: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
</code>```

Body:
Swift 4

func getAppVersion() -> String {
    return "\(Bundle.main.infoDictionary!["CFBundleShortVersionString"] ?? "")"
}

Bundle.main.infoDictionary!["CFBundleShortVersionString"]

Swift old syntax

let appVer: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]


问:
BackgroundWorker component in services
I know the BackgroundWorker should not be used in Windows Services but would anyone have a good online reference explaining why?</p>

答: I've used BackgroundWorker in windows services many times without any ill effect. While its use of SynchronizationContext may be unnecessary, I haven't observed it causing problems or poor performance.</p>

ContentLicense: CC BY-SA 2.5

Title: BackgroundWorker component in services


问:
Define common swagger annotation
Admittedly, I didn't look too hard for an answer.  My question is, when defining swagger annotations using springfox-swagger-ui, how does one define common ApiResponse used for more then one method and potentially more then one class?

See the 2 sample methods below the common ApiResponse is error 500.  Ideally, I would want to define that once. Any best practices and/or suggestions?

Sample code below:

```<code>@GET
@Path("/greeting")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Returns greeting details", notes = "Returns .....", response = Greeting.class)
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Successful retrieval of greeting details", response = Greeting.class),
    @ApiResponse(code = 404, message = "Greeting does not exist"),
    @ApiResponse(code = 500, message = "Internal server error")}
)
public Response getGreeting(.....) {
    ...
}

@GET
@Path("/something")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Returns something details", notes = "Returns .....", response = Something.class
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Successful retrieval of greeting details", response = Something.class),
    @ApiResponse(code = 404, message = "Something does not exist"),
    @ApiResponse(code = 500, message = "Internal server error")}
)
public Response getSomething(.....) {
    ...
}
</code>```

Specifically referring to:

```<code>@ApiResponse(code = 500, message = "Internal server error")
</code>```

Thank you, in advance.

答:
you can create custom annotation which use ApiResponses annotation.
And use this custom annotation at method level.
@ApiResponses()
public @interface CustomApiResponse {}</p>

Title: Define common swagger annotation

Body:
Admittedly, I didn't look too hard for an answer.  My question is, when defining swagger annotations using springfox-swagger-ui, how does one define common ApiResponse used for more then one method and potentially more then one class?

See the 2 sample methods below the common ApiResponse is error 500.  Ideally, I would want to define that once. Any best practices and/or suggestions?

Sample code below:

@GET
@Path("/greeting")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Returns greeting details", notes = "Returns .....", response = Greeting.class)
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Successful retrieval of greeting details", response = Greeting.class),
    @ApiResponse(code = 404, message = "Greeting does not exist"),
    @ApiResponse(code = 500, message = "Internal server error")}
)
public Response getGreeting(.....) {
    ...
}

@GET
@Path("/something")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Returns something details", notes = "Returns .....", response = Something.class
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Successful retrieval of greeting details", response = Something.class),
    @ApiResponse(code = 404, message = "Something does not exist"),
    @ApiResponse(code = 500, message = "Internal server error")}
)
public Response getSomething(.....) {
    ...
}

Specifically referring to:

@ApiResponse(code = 500, message = "Internal server error")

Thank you, in advance.


问:
How to add a div between two divs by Javascript
I am using wordpress and I want to add some html code on page using Javascript. I don't want to make child theme then edit php files. It is risky and I don't know about php.

I want to add a sibling div. This is an example code as default.

```<code><div class="div1">
  <div class="div1inside">
  Text
  </div>
</div>

<div class="div2">
  <div class="div2inside">
  Text
  </div>
</div>
</code>```

Now I want to add my custom div and its inside html between both div1 and div2.

```<code><div class="mydiv">
  <div class="mydivinside">
  Text
  </div>
</div>
</code>```

Please let me know how is it possible using Javascript.

答:
This link will be helpfull to get the above result.

https://plainjs.com/javascript/manipulation/insert-an-element-after-or-before-another-32/

Body:
I am using wordpress and I want to add some html code on page using Javascript. I don't want to make child theme then edit php files. It is risky and I don't know about php.

I want to add a sibling div. This is an example code as default.

  Text

  Text

Now I want to add my custom div and its inside html between both div1 and div2.

  Text

Please let me know how is it possible using Javascript.


问:
Different jQuery sources & versions in same page (googleapi, Code)
I have to pages, first for sortable list (li), which used the following Javascripts:

```<code><link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
</code>```

The second page for mmenu which have the following jquery:

```<code><script type="text/javascript" src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="/theme/mmenu/dist/jquery.mmenu.all.js"></script>
</code>```

When I want to add both scripts into a single page( where menu and sortable are working), there are some errors appear since when I remove Jquerys of sortable then the mmnue will work, and when I remove Jquery of sortable then mmenu won't work!

So please how to get both of them work on a single page?

答:
This is possible using jQuery.noConflict()

Something like:

```<code><script src='jquery-1.3.2.js'></script>
<script>
var jq132 = jQuery.noConflict();
</script>
<script src='jquery-1.4.2.js'></script>
<script>
var jq142 = jQuery.noConflict();
</script>
</code>```

See this for more examples: http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/

Body:
I have to pages, first for sortable list (li), which used the following Javascripts:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />

The second page for mmenu which have the following jquery:

When I want to add both scripts into a single page( where menu and sortable are working), there are some errors appear since when I remove Jquerys of sortable then the mmnue will work, and when I remove Jquery of sortable then mmenu won't work!

So please how to get both of them work on a single page?

Body:
This is possible using jQuery.noConflict()

Something like:

<script src='jquery-1.3.2.js'></script>
<script>
var jq132 = jQuery.noConflict();
</script>
<script src='jquery-1.4.2.js'></script>
<script>
var jq142 = jQuery.noConflict();
</script>

See this for more examples: http://blog.nemikor.com/2009/10/03/using-multiple-versions-of-jquery/


问:
Loop inside of a loop, in React JSX
I am trying to render in react, jsx, a loop inside of a loop
Like bellow:

```<code>{this.state.ans.map(function(item) {
    return (
        {this.state.quest.map(
            function(item1) {return (item1)}
        )}
        {item}
    )
})}
</code>```

This does not work any other suggestions

答:
Try it like this:

```<code>render(){
    return (
        .
        .
        .
        {this.state.ans.map((item) => {
            return (
                <div>
                    {this.state.quest.map((item1) => {
                           return (item1);
                        }
                    )}
                   {item}
               </div>
            );
        })}
    );
}
</code>```

Basically the idea is that, you should return a single element - in my example a div (with the latest react version you don't have to). And moreover, use lambdas in order for this to reference the correct context.

If you do not use ES6, you can add the following statement at the beginning of the render method:

```<code>var that = this;
</code>```

and use that afterwards with the function(){} syntax inside the return.

Title: Loop inside of a loop, in React JSX

Body:
I am trying to render in react, jsx, a loop inside of a loop
Like bellow:

{this.state.ans.map(function(item) {
    return (
        {this.state.quest.map(
            function(item1) {return (item1)}
        )}
        {item}
    )
})}

This does not work any other suggestions

Body:
Try it like this:

render(){
    return (
        .
        .
        .
        {this.state.ans.map((item) => {
            return (
                <div>
                    {this.state.quest.map((item1) => {
                           return (item1);
                        }
                    )}
                   {item}
               </div>
            );
        })}
    );
}

Basically the idea is that, you should return a single element - in my example a div (with the latest react version you don't have to). And moreover, use lambdas in order for this to reference the correct context.

If you do not use ES6, you can add the following statement at the beginning of the render method:

var that = this;

and use that afterwards with the function(){} syntax inside the return.


问:
IE11 fails with "Netscape is not supported please used internet explorer" error when launch by Selenium
I have a quite old website to be maintained, supports IE8 and above.
Now I've a plan to do some test automation on the site, using Selenium WebDriver (version 3.7.1). Almost everything works well, except for some pages that use document.getElementById(). The point is, these pages utilize the "feature" of IE11 that when no element matches with specified ID, it then returns the element with that ID as name (as denoted in this thread).

And when brower (IE11) started by selenium, it fails to invoke that code (return a NULL, causing error).

Further investigate, I found that, when launched manually, invoking navigator.appName returns "Microsoft Internet Explorer", while returns "Netscape" in the other case.

What does that difference mean, and is that the root cause of my problem. And most important, how to resolve that?

I'm launching the page with this source code:

```<code>DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
WebDriver driver = new InternetExplorerDriver(
                    new InternetExplorerOptions(ieCapabilities));
wait = new WebDriverWait(driver, 30);
driver.get(url);
</code>```

答:
As you mentioned invoking navigator.appName returns "Microsoft Internet Explorer" while returns "Netscape" in the other case is a rare but prevailing scenario. The complete error reads as :

```<code>"Netscape is not supported please used internet explorer "
</code>```

Solution:

To address this, you have to consider the following points:

Internet Explorer Driver runs in a real browser and supports Javascript.

Try to avoid any Add On's with Internet Explorer

If you have to use any mandatory Add On's, (for all IE9,IE10,IE11 and Windows 8 users)

```<code>1. Open the desired website in Internet Explorer
2. Go to "Compatibility View settings" (image shown below)
3. In a dialog box add your website in the list.
e.g. if you are trying to use "ssconline.nic.in" , then add "nic.in" in the list
</code>```

Body:
I have a quite old website to be maintained, supports IE8 and above.
Now I've a plan to do some test automation on the site, using Selenium WebDriver (version 3.7.1). Almost everything works well, except for some pages that use document.getElementById(). The point is, these pages utilize the "feature" of IE11 that when no element matches with specified ID, it then returns the element with that ID as name (as denoted in this thread).

And when brower (IE11) started by selenium, it fails to invoke that code (return a NULL, causing error).

Further investigate, I found that, when launched manually, invoking navigator.appName returns "Microsoft Internet Explorer", while returns "Netscape" in the other case.

What does that difference mean, and is that the root cause of my problem. And most important, how to resolve that?

I'm launching the page with this source code:

DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
WebDriver driver = new InternetExplorerDriver(
                    new InternetExplorerOptions(ieCapabilities));
wait = new WebDriverWait(driver, 30);
driver.get(url);

Body:
As you mentioned invoking navigator.appName returns "Microsoft Internet Explorer" while returns "Netscape" in the other case is a rare but prevailing scenario. The complete error reads as :

"Netscape is not supported please used internet explorer "

Solution:

To address this, you have to consider the following points:

Internet Explorer Driver runs in a real browser and supports Javascript.

Try to avoid any Add On's with Internet Explorer

If you have to use any mandatory Add On's, (for all IE9,IE10,IE11 and Windows 8 users)

1. Open the desired website in Internet Explorer
2. Go to "Compatibility View settings" (image shown below)
3. In a dialog box add your website in the list.
e.g. if you are trying to use "ssconline.nic.in" , then add "nic.in" in the list


问:
Install laravel in shared hosting website's subfolder
im trying to install Laravel in my shared hosting website's(which is not laravel) subfolder.
for example in: example.com/dev

Structure:

```<code>->laravel
  ->app
  ->bootstrap
->public_html
  ...example.com folders & files
  ->dev
    ->css
    ->js
    ->.htacess
    ->index.php
    ... other Laravel public files
</code>```

My example.com/dev/index.php looks like this:

```<code>... laravel codes

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/

require __DIR__.'/../../laravel/bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../../laravel/bootstrap/app.php';

... laravel codes
</code>```

Problem:
When i try to enter http://example.com/dev/ browser throws error:

This page isn’t working

mysite.com didn’t send any data.

ERR_EMPTY_RESPONSE

THERE ARE NO ANY INFORMATION/SOLUTION FOR THIS PROBLEM IN THE INTERNET.

ANY SOLUTION?

答: Your entire project should be inside your public_html folder. Then move all the contents of your public folder to public_html as well. Then edit your index.php to match the proper directory for autoload.php and app.php

Body:
im trying to install Laravel in my shared hosting website's(which is not laravel) subfolder.
for example in: example.com/dev

Structure:

->laravel
  ->app
  ->bootstrap
->public_html
  ...example.com folders & files
  ->dev
    ->css
    ->js
    ->.htacess
    ->index.php
    ... other Laravel public files

My example.com/dev/index.php looks like this:

... laravel codes

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/

require __DIR__.'/../../laravel/bootstrap/autoload.php';

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

$app = require_once __DIR__.'/../../laravel/bootstrap/app.php';

... laravel codes

Problem:
When i try to enter http://example.com/dev/ browser throws error:

This page isn’t working

mysite.com didn’t send any data.

ERR_EMPTY_RESPONSE

THERE ARE NO ANY INFORMATION/SOLUTION FOR THIS PROBLEM IN THE INTERNET.

ANY SOLUTION?


问:
How does Stack Overflow generate its SEO-friendly URLs?
What is a good complete regular expression or some other process that would take the title:

How do you change a title to be part of the URL like Stack Overflow?

and turn it into

how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow
```

that is used in the SEO-friendly URLs on Stack Overflow?

The development environment I am using is Ruby on Rails, but if there are some other platform-specific solutions (.NET, PHP, Django), I would love to see those too.

I am sure I (or another reader) will come across the same problem on a different platform down the line.

I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced.

答:
T-SQL implementation, adapted from dbo.UrlEncode:</p>

```<code>CREATE FUNCTION dbo.Slug(@string varchar(1024))
RETURNS varchar(3072)
AS
BEGIN
    DECLARE @count int, @c char(1), @i int, @slug varchar(3072)

    SET @string = replace(lower(ltrim(rtrim(@string))),' ','-')

    SET @count = Len(@string)
    SET @i = 1
    SET @slug = ''

    WHILE (@i <= @count)
    BEGIN
        SET @c = substring(@string, @i, 1)

        IF @c LIKE '[a-z0-9--]'
            SET @slug = @slug + @c

        SET @i = @i +1
    END

    RETURN @slug
END
</code>```

OwnerDisplayName: Maudite

Body:
What is a good complete regular expression or some other process that would take the title:

How do you change a title to be part of the URL like Stack Overflow?

and turn it into

how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow

that is used in the SEO-friendly URLs on Stack Overflow?

The development environment I am using is Ruby on Rails, but if there are some other platform-specific solutions (.NET, PHP, Django), I would love to see those too.

I am sure I (or another reader) will come across the same problem on a different platform down the line.

I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced.

LastEditorDisplayName: Gerald Kaszuba

Body:
T-SQL implementation, adapted from dbo.UrlEncode:

CREATE FUNCTION dbo.Slug(@string varchar(1024))
RETURNS varchar(3072)
AS
BEGIN
    DECLARE @count int, @c char(1), @i int, @slug varchar(3072)

    SET @string = replace(lower(ltrim(rtrim(@string))),' ','-')

    SET @count = Len(@string)
    SET @i = 1
    SET @slug = ''

    WHILE (@i <= @count)
    BEGIN
        SET @c = substring(@string, @i, 1)

        IF @c LIKE '[a-z0-9--]'
            SET @slug = @slug + @c

        SET @i = @i +1
    END

    RETURN @slug
END

OwnerDisplayName: Soeren Kuklau


问:
Retrieving a random record from DB
Wondering what is the best way to retrieve a random record from the database in my Ruby on Rails (2.3.9) applications. </p>

<p>The closest I got was using the below. SQLITE3 liked it by in production MySQL did not. </p>

```<code>#class PostsController < ApplicationController
...
@posts = Post.all(:order => "RANDOM()")
...
end

#view
<% @posts.each do |post| %>
...
<% end %>
</code>```

答:
The following SQL query works fine for me on MySQL:

```<code>SELECT *
FROM table
ORDER BY rand()
LIMIT 1
</code>```

I'm not sure what the rails equivalent of this, but you get the idea

I'll take a guess that the Rails equivalent of above SQL would be:

```<code>Post.all(:order => "rand()", :limit => 1)
</code>```

Title: Retrieving a random record from DB

Body:
Wondering what is the best way to retrieve a random record from the database in my Ruby on Rails (2.3.9) applications.

The closest I got was using the below. SQLITE3 liked it by in production MySQL did not.

#class PostsController < ApplicationController
...
@posts = Post.all(:order => "RANDOM()")
...
end

#view
<% @posts.each do |post| %>
...
<% end %>

Body:
The following SQL query works fine for me on MySQL:

SELECT *
FROM table
ORDER BY rand()
LIMIT 1

I'm not sure what the rails equivalent of this, but you get the idea

I'll take a guess that the Rails equivalent of above SQL would be:

Post.all(:order => "rand()", :limit => 1)


问:
Alter data in object of arrays
In a React app, I have this type of data:

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}
</code>```

I want to iterate over each object in the open and close arrays and return the existing data with additional type field. E.g.:

```<code>const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}
</code>```

I'm trying something like this, but it returns undefined instead of the altered data:

```<code>const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above
</code>```

https://jsfiddle.net/x5aspec2/

答:
You could vreate new object and map the array objects with new property.

const
    expandData = data =>
        Object
            .keys(data)
            .map(key =>
                Object.assign(
                    { [key]: data[key].map(o => Object.assign({}, o, { type: 'alert' })) }
                )
            ),
    data = { open: [{ id: 1, name: 'test 1' }, { id: 2, name: 'test 2' }], close: [{ id: 3, name: 'test 3' }, { id: 4, name: 'test 4' }] };

console.log(expandData(data));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Alter data in object of arrays

Body:
In a React app, I have this type of data:

const data = {
  open: [{
    id: 1,
    name: 'test 1'
  }, {
    id: 2,
    name: 'test 2'
  }],
  close: [{
    id: 3,
    name: 'test 3'
  }, {
    id: 4,
    name: 'test 4'
  }]
}

I want to iterate over each object in the open and close arrays and return the existing data with additional type field. E.g.:

const data = {
  open: [{
    id: 1,
    name: 'test 1',
    type: 'alert'
  }, {...],
  close: [...]
}

I'm trying something like this, but it returns undefined instead of the altered data:

const expandData = (data) => {
  return Object.keys(data).forEach((key) => {
    return data[key].map((item, idx) => ({
      ...item,
      type: 'alert'
    }))
  })
}

// call in another method
expandData(data) // the `data` above

https://jsfiddle.net/x5aspec2/

Body:
You could vreate new object and map the array objects with new property.

const
    expandData = data =>
        Object
            .keys(data)
            .map(key =>
                Object.assign(
                    { [key]: data[key].map(o => Object.assign({}, o, { type: 'alert' })) }
                )
            ),
    data = { open: [{ id: 1, name: 'test 1' }, { id: 2, name: 'test 2' }], close: [{ id: 3, name: 'test 3' }, { id: 4, name: 'test 4' }] };

console.log(expandData(data));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Location of the mysqldump file
Currently I am learning MySql using commandline in ubuntu and made a backup of my database named 'sandwich' using mysqldump command.

mysql> #mysqldump -u root -p123456 sandwich > db_backup.sql;

Where I can find this 'db_backup.sql' file on the disk. Please tell me a specific file path where i can find this file.

答:
run following command without logging into mysql terminal.

```<code>mysqldump -u root -p db_name > db_dump.sql
</code>```

It will ask for password. Enter password.

When dump is complete type following command.

```<code>ls
</code>```

You will see db_dump.sql file in the list.

Title: Location of the mysqldump file

Body:
run following command without logging into mysql terminal.

mysqldump -u root -p db_name > db_dump.sql

It will ask for password. Enter password.

When dump is complete type following command.

ls

You will see db_dump.sql file in the list.


问:
Java matchesAt() equivalent in C#
I have already discovered the question C#/.NET equivalent for Java's Matcher.matches() and Matcher.lookingAt(), but the prescribed answer for lookingAt() there does not seem to work.

All of the lookingAt() documentation I can find seems to indicate that the lookingAt() method matches from the beginning of the "region" (although it isn't quite clear if "region" is synonymous with "the string").

I have an example set of tests that I put together in both Java and .NET, but I am getting different results.

Java

```<code>@Test
public void TestRegex()
{
    String input = "자\uD83E"; // "자";
    String regex = ". () [\uD800-\uDFFF]";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher("");

    Matcher m = matcher.reset(input);
    Boolean matches = m.lookingAt(); // Returns false
}
</code>```

.NET

```<code>[Test]
public void TestRegex()
{
    String input = @"\A(?:" + "자\uD83E" + ")"; // "자"
    String regex = ". () [\uD800-\uDFFF]";
    Regex pattern = new Regex(regex, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);

    Match m = pattern.Match(input);
    Boolean matches = m.Success; // Returns true
}
</code>```

I have ruled out any issues with whitespace or that strange empty capturing group - I get the same results whether they exist or not.

I have also tried changing the regex in .NET to "자\uD83E" and using m.Success && m.Index == 0 as the condition, but the result is exactly the same. And of course, I tried both with string literals and hexadecimal characters and the result is the same.

To be clear, I am porting an application from Java to .NET. I am trying to find the equivalent functionality to lookingAt() in .NET.

So what do I need to change in .NET to make it act the same as .lookingAt() in Java? More importantly, why is this particular case returning false in Java, as I would expect it to be true like in .NET?

In case it matters, I am using .NET Standard 1.3 and Java 1.8 with 1.6 compatibility.

答:
In Java you need to use Pattern.COMMENTS flag to allow comments and arbitrary whitespaces in your regex:

```<code>Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
</code>```

You can also use (?x) at the start of regex for same effect:

```<code>String regex = "(?x). () [\uD800-\uDFFF]";
Pattern pattern = Pattern.compile(regex);
</code>```

Now matches will show true for Java code.

Now to make .NET regex equivalent of lookngAt() of Java just use start anchor:

```<code>String regex = @"\A. () [\uD800-\uDFFF]";
</code>```

Note that you're using anchor in input string, not in regex.

Title: Java matchesAt() equivalent in C#

Body:
I have already discovered the question C#/.NET equivalent for Java's Matcher.matches() and Matcher.lookingAt(), but the prescribed answer for lookingAt() there does not seem to work.

All of the lookingAt() documentation I can find seems to indicate that the lookingAt() method matches from the beginning of the "region" (although it isn't quite clear if "region" is synonymous with "the string").

I have an example set of tests that I put together in both Java and .NET, but I am getting different results.

Java

@Test
public void TestRegex()
{
    String input = "자\uD83E"; // "자";
    String regex = ". () [\uD800-\uDFFF]";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher("");

    Matcher m = matcher.reset(input);
    Boolean matches = m.lookingAt(); // Returns false
}

.NET

[Test]
public void TestRegex()
{
    String input = @"\A(?:" + "자\uD83E" + ")"; // "자"
    String regex = ". () [\uD800-\uDFFF]";
    Regex pattern = new Regex(regex, RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace);

    Match m = pattern.Match(input);
    Boolean matches = m.Success; // Returns true
}

I have ruled out any issues with whitespace or that strange empty capturing group - I get the same results whether they exist or not.

I have also tried changing the regex in .NET to "자\uD83E" and using m.Success && m.Index == 0 as the condition, but the result is exactly the same. And of course, I tried both with string literals and hexadecimal characters and the result is the same.

To be clear, I am porting an application from Java to .NET. I am trying to find the equivalent functionality to lookingAt() in .NET.

So what do I need to change in .NET to make it act the same as .lookingAt() in Java? More importantly, why is this particular case returning false in Java, as I would expect it to be true like in .NET?

In case it matters, I am using .NET Standard 1.3 and Java 1.8 with 1.6 compatibility.

Body:
In Java you need to use Pattern.COMMENTS flag to allow comments and arbitrary whitespaces in your regex:

Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);

You can also use (?x) at the start of regex for same effect:

String regex = "(?x). () [\uD800-\uDFFF]";
Pattern pattern = Pattern.compile(regex);

Now matches will show true for Java code.

Now to make .NET regex equivalent of lookngAt() of Java just use start anchor:

String regex = @"\A. () [\uD800-\uDFFF]";

Note that you're using anchor in input string, not in regex.


答:
BackgroundWorker relies on a current SynchronizationContext being set in order to function. It's really intended and designed specifically for working with UI code.

It's typically better in a service to self-manage your threads, since there are no UI synchronization issues.  Using the threading API (or .NET 4 Task API) is a much better option here.

Title: BackgroundWorker component in services

Body: I know the BackgroundWorker should not be used in Windows Services but would anyone have a good online reference explaining why?


问:
Update React Component after render
I am using react-native-sortable-listview to change order of list-item by drag and drop. Only drag item is again rendered so its position is updated but other have their previous position. When This component is re-rendered by other cause like some increment button, all position are being correct.
 So my question is when my react-native-sortable-list is rendered how can I re-render this again.
 Both ways to render by forceUpdate() and this.setState() , I could not follow as I can not update state in render function.
 What can be a possible way for doing this.

答:
Try using componentWillMount or componentDidMount:

```<code>componentWillMount = () => {
  this.setState({
    data: myData
  });
}
</code>```

Basically at whatever stage your component is rendered you need to capture that event and call setState(); You could also re-render through a button as well. User clicks a button, then you setState(); Hope this helps!

Title: Update React Component after render

Body:
Try using componentWillMount or componentDidMount:

componentWillMount = () => {
  this.setState({
    data: myData
  });
}

Basically at whatever stage your component is rendered you need to capture that event and call setState(); You could also re-render through a button as well. User clicks a button, then you setState(); Hope this helps!


问:
Only counting data that fits certain criteria in SQL on Microsoft Access
I have 1 table in microsoft access with student information (including gender and grade). I'm trying to use the SQL view to get a count of how many male and females are in each grade. Right now, this is what I have. </p>

```<code>SELECT
StudDetails.CurrClass as 'class',
Count(StudeDetails.sex) WHERE (StudDetails.sex="M" AND StudDetails.CurrClass='class') AS 'malecount', Count (StudeDetails.sex) WHERE (StudDetails.sex="F"AND StudDetails.CurrClass='class') AS 'femalecount'
FROM StudDetails
GROUP BY StudDetails.CurrClass;
</code>```

<p>I know this is super bad but I'm new to SQL. I've tried googling but I don't understand the answers or can't apply them. </p>

Body:
I have 1 table in microsoft access with student information (including gender and grade). I'm trying to use the SQL view to get a count of how many male and females are in each grade. Right now, this is what I have.

SELECT
StudDetails.CurrClass as 'class',
Count(StudeDetails.sex) WHERE (StudDetails.sex="M" AND StudDetails.CurrClass='class') AS 'malecount', Count (StudeDetails.sex) WHERE (StudDetails.sex="F"AND StudDetails.CurrClass='class') AS 'femalecount'
FROM StudDetails
GROUP BY StudDetails.CurrClass;

I know this is super bad but I'm new to SQL. I've tried googling but I don't understand the answers or can't apply them.

Body:
Given two fields in the table - Class and Gender

The table on the left will give the results shown on the right with this SQL:

SELECT      Class
            , Sex
            , COUNT(Sex) AS CountOfGender
FROM        StudDetails
GROUP BY    Class, Sex

The only downside here is that it won't show 0 if there's none of a certain gender in a class - it just won't show that gender.

+-------+--------+  +-------+--------+---------------+
| Class | Sex    |  | Class | Sex    | CountOfSex    |
+-------+--------+  +-------+--------+---------------+
|   A   |    M   |  |   A   |    F   |       2       |
+-------+--------+  +-------+--------+---------------+
|   B   |    M   |  |   A   |    M   |       3       |
+-------+--------+  +-------+--------+---------------+
|   C   |    F   |  |   B   |    M   |       1       |
+-------+--------+  +-------+--------+---------------+
|   A   |    F   |  |   C   |    F   |       1       |
+-------+--------+  +-------+--------+---------------+
|   A   |    M   |  |   D   |    M   |       2       |
+-------+--------+  +-------+--------+---------------+
|   A   |    M   |
+-------+--------+
|   D   |    M   |
+-------+--------+
|   D   |    M   |
+-------+--------+
|   A   |    F   |
+-------+--------+

Edit:
To get Male & Female in separate fields and include 0 you could then just cross-tab the query above:

TRANSFORM NZ(Sum(CountOfSex),0) AS CountOfGender
SELECT Class
FROM (
        SELECT      Class
                    , Sex
                    , COUNT(Sex) AS CountOfSex
        FROM        StudDetails
        GROUP BY    Class, Sex
      )
GROUP BY Class
PIVOT Sex

+-------+---+---+
| Class | F | M |
+-------+---+---+
|   A   | 2 | 3 |
+-------+---+---+
|   B   | 0 | 1 |
+-------+---+---+
|   C   | 1 | 0 |
+-------+---+---+
|   D   | 0 | 2 |
+-------+---+---+

Edit again:  The good thing about this method above conditionally counting Male & Female (IIF sex='M'.. etc) is that if someone decides they don't want to identify as Male or Female it will happily list any other gender you can think of.

+-------+---+---+---+
| Class | F | M | Z |
+-------+---+---+---+
|   A   | 2 | 3 | 0 |
+-------+---+---+---+
|   B   | 0 | 1 | 0 |
+-------+---+---+---+
|   C   | 1 | 0 | 0 |
+-------+---+---+---+
|   D   | 0 | 2 | 1 |
+-------+---+---+---+


问:
RecyclerView CardLayout images getting smaller in size after each refresh
I'm using RecyclerView and CardLayout on a TabLayout with 5 tabs, each represented as a fragment. Whenever I click on a tab, i first check if the fragment is visible. If true, I execute my UI code which involves invoking a REST service to fetch data from a db which is then populated to the RecyclerView by a custom adapter. I temporarily cache the data in an ArrayList so that frequent attempts to the fragment wont need another REST request. My problem is whenever I navigate to a certain tab more than once, the layout gets smaller and smaller after each attempt. Below are my Fragment, Adapter and Adapter Layout.</p>

```<code>public class BeerFragment extends Fragment {
    private RecyclerView recyclerView;
    ProgressDialog pd;
    private View rootView;
    private static final String TAG = BeerFragment.class.getSimpleName();
    public static boolean isLoadedBeer = false;
    public boolean instantiated = false;
    public BeerFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        rootView  = inflater.inflate(R.layout.activity_main2, container, false);
        initViews();
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && MaintainState.isLoadedBeer) {
            initViews();
        } else if (isVisibleToUser && !MaintainState.isLoadedBeer) {
        } else if (!isVisibleToUser && MaintainState.isLoadedBeer){
        } else if (!isVisibleToUser && !MaintainState.isLoadedBeer){
            MaintainState.isLoadedBeer = true;
        }
    }

    private void initViews(){
        pd = new ProgressDialog(getActivity());
        pd.setMessage("Fetching Beer...");
        pd.setCancelable(false);
        pd.show();
        Log.d("snopww4","noppww");
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }

        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        ArrayList albumList = new ArrayList<>();
        GalleryAdapter  adapter = new GalleryAdapter(getActivity(), albumList,2);
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, GridSpacingItemDecoration.dpToPx(getActivity(), 10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        if (!isLoadedBeer) {
            Log.d("lklk","lklk");
        String drink = FilterFragment.sorted;
        if (drink.equals("empty")){
            loadBeer("beer");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("lager")){
            loadBeer("lager");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("stout")){
            loadBeer("stout");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("malt")){
            loadBeer("malt");
            FilterFragment.sorted = "empty";
        } else {
            pd.hide();
        }
    } else {
        recyclerView.setAdapter(new GalleryAdapter(getActivity(), MaintainState.getItemsBeer(), 1));
        recyclerView.smoothScrollToPosition(0);
        pd.hide();
    }
    }

    private void loadBeer(final String item){
        try{
            Client Client = new Client();
            Service apiService = Client.getClient().create(Service.class);
            Call<GalleryResponse> call = apiService.getBeer(item);
            call.enqueue(new Callback<GalleryResponse>() {
                @Override
                public void onResponse(Call<GalleryResponse> call, Response<GalleryResponse> response) {
                    List<Gallery> items = response.body().getBeer();
                    recyclerView.setAdapter(new GalleryAdapter(getActivity(), items, 2));
                    recyclerView.smoothScrollToPosition(0);
                    MaintainState.setItemsBeer(items);
                    isLoadedBeer = true;
                    pd.hide();
                }

                @Override
                public void onFailure(Call<GalleryResponse> call, Throwable t) {
                    pd.hide();

                }
            });
        }catch (Exception e){
        }
    }
}

public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {

    private Context mContext;
    private List<Gallery> albumList;
    private int tabPosition;
    private LocalStore localStore;
    private static final String TAG = GalleryAdapter.class.getSimpleName();

    public GalleryAdapter(Context mContext, List<Gallery> albumList, int tabPosition) {
        Log.i(TAG, "INIT GalleryAdapter");
        this.mContext = mContext;
        this.albumList = albumList;
        this.tabPosition = tabPosition;
        localStore = new LocalStore(mContext);
    }

    @Override
    public GalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.album_card2, viewGroup, false);
        CardView cardView = (CardView) view.findViewById(R.id.card_view);
        cardView.setMaxCardElevation(GridSpacingItemDecoration.dpToPx(mContext, 10));
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final GalleryAdapter.MyViewHolder viewHolder, int i) {
        viewHolder.title.setText(albumList.get(i).getName());
        viewHolder.title.setTypeface(Display.displayTypefaceCabin(mContext, 1), Typeface.BOLD);
        viewHolder.count.setText("Ksh "+albumList.get(i).getPrice());
        viewHolder.count.setTypeface(Display.displayTypefaceWalkWay(mContext, 1), Typeface.BOLD);
        viewHolder.tag.setTypeface(Display.displayTypefaceOpenSansCondensed(mContext, 1), Typeface.BOLD);

        Glide.with(mContext).
                load(albumList.get(i).getThumbnail()).
                placeholder(R.drawable.placeholder).
                error(R.drawable.placeholder).
                fitCenter().
                into(viewHolder.thumbnail);
    }

    @Override
    public int getItemCount() {
        return albumList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, count, tag;
        public ImageView thumbnail, favourite;

        public MyViewHolder(final View view) {
            super(view);
            tag = (TextView) view.findViewById(R.id.tag);
            title = (TextView) view.findViewById(R.id.title);
            count = (TextView) view.findViewById(R.id.count);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            favourite = (ImageView) view.findViewById(R.id.favourite);

            thumbnail.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                }
            });
        }
    }
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:background="#f2f5f7"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_marginLeft="-10dp"
        card_view:cardCornerRadius="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:background="@drawable/image_view_drop_shadow"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/tag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="3dp"
                android:paddingBottom="3dp"
                android:text="hello"
                android:textColor="@color/white"
                android:textSize="12dp"/>

            <ImageView
                android:id="@+id/favourite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="5dp"
                android:layout_alignParentRight="true"/>

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_width="match_parent"
                android:layout_height="220dp"
                android:clickable="true"
                android:scaleType="fitXY" />

            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/thumbnail"
                android:gravity="center"
                android:textColor="#000000"
                android:paddingBottom="5dp"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/count"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/title"
                android:gravity="center"
                android:paddingBottom="15dp"
                android:textSize="14sp" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

答:
Its because of initViews(). You are calling two times first is from onCreate and second from setUserVisibleHint.

```<code>RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(mLayoutManager);
</code>```

This will crating your size smaller after each refresh.

Body:
I'm using RecyclerView and CardLayout on a TabLayout with 5 tabs, each represented as a fragment. Whenever I click on a tab, i first check if the fragment is visible. If true, I execute my UI code which involves invoking a REST service to fetch data from a db which is then populated to the RecyclerView by a custom adapter. I temporarily cache the data in an ArrayList so that frequent attempts to the fragment wont need another REST request. My problem is whenever I navigate to a certain tab more than once, the layout gets smaller and smaller after each attempt. Below are my Fragment, Adapter and Adapter Layout.

public class BeerFragment extends Fragment {
    private RecyclerView recyclerView;
    ProgressDialog pd;
    private View rootView;
    private static final String TAG = BeerFragment.class.getSimpleName();
    public static boolean isLoadedBeer = false;
    public boolean instantiated = false;
    public BeerFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        rootView  = inflater.inflate(R.layout.activity_main2, container, false);
        initViews();
        return rootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && MaintainState.isLoadedBeer) {
            initViews();
        } else if (isVisibleToUser && !MaintainState.isLoadedBeer) {
        } else if (!isVisibleToUser && MaintainState.isLoadedBeer){
        } else if (!isVisibleToUser && !MaintainState.isLoadedBeer){
            MaintainState.isLoadedBeer = true;
        }
    }

    private void initViews(){
        pd = new ProgressDialog(getActivity());
        pd.setMessage("Fetching Beer...");
        pd.setCancelable(false);
        pd.show();
        Log.d("snopww4","noppww");
        try {
        } catch (Exception e) {
            e.printStackTrace();
        }

        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        ArrayList albumList = new ArrayList<>();
        GalleryAdapter  adapter = new GalleryAdapter(getActivity(), albumList,2);
        RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(2, GridSpacingItemDecoration.dpToPx(getActivity(), 10), true));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        if (!isLoadedBeer) {
            Log.d("lklk","lklk");
        String drink = FilterFragment.sorted;
        if (drink.equals("empty")){
            loadBeer("beer");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("lager")){
            loadBeer("lager");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("stout")){
            loadBeer("stout");
            FilterFragment.sorted = "empty";
        } else if (drink.equals("malt")){
            loadBeer("malt");
            FilterFragment.sorted = "empty";
        } else {
            pd.hide();
        }
    } else {
        recyclerView.setAdapter(new GalleryAdapter(getActivity(), MaintainState.getItemsBeer(), 1));
        recyclerView.smoothScrollToPosition(0);
        pd.hide();
    }
    }

    private void loadBeer(final String item){
        try{
            Client Client = new Client();
            Service apiService = Client.getClient().create(Service.class);
            Call<GalleryResponse> call = apiService.getBeer(item);
            call.enqueue(new Callback<GalleryResponse>() {
                @Override
                public void onResponse(Call<GalleryResponse> call, Response<GalleryResponse> response) {
                    List<Gallery> items = response.body().getBeer();
                    recyclerView.setAdapter(new GalleryAdapter(getActivity(), items, 2));
                    recyclerView.smoothScrollToPosition(0);
                    MaintainState.setItemsBeer(items);
                    isLoadedBeer = true;
                    pd.hide();
                }

                @Override
                public void onFailure(Call<GalleryResponse> call, Throwable t) {
                    pd.hide();

                }
            });
        }catch (Exception e){
        }
    }
}

public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder> {

    private Context mContext;
    private List<Gallery> albumList;
    private int tabPosition;
    private LocalStore localStore;
    private static final String TAG = GalleryAdapter.class.getSimpleName();

    public GalleryAdapter(Context mContext, List<Gallery> albumList, int tabPosition) {
        Log.i(TAG, "INIT GalleryAdapter");
        this.mContext = mContext;
        this.albumList = albumList;
        this.tabPosition = tabPosition;
        localStore = new LocalStore(mContext);
    }

    @Override
    public GalleryAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.album_card2, viewGroup, false);
        CardView cardView = (CardView) view.findViewById(R.id.card_view);
        cardView.setMaxCardElevation(GridSpacingItemDecoration.dpToPx(mContext, 10));
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final GalleryAdapter.MyViewHolder viewHolder, int i) {
        viewHolder.title.setText(albumList.get(i).getName());
        viewHolder.title.setTypeface(Display.displayTypefaceCabin(mContext, 1), Typeface.BOLD);
        viewHolder.count.setText("Ksh "+albumList.get(i).getPrice());
        viewHolder.count.setTypeface(Display.displayTypefaceWalkWay(mContext, 1), Typeface.BOLD);
        viewHolder.tag.setTypeface(Display.displayTypefaceOpenSansCondensed(mContext, 1), Typeface.BOLD);

        Glide.with(mContext).
                load(albumList.get(i).getThumbnail()).
                placeholder(R.drawable.placeholder).
                error(R.drawable.placeholder).
                fitCenter().
                into(viewHolder.thumbnail);
    }

    @Override
    public int getItemCount() {
        return albumList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title, count, tag;
        public ImageView thumbnail, favourite;

        public MyViewHolder(final View view) {
            super(view);
            tag = (TextView) view.findViewById(R.id.tag);
            title = (TextView) view.findViewById(R.id.title);
            count = (TextView) view.findViewById(R.id.count);
            thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
            favourite = (ImageView) view.findViewById(R.id.favourite);

            thumbnail.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v){
                }
            });
        }
    }
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:background="#f2f5f7"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_marginLeft="-10dp"
        card_view:cardCornerRadius="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:background="@drawable/image_view_drop_shadow"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/tag"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:paddingTop="3dp"
                android:paddingBottom="3dp"
                android:text="hello"
                android:textColor="@color/white"
                android:textSize="12dp"/>

            <ImageView
                android:id="@+id/favourite"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginRight="5dp"
                android:layout_alignParentRight="true"/>

            <ImageView
                android:id="@+id/thumbnail"
                android:layout_width="match_parent"
                android:layout_height="220dp"
                android:clickable="true"
                android:scaleType="fitXY" />

            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/thumbnail"
                android:gravity="center"
                android:textColor="#000000"
                android:paddingBottom="5dp"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/count"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/title"
                android:gravity="center"
                android:paddingBottom="15dp"
                android:textSize="14sp" />

        </RelativeLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>

Body:
Its because of initViews(). You are calling two times first is from onCreate and second from setUserVisibleHint.

RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(mLayoutManager);

This will crating your size smaller after each refresh.


问:
Automapper conditionally map properties
How can I map my properties conditionally also the value is conditional.
Below is my code details:-

```<code>public class Team
{
    public string Id { get; set; }
    public Driver Driver { get; set; }
    public Driver Codriver { get; set; }
}

public class Driver
{
    public string DriverId { get; set; }
    public List<Score> Scores { get; set; }
}

public class Score
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string Value { get; set; }
    public int Score1 { get; set; }
    public int Score2 { get; set; }
}
</code>```

I want to move driver and codriver. If I want to update my Driver then Score1 will be updated else Score2. If I want to update it with Driver then Score1 detail will be moved else Score2. My mapping is as below:-

```<code>public void Move(Score sourceScore, string sourceType, Score targetScore, string targetType)
{
    Mapper.Initialize(cfg =>
    {
       cfg.CreateMap<Score, Score>()
       .ForMember(dest => dest.Score1, opt =>
       {
          opt.Condition((System.Func<Score, bool>) (src => string.Equals(targetType, "Driver")));
          opt.MapFrom(src => string.Equals(sourceType, "Driver") ? src.Score1 : src.Score2);
       })
       .ForMember(dest => dest.Score2, opt =>
       {
          opt.Condition((System.Func<Score, bool>) (src => string.Equals(targetType, "CoDriver")));
          opt.MapFrom(src => string.Equals(sourceType, "Driver") ? src.Score1 : src.Score2);
       });
    });

    Mapper.Map<Score, Score>(sourceScore, targetScore);
}
</code>```

The mapping done above doesn't map the details correctly. Am I missing something. Can someone help me with this.

答:
You have to review your logic and explain exactly what you want to obtain. Currently your code does this:

If targetType is "Driver" and sourceType is "Driver": Score1 in destination gets the value from Score1 in source.

If targetType is "Driver" and sourceType is anything but "Driver": Score1 in destination gets the value from Score2 in source.

If targetType is "CoDriver" and sourceType is "Driver": Score2 in destination gets the value from Score1 in source.

If targetType is "CoDriver" and sourceType is anything but "Driver": Score2 in destination gets the value from Score2 in source.

If this is not what you want, please modify this rules to state it crearly. Note that when you ask a question like this you should specify clearly what is not working as expected, and ideally provide a working example and some unit tests specifying desired behaviour. Like this:

My code:

```<code>internal static class MappingDrivers
{
    public static void Move(Score sourceScore, string sourceType, Score targetScore, string targetType)
    {
        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Score, Score>()
            .ForMember(dest => dest.Score1, opt =>
            {
                opt.Condition(src => string.Equals(targetType, "Driver"));
                opt.MapFrom(src => string.Equals(sourceType, "Driver") ? src.Score1 : src.Score2);
            })
            .ForMember(dest => dest.Score2, opt =>
            {
                opt.Condition(src => string.Equals(targetType, "CoDriver"));
                opt.MapFrom(src => string.Equals(sourceType, "Driver") ? src.Score1 : src.Score2);
            });
        });

        Mapper.Map(sourceScore, targetScore);
    }
}
</code>```

Unit tests specifying desired behaviour:

NOTE: I didn't use TestCase to keep things simple

```<code>internal class TestMappingDrivers
{
    [Test]
    public void WhenTargetIsDriverAndSourceIsDriver_Score1GetsValueFromScore1()
    {
        int score1 = 666;
        var source = new Score
        {
            Score1 = score1,
            Score2 = 667
        };
        var destination = new Score();

        MappingDrivers.Move(source, "Driver", destination, "Driver");

        Assert.AreEqual(score1, destination.Score2);    // Intentionally failing, it should be Assert.AreEqual(score1, destination.Score1);
    }

    [Test]
    public void WhenTargetIsDriverAndSourceIsSomethingElse_Score1GetsValueFromScore2()
    {
        int score2 = 667;
        var source = new Score
        {
            Score1 = 666,
            Score2 = score2
        };
        var destination = new Score();

        MappingDrivers.Move(source, "SomethingElse", destination, "Driver");

        Assert.AreEqual(score2, destination.Score1);   // Passing
    }

    [Test]
    public void WhenTargetIsCoDriverAndSourceIsDriver_Score1GetsValueFromScore1()
    {
        int score1 = 666;
        var source = new Score
        {
            Score1 = score1,
            Score2 = 667
        };
        var destination = new Score();

        MappingDrivers.Move(source, "Driver", destination, "CoDriver");

        Assert.AreEqual(score1, destination.Score2);   // Passing
    }

    [Test]
    public void WhenTargetIsCoDriverAndSourceIsSomethingElse_Score1GetsValueFromScore2()
    {
        int score2 = 667;
        var source = new Score
        {
            Score1 = 666,
            Score2 = score2
        };
        var destination = new Score();

        MappingDrivers.Move(source, "SomethingElse", destination, "CoDriver");

        Assert.AreEqual(score2, destination.Score2);   // Passing
    }
}
</code>```

Note also, that you should initialize your mappings just once, usually during your application startup. Here you are doing it every time the Move function is called. Look in the docs.

Finally, I would say that you are using the wrong tool for this job. AutoMapper is commonly used to map between two different classes, not from one instance of a class to other instance of the same class. You can do it, but it's "weird". I think that for what you are trying to do, a normal conditional expression (if...else) would express your intent more clearly and be less error-prone.

Title: Automapper conditionally map properties

Body:
How can I map my properties conditionally also the value is conditional.
Below is my code details:-

public class Team
{
    public string Id { get; set; }
    public Driver Driver { get; set; }
    public Driver Codriver { get; set; }
}

public class Driver
{
    public string DriverId { get; set; }
    public List<Score> Scores { get; set; }
}

public class Score
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string Value { get; set; }
    public int Score1 { get; set; }
    public int Score2 { get; set; }
}

I want to move driver and codriver. If I want to update my Driver then Score1 will be updated else Score2. If I want to update it with Driver then Score1 detail will be moved else Score2. My mapping is as below:-

public void Move(Score sourceScore, string sourceType, Score targetScore, string targetType)
{
    Mapper.Initialize(cfg =>
    {
       cfg.CreateMap<Score, Score>()
       .ForMember(dest => dest.Score1, opt =>
       {
          opt.Condition((System.Func<Score, bool>) (src => string.Equals(targetType, "Driver")));
          opt.MapFrom(src => string.Equals(sourceType, "Driver") ? src.Score1 : src.Score2);
       })
       .ForMember(dest => dest.Score2, opt =>
       {
          opt.Condition((System.Func<Score, bool>) (src => string.Equals(targetType, "CoDriver")));
          opt.MapFrom(src => string.Equals(sourceType, "Driver") ? src.Score1 : src.Score2);
       });
    });

    Mapper.Map<Score, Score>(sourceScore, targetScore);
}

The mapping done above doesn't map the details correctly. Am I missing something. Can someone help me with this.

Body:
You have to review your logic and explain exactly what you want to obtain. Currently your code does this:

If targetType is "Driver" and sourceType is "Driver": Score1 in destination gets the value from Score1 in source.

If targetType is "Driver" and sourceType is anything but "Driver": Score1 in destination gets the value from Score2 in source.

If targetType is "CoDriver" and sourceType is "Driver": Score2 in destination gets the value from Score1 in source.

If targetType is "CoDriver" and sourceType is anything but "Driver": Score2 in destination gets the value from Score2 in source.

If this is not what you want, please modify this rules to state it crearly. Note that when you ask a question like this you should specify clearly what is not working as expected, and ideally provide a working example and some unit tests specifying desired behaviour. Like this:

My code:

internal static class MappingDrivers
{
    public static void Move(Score sourceScore, string sourceType, Score targetScore, string targetType)
    {
        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Score, Score>()
            .ForMember(dest => dest.Score1, opt =>
            {
                opt.Condition(src => string.Equals(targetType, "Driver"));
                opt.MapFrom(src => string.Equals(sourceType, "Driver") ? src.Score1 : src.Score2);
            })
            .ForMember(dest => dest.Score2, opt =>
            {
                opt.Condition(src => string.Equals(targetType, "CoDriver"));
                opt.MapFrom(src => string.Equals(sourceType, "Driver") ? src.Score1 : src.Score2);
            });
        });

        Mapper.Map(sourceScore, targetScore);
    }
}

Unit tests specifying desired behaviour:

NOTE: I didn't use TestCase to keep things simple

internal class TestMappingDrivers
{
    [Test]
    public void WhenTargetIsDriverAndSourceIsDriver_Score1GetsValueFromScore1()
    {
        int score1 = 666;
        var source = new Score
        {
            Score1 = score1,
            Score2 = 667
        };
        var destination = new Score();

        MappingDrivers.Move(source, "Driver", destination, "Driver");

        Assert.AreEqual(score1, destination.Score2);    // Intentionally failing, it should be Assert.AreEqual(score1, destination.Score1);
    }

    [Test]
    public void WhenTargetIsDriverAndSourceIsSomethingElse_Score1GetsValueFromScore2()
    {
        int score2 = 667;
        var source = new Score
        {
            Score1 = 666,
            Score2 = score2
        };
        var destination = new Score();

        MappingDrivers.Move(source, "SomethingElse", destination, "Driver");

        Assert.AreEqual(score2, destination.Score1);   // Passing
    }

    [Test]
    public void WhenTargetIsCoDriverAndSourceIsDriver_Score1GetsValueFromScore1()
    {
        int score1 = 666;
        var source = new Score
        {
            Score1 = score1,
            Score2 = 667
        };
        var destination = new Score();

        MappingDrivers.Move(source, "Driver", destination, "CoDriver");

        Assert.AreEqual(score1, destination.Score2);   // Passing
    }

    [Test]
    public void WhenTargetIsCoDriverAndSourceIsSomethingElse_Score1GetsValueFromScore2()
    {
        int score2 = 667;
        var source = new Score
        {
            Score1 = 666,
            Score2 = score2
        };
        var destination = new Score();

        MappingDrivers.Move(source, "SomethingElse", destination, "CoDriver");

        Assert.AreEqual(score2, destination.Score2);   // Passing
    }
}

Note also, that you should initialize your mappings just once, usually during your application startup. Here you are doing it every time the Move function is called. Look in the docs.

Finally, I would say that you are using the wrong tool for this job. AutoMapper is commonly used to map between two different classes, not from one instance of a class to other instance of the same class. You can do it, but it's "weird". I think that for what you are trying to do, a normal conditional expression (if...else) would express your intent more clearly and be less error-prone.


问:
How to debug standalone file in Code::Blocks?
I'm programming using Code::Blocks. I set some breakpoints, but Code::Blocks seems to ignore them when I run the program.

By 'start the program' I mean simply clicking  (Build and run).

I checked under Debug and saw that F8 isn't available (Start / Continue):

The program compiles and runs fine, it just ignores breakpoints. Does anybody know how to solve this?

Note: I checked here and I think the suggested answer isn't relevant for me, because in Compiler settings I have just "C:\MinGW" under Compiler's installation directory.

edit:

I'm using Windows 8 (64bit), Code::Blocks 12.11

答:
Check out the following things:

You do not have spaces included in your project path directory.

You do not have spaces included in any of the project files.(eg. .cbp file, .c file)

If you are running codeblock on ubuntu then make sure you are running it as superuser.(eg. >gksu codeblocks)

Instead of space, you can use underscore(_) character.


问:
Silently Updating iOS Enterprise Apps in Single App Mode
I have a need to update my managed app running on a large amount of iPads without any user interaction. These devices all have the managed app locked in Single App Mode. As I understand it, it's an iOS limitation that an app cannot be updated if either of the following conditions are present:

The app to be updated is in the foreground.

Any app is locked in Single App mode.

With our use case, both of these conditions are present. I also understand that the current workaround is to do the following:

Disable Single App Mode.

Enable Single App Mode for a different app (e.g. Safari) to bring that app into the foreground.

Disable Single App Mode.

Update app.

Re-enable Single App Mode for your app when the update finishes to bring it back into the foreground.

While this method works, it has a lot of drawbacks:

It's highly manual, we have not found a way to automate it. This is especially a problem as the number of devices becomes large. Internet connections can be spotty and there is no robust way to ensure that each step has executed for all devices.

It's prone to failure. Especially between steps 4 and 5 above. It seems there are little to no guarantees of when/if an update was successful to know definitively when to re-enable Single App Mode.

It fails for devices that are offline at time of update. If a device does not have internet connection when the update is executed, there is no way to guarantee that the steps execute fully and in the correct order the next time the device comes back online.

I am looking for a scalable solution to reliably update my managed, Single App Mode app running on thousands of devices in an automated way with no user interaction. I am using Meraki for an MDM right now, for what it's worth.

答:
With iOS 11.2 you can now push a silent update to a device with it running SingleApp mode.

Apple failed to mention this to the public but is included in the beta notes.


问:
Does Java Spring Boot applications hibernate/"go dormant" overnight
I'm doing a microservice architecture with Spring boot java application.

My startups are around 16-19 seconds, so it does not look like my classpath/spring-boot application is polluted with startup stuff.

Though when I've not used a service for a while. FX. overnight, then when I use it again, it's like it has gone into some kind of hibernation, which makes the request time out.

Have anyone experienced someting similar and is there a solution ?

答:
While there's no Spring Boot specific "hibernation" functionality, there can be plenty of things that react to long periods of inactivity. From datasources' "minimum idle" connections to the GC freeing up excess (for the time being) heap space and giving it back to the OS.

If there are other memory hungry services running on the same machine, it's possible that there's swap contention when a Java app wakes up from its slumber and decides it wants to grow its heap. You could try running jstat to see what kind of memory usage the VM has at different points in time. Here's an article documenting the usage https://www.cubrid.org/blog/how-to-monitor-java-garbage-collection/

It might not be a swap issue, but I'd wager it's likely somehow related to the environment, not just Java (or Spring Boot) itself.


问:
Unity game doesn't respond to touches
I have an Android game where user moves player by touching left and right side of the screen. I tried the game on Android and all worked OK. But one day it stopped working: buttons work but I can't control the Player by touching screen sides. I tried to reinstall Unity, delete Library folder and even tried other OS. It didn't help. How can I fix my project?</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MovingPlayer : MonoBehaviour
{

    public float playerSpeed;
    public float maxPos = 2.7f;

    Vector3 position;
    public uiManager ui;
    public AudioManager am;

    public Text coinCount;

    int coin;

    bool currntPlatformAndroid = false;

    Rigidbody2D rb;

    public GameObject particleSystemPrefab;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();

#if UNITY_ANDROID
        currntPlatformAndroid = true;
#else
                currentPlatformAndroid = false;
#endif

        am.playerSound.Play();

    }

    // Use this for initialization
    void Start()
    {
        coin = 0;
        position = transform.position;
    }

    // Update is called once per frame
    void Update()
    {

        if (currntPlatformAndroid == true)
        {
            TouchMove();
            //AccelerometerMove();
        }

        else
        {

            position.x += Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;

            position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);

            transform.position = position;
        }

        position = transform.position;
        position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);

        transform.position = position;

    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "CubeObstacle")
        {
            //Destroy (gameObject);
            foreach (ContactPoint2D contact in col.contacts)
            {
                Instantiate(particleSystemPrefab, contact.point, Quaternion.identity);

            }
            //gameObject.SetActive(false);

            GameOverActivated();
            ui.gameOverActivated();
            am.playerSound.Stop();
        }

        if (col.gameObject.tag == "Coin")
        {
            Destroy(col.gameObject);
            coin += 1;
            coinCount.text = coin.ToString();

            Debug.Log("Coin");
        }

    }

    public void GameOverActivated()
    {
        Time.timeScale = 0;
        PlayerPrefs.SetInt("coins", PlayerPrefs.GetInt("coins") + coin);
    }

    void AccelerometerMove()
    {
        float x = Input.acceleration.x;

        if (x < -0.1f)
        {
            MoveLeft();
        }

        else if (x > 0.1f)
        {
            MoveRight();
        }

        else
        {
            SetVelocityZero();
        }
    }

    void TouchMove()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            float middle = Screen.width / 2;

            if (touch.position.x < middle && touch.phase == TouchPhase.Began)
            {
                MoveLeft();
            }

            else if (touch.position.x > middle && touch.phase == TouchPhase.Began)
            {
                MoveRight();
            }
        }
        else
        {
            SetVelocityZero();
        }
    }

    public void MoveLeft()
    {
        rb.velocity = new Vector2(-playerSpeed, 0);
    }

    public void MoveRight()
    {
        rb.velocity = new Vector2(playerSpeed, 0);
    }

    public void SetVelocityZero()
    {
        rb.velocity = Vector2.zero;
    }
}
</code>```

答:
You don't need to use Input.Touches, this should work fine:

```<code>void Update()
{
    #if UNITY_EDITOR
        position.x += Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;

        position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);

        transform.position = position;
    #else
        if (Input.GetMouseButton(0))
        {
            if (Input.mousePosition.x > Screen.width/2)
            {
                MoveRight();
            }
            else
            {
                MoveLeft()
            }
        }
        else
        {
            SetVelocityToZero();
        }

    #endif
}
</code>```

Hope this helps :)

Title: Unity game doesn't respond to touches

Body:
I have an Android game where user moves player by touching left and right side of the screen. I tried the game on Android and all worked OK. But one day it stopped working: buttons work but I can't control the Player by touching screen sides. I tried to reinstall Unity, delete Library folder and even tried other OS. It didn't help. How can I fix my project?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class MovingPlayer : MonoBehaviour
{

    public float playerSpeed;
    public float maxPos = 2.7f;

    Vector3 position;
    public uiManager ui;
    public AudioManager am;

    public Text coinCount;

    int coin;

    bool currntPlatformAndroid = false;

    Rigidbody2D rb;

    public GameObject particleSystemPrefab;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();

#if UNITY_ANDROID
        currntPlatformAndroid = true;
#else
                currentPlatformAndroid = false;
#endif

        am.playerSound.Play();

    }

    // Use this for initialization
    void Start()
    {
        coin = 0;
        position = transform.position;
    }

    // Update is called once per frame
    void Update()
    {

        if (currntPlatformAndroid == true)
        {
            TouchMove();
            //AccelerometerMove();
        }

        else
        {

            position.x += Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;

            position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);

            transform.position = position;
        }

        position = transform.position;
        position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);

        transform.position = position;

    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "CubeObstacle")
        {
            //Destroy (gameObject);
            foreach (ContactPoint2D contact in col.contacts)
            {
                Instantiate(particleSystemPrefab, contact.point, Quaternion.identity);

            }
            //gameObject.SetActive(false);

            GameOverActivated();
            ui.gameOverActivated();
            am.playerSound.Stop();
        }

        if (col.gameObject.tag == "Coin")
        {
            Destroy(col.gameObject);
            coin += 1;
            coinCount.text = coin.ToString();

            Debug.Log("Coin");
        }

    }

    public void GameOverActivated()
    {
        Time.timeScale = 0;
        PlayerPrefs.SetInt("coins", PlayerPrefs.GetInt("coins") + coin);
    }

    void AccelerometerMove()
    {
        float x = Input.acceleration.x;

        if (x < -0.1f)
        {
            MoveLeft();
        }

        else if (x > 0.1f)
        {
            MoveRight();
        }

        else
        {
            SetVelocityZero();
        }
    }

    void TouchMove()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            float middle = Screen.width / 2;

            if (touch.position.x < middle && touch.phase == TouchPhase.Began)
            {
                MoveLeft();
            }

            else if (touch.position.x > middle && touch.phase == TouchPhase.Began)
            {
                MoveRight();
            }
        }
        else
        {
            SetVelocityZero();
        }
    }

    public void MoveLeft()
    {
        rb.velocity = new Vector2(-playerSpeed, 0);
    }

    public void MoveRight()
    {
        rb.velocity = new Vector2(playerSpeed, 0);
    }

    public void SetVelocityZero()
    {
        rb.velocity = Vector2.zero;
    }
}

Body:
You don't need to use Input.Touches, this should work fine:

void Update()
{
    #if UNITY_EDITOR
        position.x += Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;

        position.x = Mathf.Clamp(position.x, -2.7f, 2.7f);

        transform.position = position;
    #else
        if (Input.GetMouseButton(0))
        {
            if (Input.mousePosition.x > Screen.width/2)
            {
                MoveRight();
            }
            else
            {
                MoveLeft()
            }
        }
        else
        {
            SetVelocityToZero();
        }

    #endif
}

Hope this helps :)


答:
It seems you need select MultiIndex first for DataFrame and then DataFrame.plot:

```<code>df['Amount'].plot()
</code>```

Or add Amount for remove MultiIndex in columns (change by your aggregate function):

```<code>df.groupby(['supplier','date_order'])['Amount'].sum().unstack(fill_value=0).plot()
</code>```

EDIT:

For transpose use:

```<code>df['Amount'].T.plot()
</code>```

Title: how to plot groupped dataframe by date

Body:
I have a grouped by ['supplier','date_order']  as

                                    Amount
date_order  2011        2012            2013            2014            2015            2016            2017
supplier
fourni  0.000           1667750.000     4243250.000     2530000.000     2080000.000     1036200.000     1217400.000
supp_f  5289670.200     13076233.400    14199000.000    13181860.000    16177800.000    14525880.000    1346400.000
ifou    662250.000      2135750.000     2184150.000     1829800.000     1947880.000     1424820.000     1836100.000

How can get the plot of Amount of  suppliers by years for each line in a line plot ?

Body:
It seems you need select MultiIndex first for DataFrame and then DataFrame.plot:

df['Amount'].plot()

Or add Amount for remove MultiIndex in columns (change by your aggregate function):

df.groupby(['supplier','date_order'])['Amount'].sum().unstack(fill_value=0).plot()

EDIT:

For transpose use:

df['Amount'].T.plot()