问:
Firebase analytics page is blank but Crash reports are working
I am having some trouble integrating my project with Google Firebase analytics. I have followed all the instructions and the integration seems to be complete as I do get Crash reports correctly but the Analytics page is empty.

My build.gradle contents:

```<code>compile 'com.google.firebase:firebase-core:10.2.0'
compile 'com.google.firebase:firebase-crash:10.2.0'

compile 'com.google.android.gms:play-services:10.2.0'
compile 'com.google.android.gms:play-services-wearable:10.2.0'
</code>```

The logs seem to suggest its sending the reports.

```<code>I/FirebaseInitProvider: FirebaseApp initialization successful
I/FA: App measurement is starting up, version: 10298
I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
I/FA: To enable faster debug mode event logging run:
                                                            adb shell setprop debug.firebase.analytics.app
D/FA: Debug-level message logging enabled
D/FA: Connected to remote service
D/FA: Logging event (FE): select_content, Bundle[{item_name=Demo mode entered, _o=app, _sc=SeatsActivity, _si=-6324821531545085450, content_type=image, item_id=Demo}]
D/FA: Connected to remote service
D/FA: Logging event (FE): select_content, Bundle[{item_name=Demo mode exited, _o=app, _sc=SeatsActivity, _si=-6324821531545085450, content_type=image, item_id=Demo}]
D/FA: Logging event (FE): _e, Bundle[{_o=auto, _et=14578, _sc=SeatsActivity, _si=-6324821531545085450}]
D/FA: Logging event (FE): select_content, Bundle[{item_name=User Authenticated, _o=app, content_type=image, item_id=Authentication}]
D/FA: Connected to remote service
D/FA: Logging event (FE): _e, Bundle[{_o=auto, _et=11345, _sc=AuthenticationActivity, _si=-6324821531545085449}]
D/FA: Connected to remote service
</code>```

The image seems to suggest there is some analytics but when I go to the Analytics tab its blank. I have waited for couple of days after sending the reports but still the page is blank. Am I missing anything?

答:
I found out that for G Suite / Google Apps / Enterprise accounts Google Analytics is disabled by default.

If you can get in contact with your administrator (or that's you), they can follow the instructions to enable it here:
https://support.google.com/a/answer/6304816

I did this myself, and despite the warning it might take 24 hours, Firebase Analytics page starting working for me straight away.

Body:
I am having some trouble integrating my project with Google Firebase analytics. I have followed all the instructions and the integration seems to be complete as I do get Crash reports correctly but the Analytics page is empty.

My build.gradle contents:

compile 'com.google.firebase:firebase-core:10.2.0'
compile 'com.google.firebase:firebase-crash:10.2.0'

compile 'com.google.android.gms:play-services:10.2.0'
compile 'com.google.android.gms:play-services-wearable:10.2.0'

The logs seem to suggest its sending the reports.

I/FirebaseInitProvider: FirebaseApp initialization successful
I/FA: App measurement is starting up, version: 10298
I/FA: To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
I/FA: To enable faster debug mode event logging run:
                                                            adb shell setprop debug.firebase.analytics.app
D/FA: Debug-level message logging enabled
D/FA: Connected to remote service
D/FA: Logging event (FE): select_content, Bundle[{item_name=Demo mode entered, _o=app, _sc=SeatsActivity, _si=-6324821531545085450, content_type=image, item_id=Demo}]
D/FA: Connected to remote service
D/FA: Logging event (FE): select_content, Bundle[{item_name=Demo mode exited, _o=app, _sc=SeatsActivity, _si=-6324821531545085450, content_type=image, item_id=Demo}]
D/FA: Logging event (FE): _e, Bundle[{_o=auto, _et=14578, _sc=SeatsActivity, _si=-6324821531545085450}]
D/FA: Logging event (FE): select_content, Bundle[{item_name=User Authenticated, _o=app, content_type=image, item_id=Authentication}]
D/FA: Connected to remote service
D/FA: Logging event (FE): _e, Bundle[{_o=auto, _et=11345, _sc=AuthenticationActivity, _si=-6324821531545085449}]
D/FA: Connected to remote service

The image seems to suggest there is some analytics but when I go to the Analytics tab its blank. I have waited for couple of days after sending the reports but still the page is blank. Am I missing anything?


来源: stackexchange

问:
Routing remains same when called again in angular 2
I am calling this route with this method

```<code>onDateChanged(event: IMyDateModel) {

    this.route.navigate(['/user/events',event.formatted]);
}
</code>```

My events component,

```<code>activatedroute.params.subscribe(p => { this.date = p['date?'] });
    if (this.date) {
      this.onDateChanged();
    } else {
      this.getEvents()
    }
</code>```

When I call it for the first time,it is triggering that component but when i call the same function again from the same route,then the component is not loaded with new values i.e previous route remains unchanged.Can anyone please help me .Thanks.

答:
The component will not reload if you navigate to a route that matches the current route according to your route definitions. However, you can listen to the params Observable on the ActivatedRoute to be alerted when the data in the route url changes and then re-setup your component from there.

{
    path: "user/events/:type",
    component: MyComponent
}
```

<p>Navigating from <code>/</code> to <code>user/events/unformatted</code> will load MyComponent. Routing from <code>user/events/unformatted</code> to <code>user/events/formatted</code> will not load MyComponent.</p>

<p>Inside MyComponent you can do the following:</p>

<pre class="lang-js prettyprint-override"><code>class MyComponent {
    constructor(private activatedRoute: ActivatedRoute){}

    ngOnInit(){
        this.activatedRoute.params.subscribe((params) => {
            let newFormattingType = params["type"];

            //re-setup component based on formatting type
        })
    }
}
</code>```

You need to update your call back so the check for whether the date has changed is inside your callback and you should not have the ? in the parameter name. Update your code to ressemble the following

activatedroute.params.subscribe((p) => {
    this.date = p['date'];

    if (this.date) {
      this.onDateChanged();
    } else {
      this.getEvents();
    }
 });
```

ContentLicense: CC BY-SA 3.0

Body:
I am calling this route with this method

onDateChanged(event: IMyDateModel) {

    this.route.navigate(['/user/events',event.formatted]);
}

My events component,

activatedroute.params.subscribe(p => { this.date = p['date?'] });
    if (this.date) {
      this.onDateChanged();
    } else {
      this.getEvents()
    }

When I call it for the first time,it is triggering that component but when i call the same function again from the same route,then the component is not loaded with new values i.e previous route remains unchanged.Can anyone please help me .Thanks.

Body:
The component will not reload if you navigate to a route that matches the current route according to your route definitions. However, you can listen to the params Observable on the ActivatedRoute to be alerted when the data in the route url changes and then re-setup your component from there.

{
    path: "user/events/:type",
    component: MyComponent
}

Navigating from / to user/events/unformatted will load MyComponent. Routing from user/events/unformatted to user/events/formatted will not load MyComponent.

Inside MyComponent you can do the following:

class MyComponent {
    constructor(private activatedRoute: ActivatedRoute){}

    ngOnInit(){
        this.activatedRoute.params.subscribe((params) => {
            let newFormattingType = params["type"];

            //re-setup component based on formatting type
        })
    }
}

You need to update your call back so the check for whether the date has changed is inside your callback and you should not have the ? in the parameter name. Update your code to ressemble the following

activatedroute.params.subscribe((p) => {
    this.date = p['date'];

    if (this.date) {
      this.onDateChanged();
    } else {
      this.getEvents();
    }
 });


问:
how to wrrite a delay code in c#
I need a method for a delay.

I'm looking for something that would allow me to write code similar to this:

```<code>        for (;;)
        {

            hudElem.SetString("");
            delay(50000);
            hudElem.SetString("");
            delay(50000);
            hudElem.SetString(");
            delay(50000);
            hudElem.SetString("");
            delay(50000);
            hudElem.SetString(");
            delay(50000);
        }
</code>```

waiting 50 secs

I'm Net framework 3.0 so I can't use the Delay method from .NET 4

答:
You can use this:

```<code>async Task Udskyd()
        {
            await Task.Delay(2000);//miliseconds
        }
</code>```

Just make you button async as well so it will be: private async void button4_Click(object sender, EventArgs e)

Title: how to wrrite a delay code in c#

Body:
I need a method for a delay.

I'm looking for something that would allow me to write code similar to this:

        for (;;)
        {

            hudElem.SetString("");
            delay(50000);
            hudElem.SetString("");
            delay(50000);
            hudElem.SetString(");
            delay(50000);
            hudElem.SetString("");
            delay(50000);
            hudElem.SetString(");
            delay(50000);
        }

waiting 50 secs

I'm Net framework 3.0 so I can't use the Delay method from .NET 4

Body:
You can use this:

async Task Udskyd()
        {
            await Task.Delay(2000);//miliseconds
        }

Just make you button async as well so it will be: private async void button4_Click(object sender, EventArgs e)


问:
Bot Framework (.Net) - Send additional parameters with button using PromptDialog.Choice()
I'm trying to learn Bot Framework using .Net and I have an application which displays buttons and based on the option selected, display more buttons or a list. What I want is, to send a hidden ID/parameter with the button so that when user clicks on the button, I can access the hidden parameter. I'm not using cards for this. I just want to display the buttons. Can anyone help me with this? I know this can be a very basic question but I couldn't find how to this without Cards.</p>

答:
First of all, PromptDialog.Choice behind the scenes creates a HeroCard with multiple buttons (which are basically the PromptOptions passed, see the code)

One way to pass a hidden parameter would be specifying the ActionType PostBack to your button and fill the Value property with the hidden parameter. PostBack is the way to go here since the message will be posted to the bot but client applications will not display this message (however, please note that not all the channels support the postBack action type). See this for more information

Now, since you are using PromptDialog.Choice you will have to override things in order to be able to specify the PostBack action type, since by default, the buttons created with the Choice are using ImBack (per this code)

You will have to put together a custom PromptStyler, override the Apply<T> method and add your logic to change the action type and set the buttons in the way you want based on the PromptStyle used and pass that custom styler to the PromptDialog.Choice.

By default the PromptDialog.Choice uses PromptStyle.Auto.


问:
SSIS Derived Column Date Formats
I have a large data file that I am running through SSIS. Very simple XML source into a SQL database. I seldom use SSIS so I am far from an expert.

I have some records that I push into an error table because the dates are incorrect.

What I want to say is, if the date is not in a date format, then update this date to NULL.

I don't know if Derived Column is the way to go, but it appears it should be given examples I have been reading online.

I want to fix this issue in the SSIS stage, not in SQL after the data has been loaded in to the error tables.

答:
You need to configure Error Output of the component which fails to convert from text to date.

It is usually either a Data Conversion, or a Derived Column component.
In case you are already receiving the column in date format from the source - it is your XML Source component.

1a. Double-click on yout Data Conversion or Derived Column component, and go to Configure Error Output.

1b. Double-click on your XML Source, go to the Error Output.

For your date column change the default Error and Truncation options to Ignore Failure.

The values which failed to convert will now contain NULLs instead.

https://technet.microsoft.com/en-us/library/ms141679(v=sql.110).aspx

Title: SSIS Derived Column Date Formats


问:
Pass JsonResponse to IntentService
I have My MainActivity and I can get response very well :

```<code> JSONObject responseVal = responseObj.getJSONObject("data");
                message = responseVal.getString("id");
                Log.i(TAG, "onResponse: " + message);
</code>```

and I have IntentService and want to pass that message value to it.

I tried with SharedPreferences and also with intentPutExtra but it doesn't work.

What is the best way to do that ?

答:
For sending message to your IntentService, try this:

```<code>Intent intent = new Intent(MainActivity.this, YourIntentService.class);
intent.putExtra("message", message);
startService(intent);
</code>```

To receive the message in IntentService, try this:

```<code>@Override
protected void onHandleIntent(Intent intent) {
    String message = intent.getStringExtra("message");
    ........
}
</code>```

Title: Pass JsonResponse to IntentService

Body:
I have My MainActivity and I can get response very well :

 JSONObject responseVal = responseObj.getJSONObject("data");
                message = responseVal.getString("id");
                Log.i(TAG, "onResponse: " + message);

and I have IntentService and want to pass that message value to it.

I tried with SharedPreferences and also with intentPutExtra but it doesn't work.

What is the best way to do that ?

Body:
For sending message to your IntentService, try this:

Intent intent = new Intent(MainActivity.this, YourIntentService.class);
intent.putExtra("message", message);
startService(intent);

To receive the message in IntentService, try this:

@Override
protected void onHandleIntent(Intent intent) {
    String message = intent.getStringExtra("message");
    ........
}


问:
Split URL query in Swift
I have the following URL query:

```<code>encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN
</code>```

How can I split the query to get the of encodedMessage and signature values?

答:
The right way to achieve this is to work with URLComponents:

A structure designed to parse URLs based on RFC 3986 and to construct
  URLs from their constituent parts.

By getting the url components host string and queryItems array, as follows:

```<code>if let urlComponents = URLComponents(string: "http://mydummysite.com?encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"), let host = urlComponents.host, let queryItems = urlComponents.queryItems {

    print(host) // mydummysite.com

    print(queryItems) // [encodedMessage=PD94bWwgdmVyNlPg==, signature=kcig33sdAOAr/YYGf5r4HGN]
}
</code>```

queryItems array contains URLQueryItem objects, which have name and value properties:

```<code>if let urlComponents = URLComponents(string: "http://mydummysite.com?encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"),let queryItems = urlComponents.queryItems {

    // for example, we will get the first item name and value:
    let name = queryItems[0].name // encodedMessage
    let value = queryItems[0].value // PD94bWwgdmVyNlPg==
}
</code>```

Also:

In case of you are getting the query without the full url, I'd suggest to do a pretty simple trick, by adding a dummy host as a prefix to your query string, as follows:

```<code>let myQuery = "encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"
let myDummyUrlString = "http://stackoverflow.com?" + myQuery

if let urlComponents = URLComponents(string: myDummyUrlString),let queryItems = urlComponents.queryItems {
    // for example, we will get the first item name and value:
    let name = queryItems[0].name // encodedMessage
    let value = queryItems[0].value // PD94bWwgdmVyNlPg==
} else {
    print("invalid url")
}
</code>```

Title: Split URL query in Swift

Body:
I have the following URL query:

encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN

How can I split the query to get the of encodedMessage and signature values?

Body:
The right way to achieve this is to work with URLComponents:

A structure designed to parse URLs based on RFC 3986 and to construct
  URLs from their constituent parts.

By getting the url components host string and queryItems array, as follows:

if let urlComponents = URLComponents(string: "http://mydummysite.com?encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"), let host = urlComponents.host, let queryItems = urlComponents.queryItems {

    print(host) // mydummysite.com

    print(queryItems) // [encodedMessage=PD94bWwgdmVyNlPg==, signature=kcig33sdAOAr/YYGf5r4HGN]
}

queryItems array contains URLQueryItem objects, which have name and value properties:

if let urlComponents = URLComponents(string: "http://mydummysite.com?encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"),let queryItems = urlComponents.queryItems {

    // for example, we will get the first item name and value:
    let name = queryItems[0].name // encodedMessage
    let value = queryItems[0].value // PD94bWwgdmVyNlPg==
}

Also:

In case of you are getting the query without the full url, I'd suggest to do a pretty simple trick, by adding a dummy host as a prefix to your query string, as follows:

let myQuery = "encodedMessage=PD94bWwgdmVyNlPg%3D%3D&signature=kcig33sdAOAr%2FYYGf5r4HGN"
let myDummyUrlString = "http://stackoverflow.com?" + myQuery

if let urlComponents = URLComponents(string: myDummyUrlString),let queryItems = urlComponents.queryItems {
    // for example, we will get the first item name and value:
    let name = queryItems[0].name // encodedMessage
    let value = queryItems[0].value // PD94bWwgdmVyNlPg==
} else {
    print("invalid url")
}


问:
How to use xml2json in Ionic2 project
I am developing a mobile app using Ionic2 framework. I need to convert a xml file to json format.

For this I have installed "xml2json" using command "npm install xml2json --save".

This has saved a module named "xml2json" in "node_modules" folder.

I can also see it under dependencies in "package.json" file as "xml2json": "^0.9.1"

Now when I declared it in the .ts file as "import * as xml2json from "xml2json";", I am receiving the following error: "can not find module xml2json"

I guess I need to install the typings for this module. I have tried all the possible typings commands but could not install it. I received errors like

typings ERR! caused by https://api.typings.org/entries/dt/xml2json/versions/latest responded with 404, expected it to equal 200

Please let me know how can I install typings for xml2json OR how can I use xml2json in my project. Thanks.

My system information:

typings version - 1.3.2

Cordova CLI: 6.3.0
Gulp version:  CLI version 3.9.1
Gulp local:   Local version 3.9.1
Ionic Framework Version: 2.0.0-beta.11
Ionic CLI Version: 2.0.0-beta.36
Ionic App Lib Version: 2.0.0-beta.19
OS: Distributor ID: Ubuntu Description: Ubuntu 16.04 LTS
Node Version: v6.3.0

答:
For Parsing xml to json in ionic 2 You can install the typings for xml2json now using the command

```<code>typings install xml2json --save
</code>```

If it generate error like this

```<code>'typings' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Then first use this command to install typing

```<code>npm install typings -g
</code>```

Then run previous command

```<code>typings install xml2json --save
</code>```

Then it'll work fine. Hope it work for you

Title: How to use xml2json in Ionic2 project

Body:
For Parsing xml to json in ionic 2 You can install the typings for xml2json now using the command

typings install xml2json --save

If it generate error like this

'typings' is not recognized as an internal or external command,
operable program or batch file.

Then first use this command to install typing

npm install typings -g

Then run previous command

typings install xml2json --save

Then it'll work fine. Hope it work for you


问:
how to hide specific div when i click div in vue js
```<code><template>
 <div v-for="(item ,index) in items" v-if="showing">
                <span @click="showing=false">{{item.name}}</span>
 </div>
</template>
    <script>

            export default{
                       showing:true,
                       items: [
                          {'name':'a'},
                          {'name':'b'},
                          {'name':'c'},
                       ],
            }
    </script>
</code>```

how to hide specific div when i click div
** when i do this way it`s all of them was hide**

答:
I will do something like this:

```<code><template>
   <div v-for="(item,index) in items" v-if="hide.indexOf(index) < 0">
     <span @click="hide.push(index)">{{item.name}}</span>
   </div>
</template>
<script>
  export default{
    hide :[],
    items:[
     {'name':'a'},
     {'name':'b'},
     {'name':'c'}
    ]
  }
</script>
</code>```

You can check in here https://jsfiddle.net/do68kqje/3/

Body:
<template>

                {{item.name}}

</template>

how to hide specific div when i click div
** when i do this way it`s all of them was hide**

Body:
I will do something like this:

<template>
   <div v-for="(item,index) in items" v-if="hide.indexOf(index) < 0">
     <span @click="hide.push(index)">{{item.name}}</span>
   </div>
</template>
<script>
  export default{
    hide :[],
    items:[
     {'name':'a'},
     {'name':'b'},
     {'name':'c'}
    ]
  }
</script>

You can check in here https://jsfiddle.net/do68kqje/3/


问:
Invalid init of non-const reference of type std::basic_string<char>::const_iterator& from rvalue of type std::basic_string<char>::const_iterator
I'm get the above error when I compile the following MWE on GCC

```<code>#include <string>

void frobnigate( const std::string& str )
{
    std::string::const_iterator& iter = str.begin();
}

int main()
{
    frobnigate( "all things!!!" );
}
</code>```

Am I doing something wrong or is this a GCC issue?

答:
Am I doing something wrong or is this a GCC issue?

Yes you are doing something wrong.

std::string::begin() returns a value type (rvalue, since its a temporary). But you are trying to initialize a non-const reference from an rvalue which is illegal in C++.

You definitely want:

```<code>std::string::const_iterator iter = str.begin();
</code>```

Better still:

```<code>auto iter = str.begin();
</code>```

Iterators are cheap to copy and should be used by value, so a reference or const-reference to an iterator is frowned upon.

Body:
I'm get the above error when I compile the following MWE on GCC

#include <string>

void frobnigate( const std::string& str )
{
    std::string::const_iterator& iter = str.begin();
}

int main()
{
    frobnigate( "all things!!!" );
}

Am I doing something wrong or is this a GCC issue?

Body:
Am I doing something wrong or is this a GCC issue?

Yes you are doing something wrong.

std::string::begin() returns a value type (rvalue, since its a temporary). But you are trying to initialize a non-const reference from an rvalue which is illegal in C++.

You definitely want:

std::string::const_iterator iter = str.begin();

Better still:

auto iter = str.begin();

Iterators are cheap to copy and should be used by value, so a reference or const-reference to an iterator is frowned upon.


问:
Deep linking for Facebook shareLinkContent
I'm working with deep link in iOS. I am going to share a link in Facebook using `FBSDKShareLinkContent. I have created deep linking URL in Facebook like https://fb.me/****************.

I have already done AppInviteContent and it works good like this:

```

let content : FBSDKAppInviteContent = FBSDKAppInviteContent()
content.appLinkURL = NSURL(string: "https://fb.me/****************")!
content.appInvitePreviewImageURL = NSURL(string: "http://***.***.***.***/shareImage.png" as String)!
FBSDKAppInviteDialog.showWithContent(content, delegate: self)

```

Now, I am sharing link in Facebook like this:

```<code>let shareLinkContent : FBSDKShareLinkContent = FBSDKShareLinkContent()
shareLinkContent.contentURL = NSURL(string: "https://example.com/a2d69835ae")!
shareLinkContent.contentTitle = "App_Name"
shareLinkContent.contentDescription = "Description"

let dialog : FBSDKShareDialog = FBSDKShareDialog()
dialog.fromViewController = self
dialog.delegate = self
dialog.shareContent = shareLinkContent
dialog.mode = FBSDKShareDialogMode.Web
dialog.show()
</code>```

How to set deep link URL (e.g. https://fb.me/****************) in this shareLinkContent.

答:
Remove this below code, this have been modified in latest pod version.

```<code>let dialog : FBSDKShareDialog = FBSDKShareDialog()
dialog.fromViewController = self
dialog.delegate = self
dialog.shareContent = shareLinkContent
dialog.mode = FBSDKShareDialogMode.Web
dialog.show()
</code>```

Add this code will show Facebook Share dialog:

```<code> FBSDKShareDialog.show(from: self, with: shareLinkContent, delegate: self)
</code>```

This will fix your FBSDK share issue.

For APP invite try some thing like this:

```<code>{
    let content : FBSDKAppInviteContent = FBSDKAppInviteContent()
        content.appLinkURL = NSURL(string: "https://fb.me/****************")!
        content.appInvitePreviewImageURL = NSURL(string: "http://***.***.***.***/shareImage.png" as String)!
        FBSDKAppInviteDialog.show(from: self, with: content, delegate: self)
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm working with deep link in iOS. I am going to share a link in Facebook using `FBSDKShareLinkContent. I have created deep linking URL in Facebook like https://fb.me/****************.

I have already done AppInviteContent and it works good like this:

let content : FBSDKAppInviteContent = FBSDKAppInviteContent()
content.appLinkURL = NSURL(string: "https://fb.me/****************")!
content.appInvitePreviewImageURL = NSURL(string: "http://***.***.***.***/shareImage.png" as String)!
FBSDKAppInviteDialog.showWithContent(content, delegate: self)

Now, I am sharing link in Facebook like this:

let shareLinkContent : FBSDKShareLinkContent = FBSDKShareLinkContent()
shareLinkContent.contentURL = NSURL(string: "https://example.com/a2d69835ae")!
shareLinkContent.contentTitle = "App_Name"
shareLinkContent.contentDescription = "Description"

let dialog : FBSDKShareDialog = FBSDKShareDialog()
dialog.fromViewController = self
dialog.delegate = self
dialog.shareContent = shareLinkContent
dialog.mode = FBSDKShareDialogMode.Web
dialog.show()

How to set deep link URL (e.g. https://fb.me/****************) in this shareLinkContent.

Body:
Remove this below code, this have been modified in latest pod version.

let dialog : FBSDKShareDialog = FBSDKShareDialog()
dialog.fromViewController = self
dialog.delegate = self
dialog.shareContent = shareLinkContent
dialog.mode = FBSDKShareDialogMode.Web
dialog.show()

Add this code will show Facebook Share dialog:

 FBSDKShareDialog.show(from: self, with: shareLinkContent, delegate: self)

This will fix your FBSDK share issue.

For APP invite try some thing like this:

{
    let content : FBSDKAppInviteContent = FBSDKAppInviteContent()
        content.appLinkURL = NSURL(string: "https://fb.me/****************")!
        content.appInvitePreviewImageURL = NSURL(string: "http://***.***.***.***/shareImage.png" as String)!
        FBSDKAppInviteDialog.show(from: self, with: content, delegate: self)
}


问:
C# how to Regex.Replace "\r\n" (the actual characters, not the line break)
I've got some horrible text that I'm cleaning up using several c# regular expressions. One issue that has me stumped is there are a number of '\r\n' strings in the text, the actual characters not the line breaks.

I've tried:

```<code>content = Regex.Replace(content, "\\r\\n", "");
</code>```

and:

```<code>content = Regex.Replace(content, "\r\n", "");
</code>```

but neither of them work. In the end I had to use:

```<code>content = content.Replace("\\r\\n", "\r\n");
</code>```

to get the project finished, but not being able to do it in a regex annoys me.

答:
Within a specified input string, Regex.Replacereplaces strings that match a regular expression pattern with a specified replacement string.

A typical usage would be

```<code>  string input = "This is   text with   far  too     much   " +  "   whitespace.";
  string pattern = "\\s+";
  string replacement = " ";
  Regex rgx = new Regex(pattern);
  string result = rgx.Replace(input, replacement);
</code>```

Doesn't seem like that's what you are trying to do.

ContentLicense: CC BY-SA 2.5

Body:
I've got some horrible text that I'm cleaning up using several c# regular expressions. One issue that has me stumped is there are a number of '\r\n' strings in the text, the actual characters not the line breaks.

I've tried:

content = Regex.Replace(content, "\\r\\n", "");

and:

content = Regex.Replace(content, "\r\n", "");

but neither of them work. In the end I had to use:

content = content.Replace("\\r\\n", "\r\n");

to get the project finished, but not being able to do it in a regex annoys me.

Body:
Within a specified input string, Regex.Replacereplaces strings that match a regular expression pattern with a specified replacement string.

A typical usage would be

  string input = "This is   text with   far  too     much   " +  "   whitespace.";
  string pattern = "\\s+";
  string replacement = " ";
  Regex rgx = new Regex(pattern);
  string result = rgx.Replace(input, replacement);

Doesn't seem like that's what you are trying to do.


问:
How can I redirect users to different pages based on drop down selection
I am trying to output students name from database and input field to enter result based on drop down selection of class and subject </p>

答:
function ridectMe(){
/*get the data choose*/
  var std = $("#test").val();
  /*you can see the value has been choose*/
  alert("selected : "+std);
  /*if you want to redect the pages, u can use */
  window.location.href="https://localhost/index.php?id="+std+"";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="test" onchange="ridectMe()">
<option value="test1">student 1</option>
<option value="test2">student 2</option>
<option value="test3">student 3</option>
</select></code>```

Body:
function ridectMe(){
/*get the data choose*/
  var std = $("#test").val();
  /*you can see the value has been choose*/
  alert("selected : "+std);
  /*if you want to redect the pages, u can use */
  window.location.href="https://localhost/index.php?id="+std+"";
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="test" onchange="ridectMe()">
<option value="test1">student 1</option>
<option value="test2">student 2</option>
<option value="test3">student 3</option>
</select>


问:
Debug pause doesn't work in Xcode
For some reason, pause doesn't work anymore in Xcode when I debug my Objective-C++ Unit Tests for my project. The button looks active but nothing happens when I click on it.

Has anyone experienced similar issue before?

Xcode 8.2.1, macOS Sierra 10.12.3

答: Disable Gather coverage data from the scheme (Edit scheme → Test → Info → Gather coverage data).

Title: Debug pause doesn't work in Xcode


问:
Replace only text content inside DIV using JavaScript
I want to change only text content inside an h1 tag. Here's my code:

Change only this text and keep the rest

```
</div>
</div>
</p>
<p>I've tried this code :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").innerHTML = "text changed";</code>```

But it doesn't work, here's the result:

  text changed

```

Any help would be appreciated

答:
What you are doing is changing "DeltaPlaceHolderPageTitleInTitleArea" 's innerHTML therefore you replace :

```<code><span>
<span>
<a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a>
</span>
</span>
</code>```

with:

```<code>text changed
</code>```

What you wanted to change is the title's text am I right ? To do so  :

really basic JS:

```<code>document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").children[0].children[0].children[0].innerHTML = "text changed";
</code>```

a bit more advanced :

```<code>document.querySelector("DeltaPlaceHolderPageTitleInTitleArea > span > span > a").innerHTML = "text changed";
</code>```

Or using jQuery :

```<code>$("DeltaPlaceHolderPageTitleInTitleArea > span > span > a").text("text changed");
</code>```

Body:
I want to change only text content inside an h1 tag. Here's my code:

Change only this text and keep the rest

I've tried this code :

document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").innerHTML = "text changed";

But it doesn't work, here's the result:

  text changed

Any help would be appreciated

Body:
What you are doing is changing "DeltaPlaceHolderPageTitleInTitleArea" 's innerHTML therefore you replace :

<span>
<span>
<a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a>
</span>
</span>

with:

text changed

What you wanted to change is the title's text am I right ? To do so  :

really basic JS:

document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").children[0].children[0].children[0].innerHTML = "text changed";

a bit more advanced :

document.querySelector("DeltaPlaceHolderPageTitleInTitleArea > span > span > a").innerHTML = "text changed";

Or using jQuery :

$("DeltaPlaceHolderPageTitleInTitleArea > span > span > a").text("text changed");


问:
My Tools folder has gone how to get it
Today at morning about 6 hour ago I was updating tools and installing new features from SDK Manager. And due to my Internet connection shutdown Updating process canceled automatically. Now when I try to open Android SDK Manager it says

Failed to execute tools/android.bat.

  The system cannot find the file specified.

Then I try to find the android.bat file in tools And I realized that my Tools folder is missing with all its components. But  as I know everything is fine except this problem. How can I get that folder back or download that specific folder instead of the whole android SDK.

答:
Take a look at where the SDK location is defined in Android Studio (File -> Settings -> Appearance & Behaviour -> System Settings -> Android SDK -> Android SDK location) and verify if the folder and its contents still exist on your system.

If the folder has gone, you will need to re-download the SDK (link, see "Get just the command line tools"). Download and extract to the location defined in Android Studio, or point Android SDK Location to wherever you extract the SDK to.

You will also need to re-download whatever tools and libraries you need, time consuming but unfortunately necessary if your existing SDK has indeed been wiped.

Title: My Tools folder has gone how to get it


问:
How to get the name of internal variables used in a method
How is it possible (maybe through Reflection or Roslyn APIs) to get the list of internal variables that are used in a class method?

For example, in the following code:

```<code>class C1{
   private int var1;
   public string var2;

   void action1()
    {
       int var3;
       var3=var1*var1;
       var2="Completed";
   }
}
</code>```

I would like to get var3,var1 and var2 as the list(as name and type) of variables used in the action1() method.

Secondly, I need to identify which of the above variables appear on the left side of an expression; i.e., their values have been modified in this method.

I think the answer lies in using Roslyn, but I have no idea how. Thanks!

答:
As @xanatos mentioned, it is not possible get this information from compiled assembly. You should use Roslyn for this task and have access to the source code. This answer explains how you can retrieve variables https://stackoverflow.com/a/23543883/2138959 and this article can be a good start Getting Started C# Semantic Analysis.

Going through latter article you could came up with following code:

```<code>using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Roslyn
{
    internal class Program
    {
        private static void Main()
        {
            var tree = CSharpSyntaxTree.ParseText(@"
class C1{
   private int var1;
   public string var2;

   void action1()
    {
       int var3;
       var3=var1*var1;
       var2=""Completed"";
   }
}
");
            var root = (CompilationUnitSyntax) tree.GetRoot();
            var variableDeclarations = root.DescendantNodes().OfType<VariableDeclarationSyntax>();

            Console.WriteLine("Declare variables:");

            foreach (var variableDeclaration in variableDeclarations)
                Console.WriteLine(variableDeclaration.Variables.First().Identifier.Value);

            var variableAssignments = root.DescendantNodes().OfType<AssignmentExpressionSyntax>();

            Console.WriteLine("Assign variables:");

            foreach (var variableAssignment in variableAssignments)
                Console.WriteLine($"Left: {variableAssignment.Left}, Right: {variableAssignment.Right}");
        }
    }
}
</code>```

Which produces following output:

```<code>Declare variables:
var1
var2
var3
Assign variables:
Left: var3, Right: var1*var1
Left: var2, Right: "Completed"
</code>```

Make sure to install Microsoft.CodeAnalysis NuGet package.

Body:
How is it possible (maybe through Reflection or Roslyn APIs) to get the list of internal variables that are used in a class method?

For example, in the following code:

class C1{
   private int var1;
   public string var2;

   void action1()
    {
       int var3;
       var3=var1*var1;
       var2="Completed";
   }
}

I would like to get var3,var1 and var2 as the list(as name and type) of variables used in the action1() method.

Secondly, I need to identify which of the above variables appear on the left side of an expression; i.e., their values have been modified in this method.

I think the answer lies in using Roslyn, but I have no idea how. Thanks!

Body:
As @xanatos mentioned, it is not possible get this information from compiled assembly. You should use Roslyn for this task and have access to the source code. This answer explains how you can retrieve variables https://stackoverflow.com/a/23543883/2138959 and this article can be a good start Getting Started C# Semantic Analysis.

Going through latter article you could came up with following code:

using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Roslyn
{
    internal class Program
    {
        private static void Main()
        {
            var tree = CSharpSyntaxTree.ParseText(@"
class C1{
   private int var1;
   public string var2;

   void action1()
    {
       int var3;
       var3=var1*var1;
       var2=""Completed"";
   }
}
");
            var root = (CompilationUnitSyntax) tree.GetRoot();
            var variableDeclarations = root.DescendantNodes().OfType<VariableDeclarationSyntax>();

            Console.WriteLine("Declare variables:");

            foreach (var variableDeclaration in variableDeclarations)
                Console.WriteLine(variableDeclaration.Variables.First().Identifier.Value);

            var variableAssignments = root.DescendantNodes().OfType<AssignmentExpressionSyntax>();

            Console.WriteLine("Assign variables:");

            foreach (var variableAssignment in variableAssignments)
                Console.WriteLine($"Left: {variableAssignment.Left}, Right: {variableAssignment.Right}");
        }
    }
}

Which produces following output:

Declare variables:
var1
var2
var3
Assign variables:
Left: var3, Right: var1*var1
Left: var2, Right: "Completed"

Make sure to install Microsoft.CodeAnalysis NuGet package.


问:
How to get the count of repeated value of some perticular attribute in array of object and store in Object
Suppose I have an array of Object.

code :

```<code>var arrayMap = [{continent: "Asia", Country: "China"},
{continent:"NAmerica", Country: "USA"},
{continent:"Asia", Country:"India"},
{continent:"Australia", Country:"Australia"},
{continent:"Asia", Country:"Japan"},
{continent:"Europe", Country:"UK"},
{continent:"SAmerica", Country:"Brazil"},
{continent:"Europe", Country:"Germany"},
{continent:"Asia", Country:"Rassia"},
{continent:"NAmerica", Country:"Canada"}]
</code>```

Now I have two attribute continent and Country in arrayMap in Obj. I want to the counts of country in all continent.
like :

```<code> Obj{Asia: 4, NAmerica:2, Australia:1, Europe:2, SAmerica:1}
</code>```

Can anybody help me how to get this.

答:
```<code>let groupByContinent = {}
arrayMap.map(data => {
   if(groupByContinent[data.continent])
      groupByContinent[data.continent] += 1
   else
     groupByContinent[data.continent] = 1
})
console.log(groupByContinent)
</code>```

Body:
Suppose I have an array of Object.

code :

var arrayMap = [{continent: "Asia", Country: "China"},
{continent:"NAmerica", Country: "USA"},
{continent:"Asia", Country:"India"},
{continent:"Australia", Country:"Australia"},
{continent:"Asia", Country:"Japan"},
{continent:"Europe", Country:"UK"},
{continent:"SAmerica", Country:"Brazil"},
{continent:"Europe", Country:"Germany"},
{continent:"Asia", Country:"Rassia"},
{continent:"NAmerica", Country:"Canada"}]

Now I have two attribute continent and Country in arrayMap in Obj. I want to the counts of country in all continent.
like :

 Obj{Asia: 4, NAmerica:2, Australia:1, Europe:2, SAmerica:1}

Can anybody help me how to get this.


问:
How to pass csharp binding variable to Javascript function
I want to pass c# binding variable to javascript function. Here is my code:

```<code><asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%#Bind(variable)%>'); "></asp:LinkButton>
</code>```

But it always generates an error : "htmlfile: Not implemented".

And the code is not intepreted onclick="passAccessory('<%#Bind(variable)%>');"

Does anyone knows how to solve it ?

Thanks.

Edit: I have changed the code to

```<code><asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%# Eval("lblTest.ClientID") %>');"></asp:LinkButton>
</code>```

And this is the code it's related to, it uses the lblTest.ClientID

<asp:Label ID="lblTest" runat="server" Text='<%#Bind("reference")%>' />

But i received an error: HttpException. Databinding ... does not contain a property with the name lblTest. Is there any wrong with my code.

Edit:  These posts gave me a clue.

http://www.west-wind.com/Weblog/posts/5364.aspx

I am trying to learn how to bind an IEnumerable LINQ collection to a repeater

Now i have want to use

```<code><asp:LinkButton ID="lbTest" runat="server" Text='<%#Text%>' OnClientClick='<%#string.Format("passAccessory(\"{0}\");", Eval("Ref"))%>'></asp:LinkButton>
</code>```

答:
I didn't do ASP.NET webforms for along time, but I believe it should be like this:

OnClientClick="<%# string.Format("passAccessory('{0}');", Container.DataItem("variable")) %>"

Body:
I want to pass c# binding variable to javascript function. Here is my code:

<asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%#Bind(variable)%>'); "></asp:LinkButton>

But it always generates an error : "htmlfile: Not implemented".

And the code is not intepreted onclick="passAccessory('<%#Bind(variable)%>');"

Does anyone knows how to solve it ?

Thanks.

Edit: I have changed the code to

<asp:LinkButton ID="lbID" runat="server" Text="<%#Text%>" OnClientClick="passAccessory('<%# Eval("lblTest.ClientID") %>');"></asp:LinkButton>

And this is the code it's related to, it uses the lblTest.ClientID

<asp:Label ID="lblTest" runat="server" Text='<%#Bind("reference")%>' />

But i received an error: HttpException. Databinding ... does not contain a property with the name lblTest. Is there any wrong with my code.

Edit:  These posts gave me a clue.

http://www.west-wind.com/Weblog/posts/5364.aspx

I am trying to learn how to bind an IEnumerable LINQ collection to a repeater

Now i have want to use

<asp:LinkButton ID="lbTest" runat="server" Text='<%#Text%>' OnClientClick='<%#string.Format("passAccessory(\"{0}\");", Eval("Ref"))%>'></asp:LinkButton>


问:
How to use single View Models in MVC to display multiple model in razor view?
i am working with mvc after doing so much R&D i started this student project but now stuck at the situation where i have no any idea how can i create a viewmodel to display data from two different models. </p>

答:
Possible solutions

Create another model that takes your 2 or multiple models as its properties

Use Tuples


问:
Why is Page load event not firing?
My project name is sbmanager and in that project
I have a page named  mgrGridHome.aspx
This page has the following reference:

```<code><%@ Page Language="C#" Inherits="sbmanager.mgrGridHome" MasterPageFile="~/masterpages/global.master" %>
</code>```

That has a label on it:

```<code><asp:Label id="lblCurrentTime" runat="server"></asp:Label>
</code>```

In my mgrGridHome.aspx.cs file I have  the following:

```<code>protected void page_load(object sender, EventArgs e)
        {

            lblCurrentTime.Text = "See Me";
        }
</code>```

But when I compile and run the page the label value is not set as if the page load has not fired.

But if I place the same code directly on the page like this:

```<code><script language="C#" runat="server">
    public void Page_Load(object sender, EventArgs e)
    {
        <asp:Label id="lblCurrentTime" runat="server"></asp:Label>
    }
</script>
</code>```

The label value is set.

All I want to do is set the label value when the page loads. At the moment I don't care if it is a post-back or not. Am I going about this the wrong way?

答:
Moved from Comment -

Add AutoEventWireup at Page - <%@ Page AutoEventWireup="true" ... %>

Also ensure event name is Page_Load

Title: Why is Page load event not firing?

Body:
My project name is sbmanager and in that project
I have a page named  mgrGridHome.aspx
This page has the following reference:

<%@ Page Language="C#" Inherits="sbmanager.mgrGridHome" MasterPageFile="~/masterpages/global.master" %>

That has a label on it:

<asp:Label id="lblCurrentTime" runat="server"></asp:Label>

In my mgrGridHome.aspx.cs file I have  the following:

protected void page_load(object sender, EventArgs e)
        {

            lblCurrentTime.Text = "See Me";
        }

But when I compile and run the page the label value is not set as if the page load has not fired.

But if I place the same code directly on the page like this:

The label value is set.

All I want to do is set the label value when the page loads. At the moment I don't care if it is a post-back or not. Am I going about this the wrong way?


问:
EF core error while add migration
I have problem with  EF core error while add migration. Here is my code

```<code> public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Subject> Subjects { get; set; }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<Subject>().HasKey(s => s.Id);
            builder.Entity<Subject>().Property(c => c.Name)
                .HasMaxLength(100)
                .IsRequired();

            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }
</code>```

I want to add migration with nuget but get this error

Add-Migration "New"
  C:\Applications\Projects\Education\src\Education.Web.Admin.Frontend.App\project.json(34,43):
  warning NU1012: Dependency conflict. Microsoft.EntityFrameworkCore
  1.1.1 expected Microsoft.Extensions.Logging >= 1.1.1 but received 1.0.0 No parameterless constructor was found on 'ApplicationDbContext'. Either add a parameterless constructor to
  'ApplicationDbContext' or add an implementation of
  'IDbContextFactory' in the same assembly as
  'ApplicationDbContext'.

答:
The error message seems clear enough. your Db context class has no parameterless constructor. You should add one like this:</p>

```<code>public ApplicationDbContext() : base("your connection string") {}
</code>```

Title: EF core error while add migration

Body:
I have problem with  EF core error while add migration. Here is my code

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Category> Categories { get; set; }
        public DbSet<Subject> Subjects { get; set; }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<Subject>().HasKey(s => s.Id);
            builder.Entity<Subject>().Property(c => c.Name)
                .HasMaxLength(100)
                .IsRequired();

            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }

I want to add migration with nuget but get this error

Add-Migration "New"
  C:\Applications\Projects\Education\src\Education.Web.Admin.Frontend.App\project.json(34,43):
  warning NU1012: Dependency conflict. Microsoft.EntityFrameworkCore
  1.1.1 expected Microsoft.Extensions.Logging >= 1.1.1 but received 1.0.0 No parameterless constructor was found on 'ApplicationDbContext'. Either add a parameterless constructor to
  'ApplicationDbContext' or add an implementation of
  'IDbContextFactory' in the same assembly as
  'ApplicationDbContext'.

Body:
The error message seems clear enough. your Db context class has no parameterless constructor. You should add one like this:

public ApplicationDbContext() : base("your connection string") {}


问:
Make a multi architecture static library in C
I'm working on Ubuntu and I've made a static c library following the instructions on this site.

But the resulting .a package works only on the machine where it has been compiled.

I know that an .a archive contains object files (only one in my case), so, can I package together object files compiled in different machines (i386 and amd64) in a way so GCC can know which file should be using?

If I cannot, can at least make my library recognizable by other same-arch machines?
(using -L. -llibraryname)

Example:

archive name "libvisualt64.a"

command: gcc -o main main.c -L. -lvisualt64

Says:

```
skipping incompatible ./libvisualt.a when searching for -lvisualt64
cannot find -lvisualt64
error: ld returned 1 exit status
```

In this case I compiled the source and built the archive in the same 64bit machine just yesterday.
And yesterday it worked fine.
This happens on 32bit machines too.

答:
Linux uses an executable file format called ELF.
An ELF file can only contain the necessary machine code for a single architecture.

There should be no problems using your library on another machine of the same architecture. The only potential issue could be related to dependencies.

If you really want a single binary to support multiple architectures, then you may be interested in FatELF... Though it is not supported without a kernel patch:

Up to now the FatELF is not integrated in the kernel mainline.

To address your edit, it is likely that your libvisualt64.a is not built for the same architecture that gcc is targeting...

You'll need to extract the object files from the archive, and compare them with gcc's target:

ar xv ${STATIC_LIBRARY}
file *.o
gcc -v 2>&1 | grep '^Target: '
```

<p>I see the following (compatible) outputs:</p>

<pre class="lang-none prettyprint-override"><code>test.o: ELF 64-bit LSB  relocatable, x86-64, version 1 (SYSV), not stripped
Target: x86_64-linux-gnu
</code>```

Body:
I'm working on Ubuntu and I've made a static c library following the instructions on this site.

But the resulting .a package works only on the machine where it has been compiled.

I know that an .a archive contains object files (only one in my case), so, can I package together object files compiled in different machines (i386 and amd64) in a way so GCC can know which file should be using?

If I cannot, can at least make my library recognizable by other same-arch machines?
(using -L. -llibraryname)

Example:

archive name "libvisualt64.a"

command: gcc -o main main.c -L. -lvisualt64

Says:

skipping incompatible ./libvisualt.a when searching for -lvisualt64
cannot find -lvisualt64
error: ld returned 1 exit status

In this case I compiled the source and built the archive in the same 64bit machine just yesterday.
And yesterday it worked fine.
This happens on 32bit machines too.

Body:
Linux uses an executable file format called ELF.
An ELF file can only contain the necessary machine code for a single architecture.

There should be no problems using your library on another machine of the same architecture. The only potential issue could be related to dependencies.

If you really want a single binary to support multiple architectures, then you may be interested in FatELF... Though it is not supported without a kernel patch:

Up to now the FatELF is not integrated in the kernel mainline.

To address your edit, it is likely that your libvisualt64.a is not built for the same architecture that gcc is targeting...

You'll need to extract the object files from the archive, and compare them with gcc's target:

ar xv ${STATIC_LIBRARY}
file *.o
gcc -v 2>&1 | grep '^Target: '

I see the following (compatible) outputs:

test.o: ELF 64-bit LSB  relocatable, x86-64, version 1 (SYSV), not stripped
Target: x86_64-linux-gnu


问:
How to check for only checked checkboxes in an array in javascript
I am using code.org library. I am trying to use only checked checkboxes to select two teams for a baseball game. Currently I can only select 1 team but I need to select two teams effectively by not just going to the next team in the array. I have never see such problem in JavaScript.

```<code>onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var index = 0;
    while (index < chkBoxs.length && !getChecked(chkBoxs[index])) {
      index++;
    }
    setScreen("game");
    console.log("The Teams are: " + chkBoxs[index]+" And "+chkBoxs[index+1]);
});
</code>```

答:
Assuming I understand the question, you could keep track of the selected teams individually using an array:

```<code>onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var indexes = [];
    for (var i =0; i < chkBoxs.length; i++) {
       if (getChecked(chkBoxs[index]))) {
          indexes.push(index); // store team index
       }
    }
    setScreen("game");
    console.log("The Teams are: " + chkBoxs[indexes[0]]+" And "+chkBoxs[indexes[1]]);
});
</code>```

This also assumes you always have two teams. Otherwise you'd have to handle the last line differently. If all you need is the team name:

```<code>onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var teams = [];
    for (var i =0; i < chkBoxs.length; i++) {
       if (getChecked(chkBoxs[index]))) {
          teams.push(chkBoxs[index]); // store team name
       }
    }
    setScreen("game");
    console.log("The Teams are: " + teams.join(', ') + ".");
});
</code>```

Body:
I am using code.org library. I am trying to use only checked checkboxes to select two teams for a baseball game. Currently I can only select 1 team but I need to select two teams effectively by not just going to the next team in the array. I have never see such problem in JavaScript.

onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var index = 0;
    while (index < chkBoxs.length && !getChecked(chkBoxs[index])) {
      index++;
    }
    setScreen("game");
    console.log("The Teams are: " + chkBoxs[index]+" And "+chkBoxs[index+1]);
});

Body:
Assuming I understand the question, you could keep track of the selected teams individually using an array:

onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var indexes = [];
    for (var i =0; i < chkBoxs.length; i++) {
       if (getChecked(chkBoxs[index]))) {
          indexes.push(index); // store team index
       }
    }
    setScreen("game");
    console.log("The Teams are: " + chkBoxs[indexes[0]]+" And "+chkBoxs[indexes[1]]);
});

This also assumes you always have two teams. Otherwise you'd have to handle the last line differently. If all you need is the team name:

onEvent("btnStart","click", function() {
    var chkBoxs = ["Yankees","Boston","Astros"];
    var teams = [];
    for (var i =0; i < chkBoxs.length; i++) {
       if (getChecked(chkBoxs[index]))) {
          teams.push(chkBoxs[index]); // store team name
       }
    }
    setScreen("game");
    console.log("The Teams are: " + teams.join(', ') + ".");
});


问:
Valid to use future after corresponding promise leaves scope
If you extract a future from a promise, is it valid to call future::get_value after the promise leaves scope?

```<code>std::future<void> future;
{
    std::promise<void> promise;
    future = promise.get_future();
    promise.set_value();
}
future.wait();
</code>```

I am unable to find an answer using promise's and future's documentation.

答:
Promises and future have a shared state.

A future whose promise was not fullfilled and was destroyed is a broken promise.  The shared state is given an exception and made ready.

But a future whose promise was fullfilled and then the promise was destroyed is perfectly ok.  The shared state persists.

Look at ~promise and the discussion about shared state on the main doc page.

Body:
If you extract a future from a promise, is it valid to call future::get_value after the promise leaves scope?

std::future<void> future;
{
    std::promise<void> promise;
    future = promise.get_future();
    promise.set_value();
}
future.wait();

I am unable to find an answer using promise's and future's documentation.


问:
How to set data in viewpager using ArrayList?
Here, in this viewpageradapter class is using to set data, how can I set data in viewpager. I can try to implement but I don't know how can be achieving this.I also add my PhotoviewAdater and PhotoActivity. plz solve this problem.

```<code>public class PhotoViewAdapter extends PagerAdapter {

Context context;
ArrayList<Model_image> all_folder = new ArrayList<>();
int int_position;
LayoutInflater inflater;

public PhotoViewAdapter(Context context, ArrayList<Model_image> all_folder, int int_position) {
    this.context=context;
    this.all_folder=all_folder;
    this.int_position=int_position;
}

@Override
public int getCount() {
    return all_folder.get(int_position).getAll_imagepath().size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    ImageView imageView;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View viewLayout = inflater.inflate(R.layout.activity_photo_view_adapter, container,false);

    imageView = (ImageView) container.findViewById(R.id.im_page);

     try {
        imageView.setImageResource(Integer.parseInt((all_folder.get(position).getAll_imagepath().get(int_position))));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return viewLayout;
}
}
</code>```

PhotoActivity:

```<code>public class PhotoActivity extends AppCompatActivity {

ViewPager viewPager;
int int_position;
PhotoViewAdapter photoViewAdapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_photo_view);

    int_position = getIntent().getIntExtra("pos",0);
    viewPager = (ViewPager) findViewById(R.id.imagepage);
    photoViewAdapter = new PhotoViewAdapter(getApplicationContext(), ImageActivity.all_images, int_position);
    viewPager.setAdapter(photoViewAdapter);
}
}
</code>```

Model_image:

```<code>public class Model_image {

String str_folder;
ArrayList<String> all_imagepath;

public void setStr_folder(String str_folder)
{
    this.str_folder = str_folder;
}

public void setAll_imagepath(ArrayList<String> all_imagepath)
{
    this.all_imagepath = all_imagepath;
}

public String getStr_folder()
{
    return str_folder;
}

public ArrayList<String> getAll_imagepath()
{
    return all_imagepath;
}
}
</code>```

答:
setImageResource is used to set an image from the apk resources.

rather use      imageView.setImageBitmap(BitmapFactory.decodeFile(all_folder.get(position).getPath()));

It is unclear yet from your Model_image class what an unique path can be, so you need to define a getPath() method.

Body:
Here, in this viewpageradapter class is using to set data, how can I set data in viewpager. I can try to implement but I don't know how can be achieving this.I also add my PhotoviewAdater and PhotoActivity. plz solve this problem.

public class PhotoViewAdapter extends PagerAdapter {

Context context;
ArrayList<Model_image> all_folder = new ArrayList<>();
int int_position;
LayoutInflater inflater;

public PhotoViewAdapter(Context context, ArrayList<Model_image> all_folder, int int_position) {
    this.context=context;
    this.all_folder=all_folder;
    this.int_position=int_position;
}

@Override
public int getCount() {
    return all_folder.get(int_position).getAll_imagepath().size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    ImageView imageView;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View viewLayout = inflater.inflate(R.layout.activity_photo_view_adapter, container,false);

    imageView = (ImageView) container.findViewById(R.id.im_page);

     try {
        imageView.setImageResource(Integer.parseInt((all_folder.get(position).getAll_imagepath().get(int_position))));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return viewLayout;
}
}

PhotoActivity:

public class PhotoActivity extends AppCompatActivity {

ViewPager viewPager;
int int_position;
PhotoViewAdapter photoViewAdapter;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_photo_view);

    int_position = getIntent().getIntExtra("pos",0);
    viewPager = (ViewPager) findViewById(R.id.imagepage);
    photoViewAdapter = new PhotoViewAdapter(getApplicationContext(), ImageActivity.all_images, int_position);
    viewPager.setAdapter(photoViewAdapter);
}
}

Model_image:

public class Model_image {

String str_folder;
ArrayList<String> all_imagepath;

public void setStr_folder(String str_folder)
{
    this.str_folder = str_folder;
}

public void setAll_imagepath(ArrayList<String> all_imagepath)
{
    this.all_imagepath = all_imagepath;
}

public String getStr_folder()
{
    return str_folder;
}

public ArrayList<String> getAll_imagepath()
{
    return all_imagepath;
}
}


问:
Paged queries with JdbcTemplate
I'm currently working on a migration project, to migrate data from the old db to the new one (please do not ask why I'm going through a Java application for this, it's what the customer requires).

There was some, initial, code which I'm updating now. One of the things I'm changing is using Spring's JdbcTemplate rather then the boiler-plate code which was there.

Unfortunately, I haven't found a way yet to execute paged queries on a JdbcTemplate, analogue to the old code:

```<code>Statement statement = getConnection().createStatement(
    ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
statement.setFetchDirection(ResultSet.FETCH_FORWARD);
statement.setFetchSize(1000);
return statement.executeQuery();
</code>```

The getConnection() just return a Connection object, created in plain JDBC code (it's not part of a SessionFactory or a framework implementation).

I would then loop over the resultset, mapping the rows one at a time. Does anyone know if there's an easy way to achieve the same functionality with JdbcTemplate?

TIA

答:
I think the natural choice for such an Application is Spring Batch (read the impressive Features page)

Here are the sections that should be relevant to you:

ItemReaders and ItemWriters > DataBase

and in particular JdbcPagingItemReader

Title: Paged queries with JdbcTemplate

Body:
I'm currently working on a migration project, to migrate data from the old db to the new one (please do not ask why I'm going through a Java application for this, it's what the customer requires).

There was some, initial, code which I'm updating now. One of the things I'm changing is using Spring's JdbcTemplate rather then the boiler-plate code which was there.

Unfortunately, I haven't found a way yet to execute paged queries on a JdbcTemplate, analogue to the old code:

Statement statement = getConnection().createStatement(
    ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
statement.setFetchDirection(ResultSet.FETCH_FORWARD);
statement.setFetchSize(1000);
return statement.executeQuery();

The getConnection() just return a Connection object, created in plain JDBC code (it's not part of a SessionFactory or a framework implementation).

I would then loop over the resultset, mapping the rows one at a time. Does anyone know if there's an easy way to achieve the same functionality with JdbcTemplate?

TIA


问:
How to check file type before uploading with AngularJS?
I want to upload a zip file to server. Before uploading, I have to check if it's a zip file.

If it's a zip file, then submit.

If it's not a zip file, it comes up "Not a zip file." and the file can't be uploaded.

HTML:

```<code><form action="{{restUrl}}" method="post" enctype="multipart/form-data" name="myForm" novalidate>
  <input type="file" id="fileUpload" name="fileUpload">
  <p ng-show="">Not a zip file.</p>
  <input type="submit" value="Upload">
</form>
</code>```

I wish it could be a directive or a controller in AngularJS.

答:
To validate file extension you can create Angular directive & use it in html...

please see below code to create valid-file directive

```<code>{yourModuleName}.directive('validFile', function validFile($parse) {

return {
    restrict : 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {

        ngModelCtrl.$validators.validFile = function() {

            element.on('change', function () {

                var value = element.val(),
                    model = $parse(attrs.ngModel),
                    modelSetter = model.assign;

                scope.uploadedFileType = null;

                if(!value) {

                    modelSetter(scope, '');

                } else {

                    var ext = value.substring(value.lastIndexOf('.') + 1).toLowerCase();

                    if(attrs.validFile.indexOf(ext) !== -1) {

                        scope.uploadedFileType = ext;
                        modelSetter(scope, element[0].files[0]);

                    } else {

                        scope.uploadedFileType = 'other';
                        modelSetter(scope, '');
                    }
                }
            });
        };
    }
  };
});
</code>```

in html use below

```<code><input type="file" id="payloadFile" name="payloadFile" ng-model="cntrl.payloadFile" valid-file=".xml" required/>
</code>```

submit function =>

```<code>uploadFile = function() {
      var file = cntrl.payloadFile;

        if(file == undefined || file == null) {

            return;

        } else if(file == '' && $scope.uploadedFileType == 'other') {
            document.getElementById('payloadFile').setCustomValidity('Supported file formats are *.xml');
       } else{
           //submit valid file here
       }
    }
</code>```

Check running code here

Body:
I want to upload a zip file to server. Before uploading, I have to check if it's a zip file.

If it's a zip file, then submit.

If it's not a zip file, it comes up "Not a zip file." and the file can't be uploaded.

HTML:

<form action="{{restUrl}}" method="post" enctype="multipart/form-data" name="myForm" novalidate>
  <input type="file" id="fileUpload" name="fileUpload">

Not a zip file.

  <input type="submit" value="Upload">
</form>

I wish it could be a directive or a controller in AngularJS.

Body:
To validate file extension you can create Angular directive & use it in html...

please see below code to create valid-file directive

{yourModuleName}.directive('validFile', function validFile($parse) {

return {
    restrict : 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {

        ngModelCtrl.$validators.validFile = function() {

            element.on('change', function () {

                var value = element.val(),
                    model = $parse(attrs.ngModel),
                    modelSetter = model.assign;

                scope.uploadedFileType = null;

                if(!value) {

                    modelSetter(scope, '');

                } else {

                    var ext = value.substring(value.lastIndexOf('.') + 1).toLowerCase();

                    if(attrs.validFile.indexOf(ext) !== -1) {

                        scope.uploadedFileType = ext;
                        modelSetter(scope, element[0].files[0]);

                    } else {

                        scope.uploadedFileType = 'other';
                        modelSetter(scope, '');
                    }
                }
            });
        };
    }
  };
});

in html use below

<input type="file" id="payloadFile" name="payloadFile" ng-model="cntrl.payloadFile" valid-file=".xml" required/>

submit function =>

uploadFile = function() {
      var file = cntrl.payloadFile;

        if(file == undefined || file == null) {

            return;

        } else if(file == '' && $scope.uploadedFileType == 'other') {
            document.getElementById('payloadFile').setCustomValidity('Supported file formats are *.xml');
       } else{
           //submit valid file here
       }
    }

Check running code here


问:
Extract 'p' data from 'div' with Class of div = ""
I am trying to extract the data in the div with "" as className followed by p tag.
My html looks like this

```<code><div class=""><p>I've been with USAA since 1981 - they've been a good, helpful company and easy to deal with except with making payments on their website. Every time I try to make a payment the website has a problem and I end up calling them. Today, I tried to make a credit card update (same account, different exp. date and code) before I made a payment. The website kept telling me it wouldn't accept the information.</p><p>I called the company to make the payment and was told the system had accepted the information but I couldn't make the payment until tomorrow because of the update. They refused to let me make my payment by phone. 4 times in the past 2 years it wouldn't accept my password, even after I confirmed it by - yes calling in. Other payments have not been accepted for unknown reasons - I've had to call them in. No point having a website if it doesn't work. I avoid calling because it takes so many steps to reach a live person. It's a minor complaint but it happens every time.</p></div></div>
</code>```

I am using Beautifulsoup and my code to extarct this data is :

```<code>reviewAllList = [row.text for row in soup.find_all('div',attrs={"class" : ""})]
</code>```

However, I am not able to extarct the correct data from the same. Is it that I am missing something? I am using Python 3.5.

答:
Use lambda to find all divs with an empty class attribute andthe first child is a p

```<code>rows = [str(row.get_text(strip=True)) for row in soup.find_all(lambda tag: tag.name == "div" and ("class" not in tag.attrs or not len(" ".join(tag["class"]))) and tag.findChildren()[0].name == "p")]
</code>```

Body:
I am trying to extract the data in the div with "" as className followed by p tag.
My html looks like this

I've been with USAA since 1981 - they've been a good, helpful company and easy to deal with except with making payments on their website. Every time I try to make a payment the website has a problem and I end up calling them. Today, I tried to make a credit card update (same account, different exp. date and code) before I made a payment. The website kept telling me it wouldn't accept the information.

I called the company to make the payment and was told the system had accepted the information but I couldn't make the payment until tomorrow because of the update. They refused to let me make my payment by phone. 4 times in the past 2 years it wouldn't accept my password, even after I confirmed it by - yes calling in. Other payments have not been accepted for unknown reasons - I've had to call them in. No point having a website if it doesn't work. I avoid calling because it takes so many steps to reach a live person. It's a minor complaint but it happens every time.

I am using Beautifulsoup and my code to extarct this data is :

reviewAllList = [row.text for row in soup.find_all('div',attrs={"class" : ""})]

However, I am not able to extarct the correct data from the same. Is it that I am missing something? I am using Python 3.5.

Body:
Use lambda to find all divs with an empty class attribute andthe first child is a p

rows = [str(row.get_text(strip=True)) for row in soup.find_all(lambda tag: tag.name == "div" and ("class" not in tag.attrs or not len(" ".join(tag["class"]))) and tag.findChildren()[0].name == "p")]


问:
What's the purpose of signal pt in this example
What does callq  400b90 <signal@plt> do?

How would it look line in C?

```<code>4013a2:       48 83 ec 08             sub    $0x8,%rsp
4013a6:       be a0 12 40 00          mov    $0x4012a0,%esi
4013ab:       bf 02 00 00 00          mov    $0x2,%edi
4013b0:       e8 db f7 ff ff          callq  400b90 <signal@plt>
4013b5:       48 83 c4 08             add    $0x8,%rsp
4013b9:       c3                      retq
</code>```

答:
What does callq  400b90 <signal@plt> do?

Call the signal function via the PLT (procedure linkage table). So more technical: It pushes the current instruction pointer onto the stack and jumps to signal@plt.

How would it look line in C?

```<code>void* foo(void) {
    return signal(2, (void *) 0x4012a0);
}
</code>```

Let's look at your code line-by-line:

```<code>sub    $0x8,%rsp
</code>```

This reserves some stack space. You can ignore this (the stack space is unused).

```<code>mov    $0x4012a0,%esi
mov    $0x2,%edi
</code>```

Put the value 0x4012a0 and 0x2 in the registers ESI and EDI. By the ABI, this is how arguments are passed to a function.

```<code>callq  400b90 <signal@plt>
</code>```

Call the function signal through the PLT. The PLT has something to do with the dynamic linker since we cannot be sure where the signal function will end up in memory whenthis is built. Basically, this just finds the final memory location and calls signal.

```<code>add    $0x8,%rsp
retq
</code>```

Undo the sub from earlier and return to the caller.

Body:
What does callq  400b90 <signal@plt> do?

How would it look line in C?

4013a2:       48 83 ec 08             sub    $0x8,%rsp
4013a6:       be a0 12 40 00          mov    $0x4012a0,%esi
4013ab:       bf 02 00 00 00          mov    $0x2,%edi
4013b0:       e8 db f7 ff ff          callq  400b90 <signal@plt>
4013b5:       48 83 c4 08             add    $0x8,%rsp
4013b9:       c3                      retq

Body:
What does callq  400b90 <signal@plt> do?

Call the signal function via the PLT (procedure linkage table). So more technical: It pushes the current instruction pointer onto the stack and jumps to signal@plt.

How would it look line in C?

void* foo(void) {
    return signal(2, (void *) 0x4012a0);
}

Let's look at your code line-by-line:

sub    $0x8,%rsp

This reserves some stack space. You can ignore this (the stack space is unused).

mov    $0x4012a0,%esi
mov    $0x2,%edi

Put the value 0x4012a0 and 0x2 in the registers ESI and EDI. By the ABI, this is how arguments are passed to a function.

callq  400b90 <signal@plt>

Call the function signal through the PLT. The PLT has something to do with the dynamic linker since we cannot be sure where the signal function will end up in memory whenthis is built. Basically, this just finds the final memory location and calls signal.

add    $0x8,%rsp
retq

Undo the sub from earlier and return to the caller.


答:
You can try out this.

function changeContent(){

var element = document.getElementById('DeltaPlaceHolderPageTitleInTitleArea');
element.children[0].innerHTML = "whatever";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 id="pageTitle" class="ms-core-pageTitle">
  <span id="DeltaPlaceHolderPageTitleInTitleArea">

    Change only this text and keep the rest

 </span>

  <button name="change content" onClick="changeContent()">change content</button>

</h1></code>```

Title: Replace only text content inside DIV using JavaScript

Body:
I want to change only text content inside an h1 tag. Here's my code:

Change only this text and keep the rest

I've tried this code :

document.getElementById("DeltaPlaceHolderPageTitleInTitleArea").innerHTML = "text changed";

But it doesn't work, here's the result:

  text changed

Any help would be appreciated

Body:
You can try out this.

function changeContent(){

var element = document.getElementById('DeltaPlaceHolderPageTitleInTitleArea');
element.children[0].innerHTML = "whatever";
}

<h1 id="pageTitle" class="ms-core-pageTitle">
  <span id="DeltaPlaceHolderPageTitleInTitleArea">

    <a title="some title" href="/link/page.aspx">Change only this text and keep the rest</a>

 </span>

  <button name="change content" onClick="changeContent()">change content</button>

</h1>


问:
How much flexibility it gives when you create a views using Zend forms and decorators
I need to create search view that contains 8 - 9 controls in a form. these controls are mixed type like text box, text area, combo box, check box and radio box. I also need to hide and show some of the controls based on previously selected values. There are some controls generated through ajax based on selected values. after search the same page show the results with pagination.

Can anybody let me know, should I use Zend forms and custom decorators or should I use normal html and Java Script to prepare this page. Which one is time saving job as I prefer later one.

I already have the page design in Static HTML.

答:
My personal opinion (others may disagree) is, for a simple form, just use plain-old html (with or without Zend's view helpers). I've been using ZF for years now, and I simply cannot get to grips with (Zend) forms and decorators.

Just two weeks ago, I started on a new project, and said to myself "Right, time to use Zend forms and decorators." After one full working day of messing around yet-again with the documentation, tutorials, and whatever other resources I could get my hands on, I gave up (again) and an hour later my form was ready complete with client and server side validation and filtering, using the slighty more intuitive Zend_Filter_Input interface, and jQuery. The only thing 'fancy' I used in the view in which the form appeared was the view helpers, e.g.:

```<code><?php echo $this->formText('username', isset($this->input) ? $this->input->username : '', array('size' => 32)) ?>
...
<?php echo $this->formText('email', isset($this->input) ? $this->input->email : '', array('size' => 32)) ?>
...
<?php echo $this->formSubmit('register', 'Register') ?>
</code>```

But that is just my opinion, others may have had happy endings, but not me.

Body:
My personal opinion (others may disagree) is, for a simple form, just use plain-old html (with or without Zend's view helpers). I've been using ZF for years now, and I simply cannot get to grips with (Zend) forms and decorators.

Just two weeks ago, I started on a new project, and said to myself "Right, time to use Zend forms and decorators." After one full working day of messing around yet-again with the documentation, tutorials, and whatever other resources I could get my hands on, I gave up (again) and an hour later my form was ready complete with client and server side validation and filtering, using the slighty more intuitive Zend_Filter_Input interface, and jQuery. The only thing 'fancy' I used in the view in which the form appeared was the view helpers, e.g.:

<?php echo $this->formText('username', isset($this->input) ? $this->input->username : '', array('size' => 32)) ?>
...
<?php echo $this->formText('email', isset($this->input) ? $this->input->email : '', array('size' => 32)) ?>
...
<?php echo $this->formSubmit('register', 'Register') ?>

But that is just my opinion, others may have had happy endings, but not me.


问:
Can I create Cloudwatch custom metrics with Java?
Is it possible to create AWS CloudWatch custom metrics using Java SDK provided by AWS?

The developer guide talks about publishing custom metrics through Command line tools.

Is it possible with the Java SDK? If yes, please provide the links or tutorials for that.

答:
The below code can be used to Publish Custom Metrics in AWS CloudWatch using JAVA.

```<code>AmazonCloudWatch amazonCloudWatch =
AmazonCloudWatchClientBuilder.standard().withEndpointConfiguration(
    new AwsClientBuilder.EndpointConfiguration("monitoring.us-west-1.amazonaws.com","us-west-1")).build();

PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest();
putMetricDataRequest.setNamespace("CUSTOM/SQS");

MetricDatum metricDatum1 = new MetricDatum().withMetricName("MessageCount").withDimensions(new Dimension().withName("Personalization").withValue("123"));
        metricDatum1.setValue(-1.00);
        metricDatum1.setUnit(StandardUnit.Count);
        putMetricDataRequest.getMetricData().add(metricDatum1);

PutMetricDataResult result = amazonCloudWatch.putMetricData(putMetricDataRequest);
</code>```

Only thing to remember is to include aws-java-sdk-cloudwatch

Body:
The below code can be used to Publish Custom Metrics in AWS CloudWatch using JAVA.

AmazonCloudWatch amazonCloudWatch =
AmazonCloudWatchClientBuilder.standard().withEndpointConfiguration(
    new AwsClientBuilder.EndpointConfiguration("monitoring.us-west-1.amazonaws.com","us-west-1")).build();

PutMetricDataRequest putMetricDataRequest = new PutMetricDataRequest();
putMetricDataRequest.setNamespace("CUSTOM/SQS");

MetricDatum metricDatum1 = new MetricDatum().withMetricName("MessageCount").withDimensions(new Dimension().withName("Personalization").withValue("123"));
        metricDatum1.setValue(-1.00);
        metricDatum1.setUnit(StandardUnit.Count);
        putMetricDataRequest.getMetricData().add(metricDatum1);

PutMetricDataResult result = amazonCloudWatch.putMetricData(putMetricDataRequest);

Only thing to remember is to include aws-java-sdk-cloudwatch


问:
In react-native - how to float elements in new line when they can't fit into one?
From the example here I'm wondering if it's possible to float items into new line when they can't fit into one?

```<code><View style={{flex: 1, flexDirection: 'row'}}>
  <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
  <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
  <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
  <View style={{width: 50, height: 50, backgroundColor: 'red'}} />
  <View style={{width: 50, height: 50, backgroundColor: 'green'}} />
  <View style={{width: 50, height: 50, backgroundColor: 'blue'}} />
</View>
</code>```

The blue coloured item should be in new line. Is it possible with flexbox?

答:
Apply flexWrap to root container style.

```<code><View style={{flex: 1, flexDirection: 'row', flexWrap: 'wrap'}}>
</code>```

Body:
From the example here I'm wondering if it's possible to float items into new line when they can't fit into one?

<View style={{flex: 1, flexDirection: 'row'}}>
  <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
  <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
  <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
  <View style={{width: 50, height: 50, backgroundColor: 'red'}} />
  <View style={{width: 50, height: 50, backgroundColor: 'green'}} />
  <View style={{width: 50, height: 50, backgroundColor: 'blue'}} />
</View>

The blue coloured item should be in new line. Is it possible with flexbox?

Body:
Apply flexWrap to root container style.

<View style={{flex: 1, flexDirection: 'row', flexWrap: 'wrap'}}>


问:
Constraint Layout gives error in default template in Android Studio 2.3
I've updated Android Studio 2.3, after that I am getting default ConstrainLayout as template xml.

But in that I have RelativeLayout as Child Layout and I getting following warning.

This view is not constrained, it only has designtime positions, so it will jump to (0,0) unless you add constraints.

The layout editor allows you to place widgets anywhere on the canvas,
  and it records the current position with design time attributes (such
  as layout_editor_absoluteX.) These attributes are not applied at
  runtime, so if you push your layout on a device, the widgets may
  appear in a different location than shown in the editor. To fix this,
  make sure a widget has both horizontal and vertical constraints by
  dragging from the edge connections.

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.pratikbutani.demoapp.MainActivity"
        tools:showIn="@layout/activity_main">

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/content_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:showIn="@layout/activity_main"
            tools:layout_editor_absoluteY="8dp"
            tools:layout_editor_absoluteX="8dp">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/my_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true" />

        </RelativeLayout>

    </android.support.constraint.ConstraintLayout>
</layout>
</code>```

Getting warning on RelativeLayout, What should I do?

答: Go to Design, right-click on relative layout and select Constraint layout-->Infer Constraints

Body:
I've updated Android Studio 2.3, after that I am getting default ConstrainLayout as template xml.

But in that I have RelativeLayout as Child Layout and I getting following warning.

This view is not constrained, it only has designtime positions, so it will jump to (0,0) unless you add constraints.

The layout editor allows you to place widgets anywhere on the canvas,
  and it records the current position with design time attributes (such
  as layout_editor_absoluteX.) These attributes are not applied at
  runtime, so if you push your layout on a device, the widgets may
  appear in a different location than shown in the editor. To fix this,
  make sure a widget has both horizontal and vertical constraints by
  dragging from the edge connections.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.pratikbutani.demoapp.MainActivity"
        tools:showIn="@layout/activity_main">

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/content_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:showIn="@layout/activity_main"
            tools:layout_editor_absoluteY="8dp"
            tools:layout_editor_absoluteX="8dp">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/my_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true" />

        </RelativeLayout>

    </android.support.constraint.ConstraintLayout>
</layout>

Getting warning on RelativeLayout, What should I do?


问:
Same height column bootstrap 3 row responsive
Hi I have four divs in a bootstrap row. I want all divs in this row to have the same height and not break responsibility. I don't know how to do this without breaking responsibility.

I have tried solving this with fixed heights but in terms of responsiveness this is a bad solution.

Thanks :-)

```<code><div class="row">
    <div class="col-md-3 index_div_item">
        <a href="#">
        <div class="well" id="item1">
                <h1 class="h1_item"><span class="titre_item">Title</span></h1>
                <h2 class="h2_item_glyphicon"><span class="glyphicon glyphicon-ok-circle"></span></h2>
                <p>sidiis amicorum mariti inops cum liberis uxor alitur Reguli et dotatur ex aerario filia Scipionis, cum nobilitas florem adultae virginis diuturnum absentia pauperis erubesceret patr</p>
        </div>
        </a>
    </div>
    <div class="col-md-3 index_div_item">
        <a href="#">
            <div class="well" id="item2">
                <h1 class="h1_item"><span class="titre_item">Title</span></h1>
                <h2  class="h2_item_glyphicon"><span class="glyphicon glyphicon-stats"></span></h2>
                <p>sidiis amicorum mariti inops cum liberis uxor alitur Reguli et dotatur ex aerario filia Scipionis, cum nobilitas florem adultae virginis diuturnum absentia pauperis erubesceret patr</p>
            </div>
        </a>
    </div>
    <div class="col-md-3 index_div_item">
        <a href="#">
            <div class="well" id="item3">
                <h1 class="h1_item"><span class="titre_item">Title</span></h1>
                <h2  class="h2_item_glyphicon"><span class="glyphicon glyphicon-send"></span></h2>
                <p>sidiis amicorum mariti inops cum liberis uxor alitur Reguli et dotatur ex aerario filia Scipionis, cum nobilitas florem adultae virginis diuturnum absentia pauperis erubesceret patr</p>
            </div>
        </a>
    </div>
    <div class="col-md-3 index_div_item">
        <a href="#">
            <div class="well" id="item4">
                <h1 class="h1_item"><span class="titre_item">Title</span></h1>
                <h2  class="h2_item_glyphicon"><span class="glyphicon glyphicon-cog"></span></h2>
                <p>sidiis amicorum mariti inops cum liberis uxor alitur Reguli et dotatur ex aerario filia Scipionis, cum nobilitas florem adultae virginis diuturnum absentia pauperis erubesceret patr</p>
            </div>
        </a>
    </div>
</div>
</code>```

答:
We can achieve this by -

By using table layout mechanism

Using jquery-match-height js plugin

1. By using table layout mechanism

Demo - JS Fiddle

The mechanism is -

Wrap all columns in one div

Make that div as a Table with fixed layout

Make each column as a table cell

Use vertical-align property to control content position

We can make columns of same height and vertically aligned using following css and classes.

Base css will be-

  /* columns of same height styles */

.row-full-height {
  height: 100%;
}

.col-full-height {
  height: 100%;
  vertical-align: middle;
}

.row-same-height {
  display: table;
  width: 100%;
  /* fix overflow */
  table-layout: fixed;
}

.col-xs-height {
  display: table-cell;
  float: none !important;
}

@media (min-width: 768px) {
  .col-sm-height {
    display: table-cell;
    float: none !important;
  }
}

@media (min-width: 992px) {
  .col-md-height {
    display: table-cell;
    float: none !important;
  }
}

@media (min-width: 1200px) {
  .col-lg-height {
    display: table-cell;
    float: none !important;
  }
}

/* vertical alignment styles */

.col-top {
  vertical-align: top;
}

.col-middle {
  vertical-align: middle;
}

.col-bottom {
  vertical-align: bottom;
}
```

<p>Base html will be-</p>

<pre class="lang-html prettyprint-override"><code><div class="container">
  <h2>Demo 1</h2>
  <div class="row">
    <div class="row-same-height">
      <div class="col-xs-3 col-sm-height">1st column</div>
      <div class="col-xs-3 col-sm-height col-top">2st column</div>
      <div class="col-xs-3 col-sm-height col-middle">3st column</div>
      <div class="col-xs-3 col-sm-height col-bottom">4th column</div>
    </div>
  </div>
</div>
</code>```

2. Match Media Js

MatchHeight makes the height of all selected elements exactly equal.
It handles many edge cases that cause similar plugins to fail.

Demo link - here

Body:
Hi I have four divs in a bootstrap row. I want all divs in this row to have the same height and not break responsibility. I don't know how to do this without breaking responsibility.

I have tried solving this with fixed heights but in terms of responsiveness this is a bad solution.

Thanks :-)

Title

sidiis amicorum mariti inops cum liberis uxor alitur Reguli et dotatur ex aerario filia Scipionis, cum nobilitas florem adultae virginis diuturnum absentia pauperis erubesceret patr

Title

sidiis amicorum mariti inops cum liberis uxor alitur Reguli et dotatur ex aerario filia Scipionis, cum nobilitas florem adultae virginis diuturnum absentia pauperis erubesceret patr

Title

sidiis amicorum mariti inops cum liberis uxor alitur Reguli et dotatur ex aerario filia Scipionis, cum nobilitas florem adultae virginis diuturnum absentia pauperis erubesceret patr

Title

sidiis amicorum mariti inops cum liberis uxor alitur Reguli et dotatur ex aerario filia Scipionis, cum nobilitas florem adultae virginis diuturnum absentia pauperis erubesceret patr

Body:
We can achieve this by -

By using table layout mechanism

Using jquery-match-height js plugin

1. By using table layout mechanism

Demo - JS Fiddle

The mechanism is -

Wrap all columns in one div

Make that div as a Table with fixed layout

Make each column as a table cell

Use vertical-align property to control content position

We can make columns of same height and vertically aligned using following css and classes.

Base css will be-

  /* columns of same height styles */

.row-full-height {
  height: 100%;
}

.col-full-height {
  height: 100%;
  vertical-align: middle;
}

.row-same-height {
  display: table;
  width: 100%;
  /* fix overflow */
  table-layout: fixed;
}

.col-xs-height {
  display: table-cell;
  float: none !important;
}

@media (min-width: 768px) {
  .col-sm-height {
    display: table-cell;
    float: none !important;
  }
}

@media (min-width: 992px) {
  .col-md-height {
    display: table-cell;
    float: none !important;
  }
}

@media (min-width: 1200px) {
  .col-lg-height {
    display: table-cell;
    float: none !important;
  }
}

/* vertical alignment styles */

.col-top {
  vertical-align: top;
}

.col-middle {
  vertical-align: middle;
}

.col-bottom {
  vertical-align: bottom;
}

Base html will be-

<div class="container">
  <h2>Demo 1</h2>
  <div class="row">
    <div class="row-same-height">
      <div class="col-xs-3 col-sm-height">1st column</div>
      <div class="col-xs-3 col-sm-height col-top">2st column</div>
      <div class="col-xs-3 col-sm-height col-middle">3st column</div>
      <div class="col-xs-3 col-sm-height col-bottom">4th column</div>
    </div>
  </div>
</div>

2. Match Media Js

MatchHeight makes the height of all selected elements exactly equal.
It handles many edge cases that cause similar plugins to fail.

Demo link - here