问:
GuideLine don't work in DialogFragment
I want to creat a dialogFragment like this:

Actually I got this on my phone:

button1 is covered by button2. It looks like the guideLine does not work.
If textView is long enough, it works well. But if textView is short, the problem will happen. How can i fix the problem.

my dialog xml is :

```<code>    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="32dp">

        <TextView
            android:id="@+id/dialog_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dialog Message"
            android:textAppearance="?android:attr/textAppearanceMedium"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <android.support.constraint.Guideline
            android:id="@+id/guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />

        <Button
            android:id="@+id/dialog_button_positive"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="32dp"
            android:layout_marginRight="32dp"
            android:layout_marginTop="16dp"
            android:gravity="center"
            android:text="Positive"
            android:textAppearance="?android:textAppearanceButton"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/guideline"
            app:layout_constraintTop_toBottomOf="@id/dialog_message" />

       <Button
            android:id="@+id/dialog_button_negative"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="32dp"
            android:layout_marginRight="32dp"
            android:layout_marginTop="16dp"
            android:gravity="center"
            android:text="Negative"
            android:textAppearance="?android:textAppearanceButton"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toRightOf="@id/guideline"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/dialog_message" />

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

答:
You don't need the guideline, you can use Chains instead.
Try this

```<code><android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="32dp">

    <TextView
        android:id="@+id/dialog_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dialog Message"
        android:textAppearance="?android:attr/textAppearanceMedium"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/dialog_button_positive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:gravity="center"
        android:text="Positive"
        app:layout_constraintHorizontal_chainStyle="packed"
        android:textAppearance="?android:textAppearanceButton"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/dialog_button_negative"
        app:layout_constraintTop_toBottomOf="@id/dialog_message" />

    <Button
        android:id="@+id/dialog_button_negative"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginStart="16dp"
        android:gravity="center"
        android:text="Negative"
        android:textAppearance="?android:textAppearanceButton"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toRightOf="@id/dialog_button_positive"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/dialog_message" />

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

In case you are not familiar with chains, here is a small tutorial

Title: GuideLine don't work in DialogFragment

Body:
I want to creat a dialogFragment like this:

Actually I got this on my phone:

button1 is covered by button2. It looks like the guideLine does not work.
If textView is long enough, it works well. But if textView is short, the problem will happen. How can i fix the problem.

my dialog xml is :

    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="32dp">

        <TextView
            android:id="@+id/dialog_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Dialog Message"
            android:textAppearance="?android:attr/textAppearanceMedium"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <android.support.constraint.Guideline
            android:id="@+id/guideline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />

        <Button
            android:id="@+id/dialog_button_positive"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="32dp"
            android:layout_marginRight="32dp"
            android:layout_marginTop="16dp"
            android:gravity="center"
            android:text="Positive"
            android:textAppearance="?android:textAppearanceButton"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@id/guideline"
            app:layout_constraintTop_toBottomOf="@id/dialog_message" />

       <Button
            android:id="@+id/dialog_button_negative"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="32dp"
            android:layout_marginRight="32dp"
            android:layout_marginTop="16dp"
            android:gravity="center"
            android:text="Negative"
            android:textAppearance="?android:textAppearanceButton"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toRightOf="@id/guideline"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/dialog_message" />

    </android.support.constraint.ConstraintLayout>

Body:
You don't need the guideline, you can use Chains instead.
Try this

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="32dp">

    <TextView
        android:id="@+id/dialog_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dialog Message"
        android:textAppearance="?android:attr/textAppearanceMedium"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/dialog_button_positive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:gravity="center"
        android:text="Positive"
        app:layout_constraintHorizontal_chainStyle="packed"
        android:textAppearance="?android:textAppearanceButton"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toLeftOf="@id/dialog_button_negative"
        app:layout_constraintTop_toBottomOf="@id/dialog_message" />

    <Button
        android:id="@+id/dialog_button_negative"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginStart="16dp"
        android:gravity="center"
        android:text="Negative"
        android:textAppearance="?android:textAppearanceButton"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toRightOf="@id/dialog_button_positive"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/dialog_message" />

</android.support.constraint.ConstraintLayout>

In case you are not familiar with chains, here is a small tutorial


来源: stackexchange

问:
Change the encryption algorithm of IPsec to Null on UE
We are performing network analysis using UE ( rooted Android phone). We have no problems getting information from Pcap one of the providers who use SIP without IPsec encryption. However the response from EE (UK) uses IPsec with an encryption algorithm.
We have found in some papers, such as 'Breaking and Fixing VoLTE:
Exploiting Hidden Data Channels and Mis-implementations ' by H Kim. that it's possible to

change
  the encryption algorithm of IPsec from AES to Null by modifying
  configuration file for SIP in the UE side.

We've been looking for a SIP configuration file on a rooted Android phone without success.
Does anyone here know how to achieve this?

答:
I have found an answer so I am going to post it here to help others.

IMS settings can be accessed using adb tools as below:

```<code>adb shell
am start -n com.samsung.advp.imssettings/.ImsSettingsLauncherActivity
</code>```

Initially, I did it from the app called ShortcutMaster ( available in Google Play Store). In the app you can use Search option, enter 'imssettings' and launch one of the top results. In there, you can access IMS Profile where the encryption setting is.
When I tried modying the SQLite database saved on the device the settings were ignored by the network provider.

ContentLicense: CC BY-SA 3.0

Body:
I have found an answer so I am going to post it here to help others.

IMS settings can be accessed using adb tools as below:

adb shell
am start -n com.samsung.advp.imssettings/.ImsSettingsLauncherActivity

Initially, I did it from the app called ShortcutMaster ( available in Google Play Store). In the app you can use Search option, enter 'imssettings' and launch one of the top results. In there, you can access IMS Profile where the encryption setting is.
When I tried modying the SQLite database saved on the device the settings were ignored by the network provider.


问:
KeyValuePair type inference inside Dictionary initializer
I'm building a Dictionary with key type KeyValuePair. When using KeyValuePair.Create inside Dictionary initializer it doesn't require template types and it inferred the type correctly, the following compiles correctly without even a warning:

```<code>private static readonly IDictionary<KeyValuePair<Market, MarketData>, string> channelDict =
    new Dictionary<KeyValuePair<Market, MarketData>, string> {
        { KeyValuePair.Create(Market.USD, MarketData.Trade), "trades" },
        ...
};
</code>```

Now the code was reorganized, type Market and MarketData was moved to a separate project and namespace, and the namespace is imported by using statements at the top of the file, but now the same code won't compile, it throws this error:

```<code>error CS0305: Using the generic type 'KeyValuePair<TKey, TValue>' requires 2 type arguments
</code>```

I can be sure that using namespace imported correctly, because simple add private Market _m; didn't produce any error, what's more, the definition of the dictionary:

```<code>private static readonly IDictionary<KeyValuePair<Market, MarketData>, string> channelDict =
    new Dictionary<KeyValuePair<Market, MarketData>, string>
</code>```

did not produce error neither, it is the Create method cannot compile:

```<code>KeyValuePair.Create(Market.USD, MarketData.Trade)
</code>```

So why it cannot infer the type now when type arguments is in another namespace, while it can before?

答:
After done some digging, I just found that the problem is not about initialization of KeyValuePair, rather it's because difference of target frameworks.

Initially all the code are in the same .NET Core console app, set target framework as netcoreapp2.0, and from the docs, in .NET Core 2.0, KeyValuePair is a static class with a static method Create, which will infer the type arguments correctly.

Then when I reorganized the code, I moved this part to a class library, by default, dotnet tool will set netstandard2.0 as its target framework, however, KeyValuePair and Create is not available in netstandard2.0, as you can see from docs, it says:

This API is not supported in the currently selected framework.

That's why the code failed to compile when moved to a library project, there is only generic KeyValuePair<K, V> version in netstandard framework.

As a workaround, I verified when I set target framework in the .csproj file to netcoreapp2.0 and outputtype to library, it succeeded to compile.

OTOH, library project uses netstandard by default because it makes sure the library is usable among different platform targets, so the better fix would be do not use static KeyValuePair.Create in library code, and use generic version instead: new KeyValuePair<K, V>(k, v).

Body:
I'm building a Dictionary with key type KeyValuePair. When using KeyValuePair.Create inside Dictionary initializer it doesn't require template types and it inferred the type correctly, the following compiles correctly without even a warning:

private static readonly IDictionary<KeyValuePair<Market, MarketData>, string> channelDict =
    new Dictionary<KeyValuePair<Market, MarketData>, string> {
        { KeyValuePair.Create(Market.USD, MarketData.Trade), "trades" },
        ...
};

Now the code was reorganized, type Market and MarketData was moved to a separate project and namespace, and the namespace is imported by using statements at the top of the file, but now the same code won't compile, it throws this error:

error CS0305: Using the generic type 'KeyValuePair<TKey, TValue>' requires 2 type arguments

I can be sure that using namespace imported correctly, because simple add private Market _m; didn't produce any error, what's more, the definition of the dictionary:

private static readonly IDictionary<KeyValuePair<Market, MarketData>, string> channelDict =
    new Dictionary<KeyValuePair<Market, MarketData>, string>

did not produce error neither, it is the Create method cannot compile:

KeyValuePair.Create(Market.USD, MarketData.Trade)

So why it cannot infer the type now when type arguments is in another namespace, while it can before?


问:
Progress bar goes straight to 100% on first upload only, following uploads show as expected
Problem:
When I start up any Browser, it opens up with its default web page, I open a session to my
Test File Upload with Progress bar Web Application in that Tab, or that same Web App. in a new Tab. When I
start the first file upload, it shows the Progress bar to go straight to 100% even though the file is still
uploading. If I then do the file upload again, it works as expected, the progress bar shows the file being
loaded, eg 20%, 43%, 80%, 98% then Done.
I am using the example that is published at:-
https://www.sitepoint.com/tracking-upload-progress-with-php-and-javascript/

I have modified it slightly in an effort to find out what is going on.

This problem occurs on my Web Site which is on the Internet and on my Local Server.
Both systems are LINUX, using Apache2. The Web Site on the Internet is using PHP 5.6.30.  My local server
is using PHP 7.1.5.

This same problem can be reproduced when using a Cellphone running Safari, Chrome, or FireFox.
So this looks like a Server based issue or some coding issue I have either at the Client
or Server end.

I use this type of code to upload Video files and my work around is to assume that the file
will not be fully uploaded until at least after the first progress percent loaded calculation. If I
get the '100' reply on the first pass I assume that the progress bar reading is wrong and suggest
the the file upload should be tried again. The second upload always works. In my case the maximum
size allowed for the video file 28MB.

Can anybody assist with this problem?

Below is a copy of my two PHP Web Pages.

```<code>File: progress.php
<?php
session_start();
$key = ini_get("session.upload_progress.prefix") . "form_60";
if (!empty($_SESSION[$key]))
  {
    $current = $_SESSION[$key]["bytes_processed"];
    $total = $_SESSION[$key]["content_length"];
    echo $current < $total ? ceil($current / $total * 100) : 100;
  } else
  {
      echo "100";
     }
?>

File: upload2.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["userfile"])) {
    // move_uploaded_file()
   $folder = "tmp/";
    //upload the file
    move_uploaded_file($_FILES["userfile"["tmp_name"], "$folder" . $_FILES["userfile"]["name"]);
   }
 ?>
 <html>
 <head>
 <title>File Upload Progress Bar</title>
 <style>
   #bar_blank {
   border: solid 1px #000;
   height: 20px;
   width: 300px;
  }
   #bar_color {
   background-color: #006666;
   height: 20px;
   width: 0px;
  }
   #bar_blank, #hidden_iframe {
   display: none;
  }
</style>
</head>
<body>
<div id="bar_blank">
<div id="bar_color"></div>
</div>
<div id="Message"></div>
<form action="" method="POST"
 id="form_60" enctype="multipart/form-data" target="hidden_iframe">
 <input type="hidden" value="form_60"
 name="<?php echo ini_get("session.upload_progress.name"); ?>">
 <input type="file" name="userfile"><br>
 <input type="submit" value="Start Upload">
</form>
<iframe id="hidden_iframe" name="hidden_iframe" src="about:blank"></iframe>
<!script type="text/javascript" src="upload2.js"></script>
<script type="text/javascript">
var FirstTime = 'Y';
function toggleBarVisibility() {
 var e = document.getElementById("bar_blank");
 e.style.display = (e.style.display == "block") ? "none" : "block";
}

function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
    http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
    http = new XMLHttpRequest();
}
return http;
}

function sendRequest() {
 var http = createRequestObject();
 http.open("GET", "progress.php", false);  //  was GET
 http.onreadystatechange = function () { handleResponse(http); };
 http.send(null);
}

function handleResponse(http) {
 var response;
 if (http.readyState == 4) {
    response = http.responseText;
    document.getElementById("bar_color").style.width = response + "%";
    document.getElementById("Message").innerHTML = response + "%";

 alert(response);
    if (response < 100) {
        FirstTime = 'N'
        setTimeout("sendRequest()", 1000);
    }
    else {
        alert(response);
        toggleBarVisibility();
        if (FirstTime == 'N')
           {
              document.getElementById("Message").innerHTML = "Done.";
           }
        if (FirstTime == 'Y')
           {
               document.getElementById("Message").innerHTML = "Error.";
               alert('System error, please try again.')
           }
    }
}
}

function startUpload() {
 toggleBarVisibility();
 setTimeout("sendRequest()", 1000);
}

(function () {
   document.getElementById("form_60").onsubmit = startUpload;
})();
</script>
</body>
</html>
</code>```

I have now found a workaround, which is listed below. It involves doing a Dummy request from a startup page in my application. In my case I use the Login Web Page to put the Dummy code.

```<code><script type="text/javascript">
function createRequestObject() {
    var http;
    if (navigator.appName == "Microsoft Internet Explorer") {
        http = new ActiveXObject("Microsoft.XMLHTTP");
         }
    else {
        http = new XMLHttpRequest();
         }
    return http;
}
function sendRequest() {
    var http = createRequestObject();
    http.open("GET", "progress.php", false);  //  was GET
    http.onreadystatechange = function () { handleResponse(http); };
    http.send(null);
}
function handleResponse(http)
  {
    var response;
    if (http.readyState == 4)
      {
         response = http.responseText;
        if (response < 100)
          {
             setTimeout("sendRequest()", 1000);
          }
      }
}
function startUpload() {
  setTimeout("sendRequest()", 1000);
}
window.onload = function() {
   startUpload();
}
</script>
</code>```

Now that I have learnt a bit more about Session Variables it seems that to follow the rules I should have put:-

session_start();

at the start of the upload2.php web page, as this is where the variable information is coming from in the first instance. This then works fine.

答:
It looks as though the session is not reading in the if statement at the beginning. You just echo out 100% if the Session doesn't exist. If you ammend this part:

Progress.php

```<code><?php
session_start();
$key = ini_get("session.upload_progress.prefix") . "form_60";
if (!empty($_SESSION[$key]))
  {
    $current = $_SESSION[$key]["bytes_processed"];
    $total = $_SESSION[$key]["content_length"];
    echo $current < $total ? ceil($current / $total * 100) : 100;
  } else {
     $_SESSION[$key]["bytes_processed"] = 0;
  }
?>
</code>```

It shouldn't jump straight to 100% because the Session will be active at this point rather than after the first upload. Not tested but worth a try, I'll stick this code on my test server when I get a chance to do a proper test if you don't beat me to it!

Body:
Problem:
When I start up any Browser, it opens up with its default web page, I open a session to my
Test File Upload with Progress bar Web Application in that Tab, or that same Web App. in a new Tab. When I
start the first file upload, it shows the Progress bar to go straight to 100% even though the file is still
uploading. If I then do the file upload again, it works as expected, the progress bar shows the file being
loaded, eg 20%, 43%, 80%, 98% then Done.
I am using the example that is published at:-
https://www.sitepoint.com/tracking-upload-progress-with-php-and-javascript/

I have modified it slightly in an effort to find out what is going on.

This problem occurs on my Web Site which is on the Internet and on my Local Server.
Both systems are LINUX, using Apache2. The Web Site on the Internet is using PHP 5.6.30.  My local server
is using PHP 7.1.5.

This same problem can be reproduced when using a Cellphone running Safari, Chrome, or FireFox.
So this looks like a Server based issue or some coding issue I have either at the Client
or Server end.

I use this type of code to upload Video files and my work around is to assume that the file
will not be fully uploaded until at least after the first progress percent loaded calculation. If I
get the '100' reply on the first pass I assume that the progress bar reading is wrong and suggest
the the file upload should be tried again. The second upload always works. In my case the maximum
size allowed for the video file 28MB.

Can anybody assist with this problem?

Below is a copy of my two PHP Web Pages.

File: progress.php
<?php
session_start();
$key = ini_get("session.upload_progress.prefix") . "form_60";
if (!empty($_SESSION[$key]))
  {
    $current = $_SESSION[$key]["bytes_processed"];
    $total = $_SESSION[$key]["content_length"];
    echo $current < $total ? ceil($current / $total * 100) : 100;
  } else
  {
      echo "100";
     }
?>

File: upload2.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["userfile"])) {
    // move_uploaded_file()
   $folder = "tmp/";
    //upload the file
    move_uploaded_file($_FILES["userfile"["tmp_name"], "$folder" . $_FILES["userfile"]["name"]);
   }
 ?>

 <title>File Upload Progress Bar</title>

<form action="" method="POST"
 id="form_60" enctype="multipart/form-data" target="hidden_iframe">
 <input type="hidden" value="form_60"
 name="<?php echo ini_get("session.upload_progress.name"); ?>">
 <input type="file" name="userfile">

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

<!script type="text/javascript" src="upload2.js"></script>

I have now found a workaround, which is listed below. It involves doing a Dummy request from a startup page in my application. In my case I use the Login Web Page to put the Dummy code.

Now that I have learnt a bit more about Session Variables it seems that to follow the rules I should have put:-

session_start();

at the start of the upload2.php web page, as this is where the variable information is coming from in the first instance. This then works fine.

Body:
It looks as though the session is not reading in the if statement at the beginning. You just echo out 100% if the Session doesn't exist. If you ammend this part:

Progress.php

<?php
session_start();
$key = ini_get("session.upload_progress.prefix") . "form_60";
if (!empty($_SESSION[$key]))
  {
    $current = $_SESSION[$key]["bytes_processed"];
    $total = $_SESSION[$key]["content_length"];
    echo $current < $total ? ceil($current / $total * 100) : 100;
  } else {
     $_SESSION[$key]["bytes_processed"] = 0;
  }
?>

It shouldn't jump straight to 100% because the Session will be active at this point rather than after the first upload. Not tested but worth a try, I'll stick this code on my test server when I get a chance to do a proper test if you don't beat me to it!


问:
hide e-mail on mailto: (conversion from javascript to c#/ASP.NET MVC)
I'm trying to make the email that appears on the mailto: on a, for example:
     mail-me
I've got a code in javascript doing this in a little different way:

function validacaoEmail(field) {
  user = field.value.substring(0, field.value.indexOf("@"));
  domain = field.value.substring(field.value.indexOf("@")+ 1, field.value.length);
  if ((user.length >=1) && (domain.length >=3) && (user.search("@")==-1) && (domain.search("@")==-1) && (user.search(" ")==-1) && (domain.search(" ")==-1) && (domain.search(".")!=-1) && (domain.indexOf(".") >=1)&& (domain.lastIndexOf(".") < domain.length - 1)) {
   domainend = "@"+domain;
   toonclick = 'this.href="'+'mailto:'+user+domainend+'"';

   document.getElementById("msgemail").innerHTML="" +user+ "null" +domainend+ "";
  }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="f1">
<h3>Formulário de Inscrição:</h3>
<table>
<tr>
<td>
<b>Don't click enter, click outside of the box after insert the e-mail</b>
E-mail:
<input type="text" name="email" onblur="validacaoEmail(f1.email)"  maxlength="60" size='65'>
</td>
<td>
<div id="msgemail"></div>
</td>
</tr>
</table>
</form></code>```

答:
include a new reference to System.ComponentModel.DataAnnotations
you have the choice of a regex or something like this : http://dataannotationsextensions.org/

Create Model server side:

```<code>public class MyFormViewModel{
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress] or [RegularExpression(*expression here*)]

Public String Email {Get;Set;}
}
</code>```

Create controller action:

```<code>[Post]
public ActionResult Submit(MyFormViewModel viewModel){
if (ModelState.IsValid)
        {
//Do what ever
            return View("Completed");
        }
        else
        {
//error do something
             return View();
        }
}
</code>```

If your using razor you can validate client side as well using your models and messages on them using :

```<code>@Html.ValidationMessageFor(model => model.Email)
</code>```

and in your model:

```<code>[Required(ErrorMessage = "Email is required")]
</code>```

hope that helps not sure

Body:
I'm trying to make the email that appears on the mailto: on a, for example:
     mail-me
I've got a code in javascript doing this in a little different way:

function validacaoEmail(field) {
  user = field.value.substring(0, field.value.indexOf("@"));
  domain = field.value.substring(field.value.indexOf("@")+ 1, field.value.length);
  if ((user.length >=1) && (domain.length >=3) && (user.search("@")==-1) && (domain.search("@")==-1) && (user.search(" ")==-1) && (domain.search(" ")==-1) && (domain.search(".")!=-1) && (domain.indexOf(".") >=1)&& (domain.lastIndexOf(".") < domain.length - 1)) {
   domainend = "@"+domain;
   toonclick = 'this.href="'+'mailto:'+user+domainend+'"';

   document.getElementById("msgemail").innerHTML="" +user+ "null" +domainend+ "";
  }
 }

<form name="f1">

Formulário de Inscrição:

Don't click enter, click outside of the box after insert the e-mail
E-mail:
<input type="text" name="email" onblur="validacaoEmail(f1.email)"  maxlength="60" size='65'>

</form>

Body:
include a new reference to System.ComponentModel.DataAnnotations
you have the choice of a regex or something like this : http://dataannotationsextensions.org/

Create Model server side:

public class MyFormViewModel{
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress] or [RegularExpression(*expression here*)]

Public String Email {Get;Set;}
}

Create controller action:

[Post]
public ActionResult Submit(MyFormViewModel viewModel){
if (ModelState.IsValid)
        {
//Do what ever
            return View("Completed");
        }
        else
        {
//error do something
             return View();
        }
}

If your using razor you can validate client side as well using your models and messages on them using :

@Html.ValidationMessageFor(model => model.Email)

and in your model:

[Required(ErrorMessage = "Email is required")]

hope that helps not sure


问:
In CodedUI tests with multiple iterations, UITestActionLog.html file is generated only for the last iteration
On executing tests for CodedUI in Visual Studio, why is the uiTestActionlog.html file generated only for the last iteration?  Can this be due to the overriding of the previously generated reports?

答:
This is happening because every time a new iteration runs the previous UITestActionLog file gets overwritten. Resulting in preserving only the final copy.

The path where this file is - inside your project under folder TestReuslts

Path for your understanding in my case -
D:\Project**TestResults**\krakhil\In\0eee82c0-3cb9-42fd-96fe-7314ae4b5fd5\KRAKHIL-LT\UITestAction.html

So, what i did is - I added a line of code in my CleanUp (as my every iteration goes through this method at the end. You can use according to your need)

```<code>string FileSourcePath = (TestContext.TestResultsDirectory + "\\UITestActionLog.html").Replace(@"\\", @"\");
            File.Copy(FileSourcePath, FileSourcePath.Replace("UITestActionLog.html", "UITestActionLog" + ReportFileNo++ + ".html"));
</code>```

Here at the end i will get all the UITestActionLog*.html where * will be the iteration no - i used a static variable for this. If you want u can write a line to delete the UITestActionLog.html - as u will already have a copy of it with iteration no.

```<code>File.Delete(FileSourcePath); // use this at the end of all iterations only
</code>```

Body:
This is happening because every time a new iteration runs the previous UITestActionLog file gets overwritten. Resulting in preserving only the final copy.

The path where this file is - inside your project under folder TestReuslts

Path for your understanding in my case -
D:\Project**TestResults**\krakhil\In\0eee82c0-3cb9-42fd-96fe-7314ae4b5fd5\KRAKHIL-LT\UITestAction.html

So, what i did is - I added a line of code in my CleanUp (as my every iteration goes through this method at the end. You can use according to your need)

string FileSourcePath = (TestContext.TestResultsDirectory + "\\UITestActionLog.html").Replace(@"\\", @"\");
            File.Copy(FileSourcePath, FileSourcePath.Replace("UITestActionLog.html", "UITestActionLog" + ReportFileNo++ + ".html"));

Here at the end i will get all the UITestActionLog*.html where * will be the iteration no - i used a static variable for this. If you want u can write a line to delete the UITestActionLog.html - as u will already have a copy of it with iteration no.

File.Delete(FileSourcePath); // use this at the end of all iterations only


问:
How to bind checkBox to a boolean property?
I started using vaadin framework recently.

I have a Form which contains some textFields and a checkbox, my problem is all fields are binding with their properties expect checkbox ??.

This is the form :

```<code>public class ContactForm extends FormLayout {

private Button save = new Button("Save", this::save);
private Button delete = new Button("Delete", this::delete);
private Button cancel = new Button("Cancel", this::cancel);
private TextField firstName = new TextField("First name");
private TextField lastName = new TextField("Last name");
private TextField phone = new TextField("Phone");
private TextField email = new TextField("Email");
private DateField birthDate = new DateField("Birth date");
private CheckBox bookMarks = new CheckBox("BookMarks");

private Contact contact;

// Easily bind forms to beans and manage validation and buffering
private BeanFieldGroup<Contact> formFieldBindings;

public ContactForm() {
    configureComponents();
    buildLayout();
}

private void configureComponents() {...}

private void buildLayout() {...}

void edit(Contact contact) {

    this.contact = contact;
    if (contact != null) {
        // Bind the properties of the contact POJO to fields in this form
        formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this);

        delete.setVisible(contact.getId() != null);
    }

    setVisible(contact != null);
}

@Override
public AddressbookUI getUI() {
    return (AddressbookUI) super.getUI();
}}
</code>```

This is My class Contact :

```<code>public class Contact implements Serializable, Cloneable {

private Long id;

private String firstName = "";
private String lastName = "";
private String phone = "";
private String email = "";
private Date birthDate;
private Boolean bookMarks;

// getters and setters
...
}
</code>```

What am i doing wrong? Should I bind the checkbox field manually ?

答:
I think you need to use the formFieldBindings BeanFieldGroup you've created. So change this line

```<code> formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this);
</code>```

to

```<code> formFieldBindings = new BeanFieldGroup<Contact>(Contact.class);
 formFieldBindings.setItemDataSource(contact);
 formFieldBindings.buildAndBindMemberFields(this);
</code>```

Body:
I started using vaadin framework recently.

I have a Form which contains some textFields and a checkbox, my problem is all fields are binding with their properties expect checkbox ??.

This is the form :

public class ContactForm extends FormLayout {

private Button save = new Button("Save", this::save);
private Button delete = new Button("Delete", this::delete);
private Button cancel = new Button("Cancel", this::cancel);
private TextField firstName = new TextField("First name");
private TextField lastName = new TextField("Last name");
private TextField phone = new TextField("Phone");
private TextField email = new TextField("Email");
private DateField birthDate = new DateField("Birth date");
private CheckBox bookMarks = new CheckBox("BookMarks");

private Contact contact;

// Easily bind forms to beans and manage validation and buffering
private BeanFieldGroup<Contact> formFieldBindings;

public ContactForm() {
    configureComponents();
    buildLayout();
}

private void configureComponents() {...}

private void buildLayout() {...}

void edit(Contact contact) {

    this.contact = contact;
    if (contact != null) {
        // Bind the properties of the contact POJO to fields in this form
        formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this);

        delete.setVisible(contact.getId() != null);
    }

    setVisible(contact != null);
}

@Override
public AddressbookUI getUI() {
    return (AddressbookUI) super.getUI();
}}

This is My class Contact :

public class Contact implements Serializable, Cloneable {

private Long id;

private String firstName = "";
private String lastName = "";
private String phone = "";
private String email = "";
private Date birthDate;
private Boolean bookMarks;

// getters and setters
...
}

What am i doing wrong? Should I bind the checkbox field manually ?

Body:
I think you need to use the formFieldBindings BeanFieldGroup you've created. So change this line

 formFieldBindings = BeanFieldGroup.bindFieldsBuffered(contact, this);

to

 formFieldBindings = new BeanFieldGroup<Contact>(Contact.class);
 formFieldBindings.setItemDataSource(contact);
 formFieldBindings.buildAndBindMemberFields(this);


问:
Saving a View as a Photo in iPhone App
Is there an easy way to programmatically save a view to the Photos library in an iPhone app?</p>

答:
I added these methods to my view's controller class.  They save the photo and then pop up an alert box to tell the user whether it succeeded.</p>

```<code>- (void)savePhotoOfView:(UIView *)view
{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view drawRect:view.bounds];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImageWriteToSavedPhotosAlbum(image,
                                   self,
                                   @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:),
                                   NULL);
}

- (void)   savedPhotoImage:(UIImage *)image
  didFinishSavingWithError:(NSError *)error
               contextInfo:(void *)contextInfo
{
    NSString *message = @"This image has been saved to your Photos album";
    if (error) {
        message = [error localizedDescription];
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}
</code>```

OwnerDisplayName: Kristopher Johnson

Title: Saving a View as a Photo in iPhone App

Body:
I added these methods to my view's controller class.  They save the photo and then pop up an alert box to tell the user whether it succeeded.

- (void)savePhotoOfView:(UIView *)view
{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view drawRect:view.bounds];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImageWriteToSavedPhotosAlbum(image,
                                   self,
                                   @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:),
                                   NULL);
}

- (void)   savedPhotoImage:(UIImage *)image
  didFinishSavingWithError:(NSError *)error
               contextInfo:(void *)contextInfo
{
    NSString *message = @"This image has been saved to your Photos album";
    if (error) {
        message = [error localizedDescription];
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}

LastEditorDisplayName: Kristopher Johnson


问:
Qt, POP3 and SSL?
If Gmail is using SSL does this mean that I have to implement the algorithms for encrypting and decrypting all the traffic by myself in order to download the mail?

If so, is there a fast workaround for doing this ?

I should mention that I'm making a POP3 client from scratch in Qt Creator and I want to implement all the communication by myself.

答:
You don't need to implement encryption algorithms by yourself.
Qt includes SSL support under QSsl namespace, which was introduced in Qt 4.3.
You should consider looking under QSsl namespace for required classes and enumerations.</p>

ContentLicense: CC BY-SA 2.5

Title: Qt, POP3 and SSL?


问:
Bitmap scaling while keeping centered
I'm developing an image viewer on embedded system(stm32f4) with multi-touch support. To put into perspective image viewer should have similar functionality like something you find on your smartphone.
I have completed the image scaling and pinch/zoom gesture recognition part. But it only scales from the source image origin coordinates. So if my origin(x,y[0, 0]) is top left then it will scale following that point. And if I want to look something up in bottom right corner I have to use pinch gesture and the move to location I want which is undesirable.Here's how it looks
http://i.imgur.com/IWR4wls.gifv
. It should follow center of 2 fingers.

How can I achieve scaling while following center of 2 fingers? My attempts to do it resulted in working but jumpy, shaky version basically unusable.

My scaling works by having source image always opened(in ram) taking source image [x,y] coordinates and rect i want to zoom [w,h] scaling that rect to display [w,h] and displaying it. Moving(pan gesture) is done by moving zoomRect [x,y] coordinates in source image. That means every time I move finger I have to move zoomedRect (increase [x,y]) scale that zoomedRect and display it. So fully scaled image is not being stored because of limited ram.

```<code>Source image width,height[640, 480]:
+-------------------------------+
|   zoomedRect                  |
|   +--------------+            |
|   |              |            |
|   |              |            |
|   |              |            |
|   |              |            |
|   |              |            |
|   +--------------+            |
|                               |
|                               |
|                               |
+-------------------------------+

I take zoomedRect i.e. x,y[50, 50] width,height[160, 120]
and scale it to display size w,h[640x480]
Display:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
+-------------------------------+
</code>```

Here's what I have/can calculate:

Center of 2 fingers.

Translate center of 2 fingers to source image(even when zoomed in).

Scale in fraction(1.32, 1.45...) and (source image width|height)/(zoomedRect width|height).

Edit:

I have tried to calculate center point when 2 fingers touched and then use that center for future calculations and that's the reason why all the jumping and shaking happen. But maybe there is an error on my side so I'll add some relevant code.
As I mentioned earlier I change zoomRect width, height to scale image

```<code>newWidth = tempWidth / scale;
newHeight = tempHeight / scale;
</code>```

So after zooming I need to also move near center and I do that by calculating how much scale changed
(lastWidth - newWidth)

```<code>newSourceX = newSourceX + ((int16_t)lastWidth - newWidth);
newSourceY = newSourceY + ((int16_t)lastHeight - newHeight);
</code>```

Now we need to stop at calculated center between the 2 fingers and not get out of bounds [0, 0]:

```<code>#define LIMIT(value, min, max) (value < min ? min : (value > max ? max : value))
newSourceX = LIMIT(newSourceX + ((int16_t)lastWidth - newWidth), 0, centerSourceX);
newSourceY = LIMIT(newSourceY + ((int16_t)lastHeight - newHeight), 0, centerSourceY);
</code>```

So far so good but it is not properly centered

```<code>Calculate center between two fingers on Display and translate to Source.
Because it's fully zoomed out(Source and Display are identical)
centers are also in identical positions.
Display/Source:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                centerPos      |
|                     *         |
|                               |
|                               |
+-------------------------------+

So if we zoom in zoomRect will be newWidth / 2 and newHeight / 2 further than needed.

Source:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                centerPos      |
|                     *---------+
|                     | zoomRect|
|                     |         |
+---------------------+---------+

To account for this I modify code as follows:
newSourceX = LIMIT(newSourceX + ((int16_t)lastWidth - newWidth), 0, centerSourceX - newWidth / 2);
newSourceY = LIMIT(newSourceY + ((int16_t)lastHeight - newHeight), 0, centerSourceY - newHeight / 2);

Success!!! Or not?

Source:
+-------------------------------+
|                               |
|                               |
|                               |
|             zoomRect          |
|                +---------+    |
|                |centerPos|    |
|                |     *   |    |
|                +---------+    |
|                               |
+-------------------------------+

When zooming from 1:1 it works perfectly but when I want to zoom again when
I'm zoomed in a little bit the "jump" happens because:
newSourceX + ((int16_t)lastWidth - newWidth) > centerSourceX - newWidth / 2
</code>```

Result: http://i.imgur.com/x1t6X2q.gifv

答: Perhaps lock the centre point of image from the 1st point you can calculate the centre of the two fingers, and then scale from this point.  Rather than recompute the centre point each time.  Take it as the zoom point and then movement of fingers from this point are the zoom factor, should stop the shaking effect you mentioned</p>

Title: Bitmap scaling while keeping centered

Body:
I'm developing an image viewer on embedded system(stm32f4) with multi-touch support. To put into perspective image viewer should have similar functionality like something you find on your smartphone.
I have completed the image scaling and pinch/zoom gesture recognition part. But it only scales from the source image origin coordinates. So if my origin(x,y[0, 0]) is top left then it will scale following that point. And if I want to look something up in bottom right corner I have to use pinch gesture and the move to location I want which is undesirable.Here's how it looks
http://i.imgur.com/IWR4wls.gifv
. It should follow center of 2 fingers.

How can I achieve scaling while following center of 2 fingers? My attempts to do it resulted in working but jumpy, shaky version basically unusable.

My scaling works by having source image always opened(in ram) taking source image [x,y] coordinates and rect i want to zoom [w,h] scaling that rect to display [w,h] and displaying it. Moving(pan gesture) is done by moving zoomRect [x,y] coordinates in source image. That means every time I move finger I have to move zoomedRect (increase [x,y]) scale that zoomedRect and display it. So fully scaled image is not being stored because of limited ram.

Source image width,height[640, 480]:
+-------------------------------+
|   zoomedRect                  |
|   +--------------+            |
|   |              |            |
|   |              |            |
|   |              |            |
|   |              |            |
|   |              |            |
|   +--------------+            |
|                               |
|                               |
|                               |
+-------------------------------+

I take zoomedRect i.e. x,y[50, 50] width,height[160, 120]
and scale it to display size w,h[640x480]
Display:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
|                               |
+-------------------------------+

Here's what I have/can calculate:

Center of 2 fingers.

Translate center of 2 fingers to source image(even when zoomed in).

Scale in fraction(1.32, 1.45...) and (source image width|height)/(zoomedRect width|height).

Edit:

I have tried to calculate center point when 2 fingers touched and then use that center for future calculations and that's the reason why all the jumping and shaking happen. But maybe there is an error on my side so I'll add some relevant code.
As I mentioned earlier I change zoomRect width, height to scale image

newWidth = tempWidth / scale;
newHeight = tempHeight / scale;

So after zooming I need to also move near center and I do that by calculating how much scale changed
(lastWidth - newWidth)

newSourceX = newSourceX + ((int16_t)lastWidth - newWidth);
newSourceY = newSourceY + ((int16_t)lastHeight - newHeight);

Now we need to stop at calculated center between the 2 fingers and not get out of bounds [0, 0]:

#define LIMIT(value, min, max) (value < min ? min : (value > max ? max : value))
newSourceX = LIMIT(newSourceX + ((int16_t)lastWidth - newWidth), 0, centerSourceX);
newSourceY = LIMIT(newSourceY + ((int16_t)lastHeight - newHeight), 0, centerSourceY);

So far so good but it is not properly centered

Calculate center between two fingers on Display and translate to Source.
Because it's fully zoomed out(Source and Display are identical)
centers are also in identical positions.
Display/Source:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                centerPos      |
|                     *         |
|                               |
|                               |
+-------------------------------+

So if we zoom in zoomRect will be newWidth / 2 and newHeight / 2 further than needed.

Source:
+-------------------------------+
|                               |
|                               |
|                               |
|                               |
|                               |
|                centerPos      |
|                     *---------+
|                     | zoomRect|
|                     |         |
+---------------------+---------+

To account for this I modify code as follows:
newSourceX = LIMIT(newSourceX + ((int16_t)lastWidth - newWidth), 0, centerSourceX - newWidth / 2);
newSourceY = LIMIT(newSourceY + ((int16_t)lastHeight - newHeight), 0, centerSourceY - newHeight / 2);

Success!!! Or not?

Source:
+-------------------------------+
|                               |
|                               |
|                               |
|             zoomRect          |
|                +---------+    |
|                |centerPos|    |
|                |     *   |    |
|                +---------+    |
|                               |
+-------------------------------+

When zooming from 1:1 it works perfectly but when I want to zoom again when
I'm zoomed in a little bit the "jump" happens because:
newSourceX + ((int16_t)lastWidth - newWidth) > centerSourceX - newWidth / 2

Result: http://i.imgur.com/x1t6X2q.gifv


问:
NullpointerException while invoking SendKeys through Selenium using PageFactory with Page Object
I have three classes. One for getting all elements from the Webpage, one for performing actions with those elements and one for the test scripts. I get a null pointer exception when I call a function from the test script. I figured out this is because I use @FindBy annotation, but I don't know how to fix this.

Elements Class:

```<code>public class LoginPageElements {

    @FindBy(id="loginId")
    private static WebElement userNameTextBox;

    @FindBy(id="password")
    private static WebElement userPasswordTextBox;

    @FindBy(id="QTP_LoginButton")
    private static WebElement loginButton;

    public static WebElement getUserNameTextBox(WebDriver driver){
        WebElement a=driver.findElement(By.id("loginId"));
        return a;
    }

    public static WebElement getUserPasswordTextBox(){
        return userPasswordTextBox;
    }

    public static WebElement getLoginButton(){
        return loginButton;
    }
}
</code>```

Actions Class:

```<code>public class LoginPageActions {

        public static void login(WebDriver driver,String username,String password){
            WebElement a=LoginPageElements.getUserNameTextBox(driver);
            a.sendKeys(username);
            LoginPageElements.getUserPasswordTextBox().sendKeys(password);
            LoginPageElements.getLoginButton().click();
        }

    }
</code>```

Test script:

```<code>public class Sample {
     public static String driverPath = "D:/Selenium/Chrome Driver latest/chromedriver.exe";
     public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", driverPath);

    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    options.addArguments("start-maximized");
    options.addArguments("--js-flags=--expose-gc");
    options.addArguments("--enable-precise-memory-info");
    options.addArguments("--disable-popup-blocking");
    options.addArguments("--disable-default-apps");
    options.addArguments("--enable-automation");
    options.addArguments("test-type=browser");
    options.addArguments("disable-infobars");
    options.addArguments("--disable-extensions");
    options.setExperimentalOption("useAutomationExtension", false);

    driver = new ChromeDriver(options);

    driver.get("http://10.235.80.106:8080");

    LoginPageActions.login(driver,"acb", "adasd");
}
</code>```

There is no exception when I pass the WebDriver object from the test script to the element class. The problem occurs when I use the elements initialized with FindBy annotations because of no WebDriver instantiation. How do I fix this? Thanks

答:
You need to declare the WebDriver instance and add the constructor in LoginPageElements & LoginPageActions class as:

LoginPageElements class:

```<code>WebDriver driver;

//constructor
public LoginPageElements(WebDriver loginDriver)
{
    this.driver=loginDriver;
}
</code>```

LoginPageActions class:

```<code>WebDriver driver;

//constructor
public LoginPageActions(WebDriver loginDriver)
{
    this.driver=loginDriver;
}
</code>```

Let me know if this Answers your Question.

ContentLicense: CC BY-SA 4.0

Body:
I have three classes. One for getting all elements from the Webpage, one for performing actions with those elements and one for the test scripts. I get a null pointer exception when I call a function from the test script. I figured out this is because I use @FindBy annotation, but I don't know how to fix this.

Elements Class:

public class LoginPageElements {

    @FindBy(id="loginId")
    private static WebElement userNameTextBox;

    @FindBy(id="password")
    private static WebElement userPasswordTextBox;

    @FindBy(id="QTP_LoginButton")
    private static WebElement loginButton;

    public static WebElement getUserNameTextBox(WebDriver driver){
        WebElement a=driver.findElement(By.id("loginId"));
        return a;
    }

    public static WebElement getUserPasswordTextBox(){
        return userPasswordTextBox;
    }

    public static WebElement getLoginButton(){
        return loginButton;
    }
}

Actions Class:

public class LoginPageActions {

        public static void login(WebDriver driver,String username,String password){
            WebElement a=LoginPageElements.getUserNameTextBox(driver);
            a.sendKeys(username);
            LoginPageElements.getUserPasswordTextBox().sendKeys(password);
            LoginPageElements.getLoginButton().click();
        }

    }

Test script:

public class Sample {
     public static String driverPath = "D:/Selenium/Chrome Driver latest/chromedriver.exe";
     public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", driverPath);

    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    options.addArguments("start-maximized");
    options.addArguments("--js-flags=--expose-gc");
    options.addArguments("--enable-precise-memory-info");
    options.addArguments("--disable-popup-blocking");
    options.addArguments("--disable-default-apps");
    options.addArguments("--enable-automation");
    options.addArguments("test-type=browser");
    options.addArguments("disable-infobars");
    options.addArguments("--disable-extensions");
    options.setExperimentalOption("useAutomationExtension", false);

    driver = new ChromeDriver(options);

    driver.get("http://10.235.80.106:8080");

    LoginPageActions.login(driver,"acb", "adasd");
}

There is no exception when I pass the WebDriver object from the test script to the element class. The problem occurs when I use the elements initialized with FindBy annotations because of no WebDriver instantiation. How do I fix this? Thanks

Body:
You need to declare the WebDriver instance and add the constructor in LoginPageElements & LoginPageActions class as:

LoginPageElements class:

WebDriver driver;

//constructor
public LoginPageElements(WebDriver loginDriver)
{
    this.driver=loginDriver;
}

LoginPageActions class:

WebDriver driver;

//constructor
public LoginPageActions(WebDriver loginDriver)
{
    this.driver=loginDriver;
}

Let me know if this Answers your Question.


问:
How to use a conditional operation for overgive a property to a vue component or user the default
I'm trying to use a conditional operation to figure out whether I have to pass a property to a vue-component or even use the default value for the component's property.

Something like that:

```<code><my-example-component
:example-property="myValue ? {test: 1, example: 'test'} : *use default*">
</my-example-component>
</code>```

You see my trouble^^

I know that this does not work in this way, but some of you may have a solution to fix my problem.

Have a nice day,

Markus ;-)

答:
I fixed the problem by myself.

```<code><my-example-component
:example-property="myValue ? {test: 1, example: 'test'} : NULL">
</my-example-component>
</code>```

I just commit NULL if !myVlue and the child component uses the default value for its property.

Kind Regards,

Markus ;-)

Body:
I'm trying to use a conditional operation to figure out whether I have to pass a property to a vue-component or even use the default value for the component's property.

Something like that:

<my-example-component
:example-property="myValue ? {test: 1, example: 'test'} : *use default*">
</my-example-component>

You see my trouble^^

I know that this does not work in this way, but some of you may have a solution to fix my problem.

Have a nice day,

Markus ;-)

Body:
I fixed the problem by myself.

<my-example-component
:example-property="myValue ? {test: 1, example: 'test'} : NULL">
</my-example-component>

I just commit NULL if !myVlue and the child component uses the default value for its property.

Kind Regards,

Markus ;-)


问:
Indexing a PIL image
Is PIL's image coordinate indexing reversed? Is it indexed as image[column, row]?

I have an image which I open using PIL (pillow)

```<code>img = Image.open('picture.png').load()
</code>```

and when I try to print the pixel value of the first row, second column

```<code>print(img[0,1])
</code>```

I get the pixel value of the 2nd row's first column

Can anyone clear this out?

答: PIL indexes images in Cartesian co-ordinates. So it is indexed as img[col, row].

Title: Indexing a PIL image

Body:
Is PIL's image coordinate indexing reversed? Is it indexed as image[column, row]?

I have an image which I open using PIL (pillow)

img = Image.open('picture.png').load()

and when I try to print the pixel value of the first row, second column

print(img[0,1])

I get the pixel value of the 2nd row's first column

Can anyone clear this out?


问:
Unable to set MSMQ message queue permissions using MessageQueueInstaller
I'm trying to create a private message queue for use with a Windows service. I'm creating the queue in my service's ProjectInstaller class. In the constructor for said class, I create a MessageQueueInstaller object, and add it to my local Installer.Installers property like so:

```<code>var path = _config?.Settings[QUEUE_PATH]?.Value;
if (string.IsNullOrEmpty(path))
{
    Console.WriteLine($"Could not install MSMQ message queue. Cannot install service. Missing private queue path value.");
    throw new ArgumentNullException(QUEUE_PATH, "Cannot create private message queue with null queue path.");
}
_q = new MessageQueueInstaller();
_q.Label = "Queue Name";
_q.Path = path;
_q.Transactional = true;
Installers.Add(_q);
</code>```

Since I expect credentials to be passed in when the service is installed, and I want the account the service runs under to have full access to the message queue being created, I'm subscribing to the AfterInstall event of my ServiceProcessInstaller in order to grab the username like so:

```<code>_serviceProcessInstaller.AfterInstall += (sender, args) =>
{
    _q.Permissions = new AccessControlList()
    {
        new AccessControlEntry(new Trustee(_serviceProcessInstaller.Username, null, TrusteeType.User),
            GenericAccessRights.All, StandardAccessRights.All, AccessControlEntryType.Allow)
    };
};
</code>```

This process completes successfully, and an ACL entry is added to my private queue's security tab with the expected values, however, when running the service that needs to interact with MSMQ, I receive the following error:

Access to Message Queuing system is denied

Oddly enough, if I manually create the exact same ACL entry from the queue's security tab, everything magically works!

Also, if I create all the ACLs programatically (ending up with the error above), and then set 'Everyone' to Full Control manually, it also works, but setting 'Everyone' to Full Control during the same process where we set the actual account does not work.

Finally, I am running the MSMQ service under 'NT AUTHORITY\Network Service'. I have also tried adding that account with full control programatically (appears as if all perms are set, but same error still received), and I've also tried running the MSMQ service as Local System to no avail.

I'm honestly not sure what to make of this. As far as I can tell, the permissions are identical regardless of if they were added programatically or manually, but obviously that isn't actually true or this would work.

What in the world am I missing here?

Please let me know if additional context is needed. Thanks!

答:
We are using the following code to create MSMQ queues and setting the permissions. It works all well:</p>

```<code>public void CreateQueueIfNotExists(string queueName, List<string> users)
{
    if (!MessageQueue.Exists(queueName))
    {
        MessageQueue.Create(queueName);
        var queue = new MessageQueue(queueName);
        //set permissions for those users
        foreach (var user in users)
        {
            queue.SetPermissions(user, MessageQueueAccessRights.ReceiveMessage | MessageQueueAccessRights.WriteMessage, AccessControlEntryType.Allow);
        }
    }
}
</code>```

Body:
I'm trying to create a private message queue for use with a Windows service. I'm creating the queue in my service's ProjectInstaller class. In the constructor for said class, I create a MessageQueueInstaller object, and add it to my local Installer.Installers property like so:

var path = _config?.Settings[QUEUE_PATH]?.Value;
if (string.IsNullOrEmpty(path))
{
    Console.WriteLine($"Could not install MSMQ message queue. Cannot install service. Missing private queue path value.");
    throw new ArgumentNullException(QUEUE_PATH, "Cannot create private message queue with null queue path.");
}
_q = new MessageQueueInstaller();
_q.Label = "Queue Name";
_q.Path = path;
_q.Transactional = true;
Installers.Add(_q);

Since I expect credentials to be passed in when the service is installed, and I want the account the service runs under to have full access to the message queue being created, I'm subscribing to the AfterInstall event of my ServiceProcessInstaller in order to grab the username like so:

_serviceProcessInstaller.AfterInstall += (sender, args) =>
{
    _q.Permissions = new AccessControlList()
    {
        new AccessControlEntry(new Trustee(_serviceProcessInstaller.Username, null, TrusteeType.User),
            GenericAccessRights.All, StandardAccessRights.All, AccessControlEntryType.Allow)
    };
};

This process completes successfully, and an ACL entry is added to my private queue's security tab with the expected values, however, when running the service that needs to interact with MSMQ, I receive the following error:

Access to Message Queuing system is denied

Oddly enough, if I manually create the exact same ACL entry from the queue's security tab, everything magically works!

Also, if I create all the ACLs programatically (ending up with the error above), and then set 'Everyone' to Full Control manually, it also works, but setting 'Everyone' to Full Control during the same process where we set the actual account does not work.

Finally, I am running the MSMQ service under 'NT AUTHORITY\Network Service'. I have also tried adding that account with full control programatically (appears as if all perms are set, but same error still received), and I've also tried running the MSMQ service as Local System to no avail.

I'm honestly not sure what to make of this. As far as I can tell, the permissions are identical regardless of if they were added programatically or manually, but obviously that isn't actually true or this would work.

What in the world am I missing here?

Please let me know if additional context is needed. Thanks!

Body:
We are using the following code to create MSMQ queues and setting the permissions. It works all well:

public void CreateQueueIfNotExists(string queueName, List<string> users)
{
    if (!MessageQueue.Exists(queueName))
    {
        MessageQueue.Create(queueName);
        var queue = new MessageQueue(queueName);
        //set permissions for those users
        foreach (var user in users)
        {
            queue.SetPermissions(user, MessageQueueAccessRights.ReceiveMessage | MessageQueueAccessRights.WriteMessage, AccessControlEntryType.Allow);
        }
    }
}


问:
BDD - Test pass on chrome but not on Phantomjs
I have a web app built by Django, front-end is built by React. I tried to test bdd with behave and selenium. I run a test with Chrome web driver and phantomjs one but the tests only passed using chrome. I captured a screenshot when it runs on phantom and saw that the page is not fully rendered. Please give some suggestions about this issue. Do I need do further configuration to test with phantomjs. Thank you. </p>

答:
You have 3 options:

implicitly_wait:

Implicitly wait means that the it will wait for a maximum of x seconds to search for an element so if you element will appear after 4 seconds you will get it when it will appear second if you set the implicitly wait greater than 4seconds.

Use driver.implicitly_wait(x) after creating the instance.

explicitly_wait:

Explicitly wait means the it will wait for x seconds and it will search for the element after the seconds passed so if you set 10 seconds and the element will appear after 4 seconds the element will be located with 6 seconds delay.

Use driver.explicitly_wait(x) after creating the instance

time.sleep

You can put your program to sleep and wait for the page to fully load after submitting some actions.

Use time.sleep(x) after submitting a form, clicking a button or loading a page.


问:
a "preprocessor" for HTML? without JS
In a CSS sheet, I created a new tag

```<code>gb {
    color: green;
}
</code>```

and in the HTML code, I would replace without javascript, all occurences of

```<code><gb> ■ </gb>  <!-- green bullet -->
</code>```

with something like <gb /> . (Like using the C preprocessor, but doing thing in native HTML/CSS, without need to another program (cpp) and action (preprocessing) before sending the page on the web)

In other terms, how could I create custom HTML tag, with content (saving typing the ■ code), but only using HTML/CSS ?

And, yes, a lot of content already address custom HTML tags, but

They generally use Javascript

It is not clear

I can't believe such a little thing could involve these cumbersome solutions.

The idea is just to have a short way to draw an Unicode symbol (and in color) in middle of text.

答:
Option 1

You can (but you should not) create your own HTML tag:

gb::before {
  content: "\25A0";
  color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><gb>Your text</gb></code>```

Option 2

You can use a list with
 an
 tags:

ul {
  list-style: none;
  padding-left: 0px;
}

li:before {
  content: "\25A0";
  color: green;
  padding-right:5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Line 1</li>
  <li>Line 2</li>
  <li>Line 3</li>
</ul></code>```

Option 3

You can use a  tag :

.gb::before {
  content: "\25A0";
  color: green;
  padding-right:5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="gb">Your text</span></code>```

Title: a "preprocessor" for HTML? without JS

Body:
In a CSS sheet, I created a new tag

gb {
    color: green;
}

and in the HTML code, I would replace without javascript, all occurences of

<gb> ■ </gb>

with something like <gb /> . (Like using the C preprocessor, but doing thing in native HTML/CSS, without need to another program (cpp) and action (preprocessing) before sending the page on the web)

In other terms, how could I create custom HTML tag, with content (saving typing the ■ code), but only using HTML/CSS ?

And, yes, a lot of content already address custom HTML tags, but

They generally use Javascript

It is not clear

I can't believe such a little thing could involve these cumbersome solutions.

The idea is just to have a short way to draw an Unicode symbol (and in color) in middle of text.

Body:
Option 1

You can (but you should not) create your own HTML tag:

gb::before {
  content: "\25A0";
  color: green;
}

<gb>Your text</gb>

Option 2

You can use a list with <ul> an <li> tags:

ul {
  list-style: none;
  padding-left: 0px;
}

li:before {
  content: "\25A0";
  color: green;
  padding-right:5px;
}

<ul>
  <li>Line 1</li>
  <li>Line 2</li>
  <li>Line 3</li>
</ul>

Option 3

You can use a <span> tag :

.gb::before {
  content: "\25A0";
  color: green;
  padding-right:5px;
}

<span class="gb">Your text</span>


问:
Append parameters to an existing url in Spring boot Java?
I am trying to call a rest api and get the data from the api. I need to add dynamic parameters to the url in spring boot. I am a bit lost as how should I go about it. Can anyone kindly suggest me something?

```<code>RestTemplate restTemplate = new RestTemplate();
        String consumeJSONString = restTemplate.getForObject("https://maps.googleapis.com/maps/api/geocode/json?latlng=5.47686,-73.961452&key=YOUR_API_KEY"
, String.class);
</code>```

I would like to append latlng and api key in the url dynamically. I would really appreciate any suggestions.

答:
As i got a solution to dynamic variable
where this is a Rest Url

```<code> @RequestMapping(value = "/studentdetail")
public User detailStudent(@RequestParam(value = "userid", required = true) String userid) throws SQLException { /*your task goes here*/}
</code>```

and this is what i m sending the dynamic params as userid which can be anything hopefully it will help u a lot

```<code>URL url = new URL("http://localhost:9090/testpapers?userid=" + userid);
URLConnection conn = url.openConnection();

conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
String s1=URLEncoder.encode(postDataParams, "UTF-8");

writer.write(s1);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((line = reader.readLine()) != null)
{
  System.out.println(line);
}
writer.close();
reader.close();
}
</code>```

Body:
I am trying to call a rest api and get the data from the api. I need to add dynamic parameters to the url in spring boot. I am a bit lost as how should I go about it. Can anyone kindly suggest me something?

RestTemplate restTemplate = new RestTemplate();
        String consumeJSONString = restTemplate.getForObject("https://maps.googleapis.com/maps/api/geocode/json?latlng=5.47686,-73.961452&key=YOUR_API_KEY"
, String.class);

I would like to append latlng and api key in the url dynamically. I would really appreciate any suggestions.

Body:
As i got a solution to dynamic variable
where this is a Rest Url

 @RequestMapping(value = "/studentdetail")
public User detailStudent(@RequestParam(value = "userid", required = true) String userid) throws SQLException { /*your task goes here*/}

and this is what i m sending the dynamic params as userid which can be anything hopefully it will help u a lot

URL url = new URL("http://localhost:9090/testpapers?userid=" + userid);
URLConnection conn = url.openConnection();

conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
String s1=URLEncoder.encode(postDataParams, "UTF-8");

writer.write(s1);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((line = reader.readLine()) != null)
{
  System.out.println(line);
}
writer.close();
reader.close();
}


问:
How to import function to main namespace of my module?
I am using python 2.7, and am building a module with a lot of subdirectories. The structure looks something like this:

```<code>mainmodule/
  __init__.py
  submodule/
    __init__.py
    somefunction.py
    someotherfuntion.py
</code>```

Now when importing i would, rather than having this:

```<code>>>> from mainmodule.submodule.somefunction import func
>>> func(do_some_stuff)
</code>```

i want this:

```<code>>>> import mainmodule
>>> mainmodule.func(do_some_stuff)
</code>```

Thanks in advance!

答:
You should then import and expose your function in your mainmodule's __init__.py:

```<code>from .submodule.somefunction import func
</code>```

Body:
I am using python 2.7, and am building a module with a lot of subdirectories. The structure looks something like this:

mainmodule/
  __init__.py
  submodule/
    __init__.py
    somefunction.py
    someotherfuntion.py

Now when importing i would, rather than having this:

>>> from mainmodule.submodule.somefunction import func
>>> func(do_some_stuff)

i want this:

>>> import mainmodule
>>> mainmodule.func(do_some_stuff)

Thanks in advance!

Body:
You should then import and expose your function in your mainmodule's __init__.py:

from .submodule.somefunction import func


问:
How to replace everything with blank after question mark in a string?
I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

```<code>var str = "/root/Users?SkillId=201;"
</code>```

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

```<code>var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable
</code>```

I don't want to use for loop for this. Isn't there is any better way to do this?

答:
Simply use JavaScript function

```<code>var str = "/root/Users?SkillId=201;";
var str = str.substring( 0, str.indexOf("?")-1 );
console.log(str);
</code>```

here is the fiddle:
https://jsfiddle.net/ahmednawazbutt/2fatxLfe/3/

Body:
I am trying to replace everything with blank after question mark.

Suppose I have a string like below:

var str = "/root/Users?SkillId=201;"

Now I want to replace everything with blank after ?.

Expected output: "/root/Users"

I tried below solution:

var str = "/root/Users?SkillId=201;".replace(/[^? ]/g, "");
console.log(str); // output : ?

str = str.split('?')[0] // though worked but not readable

I don't want to use for loop for this. Isn't there is any better way to do this?

Body:
Simply use JavaScript function

var str = "/root/Users?SkillId=201;";
var str = str.substring( 0, str.indexOf("?")-1 );
console.log(str);

here is the fiddle:
https://jsfiddle.net/ahmednawazbutt/2fatxLfe/3/


问:
TestNG ERROR Cannot find class in classpath
I'm trying to run testng via command line and I have following things in classpath:

testng jar, jar of compiled test case file, and other required jars.

testng.xml points to appropriate class in the hierarchy.

Testng doesn't run instead it throws:

```<code>[TestNG] [ERROR]  Cannot find class in classpath: (name of testcase file)
</code>```

I encountered the same issue before and I just added.

In classpath and it solved the problem. But this time it did not seem to solve it. Any workarounds?

答:
When I converted my project with default pacage and a class named addition,
to testng.xml.
It got converted as:

```<code><classes>
      <class name=".addition"/>
</classes>
</code>```

and was throwing error that class cannot be loaded.
If I remove . before addition, the code works fine.
So be careful with default package.

Body:
I'm trying to run testng via command line and I have following things in classpath:

testng jar, jar of compiled test case file, and other required jars.

testng.xml points to appropriate class in the hierarchy.

Testng doesn't run instead it throws:

[TestNG] [ERROR]  Cannot find class in classpath: (name of testcase file)

I encountered the same issue before and I just added.

In classpath and it solved the problem. But this time it did not seem to solve it. Any workarounds?

Body:
When I converted my project with default pacage and a class named addition,
to testng.xml.
It got converted as:

<classes>
      <class name=".addition"/>
</classes>

and was throwing error that class cannot be loaded.
If I remove . before addition, the code works fine.
So be careful with default package.


问:
jQuery wrap failing on IE8, fine on Firefox
I have a jQuery statement which worked fine on IE7 and works on FF, but is failing on IE8.

The line is:

```<code>ScratchIFrame().find("fullwordmatch").wrap("<nonmarkupmatch></nonmarkupmatch>");
</code>```

I added the following before it:

```<code>alert(ScratchIFrame().find("fullwordmatch").length);
alert(ScratchIFrame().html());
</code>```

and get the results:

```<code>1
<fullwordmatch>test</fullwordmatch>
</code>```

the error occurring is:

```<code>Message: Unexpected call to method or property access.
Line: 12
Char: 2305
Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
</code>```

Does anyone know what the problem might be?

Thanks,
Dan

答: I ran into the same issue myself.  The cause in my scenario was that I was adding an input element but assigned a .text() to the input tag.  When appending the input tag, it failed generating the same error as you have encountered.</p>

Body:
I have a jQuery statement which worked fine on IE7 and works on FF, but is failing on IE8.

The line is:

ScratchIFrame().find("fullwordmatch").wrap("<nonmarkupmatch></nonmarkupmatch>");

I added the following before it:

alert(ScratchIFrame().find("fullwordmatch").length);
alert(ScratchIFrame().html());

and get the results:

1
<fullwordmatch>test</fullwordmatch>

the error occurring is:

Message: Unexpected call to method or property access.
Line: 12
Char: 2305
Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

Does anyone know what the problem might be?

Thanks,
Dan


问:
My list view is lagging can anyone help me to fix this?
i"m posting my adapter class and layout. can anyone suggest me how can i get rid from this lagging problem.
i tried view holder but it didn't work.
so any other solution possible then tell me fast.
my layout files are as follows

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_margin="10dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center"
            android:layout_marginBottom="5dp">
            <FrameLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="5dp">
                <View
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center"

                    android:background="@drawable/circle2"/>
                <com.hitesh.custom.Custom_font
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:textColor="#fff"
                    android:textSize="13sp"

                    android:layout_gravity="center"
                    android:text=""/>

            </FrameLayout>
            <com.hitesh.custom.Custom_Roboto_Regular
                android:id="@+id/tv1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:textSize="25sp" />

        </LinearLayout>

        <com.hitesh.custom.Custom_Roboto_Light
            android:id="@+id/tv2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:lineSpacingExtra="1dp"
            android:textSize="18sp" />

     </LinearLayout>

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

   </LinearLayout>
</code>```

and adapter

```<code>public class Rules_d_adapter  extends BaseAdapter{

private Context context;
List<String> question =new ArrayList<String>();
List<String> answer =new ArrayList<String>();
public Rules_d_adapter(Context con,List<String> Lines,List<String> Lines2)
{question=Lines;
    answer=Lines2;
    context = con;
}

@Override
public int getCount() {
    return question.size();
}

@Override
public Object getItem(int i) {
    return question.size();
}

@Override
public long getItemId(int i) {
    return question.size();
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    LayoutInflater inflater = (LayoutInflater)
    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.rules_d_adapter, viewGroup, false);
    Custom_Roboto_Light tv2 =
    (Custom_Roboto_Light)view.findViewById(R.id.tv2) ;
    Custom_Roboto_Regular tv = (Custom_Roboto_Regular)
    view.findViewById(R.id.tv1) ;
    tv.setText(question.get(i));
    tv2.setText(answer.get(i));

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

答:
if you still happy with ListView then you can take idea from below
  code

here i am using Cursor but you can use  ArrayList in place of Cursor

```<code>public class Custom_Adapter_Products extends BaseAdapter {
    Context context;
    Cursor mCursor;
    static int[] intArr;
    DatabaseAdapter db;
    public ImageLoader imageLoader;

    public Custom_Adapter_Products(Context context, Cursor mCursor){
        this.context = context;
        this.mCursor = mCursor;
        this.intArr = new int[this.mCursor.getCount()];
        imageLoader=new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return mCursor.getCount();
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        try{
                ViewHolder holder;
                this.mCursor.moveToPosition(position);
                LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                if (convertView == null)
                {
                    convertView = vi.inflate(R.layout.lv_row_for_products, null);
                    holder = createViewHolder(convertView);
                    convertView.setTag(holder);
                    holder.btnMinus.setTag(holder);
                    holder.btnAdd.setTag(holder);
                }
                else
                {
                    holder = (ViewHolder) convertView.getTag();
                }

                holder.btnMinus.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try{
                        ViewHolder holder = (ViewHolder) v.getTag();
                        // Do whatever you want
                    }catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
            });

        }catch (Exception e){
            // TODO: handle exception
            e.printStackTrace();
        }
        return convertView;
    }

    private static class ViewHolder
    {
        public TextView tvProductName;
        public TextView tvPrice;
        public TextView tvMRP;
        public TextView tvMOQ;
        public TextView tvPercent;
        public TextView tvQuantity;
        public ImageView imgProduct;
        public ProgressBar pBar;
        public Button btnMinus;
        public Button btnAdd;
    }

    private ViewHolder createViewHolder(View v) {
        ViewHolder holder = new ViewHolder();
        try{
            holder.tvProductName = (TextView) v.findViewById(R.id.tvProductName);
            holder.tvPrice = (TextView) v.findViewById(R.id.tvPrice);
            holder.tvMRP = (TextView) v.findViewById(R.id.tvMRP);
            holder.tvMOQ = (TextView) v.findViewById(R.id.tvMOQ);
            holder.tvQuantity = (TextView) v.findViewById(R.id.tvQuantity);
            holder.imgProduct = (ImageView) v.findViewById(R.id.imgProduct);
            holder.pBar = (ProgressBar) v.findViewById(R.id.img_pb);
            holder.btnMinus = (Button) v.findViewById(R.id.btnMinus);
            holder.btnAdd = (Button) v.findViewById(R.id.btnAdd);
            holder.tvPercent = (TextView) v.findViewById(R.id.tvPercent);
        }catch (Exception e) {
        // TODO: handle exception
            e.printStackTrace();
    }
        return holder;
    }
}
</code>```

Body:
i"m posting my adapter class and layout. can anyone suggest me how can i get rid from this lagging problem.
i tried view holder but it didn't work.
so any other solution possible then tell me fast.
my layout files are as follows

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_margin="10dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_gravity="center"
            android:layout_marginBottom="5dp">
            <FrameLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="5dp">
                <View
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center"

                    android:background="@drawable/circle2"/>
                <com.hitesh.custom.Custom_font
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAlignment="center"
                    android:textColor="#fff"
                    android:textSize="13sp"

                    android:layout_gravity="center"
                    android:text=""/>

            </FrameLayout>
            <com.hitesh.custom.Custom_Roboto_Regular
                android:id="@+id/tv1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:textSize="25sp" />

        </LinearLayout>

        <com.hitesh.custom.Custom_Roboto_Light
            android:id="@+id/tv2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:lineSpacingExtra="1dp"
            android:textSize="18sp" />

     </LinearLayout>

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

   </LinearLayout>

and adapter

public class Rules_d_adapter  extends BaseAdapter{

private Context context;
List<String> question =new ArrayList<String>();
List<String> answer =new ArrayList<String>();
public Rules_d_adapter(Context con,List<String> Lines,List<String> Lines2)
{question=Lines;
    answer=Lines2;
    context = con;
}

@Override
public int getCount() {
    return question.size();
}

@Override
public Object getItem(int i) {
    return question.size();
}

@Override
public long getItemId(int i) {
    return question.size();
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    LayoutInflater inflater = (LayoutInflater)
    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.rules_d_adapter, viewGroup, false);
    Custom_Roboto_Light tv2 =
    (Custom_Roboto_Light)view.findViewById(R.id.tv2) ;
    Custom_Roboto_Regular tv = (Custom_Roboto_Regular)
    view.findViewById(R.id.tv1) ;
    tv.setText(question.get(i));
    tv2.setText(answer.get(i));

    return view;
    }
    }

Body:
if you still happy with ListView then you can take idea from below
  code

here i am using Cursor but you can use  ArrayList in place of Cursor

public class Custom_Adapter_Products extends BaseAdapter {
    Context context;
    Cursor mCursor;
    static int[] intArr;
    DatabaseAdapter db;
    public ImageLoader imageLoader;

    public Custom_Adapter_Products(Context context, Cursor mCursor){
        this.context = context;
        this.mCursor = mCursor;
        this.intArr = new int[this.mCursor.getCount()];
        imageLoader=new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return mCursor.getCount();
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        try{
                ViewHolder holder;
                this.mCursor.moveToPosition(position);
                LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                if (convertView == null)
                {
                    convertView = vi.inflate(R.layout.lv_row_for_products, null);
                    holder = createViewHolder(convertView);
                    convertView.setTag(holder);
                    holder.btnMinus.setTag(holder);
                    holder.btnAdd.setTag(holder);
                }
                else
                {
                    holder = (ViewHolder) convertView.getTag();
                }

                holder.btnMinus.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    try{
                        ViewHolder holder = (ViewHolder) v.getTag();
                        // Do whatever you want
                    }catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
            });

        }catch (Exception e){
            // TODO: handle exception
            e.printStackTrace();
        }
        return convertView;
    }

    private static class ViewHolder
    {
        public TextView tvProductName;
        public TextView tvPrice;
        public TextView tvMRP;
        public TextView tvMOQ;
        public TextView tvPercent;
        public TextView tvQuantity;
        public ImageView imgProduct;
        public ProgressBar pBar;
        public Button btnMinus;
        public Button btnAdd;
    }

    private ViewHolder createViewHolder(View v) {
        ViewHolder holder = new ViewHolder();
        try{
            holder.tvProductName = (TextView) v.findViewById(R.id.tvProductName);
            holder.tvPrice = (TextView) v.findViewById(R.id.tvPrice);
            holder.tvMRP = (TextView) v.findViewById(R.id.tvMRP);
            holder.tvMOQ = (TextView) v.findViewById(R.id.tvMOQ);
            holder.tvQuantity = (TextView) v.findViewById(R.id.tvQuantity);
            holder.imgProduct = (ImageView) v.findViewById(R.id.imgProduct);
            holder.pBar = (ProgressBar) v.findViewById(R.id.img_pb);
            holder.btnMinus = (Button) v.findViewById(R.id.btnMinus);
            holder.btnAdd = (Button) v.findViewById(R.id.btnAdd);
            holder.tvPercent = (TextView) v.findViewById(R.id.tvPercent);
        }catch (Exception e) {
        // TODO: handle exception
            e.printStackTrace();
    }
        return holder;
    }
}


问:
What is the best way to chain observables in Angular?
If I have a service call that relies on the result of another service call what is the best way to chain them?

myService.getStuffFromServer().subscribe(data => {
  let manipulatedData = functionThatManipulatesData(data);
  myService.getMoreStuffFromServer(manipulatedData).subscribe(moreData => {
    doStuffWithMoreData(moreData);
  });
});
```

Is the way I have been doing it but the nesting gets a bit messy sometimes. Is there a cleaner way?

答:
As mentioned in the comments its very simple.

```<code>myService.getStuffFromServer().
  .map(functionThatManipulatesData)
  .flatMap(myService.getMoreStuffFromServer)
  .subscribe(doStuffWithMoreData);
</code>```

map transforms each element of a stream from one type of data to another.
  But if that transformation involves an asynchronous call we use flatMap.

Most simple way I can describe and this thinking helped me a lot.

We can use flatMap also to add more than one item to the stream. For example , map takes one item and replaces that with new item. What if we want to take one item and add 3 items in its place . For example I want to replace a number with its square and cube too .

```<code>----1---2---3---
</code>```

to

```<code>----1---1---1---2---4---8---3---9---27----
</code>```

Then we can use flatMap

```<code>stream.flatMap(num => Observable.of(num, num*num, num*num*num));
</code>```

Now flatMap replaces each element with three new elements. These are two important functionalities of flatmap.
Hope I confused you enough :)

Body:
If I have a service call that relies on the result of another service call what is the best way to chain them?

myService.getStuffFromServer().subscribe(data => {
  let manipulatedData = functionThatManipulatesData(data);
  myService.getMoreStuffFromServer(manipulatedData).subscribe(moreData => {
    doStuffWithMoreData(moreData);
  });
});

Is the way I have been doing it but the nesting gets a bit messy sometimes. Is there a cleaner way?

Body:
As mentioned in the comments its very simple.

myService.getStuffFromServer().
  .map(functionThatManipulatesData)
  .flatMap(myService.getMoreStuffFromServer)
  .subscribe(doStuffWithMoreData);

map transforms each element of a stream from one type of data to another.
  But if that transformation involves an asynchronous call we use flatMap.

Most simple way I can describe and this thinking helped me a lot.

We can use flatMap also to add more than one item to the stream. For example , map takes one item and replaces that with new item. What if we want to take one item and add 3 items in its place . For example I want to replace a number with its square and cube too .

----1---2---3---

to

----1---1---1---2---4---8---3---9---27----

Then we can use flatMap

stream.flatMap(num => Observable.of(num, num*num, num*num*num));

Now flatMap replaces each element with three new elements. These are two important functionalities of flatmap.
Hope I confused you enough :)