问:
Redirecting from cshtml page
I want to redirect to a different view depending on the result of a dataset, but I keep getting returned to the page I am currently on, and can't work out why. I drop into the if statement the action gets called but once i return the view to the new page, it returns me back to the current page.

CSHTML page

```<code>@{
ViewBag.Title = "Search Results";
EnumerableRowCollection<DataRow> custs = ViewBag.Customers;

bool anyRows = custs.Any();
if(anyRows == false)
{

    Html.Action("NoResults","Home");

}
// redirect to no search results view
</code>```

}

Controller

```<code> public ActionResult NoResults()
    {
       return View("NoResults");

    }
</code>```

View I cant get too..

```<code>@{
ViewBag.Title = "NoResults";
 }

<h2>NoResults</h2>
</code>```

答:
You can go to method of same controller..using this line , and if you want to pass some parameters to that action it can be done by writing inside ( new { } )..
Note:- you can add as many parameter as required.

@Html.ActionLink("MethodName", new { parameter = Model.parameter })

Title: Redirecting from cshtml page

Body:
I want to redirect to a different view depending on the result of a dataset, but I keep getting returned to the page I am currently on, and can't work out why. I drop into the if statement the action gets called but once i return the view to the new page, it returns me back to the current page.

CSHTML page

@{
ViewBag.Title = "Search Results";
EnumerableRowCollection<DataRow> custs = ViewBag.Customers;

bool anyRows = custs.Any();
if(anyRows == false)
{

    Html.Action("NoResults","Home");

}
// redirect to no search results view

}

Controller

 public ActionResult NoResults()
    {
       return View("NoResults");

    }

View I cant get too..

@{
ViewBag.Title = "NoResults";
 }

NoResults


来源: stackexchange

问:
How to join two different cores from two different Solr servers?
So I have some cores in one solr server and some cores in another solr server and I need to join them.

The schema of the cores are different with no matching attribute name but matching attribute value. I tried to do it with join & shards but both didn't work. Can you help me out?

attribute1 is in abc:7892/solr/core1

attribute2, attribute3 is in xyz:8983/solr/core2

```<code>{!join from=attribute1 to=attribute2 fromIndex="xyz:8983/solr/core2"} attribute3:*
</code>```

Error Message :

Cross-core join: no such core xyz:8983/solr/core2

Thanks.

答:
join does not support joining across different servers, even in SolrCloud mode it has constraints in that sense, see here.

What you could do is use Streaming Expressions, by using a search as a source, and then you have several types of joins etc, look at the docs and examples.

ContentLicense: CC BY-SA 3.0

Body:
So I have some cores in one solr server and some cores in another solr server and I need to join them.

The schema of the cores are different with no matching attribute name but matching attribute value. I tried to do it with join & shards but both didn't work. Can you help me out?

attribute1 is in abc:7892/solr/core1

attribute2, attribute3 is in xyz:8983/solr/core2

{!join from=attribute1 to=attribute2 fromIndex="xyz:8983/solr/core2"} attribute3:*

Error Message :

Cross-core join: no such core xyz:8983/solr/core2

Thanks.


问:
Capsule Exception
I'm trying to launch the Corda Tutorial App, and get this error after I '$ sh runnodes'. Haven't worked with JDK before, so seeking granular explanation.

bash -c 'cd
  /Users/marieleaf/Dropbox/blockchain/corda/cordapp-tutorial/kotlin-source/build/nodes/Controller;
  /usr/libexec/java_home -v 1.8 --exec java -Dname=Controller-corda.jar
  -Dcapsule.jvm.args=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
  -jar corda.jar && exit'     CAPSULE EXCEPTION: Could not find Java installation for requested version [Min. Java version: 1.8.0
  JavaVersion: null Min. update version: {1.8=131}] (JDK required:
  false). You can override the used Java version with the
  -Dcapsule.java.home flag. (for stack trace, run with -Dcapsule.log=verbose)

答:
You do not have the correct Java version. The required Java version can be found here: https://docs.corda.net/getting-set-up.html#software-requirements (as of Corda 3.1, Corda's minimum supported version of the JVM is version 8u131 of the Oracle JDK 8 JVM).

You can run java -version from the terminal to make sure that your installation has been recognised.

Title: Capsule Exception

ContentLicense: CC BY-SA 4.0


问:
display dropdown list on alert (or on dialog box) in html
My project requirement is to display alert or dialog box on click of button, on that alert, display drop down list with some values, select the drop down list value and save it in array list using HTML.
i have tried this    but it not working.
alert dialog should like below image.

<img src="https://i.stack.imgur.com/1mkZ5.png" alt="

答:
Try this code...

```<code><a data-target="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

  <div class="modal-dialog">
  <div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
  </div>
  <div class="modal-body">
    <select>
              <option>test</option>
              <option>test</option>
              <option>test</option>
              <option>test</option>
              <option>test</option>
          </select>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
  </div>
  </div>
  </div>
</div>
</code>```

https://codepen.io/chandrashekhar/pen/yXNBmQ?editors=1100

here is a link for reference

you have added hide class to modal and also missed some code try this it works..

Body:
Try this code...

<a data-target="#myModal" role="button" class="btn" data-toggle="modal">Launch demo modal</a>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

  <div class="modal-dialog">
  <div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal header</h3>
  </div>
  <div class="modal-body">
    <select>
              <option>test</option>
              <option>test</option>
              <option>test</option>
              <option>test</option>
              <option>test</option>
          </select>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
  </div>
  </div>
  </div>
</div>

https://codepen.io/chandrashekhar/pen/yXNBmQ?editors=1100

here is a link for reference

you have added hide class to modal and also missed some code try this it works..


问:
SQL update all records except the last one with a value
I need to make a query where only the last line of each user that has a car gets a license plate number.

```<code>ID    UserId    LicensePlate    HasCar
1     1         ABC123          1
2     1         ABC123          1
3     2         NULL            0
4     3         UVW789          1
5     3         UVW789          1
</code>```

Should become:

```<code>ID    UserId    LicensePlate    HasCar
1     1         NULL            1
2     1         ABC123          1
3     2         NULL            0
4     3         NULL            1
5     3         UVW789          1
</code>```

So I basically need to find all users with a licenseplate and change all but the last one and make the LicensePlate NULL

答:
By using LAG Function also you can achieve it.</p>

```<code>  ;WITH License(ID,UserId,LicensePlate,HasCar)
as
(
SELECT 1,1,'ABC123',1 UNION ALL
SELECT 2,1,'ABC123',1 UNION ALL
SELECT 3,2,NULL   ,0  UNION ALL
SELECT 4,3,'UVW789',1 UNION ALL
SELECT 5,3,'UVW789',1
)

SELECT ID,UserId,LAG(LicensePlate,1,NULL) OVER(PARTITION BY UserId ORDER BY LicensePlate),HasCar FROM License
</code>```

Body:
I need to make a query where only the last line of each user that has a car gets a license plate number.

ID    UserId    LicensePlate    HasCar
1     1         ABC123          1
2     1         ABC123          1
3     2         NULL            0
4     3         UVW789          1
5     3         UVW789          1

Should become:

ID    UserId    LicensePlate    HasCar
1     1         NULL            1
2     1         ABC123          1
3     2         NULL            0
4     3         NULL            1
5     3         UVW789          1

So I basically need to find all users with a licenseplate and change all but the last one and make the LicensePlate NULL

Body:
By using LAG Function also you can achieve it.

  ;WITH License(ID,UserId,LicensePlate,HasCar)
as
(
SELECT 1,1,'ABC123',1 UNION ALL
SELECT 2,1,'ABC123',1 UNION ALL
SELECT 3,2,NULL   ,0  UNION ALL
SELECT 4,3,'UVW789',1 UNION ALL
SELECT 5,3,'UVW789',1
)

SELECT ID,UserId,LAG(LicensePlate,1,NULL) OVER(PARTITION BY UserId ORDER BY LicensePlate),HasCar FROM License


问:
Error compiler, cannot convert parameter 2 from MyStruct1 to const void*, for memcpy
I am trying to copy the data from on structure to another. The bytes are identical that each struct can handle are the same. My declarations and the memcpy are below:

```<code>    typedef struct{
        CString strNumber;
        CString strAlpha;

    } _Number;

    typedef struct{
        CString strIterration;
        _Number NumberOne;
        _Number NumberTwo;
    } _Store;

_Store Data1;
_Store Data2;
</code>```

Now let's say that the first struct Data1 has data and the second is just declared.

I am using the following code:

```<code>memcpy(&Data2, Data1,   sizeof(_Store));
</code>```

I cannot compile as the error appears. Any ideas? Any other approaches to copy the data?

答:
The obvious other approach is simple assignment, i.e., Data2 = Data1; </p>

<p>This saves you from caring how many bytes are in the _Store structure and also from whether CString has an operator =. </p>

ContentLicense: CC BY-SA 2.5

Body:
I am trying to copy the data from on structure to another. The bytes are identical that each struct can handle are the same. My declarations and the memcpy are below:

    typedef struct{
        CString strNumber;
        CString strAlpha;

    } _Number;

    typedef struct{
        CString strIterration;
        _Number NumberOne;
        _Number NumberTwo;
    } _Store;

_Store Data1;
_Store Data2;

Now let's say that the first struct Data1 has data and the second is just declared.

I am using the following code:

memcpy(&Data2, Data1,   sizeof(_Store));

I cannot compile as the error appears. Any ideas? Any other approaches to copy the data?

Body:
The obvious other approach is simple assignment, i.e., Data2 = Data1;

This saves you from caring how many bytes are in the _Store structure and also from whether CString has an operator =.


问:
Keeping MonthPicker Open using Jquery UI
I want monthpicker to open all the time when page loads. And Change Month or Year it will Automatically Updated to lable. I can Handle Event for label updates and etc.

but I want it Open on Page is loaded.
I'm following this answer :- https://stackoverflow.com/a/6013093/4952944

I have tried :- http://jqueryui.com/datepicker/#inline But it works for date I want to make it work for Month and year picker.

I tried a demo with if I us a Division with jquery UI.

```<code>Date: <div id="datepicker"></div>
</code>```

And I use Jquery like this :-

```<code>$( function() {
        $( "#datepicker" ).datepicker();
} );
</code>```

It works datepicker opens Inline and open continuously.
But I want to make it work for above SO's code. I tried everything like put it on when page loads.
I'm not sure But may be due to some change events it's not loading on page Load.

答:
I got My solution. On page Load hide the calendar view.

```<code>$('.ui-datepicker-calendar').css('display','none');
</code>```

And I have change the script as per my requirement.
But here two things to note on page load hide the calendar view. And use below script when onChangeMonthYear event is fired,

```<code>setTimeout(function() {
                   $('.ui-datepicker-calendar').hide();
});
</code>```

Script :-

```<code><script type="text/javascript">
    $( function() {
        $(".monthPicker").datepicker({
            dateFormat: 'MM yy',
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            beforeShow: true,
            onChangeMonthYear: function(dateText, inst) {
                setTimeout(function() {
                   $('.ui-datepicker-calendar').hide();
                });
                var month = $(".ui-datepicker-month :selected").val();
                var year = $(".ui-datepicker-year :selected").val();
                alert(month);
                alert(year);
            }
        });
        $(".monthPicker").focus(function () {
            $(".ui-datepicker-calendar").hide();
            $("#ui-datepicker-div").position({
                my: "center top",
                at: "center bottom",
                of: $(this)
            });
        });
    });
</script>
</code>```

HTML :-

```<code><div class="monthPicker" id="month"></div>
</code>```

Body:
I want monthpicker to open all the time when page loads. And Change Month or Year it will Automatically Updated to lable. I can Handle Event for label updates and etc.

but I want it Open on Page is loaded.
I'm following this answer :- https://stackoverflow.com/a/6013093/4952944

I have tried :- http://jqueryui.com/datepicker/#inline But it works for date I want to make it work for Month and year picker.

I tried a demo with if I us a Division with jquery UI.

Date:

And I use Jquery like this :-

$( function() {
        $( "#datepicker" ).datepicker();
} );

It works datepicker opens Inline and open continuously.
But I want to make it work for above SO's code. I tried everything like put it on when page loads.
I'm not sure But may be due to some change events it's not loading on page Load.

Body:
I got My solution. On page Load hide the calendar view.

$('.ui-datepicker-calendar').css('display','none');

And I have change the script as per my requirement.
But here two things to note on page load hide the calendar view. And use below script when onChangeMonthYear event is fired,

setTimeout(function() {
                   $('.ui-datepicker-calendar').hide();
});

Script :-

<script type="text/javascript">
    $( function() {
        $(".monthPicker").datepicker({
            dateFormat: 'MM yy',
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            beforeShow: true,
            onChangeMonthYear: function(dateText, inst) {
                setTimeout(function() {
                   $('.ui-datepicker-calendar').hide();
                });
                var month = $(".ui-datepicker-month :selected").val();
                var year = $(".ui-datepicker-year :selected").val();
                alert(month);
                alert(year);
            }
        });
        $(".monthPicker").focus(function () {
            $(".ui-datepicker-calendar").hide();
            $("#ui-datepicker-div").position({
                my: "center top",
                at: "center bottom",
                of: $(this)
            });
        });
    });
</script>

HTML :-

<div class="monthPicker" id="month"></div>


问:
Best way to remove duplicated columns in linux
It should be like running uniq command, but by columns. For example:

A B C B

A C B C

A A A A

Second and fourth columns are identical. Which is the best way to obtain the following result?

A B C

A C B

A A A

However, at first it is unknown which columns are identical, much like with the uniq command for rows.

答:
Perl to the rescue!

```<code>perl -lane '
    push @{ $c[$_] }, $F[$_] for 0 .. $#F;
    }{
    for (@c) {
        $s = join "|", @$_;
        $seen{$s}++ or push @r, $_;
    }
    print join " ", map shift @$_, @r while @{ $r[0] }
    ' -- inputfile
</code>```

The first line pivots the input, i.e. it creates the following structure:

```<code>@c = ( [ 'A', 'A', 'A' ],
       [ 'B', 'C', 'A' ],
       [ 'C', 'B', 'A' ],
       [ 'B', 'C', 'A' ] );
</code>```

The }{ (called "Eskimo greeting") separates the code run for each line from the code run after the whole input has been processed. It walks the @c array and only keeps the unique columns (by creating a string from each of them like A|A|A, B|C|A, etc. and storing them in the %seen hash.

The structure will be

```<code>@r = ( [ 'A', 'A', 'A' ],
       [ 'B', 'C', 'A' ],
       [ 'C', 'B', 'A' ] );
</code>```

and the hash will look like

```<code>%seen = ( 'B|C|A' => 2,
          'A|A|A' => 1,
          'C|B|A' => 1
);
</code>```

The last print shifts the first element of each column, i.e. it pivots the result back.

Body:
Perl to the rescue!

perl -lane '
    push @{ $c[$_] }, $F[$_] for 0 .. $#F;
    }{
    for (@c) {
        $s = join "|", @$_;
        $seen{$s}++ or push @r, $_;
    }
    print join " ", map shift @$_, @r while @{ $r[0] }
    ' -- inputfile

The first line pivots the input, i.e. it creates the following structure:

@c = ( [ 'A', 'A', 'A' ],
       [ 'B', 'C', 'A' ],
       [ 'C', 'B', 'A' ],
       [ 'B', 'C', 'A' ] );

The }{ (called "Eskimo greeting") separates the code run for each line from the code run after the whole input has been processed. It walks the @c array and only keeps the unique columns (by creating a string from each of them like A|A|A, B|C|A, etc. and storing them in the %seen hash.

The structure will be

@r = ( [ 'A', 'A', 'A' ],
       [ 'B', 'C', 'A' ],
       [ 'C', 'B', 'A' ] );

and the hash will look like

%seen = ( 'B|C|A' => 2,
          'A|A|A' => 1,
          'C|B|A' => 1
);

The last print shifts the first element of each column, i.e. it pivots the result back.


问:
How to add an element in this ArrayList?
i've been trying to  make this work but how can I add a fourth element
in this ArrayList "hourCounts"?  </p>

```<code>public class HourCounts {

    private String[] hourCounts = {"One","Two","Three"};
    public hourCounts() {
      hourCount[3] = new String ("Four") ; // how do I write the code to add a
                                           // new element that says "Four"?
    }

    public void countHours() {
      int hour = 0;
       while(hour < hourCounts.length) {
          System.out.println(hour + ": " + hourCounts[hour]);
          hour++;
       }
    }
}
</code>```

答:
Java arrays have a fixed length (at time of construction), you might copy your current array to add another element. Like,

```<code>private String[] hourCounts = { "One", "Two", "Three" };

public hourCounts()
{
    hourCounts = Arrays.copyOf(hourCounts, hourCounts.length + 1);
    hourCounts[hourCounts.length - 1] = "Four";
}
</code>```

But, I think you wanted a List like

```<code>private List<String> hourCounts = new ArrayList<>(Arrays.asList(
        "One", "Two", "Three"));

public hourCounts() {
    hourCounts.add("Four");
}

public void countHours() {
    int hour = 0;
    while (hour < hourCounts.size()) {
        System.out.println(hour + ": " + hourCounts.get(hour));
        hour++;
    }
}
</code>```

Finally, please follow Java naming conventions (and don't name the class the same as a field in that class).

Body:
i've been trying to  make this work but how can I add a fourth element
in this ArrayList "hourCounts"?

public class HourCounts {

    private String[] hourCounts = {"One","Two","Three"};
    public hourCounts() {
      hourCount[3] = new String ("Four") ; // how do I write the code to add a
                                           // new element that says "Four"?
    }

    public void countHours() {
      int hour = 0;
       while(hour < hourCounts.length) {
          System.out.println(hour + ": " + hourCounts[hour]);
          hour++;
       }
    }
}

Body:
Java arrays have a fixed length (at time of construction), you might copy your current array to add another element. Like,

private String[] hourCounts = { "One", "Two", "Three" };

public hourCounts()
{
    hourCounts = Arrays.copyOf(hourCounts, hourCounts.length + 1);
    hourCounts[hourCounts.length - 1] = "Four";
}

But, I think you wanted a List like

private List<String> hourCounts = new ArrayList<>(Arrays.asList(
        "One", "Two", "Three"));

public hourCounts() {
    hourCounts.add("Four");
}

public void countHours() {
    int hour = 0;
    while (hour < hourCounts.size()) {
        System.out.println(hour + ": " + hourCounts.get(hour));
        hour++;
    }
}

Finally, please follow Java naming conventions (and don't name the class the same as a field in that class).


问:
Python code for digit-to-digit invariants
I have written code that determines which natural numbers less than or equal to 1 000 000 are perfect digit-to-digit invariants (they can be written as the sum of their digits each raised to a power equal to the digit; see https://en.wikipedia.org/wiki/Perfect_digit-to-digit_invariant) and expresses them as in this form.

```<code>def f(n):
    y = str(n)
    l = len(y)
    list = []
    for i in range(0,l):
        list.append(int(y[i]))
    list2 = []
    for i in list:
        list2.append(i**i)
    return sum(list2)

N = 10**6
n = np.linspace(1,N,N,dtype=int)
list = []
for i in n:
    if i == f(i):
        list.append(i)

list = np.array(list)

list2 = []
for i in list:
    list2.append(str(i))

for i in list2:
    for j in range(0,len(i)-1):
        print(i[j],'^',i[j],'+')
    print(i[-1],'^',i[-1],'=',int(i))
    print('----------')
</code>```

The output that running this code gives is:

```<code>1 ^ 1 = 1
----------
3 ^ 3 +
4 ^ 4 +
3 ^ 3 +
5 ^ 5 = 3435
----------
</code>```

The code gives the correct answer but I want the expression 3^3 + 4^4 + 3^3 + 5^5 = 3435 to appear on one line. Is there a way to do this?

答:
print() statements by default print a newline as well. To suppress that behavior and continue printing on the same line, add the end='' parameter like so:

```<code>for i in list2:
    for j in range(0, len(i)-1):
        print(i[j],'^',i[j],'+', end='')
    print(i[-1],'^',i[-1],'=',int(i))
    print('----------')
</code>```

Alternatively, and more pythonically you could replace the inner loop by join()ing the string componets and formatting the output as follows:

```<code>for i in list2:
    print(' + '.join(['{0:}^{0:}'.format(x) for x in i]) + ' = {}'.format(i))
    print('----------')
</code>```

Body:
I have written code that determines which natural numbers less than or equal to 1 000 000 are perfect digit-to-digit invariants (they can be written as the sum of their digits each raised to a power equal to the digit; see https://en.wikipedia.org/wiki/Perfect_digit-to-digit_invariant) and expresses them as in this form.

def f(n):
    y = str(n)
    l = len(y)
    list = []
    for i in range(0,l):
        list.append(int(y[i]))
    list2 = []
    for i in list:
        list2.append(i**i)
    return sum(list2)

N = 10**6
n = np.linspace(1,N,N,dtype=int)
list = []
for i in n:
    if i == f(i):
        list.append(i)

list = np.array(list)

list2 = []
for i in list:
    list2.append(str(i))

for i in list2:
    for j in range(0,len(i)-1):
        print(i[j],'^',i[j],'+')
    print(i[-1],'^',i[-1],'=',int(i))
    print('----------')

The output that running this code gives is:

1 ^ 1 = 1
----------
3 ^ 3 +
4 ^ 4 +
3 ^ 3 +
5 ^ 5 = 3435
----------

The code gives the correct answer but I want the expression 3^3 + 4^4 + 3^3 + 5^5 = 3435 to appear on one line. Is there a way to do this?

Body:
print() statements by default print a newline as well. To suppress that behavior and continue printing on the same line, add the end='' parameter like so:

for i in list2:
    for j in range(0, len(i)-1):
        print(i[j],'^',i[j],'+', end='')
    print(i[-1],'^',i[-1],'=',int(i))
    print('----------')

Alternatively, and more pythonically you could replace the inner loop by join()ing the string componets and formatting the output as follows:

for i in list2:
    print(' + '.join(['{0:}^{0:}'.format(x) for x in i]) + ' = {}'.format(i))
    print('----------')


问:
how to read some data from particular url in android
how to read some data from particular url  in android</p>

答: You can use HttpClient to download the content identified by an URL. </p>


答:
Try the end=" " option in print

```<code>for j in range(0,len(i)-1):
    print(i[j],'^',i[j],'+', end=" ")
</code>```

Title: Python code for digit-to-digit invariants

Body:
Try the end=" " option in print

for j in range(0,len(i)-1):
    print(i[j],'^',i[j],'+', end=" ")


问:
C# - Could not load type FirefoxDriverService
I have the following code:

```<code>    FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(currentDir.Remove(0, 6), "geckodriver.exe");
    //service.HideCommandPromptWindow = true;
    service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox (x86)\firefox.exe";
    driver = new FirefoxDriver(service);
    driver.Manage().Window.Maximize();
</code>```

But I get the following error:

Error message: System.TypeLoadException : Could not load type
  'OpenQA.Selenium.Firefox.FirefoxDriverService' from assembly
  'WebDriver, Version=2.45.0.0, Culture=neutral, PublicKeyToken=null'.

Why is this happening?

答:
Version 2.45 is a pretty old WebDriver driver, it is from 2015. Above all, that assembly doesn't contain a type FirefoxDriverService so your code shouldn't have compiled in the first place.

What I expect, using my Crystall ball, is that you compiled against a newer version of the webdriver but in the copy step somehow a stale driver version made it into the folder you run your code from.

With the current driver (3.4.0) and version 0.16.1 of the Gecko driver your code example works for me, when I run it in LinqPAD

```<code>void Main()
{
    var service = FirefoxDriverService.CreateDefaultService(
        ".",
        "geckodriver.exe");
    service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox (x86)\firefox.exe";
    var driver = new FirefoxDriver(service);
    driver.Manage().Window.Maximize();
}
</code>```

Body:
I have the following code:

    FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(currentDir.Remove(0, 6), "geckodriver.exe");
    //service.HideCommandPromptWindow = true;
    service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox (x86)\firefox.exe";
    driver = new FirefoxDriver(service);
    driver.Manage().Window.Maximize();

But I get the following error:

Error message: System.TypeLoadException : Could not load type
  'OpenQA.Selenium.Firefox.FirefoxDriverService' from assembly
  'WebDriver, Version=2.45.0.0, Culture=neutral, PublicKeyToken=null'.

Why is this happening?

Body:
Version 2.45 is a pretty old WebDriver driver, it is from 2015. Above all, that assembly doesn't contain a type FirefoxDriverService so your code shouldn't have compiled in the first place.

What I expect, using my Crystall ball, is that you compiled against a newer version of the webdriver but in the copy step somehow a stale driver version made it into the folder you run your code from.

With the current driver (3.4.0) and version 0.16.1 of the Gecko driver your code example works for me, when I run it in LinqPAD

void Main()
{
    var service = FirefoxDriverService.CreateDefaultService(
        ".",
        "geckodriver.exe");
    service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox (x86)\firefox.exe";
    var driver = new FirefoxDriver(service);
    driver.Manage().Window.Maximize();
}


问:
jQuery Color Picker on-functions fails
Hey all. I've added jQuery colorPicker to my webpage and I'm trying to implement the forth example of it. You can find it on this page.

http://www.eyecon.ro/colorpicker/#about

After my implementation, everything works except for the options added in the colorPicker. I can't change the standard color and onShow, onHide & onChange never fires.

Can anyone see why?

Here's my code:

```<code>jQuery('document').ready(function(){
$('#colorSelector').ColorPicker({
 color: '#0000ff',
 onShow: function (colpkr) {
  $(colpkr).fadeIn(500);
  return false;
 },
 onHide: function (colpkr) {
  $(colpkr).fadeOut(500);
  return false;
 },
 onChange: function (hsb, hex, rgb) {
  $('#colorSelector div').css('backgroundColor', '#' + hex);
 }
});
</code>```

});

And here's the rest of the code implemented:

```<code><div class="settings-color"><div id="colorSelector"></div></div>
</code>```

Added scripts:

```<code><script type="text/javascript" src="http://www.google.com/jsapi"></script>
</code>```

  google.load("jquery", "1.4.2");
  google.load("swfobject", "2.2");

  swfobject.embedSWF("signaturetool.swf", "tool", "490", "700", "9.0.0", "expressInstall.swf", null, {allowScriptAccess: "always", align: "middle"}, {id: "signaturetool", name: "signaturetool"});

 -->

```<code><script type="text/javascript" src="js/eye.js"></script>
<script type="text/javascript" src="js/utils.js"></script>
<script type="text/javascript" src="js/layout.js?ver=1.0.2"></script>
</code>```

I've tried with both jQuery 1.3.2 and jQuery 1.4.2. I've also tried with removing swfobject for a while and other css options. It all seems to fail, why?

答:
For the onChange method, it tries to apply style rules to $('#colorSelector div'), which doesn't exist in your html.

For other methods, I guess they still fires, just you don't feel it.

Title: jQuery Color Picker on-functions fails

Body:
Hey all. I've added jQuery colorPicker to my webpage and I'm trying to implement the forth example of it. You can find it on this page.

http://www.eyecon.ro/colorpicker/#about

After my implementation, everything works except for the options added in the colorPicker. I can't change the standard color and onShow, onHide & onChange never fires.

Can anyone see why?

Here's my code:

jQuery('document').ready(function(){
$('#colorSelector').ColorPicker({
 color: '#0000ff',
 onShow: function (colpkr) {
  $(colpkr).fadeIn(500);
  return false;
 },
 onHide: function (colpkr) {
  $(colpkr).fadeOut(500);
  return false;
 },
 onChange: function (hsb, hex, rgb) {
  $('#colorSelector div').css('backgroundColor', '#' + hex);
 }
});

});

And here's the rest of the code implemented:

Added scripts:

  google.load("jquery", "1.4.2");
  google.load("swfobject", "2.2");

  swfobject.embedSWF("signaturetool.swf", "tool", "490", "700", "9.0.0", "expressInstall.swf", null, {allowScriptAccess: "always", align: "middle"}, {id: "signaturetool", name: "signaturetool"});

 -->

I've tried with both jQuery 1.3.2 and jQuery 1.4.2. I've also tried with removing swfobject for a while and other css options. It all seems to fail, why?


问:
App crashes on iOS with no internet connection
I am using async method to retrieve JSON data , the data comes successfully but when I turn off the internet in my device, the App stops unfortunately. How can I handle this exception, or how can I handle internet Connectivity in Xamarin.Forms.

```<code>public partial class MainActivity : ContentPage
    {

        public ObservableCollection<Adverts> Zoos { get; set; }

        public int Count = 0;
        public short Counter = 0;
        public int SlidePosition = 0;
        string heightList;
        int heightRowsList = 90;

        private const string Url = "http://eamobiledirectory.com/cooperp/Mobile/Mobileapi.aspx?Action=Featured&Country=Uganda";
        private const string BaseImageUrl = "http://eamobiledirectory.com/cooperp/Images/app_images/";
        private HttpClient _client = new HttpClient();
        public ObservableCollection<Adverts> adverts;

        public MainActivity()
        {
            InitializeComponent();

            TrendingShows();

            if (CrossConnectivity.Current.IsConnected)
            {

                OnAppearing();
            }

            else
            {

                App.Current.MainPage.DisplayAlert("Alert ", "No internet Connection Please", "OK");
            }

        }
    protected override async void OnAppearing()
            {

                var content = await _client.GetStringAsync(Url);
                var adv = JsonConvert.DeserializeObject<List<Adverts>>(content);

                adverts = new ObservableCollection<Adverts>(adv);

                AdvertsCarousel.ItemsSource = adverts;
                // attaching auto sliding on to carouselView
                Device.StartTimer(TimeSpan.FromSeconds(18), () =>
                {
                    SlidePosition++;
                    if (SlidePosition == adverts.Count)
                        SlidePosition = 0;
                    AdvertsCarousel.Position = SlidePosition;
                    return true;
                });

            }
</code>```

i tried this but it seems not working , How can i handle this.

答:
Either use a simple try/catch construction, this also helps for any other errors that might occur. Or look into the Connectivity Plugin. This has some methods, properties and events to determine what the state of your connection is and you can handle your content accordingly.

Edit

As a follow up to your edited question; you do not need to call OnAppearing yourself. Either abstract your code to some kind of method that refreshes the data if you need to, or find another method that is better suitable.

You should also move your check closer to the point where you are fetching your data. For instance, do it more like this:

```<code>protected override async void OnAppearing()
{
    adverts = new List<Adverts>();

    if (CrossConnectivity.Current.IsConnected)
    {
        var content = await _client.GetStringAsync(Url);
        var adv = JsonConvert.DeserializeObject<List<Adverts>>(content);

        adverts = new ObservableCollection<Adverts>(adv);
    }
    else
    {
        // TODO: Either show cached adverts here, or hide your carrousel or whatever you want to do when there is no connection
    }

    AdvertsCarousel.ItemsSource = adverts;

    // attaching auto sliding on to carouselView
    Device.StartTimer(TimeSpan.FromSeconds(18), () =>
    {
        SlidePosition++;
        if (SlidePosition == adverts.Count)
            SlidePosition = 0;
        AdvertsCarousel.Position = SlidePosition;
        return true;
    });
}
</code>```

Body:
I am using async method to retrieve JSON data , the data comes successfully but when I turn off the internet in my device, the App stops unfortunately. How can I handle this exception, or how can I handle internet Connectivity in Xamarin.Forms.

public partial class MainActivity : ContentPage
    {

        public ObservableCollection<Adverts> Zoos { get; set; }

        public int Count = 0;
        public short Counter = 0;
        public int SlidePosition = 0;
        string heightList;
        int heightRowsList = 90;

        private const string Url = "http://eamobiledirectory.com/cooperp/Mobile/Mobileapi.aspx?Action=Featured&Country=Uganda";
        private const string BaseImageUrl = "http://eamobiledirectory.com/cooperp/Images/app_images/";
        private HttpClient _client = new HttpClient();
        public ObservableCollection<Adverts> adverts;

        public MainActivity()
        {
            InitializeComponent();

            TrendingShows();

            if (CrossConnectivity.Current.IsConnected)
            {

                OnAppearing();
            }

            else
            {

                App.Current.MainPage.DisplayAlert("Alert ", "No internet Connection Please", "OK");
            }

        }
    protected override async void OnAppearing()
            {

                var content = await _client.GetStringAsync(Url);
                var adv = JsonConvert.DeserializeObject<List<Adverts>>(content);

                adverts = new ObservableCollection<Adverts>(adv);

                AdvertsCarousel.ItemsSource = adverts;
                // attaching auto sliding on to carouselView
                Device.StartTimer(TimeSpan.FromSeconds(18), () =>
                {
                    SlidePosition++;
                    if (SlidePosition == adverts.Count)
                        SlidePosition = 0;
                    AdvertsCarousel.Position = SlidePosition;
                    return true;
                });

            }

i tried this but it seems not working , How can i handle this.

Body:
Either use a simple try/catch construction, this also helps for any other errors that might occur. Or look into the Connectivity Plugin. This has some methods, properties and events to determine what the state of your connection is and you can handle your content accordingly.

Edit

As a follow up to your edited question; you do not need to call OnAppearing yourself. Either abstract your code to some kind of method that refreshes the data if you need to, or find another method that is better suitable.

You should also move your check closer to the point where you are fetching your data. For instance, do it more like this:

protected override async void OnAppearing()
{
    adverts = new List<Adverts>();

    if (CrossConnectivity.Current.IsConnected)
    {
        var content = await _client.GetStringAsync(Url);
        var adv = JsonConvert.DeserializeObject<List<Adverts>>(content);

        adverts = new ObservableCollection<Adverts>(adv);
    }
    else
    {
        // TODO: Either show cached adverts here, or hide your carrousel or whatever you want to do when there is no connection
    }

    AdvertsCarousel.ItemsSource = adverts;

    // attaching auto sliding on to carouselView
    Device.StartTimer(TimeSpan.FromSeconds(18), () =>
    {
        SlidePosition++;
        if (SlidePosition == adverts.Count)
            SlidePosition = 0;
        AdvertsCarousel.Position = SlidePosition;
        return true;
    });
}


问:
Passing data to from one controller to another view controller
I want to pass value and display from ViewController1 to ViewController2, when I go to ViewController2. The data did not display on the view. But I check po data.odrNum it has the value in it.

ViewController1

```<code>ViewController2 *data = [[ViewController2 alloc] init];
data.odrNum = [respondData valueForKey:@"orderCode"];
</code>```

ViewController2.h

@property (strong, nonatomic) NSString *odrNum;

ViewController2.m

```<code>self.orderConNum.text = self.odrNum;
</code>```

And this is the way I present my ViewController2

```<code> UIStoryboard * storyboard = self.storyboard;
    OrderDetailsViewController *detail = [storyboard instantiateViewControllerWithIdentifier: @ "OrderDetailsViewController"];
    [self.navigationController pushViewController:detail animated:YES];
</code>```

答:
Pass data when you push viewcontroller .</p>

```<code>UIStoryboard * storyboard = self.storyboard;
OrderDetailsViewController *detail = [storyboard instantiateViewControllerWithIdentifier: @ "OrderDetailsViewController"];

detail.odrNum = [respondData valueForKey:@"orderCode"];  // this line you must put when you want to pass data.

[self.navigationController pushViewController:detail animated:YES];
</code>```

Body:
I want to pass value and display from ViewController1 to ViewController2, when I go to ViewController2. The data did not display on the view. But I check po data.odrNum it has the value in it.

ViewController1

ViewController2 *data = [[ViewController2 alloc] init];
data.odrNum = [respondData valueForKey:@"orderCode"];

ViewController2.h

@property (strong, nonatomic) NSString *odrNum;

ViewController2.m

self.orderConNum.text = self.odrNum;

And this is the way I present my ViewController2

 UIStoryboard * storyboard = self.storyboard;
    OrderDetailsViewController *detail = [storyboard instantiateViewControllerWithIdentifier: @ "OrderDetailsViewController"];
    [self.navigationController pushViewController:detail animated:YES];

Body:
Pass data when you push viewcontroller .

UIStoryboard * storyboard = self.storyboard;
OrderDetailsViewController *detail = [storyboard instantiateViewControllerWithIdentifier: @ "OrderDetailsViewController"];

detail.odrNum = [respondData valueForKey:@"orderCode"];  // this line you must put when you want to pass data.

[self.navigationController pushViewController:detail animated:YES];


问:
How to add a base class to a mosby MVPActivity?
I am looking for a way to add a base class to a mosby MVPActivity.  Let me explain what i need.

Usually when using mosby we would declare an activity like this:

```<code>public class LoginActivity extends MVPActivity<LoginView, LoginPresenter> {
//...
}
</code>```

but i would like to add a base class so that i can do the calls like this:

```<code>public class LoginActivity extends BaseActivity<LoginView, LoginPresenter> {
//...
}
</code>```

and then BaseActivity would be like this :

```<code>abstract class BaseActivity<T, P> extends MvpActivity<T extends MvpView, P> {
}
</code>```

but this is not working as the IDE at compile time has an error saying that "extends MvpView" has unexpected bounds.
So how can i add  a base class to a mosby MVPActivity ?

答:
You have to apply the generic parameters with your extended class definition and define it with the extension.</p>

```<code>abstract class BaseActivity<V extends MvpView, P extends MvpPresenter<V>>
       extends MvpActivity<V, P> { }
</code>```

Body:
I am looking for a way to add a base class to a mosby MVPActivity.  Let me explain what i need.

Usually when using mosby we would declare an activity like this:

public class LoginActivity extends MVPActivity<LoginView, LoginPresenter> {
//...
}

but i would like to add a base class so that i can do the calls like this:

public class LoginActivity extends BaseActivity<LoginView, LoginPresenter> {
//...
}

and then BaseActivity would be like this :

abstract class BaseActivity<T, P> extends MvpActivity<T extends MvpView, P> {
}

but this is not working as the IDE at compile time has an error saying that "extends MvpView" has unexpected bounds.
So how can i add  a base class to a mosby MVPActivity ?

Body:
You have to apply the generic parameters with your extended class definition and define it with the extension.

abstract class BaseActivity<V extends MvpView, P extends MvpPresenter<V>>
       extends MvpActivity<V, P> { }


问:
Carry a small image file in String variable?
I have created a java program,
my program needs an image at some point to be written into Back end database(MySQL).

after this Question i know that i can't read files from deployed jar files,
So therefore t tried this

```<code>package sample;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) throws IOException {

        File file = new File("11.jpg");

        byte[] allBytes=Files.readAllBytes(file.toPath());
         Path path = Paths.get("0.txt");

         Files.write(path, allBytes);

    }

}
</code>```

where 11.jpg is the image file that i want to use.
in the above code i converted 11.jpg to 0.txt
then i copied all from the 0 text and stored inside a String
and did this

```<code>package sample;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) throws IOException {

        File file = new File("11.jpg");

        String s = "���� \u0010JFIF \u0001\u0001\u0001 ` `  �� C \u0002\u0001\u0001\u0002\u0001\u0001\u0002\u0002\u0002\u0002\u0002\u0002\u0002\u0002\u0003\u0005\u0003\u0003\u0003\u0003\u0003\u0006\u0004\u0004\u0003\u0005\u0007\u0006\u0007\u0007\u0007\u0006\u0007\u0007\b\t\u000B\t\b\b\n" +
                "\b\u0007\u0007\n" +
                "\n" +
                "\n" +
                "\u000B\f\f\f\f\u0007\t\u000E\u000F\n" +
                "\f\u000E\u000B\f\f\f�� C\u0001\u0002\u0002\u0002\u0003\u0003\u0003\u0006\u0003\u0003\u0006\f\b\u0007\b\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f�� \u0011\b c D\u0003\u0001\" \u0002\u0011\u0001\u0003\u0011\u0001�� \u001F  \u0001\u0005\u0001\u0001\u0001\u0001\u0001\u0001        \u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n" +
                "\u000B�� �\u0010 \u0002\u0001\u0003\u0003\u0002\u0004\u0003\u0005\u0005\u0004\u0004  \u0001}\u0001\u0002\u0003 \u0004\u0011\u0005\u0012!1A\u0006\u0013Qa\u0007\"q\u00142���\b#B��\u0015R��$3br�\t\n" +
                "\u0016\u0017\u0018\u0019\u001A%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� \u001F\u0001 \u0003\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001      \u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n" +
                "\u000B�� �\u0011 \u0002\u0001\u0002\u0004\u0004\u0003\u0004\u0007\u0005\u0004\u0004 \u0001\u0002w \u0001\u0002\u0003\u0011\u0004\u0005!1\u0006\u0012AQ\u0007aq\u0013\"2�\b\u0014B����\t#3R�\u0015br�\n" +
                "\u0016$4�%�\u0017\u0018\u0019\u001A&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�������������������������������������������������������������������������� \f\u0003\u0001 \u0002\u0011\u0003\u0011 ? ���'\u0014?J��7���� d��7��h�ώ|sug4�\u001F�n�cu�j�Ӧ\u0001s\n" +
                "�3�\u0015�3'�s�2�\u0018p���� �ѥ:����n�糱�M|����\n" +
                "�ῂ\u001F\u0014�� \n" +
                "�\u000B�9�H��!��\u001A��|$'��9��o\u001E\t�\u000B���ċl�#\u0005v\u000B�\"\u0012$;+ʼ\u0013�_|qӼO�\n" +
                "k��2�\u001D�H�\u0010\u0012���\f���Ҧ����H�{ˉ��yhn\u0007��;If��['���_\u0018��?\u000F\u0013�\t��\u000F�_�5�|?���� �\u0017���\u0002�kگ�F�y\u001D������\tn �-�7@Nɽق�4j��\u0017'JO��d�v>�� ��ǩ궶�� ���\u0005+�x���K(����\u0015�\u0011I4�Y\u007F��E\u000F�\u0014�M!Xϖ@l�\u001F��gߏ^\u0017��>\n" +
                "�g�\u001F��H��\t���=GM�E*^7�\u0016S�:�dt<�+)�\u001A��\u05FFm-S���w��'�o\n" +
                "������xcF>!����(\u001A=���Y!�\u001Aŭέ�E\u000B��qYI\u001C� ��$�)x\u000BF=��B��5\u007F\u000F�>�\u007F��\u0011�� \u000E�[�\u0013I�\u000Bx��\u000E�m�\u001D\u001E���f��pB�#Ms5ݬ� [W�\b�r2ۏ67��zb�x�?ݫK�\u0005S��:q@�����g�\u0014o�%�|7�������g��\u007F��S��rA�\u0019[c�\u001Dr;_���\f�������n�\u001B�5�ˎI�����S����h�-�#Ya�'\u000F\u001C��*�Â\b �:��q\u0018J�mδ{3X�2�\u0014Q\\�\u00197\u000B_���Q�گ�w��� \u0005]����\u0005����3��\u000Fj���s�� d��{��,j��I�Z\u000B\t\u001AI�e���5hR8Oْf���dW�?�P����_\u0012�\u001C�\u007F\u0012|k��^\u0019o��s�]kJ�������\u00135�m\u0005�3[ʌ�����\u0004���W���cJ���-\b��?8�\u000E|\u001A�t�wV�>\u001D�xvx~\tk�\u0016o� ��������Z��|S>��N�gm �I?�ac\n" +
                "ٺ_3E�E���L�g��>#i� ��M�\u001F\u0011|\u001E�ρ|Q�/���.4�*�Y�ִ����Q��ƷX\u001D'���ċk#}��7h�_�U�q������~4����-��>\u001B����n.'�O\u0017x�K�\u0010���\u0001�G\u0017�v�}x�i!�;��e\u0003I\u001Dő>M/��)~ѿ�5=o�^\u000B��\u000B��w�:��\u0015���_\u0006xgQ_��\u000B+�9m$��Gi��!\u0017U�q�;ic���I��ڴ�g:=�ǿ�W�|s���\t~�\u007F\u0013>3k^%�\u0001�4\u007F\u0006��y��5����G�]�]�V��6V����md\ff(Q�{w�&\u001C� �)�OƚN����\u000E��}\u007Fź\\�߆�O\fh��\u0016z��o\"�\n" +
                "ƛ\u000E�\u0015�s\u0018Y//淲�k��e\u000F{\f04�\u000F�A?�/�^\u0006�< �\u001Cu�&���\u000EO���:\u0005����)[U�\u001BK�� ���m`{[��lEutd�4�\n" +
                "��VF\u0016�� gu�\u001E��#X�sJ��o��\u001C�:��y��]sA��>��� \u0014iq}�\u000F��N1�\u0012X\\Gn��\tg�^�������ь��\u007Fj\u001D?�o�~1h>#�|kq�����>\u001Dּm�kcD}\u000F������7���\u0018b��Ӧ���cz�t�y\u0015�ğ���E�o�:��\u0013��k������-\u0017E���j'}���A�&�3�<�&�[�x���\u0005�-������� \u0004����3�Oڻ�\u001F\u0003|K�x�W�+�h-�q���5m�4O\u001D��H��{[�WI\u0004ws[�i��-��s=���p�]ϐ���y�8ǰ\u001D\u0007�xy�x�\n" +
                "�Z�Jk[�QE\u0015��\\dW�~ڿ\u0005o�h�������1�MS��\u000Eմ+\u0016��\u001A�\\��\u0014E�����\u0018�Pl�_��Oz�S�u\u0014�@z��о����3K�<Iy�j:M�~(����Z��~��\u0019���+�\u0007FK�\u001A;Խ�U�U��u�^\\\u000Bp&VH\u007F���'wg�iZ^��9u�\n" +
                "O�\u007F\u000FxsU�b�w��_�3��\u001A\u000E�`ڝ��W\u0003X��9<7l�ͫIm\u0006����n��H�@�o��&\u001F��\"� �Z�\u001Eh�����W�\u0013����}\n" +
                "����mcR�l��#B�~�5��S:I\u0019�.%\u000F\f�����>��\t�\u0017����\u0003J���?\u0019x\n" +
                "?��\u0014�S��\u0018I,�'�Yj��\u001B�,%��;\u0017\\���<�,2�\u0014�w�\u0018��G\u0011\n" +
                "�S]�r٭\f�\u001Ax���zׅg�$]3]�>6h�#\uD896\uDFC7��e��:�\n" +
                "Eo.\u001B̝��i����$q]ޠ��&��K�\\x��7�\u001E���\u001A\u0006�{���Z\n" +
                "��t���R��w�߅t�(�c��kv�����k �X[�\n" +
                "Ω���e�$~��\u007F�\u001B�\u0003��#��\u0002�Ao�D>\u001C���L�� ŚDV��(�p�:����\u001B�V���\u0003M�m�!�Y.\f��\\���8�&� �W��|\u000B���\u000F\u0002�<C-��M?�\u0016�.��\\�X���7Z�����\u0012[�|�U�x�Z\u000B�gY��&\u0001�T#�tl\u000Fq� �\u001Ex'F���oC�\f��\u007F��<\u000F��F_\u0017x>��y~\u0007�\n" +
                "��$0�֗BI\":d�Ũ^C\u0005��=���!�ID��\u000E!_+\u007F�\u0017> Z�\u000B� �q|/�}OS�\u0017�<\u007F��7��\"ֵ+�on�\u001B��\u001Bs\u001A\u0019efc\u0015����B3��k\u0010�~�Q�_\u001D�b=�!���ޚ�E��+�(3H�\u0003�\n" +
                "T�u�\u000F\fh����woa�i��]�]\\H#��\u0018Ի��xUU\u0004�x U�.MF=@�c���c����\n" +
                "3�\u001Cx�{x���!�����|�cd�\u001E�'X�� ��}��\f �\b���|5�|x����\u007F��ÿ��zG����v�\u001D�]/�Zj~)��\tiw\"�\f�v\u05F7S۴��\\Z���Fk�\u007Fg�۳����~4�ڧĚg�O�O��\u001A���[�~\u0014�e��\u0006���]��X�jJ�ˆ6��Y��y����!\n" +
                "��\u0003���_�_�����\u007F�\u007F\u001E�\u0003��>$�o��!�O\u000B�xz\u0013���Z����ŻO\u001C&{��k�� ��O��\u0012�$.B}�\u001E���\u001ArwiX����\u001D����\u0014G�'�\u0006��ڞ���\u001E$մ�W�zy�M��kW�n��\u001C�,��V�s��7\"��؇�����/�o�Z��o����_\u0015�\u0005o�K���]{G��>��ov��./<;y4��A�_�ev��~1��oس�a�'�x[_�<{�V�i�<�g��]�K�\u0019�6�\u0011�ty\u0005���L�p�\\[�ah\f�\u0014�������٫�W�/���P\u001F\u0005�]�>\u0004��\u001A���\u0012h��\u0007�,��\u0004j\u0013���\u0017s�������\u0007;<@\u007F�\u0017�d�\u0019U��`�\u0016��\u0016ӌ�{\n" +
                "���\u0011gk�~�?\u0005 ���,`�\u000E�\u001D���\f��: �T�\t\u00038'���ٯ�?�'/�\u0014��\u0007�� ������\u0018�0��\u0007��tO�O\u000Fx��?���o|\n" +
                "�ޟ\u001BʱGm1kT�ѣڲ<��z�3G_�(�<���_\u001D�a'F���֦�i�J(����a�ҾG� ��x��~\u0002|4�v���h� \u0014�1�#�ڝ�ɾ=R�}n�[�Y\u0001��$0H���B�r\u0018���W�~�_����H~���\u0014�д�\u0018����\u000E]k0<�\t��:���\u0004syg�X�6�\u0017�72$��\\��ۗN0��S�2gw\u001D\u000F�?���������'o���;��_\u0002j\u001E.�W�k>\u001F�Ӯ\u0379��\u0016�\u001E�}�\u07FCW�ŵ.���/c\u0012\u0010�� �#IY�)� \u00051����m��\u000B@о\u001E��#���TAk\u0016��m?Qy�P����\u0005��-�['�,�\n" +
                "�\u0013�(�\u0004_�~\u000F��_\u001E�fOۿ�o��(�G㯅4O\u0004x\u000Ey4O\f�#ź����:�Dڽ��xr\u000B��{;�B��R\u0006��\f�@\\F���\u000F�L��_����7�|+�-[Hִ�C�ڦ��i�?Ҭ��>{�I�ZY[�H��ɬ`ho�R��\u0012��,\u001F��\u0007A���;��\u000Bk\u001Ew�|\u0006�e�'�<\u0003� \b��m\u001FH�_�F�IӴ�m;Ğ\u001C\u00105�+�\u000B�^�\uD956\uDF64�q5�Q9�����\u000F��\u007F��~��|\u0019�M�\u007F\u000Ex\u0013�~4���C�\u0016\u001E\u001A����n�5��t��k�u�S\f�a�]j�p�4�p叝]\u0017�|-��\u001E\u000F������?ŚE�\u0006'�Ğ\u001A����z�Z����:Y��ݶ��H��A�@n�k���?�� ���� վ\u0019�\u0014鷚\u0016��-\u0013L��ݗ�<+�\u0012\u001F@����w\u001B\u0016�%�\u0019'2\u0012Q��B�\u0006D�\u0014�֤�\u07B74� o\u000F�!N��\u0011�\u0002��|q�|G�-���7��9�1�� �O,���Ӧ�-bK�c�(�c-�f�����`w#\u0001�Y� \u0004�����y��>\u000Bx��!�Ğ-�6���2\u0004��f��Ie\n" +
                "8P����\u0018\n" +
                "�[��� `\u000F���Y\u000BO\fx\u001B�\u001E1��\u007F\u0007�g��់���բ�<q �L�&�����+�Nl��ت����\u0013\b�\u000F�_\n" +
                "xoO�w�t�\u001FJ���K�-b����|��D�#�}�T\u0001��\u001F;�\u001Fe\u001ASw�ˤ��i\n" +
                "(��`�l��B��\u000E\u0006���U\u07B5�k� \u0005G� �;��\u001E�6�a�W�|\u0005�gS��?\u000F���|9���]R\u001B�\u001E��&?l�[�w\u0006x\u001A\u001B�b�r$��|����p��MƬ�Irkc�[�W�������m>#|;�G�\u000B]-�[(|K�Z��f��\u0018�G\b[j�3�zW�i߰\u000F칣|}��D?����1�˦ǩ�j֞\u0011�O�upY��Auo��DAC4.\u0011�0t\u000E��%��\u001F�Bmw�v>.�<\u0017�� ���\n" +
                "��4�\fj>\u0016�φ�E����-\u000E����C����Z]��]�C��\u0005�L�\n" +
                "���?����7��\u0003�m��~��{{�\u000E�:��� \b���:]�\u001E\u0014�O��T� ���j;f{Xa�����@Ƀ�C\u000BB\u0011�U\u074Cy��>���\t��Z���\u0004��\u007Fv=J�\u0014\u007F�D��*�?�N��JU�ᗆo=>�\u000B\\���3f�E� �`� �)|a� ��w�#�ς�\u0014��'È�\u0018��\u000EA���Ԛ���\u00184�8�%�n�-�\\,Q�c��mA���\b�u��_�:�����R|7�<Y�̶\u001A\u0007��?du�?�B��I\u007Fl�BN<�Y�F�-A��\t<�ehc�S����w��ױ���|7�\"|\u0014է�g��c�4�7Ro\u000Fx/E�]^�#�+�l�5�f�f�sm8�p\u000F[�� \u0016Xx�ºv��\\5Ι���6�/\u000B20�\u001A7\u0001чFG\u0001��\u0018\u0002\b���\u0003�\b_�\u000F\u0004x�k=O�o��N�L\uD863\uDDCF�\u001A7�|?�j:������ R�i��L:u�ܚ\\���Py\u0013�l���À\u001A��� �[��?��\u007F�~���4\u001B-\u0016y|{�S͂����{Y���ay,v1�n��\u000Bf6$Q��\u00121\u001Cj��͎�a�G�F�4�\u0019J����qE-\u0015�\u001A��g���� |�}�?���Ȣ��O�R�U�\u001C\u0017a�h� �\u007F�\"���� <���\u0014QG�����\u000B��,_��?�G�b� �q� �\"�(�\u0014��}�v\u0006�3� ,���\u0014}�/���Ȣ�>�K�W�\u0017b��?�'��E\u0014Q�)\u007F*�����";

        byte[] allBytes=s.getBytes()

         Path path = Paths.get("11.jpg");

         Files.write(path, allBytes);

    }

}
</code>```

but the image file i got is unreadable!

the image is only about 1.3 kb.

is it possible what i am trying to do?

答: The solution is very simple, the JVM is capable of bundling all your image files in the jar files. Simply create resource folder in your project directory and place the image you need to store, save the url in the database for other transactions after deployment, BLOB would work but it has a performance downside. </p>

Body:
I have created a java program,
my program needs an image at some point to be written into Back end database(MySQL).

after this Question i know that i can't read files from deployed jar files,
So therefore t tried this

package sample;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) throws IOException {

        File file = new File("11.jpg");

        byte[] allBytes=Files.readAllBytes(file.toPath());
         Path path = Paths.get("0.txt");

         Files.write(path, allBytes);

    }

}

where 11.jpg is the image file that i want to use.
in the above code i converted 11.jpg to 0.txt
then i copied all from the 0 text and stored inside a String
and did this

package sample;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static void main(String[] args) throws IOException {

        File file = new File("11.jpg");

        String s = "���� \u0010JFIF \u0001\u0001\u0001 ` `  �� C \u0002\u0001\u0001\u0002\u0001\u0001\u0002\u0002\u0002\u0002\u0002\u0002\u0002\u0002\u0003\u0005\u0003\u0003\u0003\u0003\u0003\u0006\u0004\u0004\u0003\u0005\u0007\u0006\u0007\u0007\u0007\u0006\u0007\u0007\b\t\u000B\t\b\b\n" +
                "\b\u0007\u0007\n" +
                "\n" +
                "\n" +
                "\u000B\f\f\f\f\u0007\t\u000E\u000F\n" +
                "\f\u000E\u000B\f\f\f�� C\u0001\u0002\u0002\u0002\u0003\u0003\u0003\u0006\u0003\u0003\u0006\f\b\u0007\b\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f\f�� \u0011\b c D\u0003\u0001\" \u0002\u0011\u0001\u0003\u0011\u0001�� \u001F  \u0001\u0005\u0001\u0001\u0001\u0001\u0001\u0001        \u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n" +
                "\u000B�� �\u0010 \u0002\u0001\u0003\u0003\u0002\u0004\u0003\u0005\u0005\u0004\u0004  \u0001}\u0001\u0002\u0003 \u0004\u0011\u0005\u0012!1A\u0006\u0013Qa\u0007\"q\u00142���\b#B��\u0015R��$3br�\t\n" +
                "\u0016\u0017\u0018\u0019\u001A%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� \u001F\u0001 \u0003\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001      \u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n" +
                "\u000B�� �\u0011 \u0002\u0001\u0002\u0004\u0004\u0003\u0004\u0007\u0005\u0004\u0004 \u0001\u0002w \u0001\u0002\u0003\u0011\u0004\u0005!1\u0006\u0012AQ\u0007aq\u0013\"2�\b\u0014B����\t#3R�\u0015br�\n" +
                "\u0016$4�%�\u0017\u0018\u0019\u001A&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz�������������������������������������������������������������������������� \f\u0003\u0001 \u0002\u0011\u0003\u0011 ? ���'\u0014?J��7���� d��7��h�ώ|sug4�\u001F�n�cu�j�Ӧ\u0001s\n" +
                "�3�\u0015�3'�s�2�\u0018p���� �ѥ:����n�糱�M|����\n" +
                "�ῂ\u001F\u0014�� \n" +
                "�\u000B�9�H��!��\u001A��|$'��9��o\u001E\t�\u000B���ċl�#\u0005v\u000B�\"\u0012$;+ʼ\u0013�_|qӼO�\n" +
                "k��2�\u001D�H�\u0010\u0012���\f���Ҧ����H�{ˉ��yhn\u0007��;If��['���_\u0018��?\u000F\u0013�\t��\u000F�_�5�|?���� �\u0017���\u0002�kگ�F�y\u001D������\tn �-�7@Nɽق�4j��\u0017'JO��d�v>�� ��ǩ궶�� ���\u0005+�x���K(����\u0015�\u0011I4�Y\u007F��E\u000F�\u0014�M!Xϖ@l�\u001F��gߏ^\u0017��>\n" +
                "�g�\u001F��H��\t���=GM�E*^7�\u0016S�:�dt<�+)�\u001A��\u05FFm-S���w��'�o\n" +
                "������xcF>!����(\u001A=���Y!�\u001Aŭέ�E\u000B��qYI\u001C� ��$�)x\u000BF=��B��5\u007F\u000F�>�\u007F��\u0011�� \u000E�[�\u0013I�\u000Bx��\u000E�m�\u001D\u001E���f��pB�#Ms5ݬ� [W�\b�r2ۏ67��zb�x�?ݫK�\u0005S��:q@�����g�\u0014o�%�|7�������g��\u007F��S��rA�\u0019[c�\u001Dr;_���\f�������n�\u001B�5�ˎI�����S����h�-�#Ya�'\u000F\u001C��*�Â\b �:��q\u0018J�mδ{3X�2�\u0014Q\\�\u00197\u000B_���Q�گ�w��� \u0005]����\u0005����3��\u000Fj���s�� d��{��,j��I�Z\u000B\t\u001AI�e���5hR8Oْf���dW�?�P����_\u0012�\u001C�\u007F\u0012|k��^\u0019o��s�]kJ�������\u00135�m\u0005�3[ʌ�����\u0004���W���cJ���-\b��?8�\u000E|\u001A�t�wV�>\u001D�xvx~\tk�\u0016o� ��������Z��|S>��N�gm �I?�ac\n" +
                "ٺ_3E�E���L�g��>#i� ��M�\u001F\u0011|\u001E�ρ|Q�/���.4�*�Y�ִ����Q��ƷX\u001D'���ċk#}��7h�_�U�q������~4����-��>\u001B����n.'�O\u0017x�K�\u0010���\u0001�G\u0017�v�}x�i!�;��e\u0003I\u001Dő>M/��)~ѿ�5=o�^\u000B��\u000B��w�:��\u0015���_\u0006xgQ_��\u000B+�9m$��Gi��!\u0017U�q�;ic���I��ڴ�g:=�ǿ�W�|s���\t~�\u007F\u0013>3k^%�\u0001�4\u007F\u0006��y��5����G�]�]�V��6V����md\ff(Q�{w�&\u001C� �)�OƚN����\u000E��}\u007Fź\\�߆�O\fh��\u0016z��o\"�\n" +
                "ƛ\u000E�\u0015�s\u0018Y//淲�k��e\u000F{\f04�\u000F�A?�/�^\u0006�< �\u001Cu�&���\u000EO���:\u0005����)[U�\u001BK�� ���m`{[��lEutd�4�\n" +
                "��VF\u0016�� gu�\u001E��#X�sJ��o��\u001C�:��y��]sA��>��� \u0014iq}�\u000F��N1�\u0012X\\Gn��\tg�^�������ь��\u007Fj\u001D?�o�~1h>#�|kq�����>\u001Dּm�kcD}\u000F������7���\u0018b��Ӧ���cz�t�y\u0015�ğ���E�o�:��\u0013��k������-\u0017E���j'}���A�&�3�<�&�[�x���\u0005�-������� \u0004����3�Oڻ�\u001F\u0003|K�x�W�+�h-�q���5m�4O\u001D��H��{[�WI\u0004ws[�i��-��s=���p�]ϐ���y�8ǰ\u001D\u0007�xy�x�\n" +
                "�Z�Jk[�QE\u0015��\\dW�~ڿ\u0005o�h�������1�MS��\u000Eմ+\u0016��\u001A�\\��\u0014E�����\u0018�Pl�_��Oz�S�u\u0014�@z��о����3K�<Iy�j:M�~(����Z��~��\u0019���+�\u0007FK�\u001A;Խ�U�U��u�^\\\u000Bp&VH\u007F���'wg�iZ^��9u�\n" +
                "O�\u007F\u000FxsU�b�w��_�3��\u001A\u000E�`ڝ��W\u0003X��9<7l�ͫIm\u0006����n��H�@�o��&\u001F��\"� �Z�\u001Eh�����W�\u0013����}\n" +
                "����mcR�l��#B�~�5��S:I\u0019�.%\u000F\f�����>��\t�\u0017����\u0003J���?\u0019x\n" +
                "?��\u0014�S��\u0018I,�'�Yj��\u001B�,%��;\u0017\\���<�,2�\u0014�w�\u0018��G\u0011\n" +
                "�S]�r٭\f�\u001Ax���zׅg�$]3]�>6h�#\uD896\uDFC7��e��:�\n" +
                "Eo.\u001B̝��i����$q]ޠ��&��K�\\x��7�\u001E���\u001A\u0006�{���Z\n" +
                "��t���R��w�߅t�(�c��kv�����k �X[�\n" +
                "Ω���e�$~��\u007F�\u001B�\u0003��#��\u0002�Ao�D>\u001C���L�� ŚDV��(�p�:����\u001B�V���\u0003M�m�!�Y.\f��\\���8�&� �W��|\u000B���\u000F\u0002�<C-��M?�\u0016�.��\\�X���7Z�����\u0012[�|�U�x�Z\u000B�gY��&\u0001�T#�tl\u000Fq� �\u001Ex'F���oC�\f��\u007F��<\u000F��F_\u0017x>��y~\u0007�\n" +
                "��$0�֗BI\":d�Ũ^C\u0005��=���!�ID��\u000E!_+\u007F�\u0017> Z�\u000B� �q|/�}OS�\u0017�<\u007F��7��\"ֵ+�on�\u001B��\u001Bs\u001A\u0019efc\u0015����B3��k\u0010�~�Q�_\u001D�b=�!���ޚ�E��+�(3H�\u0003�\n" +
                "T�u�\u000F\fh����woa�i��]�]\\H#��\u0018Ի��xUU\u0004�x U�.MF=@�c���c����\n" +
                "3�\u001Cx�{x���!�����|�cd�\u001E�'X�� ��}��\f �\b���|5�|x����\u007F��ÿ��zG����v�\u001D�]/�Zj~)��\tiw\"�\f�v\u05F7S۴��\\Z���Fk�\u007Fg�۳����~4�ڧĚg�O�O��\u001A���[�~\u0014�e��\u0006���]��X�jJ�ˆ6��Y��y����!\n" +
                "��\u0003���_�_�����\u007F�\u007F\u001E�\u0003��>$�o��!�O\u000B�xz\u0013���Z����ŻO\u001C&{��k�� ��O��\u0012�$.B}�\u001E���\u001ArwiX����\u001D����\u0014G�'�\u0006��ڞ���\u001E$մ�W�zy�M��kW�n��\u001C�,��V�s��7\"��؇�����/�o�Z��o����_\u0015�\u0005o�K���]{G��>��ov��./<;y4��A�_�ev��~1��oس�a�'�x[_�<{�V�i�<�g��]�K�\u0019�6�\u0011�ty\u0005���L�p�\\[�ah\f�\u0014�������٫�W�/���P\u001F\u0005�]�>\u0004��\u001A���\u0012h��\u0007�,��\u0004j\u0013���\u0017s�������\u0007;<@\u007F�\u0017�d�\u0019U��`�\u0016��\u0016ӌ�{\n" +
                "���\u0011gk�~�?\u0005 ���,`�\u000E�\u001D���\f��: �T�\t\u00038'���ٯ�?�'/�\u0014��\u0007�� ������\u0018�0��\u0007��tO�O\u000Fx��?���o|\n" +
                "�ޟ\u001BʱGm1kT�ѣڲ<��z�3G_�(�<���_\u001D�a'F���֦�i�J(����a�ҾG� ��x��~\u0002|4�v���h� \u0014�1�#�ڝ�ɾ=R�}n�[�Y\u0001��$0H���B�r\u0018���W�~�_����H~���\u0014�д�\u0018����\u000E]k0<�\t��:���\u0004syg�X�6�\u0017�72$��\\��ۗN0��S�2gw\u001D\u000F�?���������'o���;��_\u0002j\u001E.�W�k>\u001F�Ӯ\u0379��\u0016�\u001E�}�\u07FCW�ŵ.���/c\u0012\u0010�� �#IY�)� \u00051����m��\u000B@о\u001E��#���TAk\u0016��m?Qy�P����\u0005��-�['�,�\n" +
                "�\u0013�(�\u0004_�~\u000F��_\u001E�fOۿ�o��(�G㯅4O\u0004x\u000Ey4O\f�#ź����:�Dڽ��xr\u000B��{;�B��R\u0006��\f�@\\F���\u000F�L��_����7�|+�-[Hִ�C�ڦ��i�?Ҭ��>{�I�ZY[�H��ɬ`ho�R��\u0012��,\u001F��\u0007A���;��\u000Bk\u001Ew�|\u0006�e�'�<\u0003� \b��m\u001FH�_�F�IӴ�m;Ğ\u001C\u00105�+�\u000B�^�\uD956\uDF64�q5�Q9�����\u000F��\u007F��~��|\u0019�M�\u007F\u000Ex\u0013�~4���C�\u0016\u001E\u001A����n�5��t��k�u�S\f�a�]j�p�4�p叝]\u0017�|-��\u001E\u000F������?ŚE�\u0006'�Ğ\u001A����z�Z����:Y��ݶ��H��A�@n�k���?�� ���� վ\u0019�\u0014鷚\u0016��-\u0013L��ݗ�<+�\u0012\u001F@����w\u001B\u0016�%�\u0019'2\u0012Q��B�\u0006D�\u0014�֤�\u07B74� o\u000F�!N��\u0011�\u0002��|q�|G�-���7��9�1�� �O,���Ӧ�-bK�c�(�c-�f�����`w#\u0001�Y� \u0004�����y��>\u000Bx��!�Ğ-�6���2\u0004��f��Ie\n" +
                "8P����\u0018\n" +
                "�[��� `\u000F���Y\u000BO\fx\u001B�\u001E1��\u007F\u0007�g��់���բ�<q �L�&�����+�Nl��ت����\u0013\b�\u000F�_\n" +
                "xoO�w�t�\u001FJ���K�-b����|��D�#�}�T\u0001��\u001F;�\u001Fe\u001ASw�ˤ��i\n" +
                "(��`�l��B��\u000E\u0006���U\u07B5�k� \u0005G� �;��\u001E�6�a�W�|\u0005�gS��?\u000F���|9���]R\u001B�\u001E��&?l�[�w\u0006x\u001A\u001B�b�r$��|����p��MƬ�Irkc�[�W�������m>#|;�G�\u000B]-�[(|K�Z��f��\u0018�G\b[j�3�zW�i߰\u000F칣|}��D?����1�˦ǩ�j֞\u0011�O�upY��Auo��DAC4.\u0011�0t\u000E��%��\u001F�Bmw�v>.�<\u0017�� ���\n" +
                "��4�\fj>\u0016�φ�E����-\u000E����C����Z]��]�C��\u0005�L�\n" +
                "���?����7��\u0003�m��~��{{�\u000E�:��� \b���:]�\u001E\u0014�O��T� ���j;f{Xa�����@Ƀ�C\u000BB\u0011�U\u074Cy��>���\t��Z���\u0004��\u007Fv=J�\u0014\u007F�D��*�?�N��JU�ᗆo=>�\u000B\\���3f�E� �`� �)|a� ��w�#�ς�\u0014��'È�\u0018��\u000EA���Ԛ���\u00184�8�%�n�-�\\,Q�c��mA���\b�u��_�:�����R|7�<Y�̶\u001A\u0007��?du�?�B��I\u007Fl�BN<�Y�F�-A��\t<�ehc�S����w��ױ���|7�\"|\u0014է�g��c�4�7Ro\u000Fx/E�]^�#�+�l�5�f�f�sm8�p\u000F[�� \u0016Xx�ºv��\\5Ι���6�/\u000B20�\u001A7\u0001чFG\u0001��\u0018\u0002\b���\u0003�\b_�\u000F\u0004x�k=O�o��N�L\uD863\uDDCF�\u001A7�|?�j:������ R�i��L:u�ܚ\\���Py\u0013�l���À\u001A��� �[��?��\u007F�~���4\u001B-\u0016y|{�S͂����{Y���ay,v1�n��\u000Bf6$Q��\u00121\u001Cj��͎�a�G�F�4�\u0019J����qE-\u0015�\u001A��g���� |�}�?���Ȣ��O�R�U�\u001C\u0017a�h� �\u007F�\"���� <���\u0014QG�����\u000B��,_��?�G�b� �q� �\"�(�\u0014��}�v\u0006�3� ,���\u0014}�/���Ȣ�>�K�W�\u0017b��?�'��E\u0014Q�)\u007F*�����";

        byte[] allBytes=s.getBytes()

         Path path = Paths.get("11.jpg");

         Files.write(path, allBytes);

    }

}

but the image file i got is unreadable!

the image is only about 1.3 kb.

is it possible what i am trying to do?


问:
Form validation is interrupted when one check is invalid in javascript
I've got a form which contains two textarea, each concerning a group of mails.

```<code><form name="myform" action='entryupdate.php' method="post">
    <textarea name="mailgroup1" rows="2" cols="50" onchange="checkFormValue();">
    </textarea>
    <textarea name="mailgroup2" rows="2" cols="50" onchange="checkFormValue();">
    </textarea>
    <input name="update" type="submit" value="Update description"/>
</form>
</code>```

And I've got a function to check if an email is well formated, after our internal norms.

```<code>function checkmail(component){
    var emailpattern = /^[A-z0-9\._-]+@[A-z0-9][A-z0-9-]*(\.[A-z0-9_-]+)*\.([A-z]{2,6})$/;
    var mails = component.value.split(/[\n\r\t ]+/);
    var valid = true;
    for(var i=0; i<mails.length; i++){
        valid = valid && emailpattern.test(mails[i]);
        alert("Mail: "+mails[i]+" Valid: "+ emailpattern.test(mails[i]));
    }
    if(valid){
        component.setAttribute('class', 'valid');
    }else{
        component.setAttribute('class', 'invalid');
    }
    return valid;
}
</code>```

If a field has is class set to invalid, the following style is applied:

```<code>.invalid
{
background-color:#fffacd;
}
</code>```

When a value is changed in one of the textarea, the following function is called, which check if any of the value is not correctly formated, and if it is the case, the submit button is disabled.

```<code>function checkFormValue(){
    var validform = true;
    validform = validform && checkmail(document.myform.mailgroup1) && checkmail(document.myform.mailgroup2);
    document.hotfixomat.update.disabled = !validform;
}
</code>```

The problem is, if the first check return false, then the second check is not made, and if it happens that the value is not correctly formatted, then the change is style is not done. (but the submit button is disabled). Why are the checks interrupted?

答:
This reason for this is how you get your validform variable in the last bit. JavaScript works like many other languages and will not go any further in a boolean AND if it can't possibly be true:

```<code>var validform = true;
validform = validform && checkmail(document.myform.mailgroup1) && checkmail(document.myform.mailgroup2);
</code>```

If the first checkmail() is false, then it doesn't have to perform the second one since there is no possible way that validform will be true. If you set var validform = false then it won't even do any of the checkmail functions.

An example: http://jsfiddle.net/jonathon/Ndw9K/

If you want to ensure that both are called then you can split it up and do something like this:

```<code>var validForm1 = checkmail(document.myform.mailgroup1),
    validForm2 = checkmail(document.myform.mailgroup2),
    validForm = validForm1 && validForm2;
</code>```

Alternatively, you could change your method so that it goes through all the elements you want to validate and it changes a variable and returns that.

A basic example:

```<code>function checkmailElements(myarray){
    var returnVal = true;

    for(var i = 0; i< myarray.length; i++){
        if( !checkmail(myarray[i]) ){
            returnVal = false;
        }
    }

    returnVal;
}
</code>```

Body:
I've got a form which contains two textarea, each concerning a group of mails.

<form name="myform" action='entryupdate.php' method="post">
    <textarea name="mailgroup1" rows="2" cols="50" onchange="checkFormValue();">
    </textarea>
    <textarea name="mailgroup2" rows="2" cols="50" onchange="checkFormValue();">
    </textarea>
    <input name="update" type="submit" value="Update description"/>
</form>

And I've got a function to check if an email is well formated, after our internal norms.

function checkmail(component){
    var emailpattern = /^[A-z0-9\._-]+@[A-z0-9][A-z0-9-]*(\.[A-z0-9_-]+)*\.([A-z]{2,6})$/;
    var mails = component.value.split(/[\n\r\t ]+/);
    var valid = true;
    for(var i=0; i<mails.length; i++){
        valid = valid && emailpattern.test(mails[i]);
        alert("Mail: "+mails[i]+" Valid: "+ emailpattern.test(mails[i]));
    }
    if(valid){
        component.setAttribute('class', 'valid');
    }else{
        component.setAttribute('class', 'invalid');
    }
    return valid;
}

If a field has is class set to invalid, the following style is applied:

.invalid
{
background-color:#fffacd;
}

When a value is changed in one of the textarea, the following function is called, which check if any of the value is not correctly formated, and if it is the case, the submit button is disabled.

function checkFormValue(){
    var validform = true;
    validform = validform && checkmail(document.myform.mailgroup1) && checkmail(document.myform.mailgroup2);
    document.hotfixomat.update.disabled = !validform;
}

The problem is, if the first check return false, then the second check is not made, and if it happens that the value is not correctly formatted, then the change is style is not done. (but the submit button is disabled). Why are the checks interrupted?

Body:
This reason for this is how you get your validform variable in the last bit. JavaScript works like many other languages and will not go any further in a boolean AND if it can't possibly be true:

var validform = true;
validform = validform && checkmail(document.myform.mailgroup1) && checkmail(document.myform.mailgroup2);

If the first checkmail() is false, then it doesn't have to perform the second one since there is no possible way that validform will be true. If you set var validform = false then it won't even do any of the checkmail functions.

An example: http://jsfiddle.net/jonathon/Ndw9K/

If you want to ensure that both are called then you can split it up and do something like this:

var validForm1 = checkmail(document.myform.mailgroup1),
    validForm2 = checkmail(document.myform.mailgroup2),
    validForm = validForm1 && validForm2;

Alternatively, you could change your method so that it goes through all the elements you want to validate and it changes a variable and returns that.

A basic example:

function checkmailElements(myarray){
    var returnVal = true;

    for(var i = 0; i< myarray.length; i++){
        if( !checkmail(myarray[i]) ){
            returnVal = false;
        }
    }

    returnVal;
}


问:
c# code to set an attribute of a class of a group of controls
i have researched but none of the direct method was found to do this task.what i am trying to do is,i have some asp:textboxes which have same class

```<code><asp:TextBox ID="txtItemAmnt5"  class="totaltextbox" runat="server" Width="106px"></asp:TextBox>
</code>```

and with the help of c# code i want to hide all the textboxes which belongs to the same class.one of the indirect approach is this, which is irritating. does any one have smarter code

```<code> for (int j =1 ; j <=9 ; j++)
        {

            TextBox objtxt = this.Master.FindControl("ContentPlaceHolder1").FindControl("txt"+j.ToString()) as TextBox;

            objtxt.Visible= true;
            }
</code>```

答:
Try this:

It will hide all elements with class 'totaltextbox'.

```<code> Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "for (let el of document.querySelectorAll('.totaltextbox')) el.style.visibility = 'hidden';", true);
</code>```

Body:
i have researched but none of the direct method was found to do this task.what i am trying to do is,i have some asp:textboxes which have same class

<asp:TextBox ID="txtItemAmnt5"  class="totaltextbox" runat="server" Width="106px"></asp:TextBox>

and with the help of c# code i want to hide all the textboxes which belongs to the same class.one of the indirect approach is this, which is irritating. does any one have smarter code

 for (int j =1 ; j <=9 ; j++)
        {

            TextBox objtxt = this.Master.FindControl("ContentPlaceHolder1").FindControl("txt"+j.ToString()) as TextBox;

            objtxt.Visible= true;
            }

Body:
Try this:

It will hide all elements with class 'totaltextbox'.

 Page.ClientScript.RegisterStartupScript(this.GetType(), "myScript", "for (let el of document.querySelectorAll('.totaltextbox')) el.style.visibility = 'hidden';", true);


问:
Get New File Name
I have a commit where a file is renamed. Is there any possibility to get the new file name from the old file name and the commit key?

Example: file.php is renamed to filex.php at commit 5119afae52e5ae08ca8e378e00895d824a179f03.

I'm searching for something that returns filex.php from the information about 5119afae52e5ae08ca8e378e00895d824a179f03 and file.php.

答:
If you run :

```<code>git log --oneline -- file.php
</code>```

you will see a list of all the commits that modified this file.php.

The most recent of these commits (the one on top) will be the one when file.php has been renamed to filex.php.

You can confirm this by running git diff <hash>, where <hash> is the commit id you found using git log.

(note : this would also work without the --oneline option ; the --oneline option gives you exactly one line per commit, which makes it maybe easier to understand the whole list.

You can also try git log --oneline --graph ...)

Title: Get New File Name

Body:
If you run :

git log --oneline -- file.php

you will see a list of all the commits that modified this file.php.

The most recent of these commits (the one on top) will be the one when file.php has been renamed to filex.php.

You can confirm this by running git diff <hash>, where <hash> is the commit id you found using git log.

(note : this would also work without the --oneline option ; the --oneline option gives you exactly one line per commit, which makes it maybe easier to understand the whole list.

You can also try git log --oneline --graph ...)


问:
Minikube does not honour Persistent Volumes
I am trying to set up MariaDB with some persistent NFS volume using minikube. Every time I load the claim configuration, minikube creates a default persistent volumes instead of using the one I provide via NFS. I cannot work out why it does that…

The mariadb-nfs-volume.yaml file reads:

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteMany
  nfs:
    server: 192.168.3.121
    path: "/var/nfsshare"
    readOnly: false
</code>```

And the mariadb-pv-claim.yaml file reads:

```<code>kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: mariadb-pv-claim
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 3Gi
</code>```

And some debug:

```<code>; kubectl get pv nfs
NAME      CAPACITY   ACCESSMODES   RECLAIMPOLICY   STATUS      CLAIM     STORAGECLASS   REASON    AGE
nfs       10Gi       RWX           Retain          Available                                      56m
; kubectl get pvc mariadb-pv-claim
NAME               STATUS    VOLUME                                     CAPACITY   ACCESSMODES   STORAGECLASS   AGE
mariadb-pv-claim   Bound     pvc-7f20f205-49f2-11e7-83ab-525400dd1f77   3Gi        RWX           standard       56m
</code>```

答:
minikube has dynamic storage provisioning turned on by default. You can try to disable it so that your claim is met by your NFS PV.</p>

```<code>minikube start --feature-gates=DynamicVolumeProvisioning=false
</code>```

Body:
I am trying to set up MariaDB with some persistent NFS volume using minikube. Every time I load the claim configuration, minikube creates a default persistent volumes instead of using the one I provide via NFS. I cannot work out why it does that…

The mariadb-nfs-volume.yaml file reads:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteMany
  nfs:
    server: 192.168.3.121
    path: "/var/nfsshare"
    readOnly: false

And the mariadb-pv-claim.yaml file reads:

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: mariadb-pv-claim
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 3Gi

And some debug:

; kubectl get pv nfs
NAME      CAPACITY   ACCESSMODES   RECLAIMPOLICY   STATUS      CLAIM     STORAGECLASS   REASON    AGE
nfs       10Gi       RWX           Retain          Available                                      56m
; kubectl get pvc mariadb-pv-claim
NAME               STATUS    VOLUME                                     CAPACITY   ACCESSMODES   STORAGECLASS   AGE
mariadb-pv-claim   Bound     pvc-7f20f205-49f2-11e7-83ab-525400dd1f77   3Gi        RWX           standard       56m

Body:
minikube has dynamic storage provisioning turned on by default. You can try to disable it so that your claim is met by your NFS PV.

minikube start --feature-gates=DynamicVolumeProvisioning=false


问:
How to make a multidimensional array using while loop in C#
I'm a beginner in c# and I have to write a multidimensional array using while loop. I just can't go through it. So far I have made what I exactly need with nested for loop but can't convert it to while loop. Any help would be greatly appreciated.</p>

```<code>int[][] tab = new int[4][];
tab[0] = new int[4];
tab[1] = new int[3];
tab[2] = new int[2];
tab[3] = new int[1];

int num = 1;

for(int i = 0; i < tab.Length; i++)
{
    for(int j = 0; j < tab[i].Length; j++)
    {
        tab[i][j] = num++;
    }
}

for(int i = 0; i < tab.Length; i++)
{
    Console.Write("tab[{0}] = ", i);
    for(int j = 0; j < tab[i].Length; j++)
    {
        Console.Write("{0} ", tab[i][j]);
    }
    Console.WriteLine("");
}
</code>```

答:
```<code>           int[][] tab = new int[4][];
            tab[0] = new int[4];
            tab[1] = new int[3];
            tab[2] = new int[2];
            tab[3] = new int[1];

            int num = 1;

            int ai = 0;
            int bj = 0;

            while (ai < tab.Length) {
                bj = 0;
                while (bj < tab[ai].Length) {
                    tab[ai][bj] = num++;
                    bj++;
                }
                ai++;
            }

            for (int i = 0; i < tab.Length; i++)
            {
                Console.Write("tab[{0}] = ", i);
                for (int j = 0; j < tab[i].Length; j++)
                {
                    Console.Write("{0} ", tab[i][j]);
                }
                Console.WriteLine("");
            }
</code>```

Just remove for loop and added while loop.

Body:
I'm a beginner in c# and I have to write a multidimensional array using while loop. I just can't go through it. So far I have made what I exactly need with nested for loop but can't convert it to while loop. Any help would be greatly appreciated.

int[][] tab = new int[4][];
tab[0] = new int[4];
tab[1] = new int[3];
tab[2] = new int[2];
tab[3] = new int[1];

int num = 1;

for(int i = 0; i < tab.Length; i++)
{
    for(int j = 0; j < tab[i].Length; j++)
    {
        tab[i][j] = num++;
    }
}

for(int i = 0; i < tab.Length; i++)
{
    Console.Write("tab[{0}] = ", i);
    for(int j = 0; j < tab[i].Length; j++)
    {
        Console.Write("{0} ", tab[i][j]);
    }
    Console.WriteLine("");
}

Body:
           int[][] tab = new int[4][];
            tab[0] = new int[4];
            tab[1] = new int[3];
            tab[2] = new int[2];
            tab[3] = new int[1];

            int num = 1;

            int ai = 0;
            int bj = 0;

            while (ai < tab.Length) {
                bj = 0;
                while (bj < tab[ai].Length) {
                    tab[ai][bj] = num++;
                    bj++;
                }
                ai++;
            }

            for (int i = 0; i < tab.Length; i++)
            {
                Console.Write("tab[{0}] = ", i);
                for (int j = 0; j < tab[i].Length; j++)
                {
                    Console.Write("{0} ", tab[i][j]);
                }
                Console.WriteLine("");
            }

Just remove for loop and added while loop.


问:
Android 2.1 GoogleMaps ItemizedOverlay ConcurrentModificationException
I cannot figure out the origin of the ConcurrentModificationException. In my activity I'm calling
 updateMapOverlay(). I'm also calling updateMapOverlay() inside another Thread (a TimerTask) that is invoked on regular intervals. I'm taking the appropriate locks when invoking updateMapOverlay() from both the threads. Is this problem being caused because I'm invoking updateMapOverlay from inside a non-UI thread (i.e., TimerTask). Has anyone else faced a similar issue ?

    private void updateMapOverlay() {

```<code>    this.itemizedOverlay.refreshItems(createOverlayItemsList());
    List<Overlay> overlays = mapView.getOverlays();
    overlays.clear();
    overlays.add(cotItemizedOverlay);
            this.mapview.invalidate();

}
</code>```

Thanks.

Exception:

```<code>W/dalvikvm(10641): threadid=3: thread exiting with uncaught exception (group=0x4001b180)
E/AndroidRuntime(10641): Uncaught handler: thread main exiting due to uncaught exception
E/AndroidRuntime(10641): java.util.ConcurrentModificationException
E/AndroidRuntime(10641):    at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:64)
E/AndroidRuntime(10641):    at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:41)
E/AndroidRuntime(10641):    at com.google.android.maps.MapView.onDraw(MapView.java:494)
E/AndroidRuntime(10641):    at android.view.View.draw(View.java:6535)
E/AndroidRuntime(10641):    at android.view.ViewGroup.drawChild(ViewGroup.java:1531)
E/AndroidRuntime(10641):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1258)
E/AndroidRuntime(10641):    at android.view.ViewGroup.drawChild(ViewGroup.java:1529)
E/AndroidRuntime(10641):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1258)
E/AndroidRuntime(10641):    at android.view.View.draw(View.java:6538)
E/AndroidRuntime(10641):    at android.widget.FrameLayout.draw(FrameLayout.java:352)
E/AndroidRuntime(10641):    at android.view.ViewGroup.drawChild(ViewGroup.java:1531)
E/AndroidRuntime(10641):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1258)
E/AndroidRuntime(10641):    at android.view.ViewGroup.drawChild(ViewGroup.java:1529)
E/AndroidRuntime(10641):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1258)
E/AndroidRuntime(10641):    at android.view.View.draw(View.java:6538)
E/AndroidRuntime(10641):    at android.widget.FrameLayout.draw(FrameLayout.java:352)
E/AndroidRuntime(10641):    at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1830)
E/AndroidRuntime(10641):    at android.view.ViewRoot.draw(ViewRoot.java:1349)
E/AndroidRuntime(10641):    at android.view.ViewRoot.performTraversals(ViewRoot.java:1114)
E/AndroidRuntime(10641):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1633)
E/AndroidRuntime(10641):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(10641):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(10641):    at android.app.ActivityThread.main(ActivityThread.java:4363)
E/AndroidRuntime(10641):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(10641):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(10641):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
E/AndroidRuntime(10641):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
E/AndroidRuntime(10641):    at dalvik.system.NativeStart.main(Native Method)
I/Process (   95): Sending signal. PID: 10641 SIG: 3
</code>```

答:
Generally speaking you should be safe as long as you only modify your ItemizedOverlay's backing List/Map on the UI thread.

As Mark pointed out, AsyncTask's:

```<code>@Override
protected void onPostExecute(Cursor cursor) {

    // modify List/Map

    populate();
    mapView.invalidate();
}
</code>```

is always executed on the UI thread, so modifications are safe here.

Body:
I cannot figure out the origin of the ConcurrentModificationException. In my activity I'm calling
 updateMapOverlay(). I'm also calling updateMapOverlay() inside another Thread (a TimerTask) that is invoked on regular intervals. I'm taking the appropriate locks when invoking updateMapOverlay() from both the threads. Is this problem being caused because I'm invoking updateMapOverlay from inside a non-UI thread (i.e., TimerTask). Has anyone else faced a similar issue ?

    private void updateMapOverlay() {

    this.itemizedOverlay.refreshItems(createOverlayItemsList());
    List<Overlay> overlays = mapView.getOverlays();
    overlays.clear();
    overlays.add(cotItemizedOverlay);
            this.mapview.invalidate();

}

Thanks.

Exception:

W/dalvikvm(10641): threadid=3: thread exiting with uncaught exception (group=0x4001b180)
E/AndroidRuntime(10641): Uncaught handler: thread main exiting due to uncaught exception
E/AndroidRuntime(10641): java.util.ConcurrentModificationException
E/AndroidRuntime(10641):    at java.util.AbstractList$SimpleListIterator.next(AbstractList.java:64)
E/AndroidRuntime(10641):    at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:41)
E/AndroidRuntime(10641):    at com.google.android.maps.MapView.onDraw(MapView.java:494)
E/AndroidRuntime(10641):    at android.view.View.draw(View.java:6535)
E/AndroidRuntime(10641):    at android.view.ViewGroup.drawChild(ViewGroup.java:1531)
E/AndroidRuntime(10641):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1258)
E/AndroidRuntime(10641):    at android.view.ViewGroup.drawChild(ViewGroup.java:1529)
E/AndroidRuntime(10641):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1258)
E/AndroidRuntime(10641):    at android.view.View.draw(View.java:6538)
E/AndroidRuntime(10641):    at android.widget.FrameLayout.draw(FrameLayout.java:352)
E/AndroidRuntime(10641):    at android.view.ViewGroup.drawChild(ViewGroup.java:1531)
E/AndroidRuntime(10641):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1258)
E/AndroidRuntime(10641):    at android.view.ViewGroup.drawChild(ViewGroup.java:1529)
E/AndroidRuntime(10641):    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1258)
E/AndroidRuntime(10641):    at android.view.View.draw(View.java:6538)
E/AndroidRuntime(10641):    at android.widget.FrameLayout.draw(FrameLayout.java:352)
E/AndroidRuntime(10641):    at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1830)
E/AndroidRuntime(10641):    at android.view.ViewRoot.draw(ViewRoot.java:1349)
E/AndroidRuntime(10641):    at android.view.ViewRoot.performTraversals(ViewRoot.java:1114)
E/AndroidRuntime(10641):    at android.view.ViewRoot.handleMessage(ViewRoot.java:1633)
E/AndroidRuntime(10641):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(10641):    at android.os.Looper.loop(Looper.java:123)
E/AndroidRuntime(10641):    at android.app.ActivityThread.main(ActivityThread.java:4363)
E/AndroidRuntime(10641):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(10641):    at java.lang.reflect.Method.invoke(Method.java:521)
E/AndroidRuntime(10641):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
E/AndroidRuntime(10641):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
E/AndroidRuntime(10641):    at dalvik.system.NativeStart.main(Native Method)
I/Process (   95): Sending signal. PID: 10641 SIG: 3

Body:
Generally speaking you should be safe as long as you only modify your ItemizedOverlay's backing List/Map on the UI thread.

As Mark pointed out, AsyncTask's:

@Override
protected void onPostExecute(Cursor cursor) {

    // modify List/Map

    populate();
    mapView.invalidate();
}

is always executed on the UI thread, so modifications are safe here.


答:
A for loop is a dressed up while loop, you're already very close.

consider that

```<code>for(a; b; c) { ...; }
</code>```

is equal to (without the break/continue labels for brevity)

```<code> { a; while (b) { ...; c; } }
</code>```

You should be able to do this conversion easily. But I think a teacher should also just accept code with a for loop as it is functionally a while loop.

Now there could be other constraints in your homework, like allowing nested loops or the  [,] or [][] style multi dimensional arrays (again, functionally the same, different C# notations for slightly different feature sets).

Title: How to make a multidimensional array using while loop in C#

Body:
A for loop is a dressed up while loop, you're already very close.

consider that

for(a; b; c) { ...; }

is equal to (without the break/continue labels for brevity)

 { a; while (b) { ...; c; } }

You should be able to do this conversion easily. But I think a teacher should also just accept code with a for loop as it is functionally a while loop.

Now there could be other constraints in your homework, like allowing nested loops or the  [,] or [][] style multi dimensional arrays (again, functionally the same, different C# notations for slightly different feature sets).


问:
add sender's name in the from field of the email in python
I am trying to send email with below code.

```<code>import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()

cont = """\
   <html>
     <head></head>
     <body>
       <p>Hi!<br>
          How are you?<br>
          Here is the <a href="http://www.google.com">link</a> you wanted.
       </p>
     </body>
   </html>
   """
mail_me(cont,['xyz@xyzcom'])
</code>```

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

```<code>[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]
</code>```

I have attached a screenshot of the email that i receive.

how can i fix this according to my need.

答:
A space is not a valid character in an email address. Special characters are only allowed in the external representation that shall be enclosed in double quotes. Additionaly, most SMTP servers actually use header rewriting to ensure that addresses are in standard format. As yours actually contains a space it is splitted and as it is not enclosed in quotes, the server address is appended to it.

You have just to replace msg['From'] = "XYZ ABC" with

```<code>msg['From'] = '"XYZ ABC"'
</code>```

forcing inclusion of the address in double quotes.

Body:
I am trying to send email with below code.

import smtplib
from email.mime.text import MIMEText

sender = 'sender@sender.com'

def mail_me(cont, receiver):
    msg = MIMEText(cont, 'html')
    recipients = ",".join(receiver)
    msg['Subject'] = 'Test-email'
    msg['From'] = "XYZ ABC"
    msg['To'] = recipients
    # Send the message via our own SMTP server.
    try:
        s = smtplib.SMTP('localhost')
        s.sendmail(sender, receiver, msg.as_string())
        print "Successfully sent email"
    except SMTPException:
        print "Error: unable to send email"
    finally:
        s.quit()

cont = """\

Hi!

          How are you?

          Here is the link you wanted.

   """
mail_me(cont,['xyz@xyzcom'])

I want "XYZ ABC" to appear as the sender's name when the email is received and its email address as 'sender@sender.com'. but when i receive email i am receiving weird details in "from" fields of the email message.

[![from:    XYZ@<machine-hostname-appearing-here>
reply-to:   XYZ@<machine-hostname-appearing-here>,
ABC@<machine-hostname-appearing-here>][1]][1]

I have attached a screenshot of the email that i receive.

how can i fix this according to my need.

Body:
A space is not a valid character in an email address. Special characters are only allowed in the external representation that shall be enclosed in double quotes. Additionaly, most SMTP servers actually use header rewriting to ensure that addresses are in standard format. As yours actually contains a space it is splitted and as it is not enclosed in quotes, the server address is appended to it.

You have just to replace msg['From'] = "XYZ ABC" with

msg['From'] = '"XYZ ABC"'

forcing inclusion of the address in double quotes.


问:
Convert string to Title Case with JavaScript
Is there a simple way to convert a string to Title Case? E.g. john smith becomes John Smith. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner.

答:
Try this, shortest way:</p>

```<code>str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
</code>```

OwnerDisplayName: MDCore

Body:
Try this, shortest way:

str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());


问:
Is there any method in Kotlin which allow me to translate a value from a range into another range?
I have a value inside a range of numbers (for instance 0..100) which I want to translate it into another range, (for instance to 0..9). So the result would be:

50 -> 4 or 100 -> 9, ...

Is there any method in Kotlin which helps me in this regard?

Body: val r2 = IntRange(0, 100).filter { it %10 ==0 }.map { it /10 }


问:
Equivalent to GOTO in conditions, Python
Since there is no goto operator in Python, what technique can be used instead?

Condition
If it is true, go to thread 1, if is false, go to thread 2
In thread we do something small and after that we go to thread 2 where all other actions take place.

答:
Since there is no goto operator in Python, what technique can be used instead?

Constructing your code logically and semantically.

```<code>if condition:
    perform_some_action()

perform_other_actions()
</code>```

Body:
Since there is no goto operator in Python, what technique can be used instead?

Constructing your code logically and semantically.

if condition:
    perform_some_action()

perform_other_actions()


问:
iOS/Android does keep linking requires an HTTP server
I want to let users click on a link on an email or SMS message, and then open the app and deep link into a specific page/ViewController.

I know there is a more general implementation, when user browse your website with a mobile web browser, and if your app is installed, launch your app instead of keep browsing it in the web browser.

I was wondering if deep linking itself can be done without setting up a server?

In iOS parlance, I want to register a custom URI scheme, and when user taps on a link via the custom URI scheme in a mobile email client or SMS message app, open our app, and get some payload into it as well so I can deep link into a specific ViewController.

(Sorry I don't know Android well, though I do need it on Android as well. I'm actually working with Cordova.)

答:
No, deep linking on Android does not require an http server

https://developer.android.com/training/app-indexing/deep-linking.html

It works the same way - a custom URI scheme

To enable Google to crawl your app content and allow users to enter your app from search results, you must add intent filters for the relevant activities in your app manifest. These intent filters allow deep linking to the content in any of your activities. For example, the user might click on a deep link to view a page within a shopping app that describes a product offering that the user is searching fo


问:
Rails URI::regexp match with no scheme
I need to validate URL with URI::regexp but some URLs have no scheme.

I tried using,

```<code>URI::regexp(["http", "http])
URI::regexp(%w(http https tel)
</code>```

but they cannot validate empty scheme such as "www.google.com" "google.com".

How can I include/validate such URLs?

答:
```<code>inp = %w|www.google.com
         www.http.com
         http://google.com
         https://google.com|.map do |e|
  e.gsub(/\A(?!http)/, "http://")
end
#⇒ [
#   [0] "http://www.google.com",
#   [1] "http://www.http.com",
#   [2] "http://google.com",
#   [3] "https://google.com"
# ]
_.map { |e| URI::regexp(%w|http https|) =~ e }
#⇒ [0, 0, 0, 0]
</code>```

Title: Rails URI::regexp match with no scheme

Body:
I need to validate URL with URI::regexp but some URLs have no scheme.

I tried using,

URI::regexp(["http", "http])
URI::regexp(%w(http https tel)

but they cannot validate empty scheme such as "www.google.com" "google.com".

How can I include/validate such URLs?