问:
Laravel update Query not work Call to a member function fill() on null
When i update data with changing user id in my drop down value and allocate a specific venue to user it return error and cannot update data.

Error :Call to a member function fill() on null

Image Added: where client is a users and when i allocate star venue to vinay it returns error

Here is my model function code  which i try

```<code>  public static function saveOrUpdate(Request $request) {
    try {

        $checkBoxes = [
            'is_premium',
            'is_verified',
            'is_outside_catering',
            'is_indoor',
            'is_outdoor',
            'has_parking',
            'has_valet'
        ];
        foreach($checkBoxes as $checkbox) {
            if(!$request->has($checkbox)) {
                $request->merge([$checkbox => 0]);
            }
        }

        $venue = false;

        DB::transaction(function () use ($request, &$venue) {
            $id = $request->get('id', false); // gt id here
            $clientId = $request->get('client_id', false); // gt cleint id here
            $client = Client::findOrFail($clientId);
            $venue = $client->venues()->findOrNew($id); // gt venue data
            // added dd($venue) below
            //dd($request->all()); Added array in below

            $venue->fill($request->all());

            try {
                $venue->save();
                $occasions = $request->get('occasions', []);
                $venue->occasions()->sync($occasions);

                if($id) {
                    // Here I am gtng error
                    $venue->venueParameter->fill($request->all())->save();
                } else {
                    $venue->venueParameter()->create($request->all());
                }
            } catch (\Exception $ex) {
                echo $ex->getMessage();
                dd($ex->getTraceAsString());
            }
        });

        return $venue;
    } catch (\Exception $ex) {
        throw $ex;
    }
}
</code>```

Here is venue model function for parameter

```<code>    public function venueParameter() {
    //dd("Welcome"); gt here successfully
    return $this->hasOne(VenueParameter::class);
}
</code>```

Here is my venueparameter model

```<code><?php

     namespace App;

     use Illuminate\Database\Eloquent\Model;

  class VenueParameter extends Model
  {

    protected $fillable = [

    'venue_id',
    'min_capacity',
    'max_capacity',
    'is_outside_catering',
    'price_list_view',
    'price_details_view',
    'area',
    'is_indoor',
    'indoor_area',
    'is_outdoor',
    'outdoor_area',
    'has_parking',
    'no_of_parkings',
    'has_valet',
    'no_of_rooms',
    'decorator',
];

public $timestamps = false;

const DECORATOR = [
    'Inside' => 'Inside',
    'Outside' => 'Outside',
    'Both' => 'Both'
];

public function venue() {

    return $this->belongsTo(Venue::class);
}
 }
</code>```

Here is what i gt when i dd($request->all())

```<code>                        "_token" => "dJcVc2pP6fGtBD9FUZYFMnKfHf0ArScjy9mLJfcg"
                        "id" => "8"
                        "name" => "test"
                        "client_id" => "2"
                        "logo" => "public/venue-logo/BO7ZuxbZyUZjo7u35WAyx4ReNlBnGxcFIKo77euo.jpeg"
                        "venue_type_id" => "1"
                        "is_premium" => "1"
                        "is_verified" => "1"
                        "tripadvisor_url" => "http://test.com/home"
                        "venue_url" => "http://test.com/home"
                        "status" => "Active"
                        "min_capacity" => "1"
                        "max_capacity" => "1"
                        "price_list_view" => "1"
                        "price_details_view" => ""
                        "area" => "5000"
                        "indoor_area" => "0"
                        "outdoor_area" => "0"
                        "no_of_parkings" => "0"
                        "decorator" => "Inside"
                        "is_outside_catering" => 0
                        "is_indoor" => 0
                        "is_outdoor" => 0
                        "has_parking" => 0
                        "has_valet" => 0
</code>```

Here is what i gt when i dd($venue)

```<code>  #attributes: array:12 [▼
"id" => 11
"client_id" => 1
"name" => "zuber"
"venue_url" => "http://premiumbanquets.com/home"
"logo" => "public/venue-logo/Rkt8SV5OLz8pMW6sFfJJUhUFmhSI2VCfBLvI6STd.jpeg"
"venue_type_id" => 1
"is_premium" => 1
"is_verified" => 1
"tripadvisor_url" => "http://premiumbanquets.com/home"
"status" => "Active"
"created_at" => "2017-12-04 13:19:25"
"updated_at" => "2017-12-04 13:19:25"
</code>```

]

How can i overcome on this problem?

答:
This error is self descriptive

Error :Call to a member function fill() on null here $vanue get null value try to print $vanue data and check it dd($vanue);

```<code>    DB::transaction(function () use ($request, &$venue) {
    $id = $request->get('id', false); // gt id here
    $clientId = $request->get('client_id', false); // gt cleint id here
    $client = Client::findOrFail($clientId);
    $venue = $client->venues()->findOrNew($id); // gt venue data
    **//dd($request->all()); Added array in below**

    $venue->fill($request->all()); **//here value of  $venue  is null or blank**

    dd($vanue) // check this whether it contain NULL or not
</code>```

Body:
When i update data with changing user id in my drop down value and allocate a specific venue to user it return error and cannot update data.

Error :Call to a member function fill() on null

Image Added: where client is a users and when i allocate star venue to vinay it returns error

Here is my model function code  which i try

  public static function saveOrUpdate(Request $request) {
    try {

        $checkBoxes = [
            'is_premium',
            'is_verified',
            'is_outside_catering',
            'is_indoor',
            'is_outdoor',
            'has_parking',
            'has_valet'
        ];
        foreach($checkBoxes as $checkbox) {
            if(!$request->has($checkbox)) {
                $request->merge([$checkbox => 0]);
            }
        }

        $venue = false;

        DB::transaction(function () use ($request, &$venue) {
            $id = $request->get('id', false); // gt id here
            $clientId = $request->get('client_id', false); // gt cleint id here
            $client = Client::findOrFail($clientId);
            $venue = $client->venues()->findOrNew($id); // gt venue data
            // added dd($venue) below
            //dd($request->all()); Added array in below

            $venue->fill($request->all());

            try {
                $venue->save();
                $occasions = $request->get('occasions', []);
                $venue->occasions()->sync($occasions);

                if($id) {
                    // Here I am gtng error
                    $venue->venueParameter->fill($request->all())->save();
                } else {
                    $venue->venueParameter()->create($request->all());
                }
            } catch (\Exception $ex) {
                echo $ex->getMessage();
                dd($ex->getTraceAsString());
            }
        });

        return $venue;
    } catch (\Exception $ex) {
        throw $ex;
    }
}

Here is venue model function for parameter

    public function venueParameter() {
    //dd("Welcome"); gt here successfully
    return $this->hasOne(VenueParameter::class);
}

Here is my venueparameter model

<?php

     namespace App;

     use Illuminate\Database\Eloquent\Model;

  class VenueParameter extends Model
  {

    protected $fillable = [

    'venue_id',
    'min_capacity',
    'max_capacity',
    'is_outside_catering',
    'price_list_view',
    'price_details_view',
    'area',
    'is_indoor',
    'indoor_area',
    'is_outdoor',
    'outdoor_area',
    'has_parking',
    'no_of_parkings',
    'has_valet',
    'no_of_rooms',
    'decorator',
];

public $timestamps = false;

const DECORATOR = [
    'Inside' => 'Inside',
    'Outside' => 'Outside',
    'Both' => 'Both'
];

public function venue() {

    return $this->belongsTo(Venue::class);
}
 }

Here is what i gt when i dd($request->all())

                        "_token" => "dJcVc2pP6fGtBD9FUZYFMnKfHf0ArScjy9mLJfcg"
                        "id" => "8"
                        "name" => "test"
                        "client_id" => "2"
                        "logo" => "public/venue-logo/BO7ZuxbZyUZjo7u35WAyx4ReNlBnGxcFIKo77euo.jpeg"
                        "venue_type_id" => "1"
                        "is_premium" => "1"
                        "is_verified" => "1"
                        "tripadvisor_url" => "http://test.com/home"
                        "venue_url" => "http://test.com/home"
                        "status" => "Active"
                        "min_capacity" => "1"
                        "max_capacity" => "1"
                        "price_list_view" => "1"
                        "price_details_view" => ""
                        "area" => "5000"
                        "indoor_area" => "0"
                        "outdoor_area" => "0"
                        "no_of_parkings" => "0"
                        "decorator" => "Inside"
                        "is_outside_catering" => 0
                        "is_indoor" => 0
                        "is_outdoor" => 0
                        "has_parking" => 0
                        "has_valet" => 0

Here is what i gt when i dd($venue)

  #attributes: array:12 [▼
"id" => 11
"client_id" => 1
"name" => "zuber"
"venue_url" => "http://premiumbanquets.com/home"
"logo" => "public/venue-logo/Rkt8SV5OLz8pMW6sFfJJUhUFmhSI2VCfBLvI6STd.jpeg"
"venue_type_id" => 1
"is_premium" => 1
"is_verified" => 1
"tripadvisor_url" => "http://premiumbanquets.com/home"
"status" => "Active"
"created_at" => "2017-12-04 13:19:25"
"updated_at" => "2017-12-04 13:19:25"

]

How can i overcome on this problem?

Body:
This error is self descriptive

Error :Call to a member function fill() on null here $vanue get null value try to print $vanue data and check it dd($vanue);

    DB::transaction(function () use ($request, &$venue) {
    $id = $request->get('id', false); // gt id here
    $clientId = $request->get('client_id', false); // gt cleint id here
    $client = Client::findOrFail($clientId);
    $venue = $client->venues()->findOrNew($id); // gt venue data
    **//dd($request->all()); Added array in below**

    $venue->fill($request->all()); **//here value of  $venue  is null or blank**

    dd($vanue) // check this whether it contain NULL or not


来源: stackexchange

问:
Sorting descending by month string and ascending by week string
I have a column used for data validation drop down in the following format:

```<code>M01 W01 random strings
M01 W02 random strings
M01 W03 random strings
M02 W01 random strings
M02 W02 random strings
M02 W03 random strings
</code>```

M=Month, W=Week

Right now I have column sorted by descending so most recent Month is on top:

```<code>M02 W03 random strings
M02 W02 random strings
M02 W01 random strings
M01 W03 random strings
M01 W02 random strings
M01 W01 random strings
</code>```

Is there a way to also sort it so Weeks are ascending:

```<code>M02 W01 random strings
M02 W02 random strings
M02 W03 random strings
M01 W01 random strings
M01 W02 random strings
M01 W03 random strings
</code>```

I think regextract "M00" into one range, then use it to query sort original column but can't seem to get it to work:

=query({original column; regextract M00} , "select Col1, order by Col2 desc"}

EDIT: NVM I'm an idiot, all I had to do was replace ; with , in query{}.

答:
Why not regular sort function?

=SORT(A:C,1,0,2,1)

Edit

In case it was 1 column, use regex first:

=TRANSPOSE(QUERY(TRANSPOSE(
SORT(IFERROR(REGEXEXTRACT(A:A,"(M\d{2}) (W\d{2}) (.*)")),1,0,2,1)
),,2^50))

transpose and query part is to join text back:

```<code>M02 W01 random strings
M02 W02 random strings
M02 W03 random strings
M01 W01 random strings
M01 W02 random strings
M01 W03 random strings
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a column used for data validation drop down in the following format:

M01 W01 random strings
M01 W02 random strings
M01 W03 random strings
M02 W01 random strings
M02 W02 random strings
M02 W03 random strings

M=Month, W=Week

Right now I have column sorted by descending so most recent Month is on top:

M02 W03 random strings
M02 W02 random strings
M02 W01 random strings
M01 W03 random strings
M01 W02 random strings
M01 W01 random strings

Is there a way to also sort it so Weeks are ascending:

M02 W01 random strings
M02 W02 random strings
M02 W03 random strings
M01 W01 random strings
M01 W02 random strings
M01 W03 random strings

I think regextract "M00" into one range, then use it to query sort original column but can't seem to get it to work:

=query({original column; regextract M00} , "select Col1, order by Col2 desc"}

EDIT: NVM I'm an idiot, all I had to do was replace ; with , in query{}.

Body:
Why not regular sort function?

=SORT(A:C,1,0,2,1)

Edit

In case it was 1 column, use regex first:

=TRANSPOSE(QUERY(TRANSPOSE(
SORT(IFERROR(REGEXEXTRACT(A:A,"(M\d{2}) (W\d{2}) (.*)")),1,0,2,1)
),,2^50))

transpose and query part is to join text back:

M02 W01 random strings
M02 W02 random strings
M02 W03 random strings
M01 W01 random strings
M01 W02 random strings
M01 W03 random strings


问:
Recursive function to add all the digits

I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)

I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?

```<code>def digit_sum(n):
    if n//10 <= 0:
        return n%10
    return digit_sum(n//10) + n%10
</code>```

答:
You can do the following:</p>

```<code>def digit_sum(n):
    if n < 10:
        return n
    return digit_sum(sum(map(int, str(n))))
</code>```

Body:
I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)

I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?

def digit_sum(n):
    if n//10 <= 0:
        return n%10
    return digit_sum(n//10) + n%10

Body:
You can do the following:

def digit_sum(n):
    if n < 10:
        return n
    return digit_sum(sum(map(int, str(n))))


问:
Arrow function (Lambda function) with Angular 4
I know little about lambda, and lambda expression is treated as a function. and we have lots of ways to do that.

This is my simple function on TypeScript file

```<code> byPan(card1,card2){
    return card1.pan == card2.pan;
 }
</code>```

which I am using in HTML file like

```<code> <select [compareWith]="byPan" class="form-control" [(ngModel)]="card">
     <option *ngFor="let cardInfo of cards" [ngValue]="cardInfo">{{cardInfo.pan}}</option>
 </select>
</code>```

If I want to replace this function in lambda then I can write as follows.

```<code>var myFunc2 = (card1, card2) => { return card1.pan == card2.pan};
</code>```

So my question is, Can I use this lambda function directly on any angular property like compareWith or something like?

```<code> <select [compareWith]="(card1,card2)=> { return card1.pan == card2.pan}" class="form-control" [(ngModel)]="card">
     <option *ngFor="let cardInfo of cards" [ngValue]="cardInfo">{{cardInfo.pan}}</option>
 </select>
</code>```

答:
You can't just execute arrow function in template. Angular will accept only expressions that can bind with component or directives. So basically no, you can't use arrow function in template. It's the best to leave it as a method in your component.

However if you are looking on small expressions you can use shorthand if it could look like:

```<code>[compareWith]="card1.pan == card2.pan" // returns bool value
</code>```

or

```<code>[compareWith]="card1.pan == card2.pan ? 'foo' : 'bar".
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know little about lambda, and lambda expression is treated as a function. and we have lots of ways to do that.

This is my simple function on TypeScript file

 byPan(card1,card2){
    return card1.pan == card2.pan;
 }

which I am using in HTML file like

 <select [compareWith]="byPan" class="form-control" [(ngModel)]="card">
     <option *ngFor="let cardInfo of cards" [ngValue]="cardInfo">{{cardInfo.pan}}</option>
 </select>

If I want to replace this function in lambda then I can write as follows.

var myFunc2 = (card1, card2) => { return card1.pan == card2.pan};

So my question is, Can I use this lambda function directly on any angular property like compareWith or something like?

 <select [compareWith]="(card1,card2)=> { return card1.pan == card2.pan}" class="form-control" [(ngModel)]="card">
     <option *ngFor="let cardInfo of cards" [ngValue]="cardInfo">{{cardInfo.pan}}</option>
 </select>

Body:
You can't just execute arrow function in template. Angular will accept only expressions that can bind with component or directives. So basically no, you can't use arrow function in template. It's the best to leave it as a method in your component.

However if you are looking on small expressions you can use shorthand if it could look like:

[compareWith]="card1.pan == card2.pan" // returns bool value

or

[compareWith]="card1.pan == card2.pan ? 'foo' : 'bar".


问:
JavaScript changing CSS not working inside of if statement
Here is my html :

```<code><a class="btn btn-primary btn-lg" id="signUpBtn" href="./pages/createaccount.php" onmouseover="rotateBtn()"> Sign up »</a>
</code>```

Here is the JS... the style changes don't work when I take it out of the if statement. I need the if statement to toggle back and forth between the two rotations.
Doing this to learn, want to use JS and also see how it works with jQuery

```<code>function rotateBtn() {
var isRotated = 0;
document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}
</code>```

答:
The problem lies in the following code:

```<code>if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}
</code>```

After assigning isRotated = 1 in the first if(), the second if() also gets executed because its condition is satisfied.

To avoid this, just include an else statement for the second if()

```<code>if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

else if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}
</code>```

Body:
Here is my html :

 Sign up »

Here is the JS... the style changes don't work when I take it out of the if statement. I need the if statement to toggle back and forth between the two rotations.
Doing this to learn, want to use JS and also see how it works with jQuery

function rotateBtn() {
var isRotated = 0;
document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}

Body:
The problem lies in the following code:

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}

After assigning isRotated = 1 in the first if(), the second if() also gets executed because its condition is satisfied.

To avoid this, just include an else statement for the second if()

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

else if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}


问:
Fixing an error while querying for existing an data
I am trying to determine if a variable already exists, so I won't create a duplicate. But I keep getting an error:

Cannot convert from System.Linq.IQueryable

Here's the code that results in the error:

```<code>public List<QuestionTag> ParseTags(string tags)
{
    var tagList = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
    var questionTags = new List<QuestionTag>();
    var anyNewTags = false;

foreach (var tag in tagList)
{
    var tagExists = _context.Tags.Where(x => x.Name == tag);
    if (tagExists == null)
    {
        var newTag = new QuestionTag() { Tag = new Tag() { Name = tag } };
        _context.QuestionTags.Add(newTag);
        questionTags.Add(newTag);

        anyNewTags = true;
    }
    else
    {
        questionTags.Add(tagExists); // ERROR OCCURS HERE
    }

}
if (anyNewTags) _context.SaveChanges();
return questionTags;
</code>```

}

答:
You tagExists query hasn't yielded a result yet, hence the error. In order to make it yield, use either .ToList(), First() or FirstOrDefault().

Assuming it results in a list, then use:

```<code>questionTags.AddRange(tagExists.ToList());
</code>```

Assuming it results in a single object, then use:

```<code>questionTags.Add(tagExists.First());
</code>```

====== Edit =======

Your questionTags is of type List<QuestionTag>, but when you add tagExists, this is of type Tags.

So change this,

```<code>var tagExists = _context.Tags.Where(x => x.Name == tag).Select(x => new QuestionTag { Tag = new Tag { Name = x.Name} }).FirstOrDefault();
</code>```

Body:
I am trying to determine if a variable already exists, so I won't create a duplicate. But I keep getting an error:

Cannot convert from System.Linq.IQueryable

Here's the code that results in the error:

public List<QuestionTag> ParseTags(string tags)
{
    var tagList = tags.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
    var questionTags = new List<QuestionTag>();
    var anyNewTags = false;

foreach (var tag in tagList)
{
    var tagExists = _context.Tags.Where(x => x.Name == tag);
    if (tagExists == null)
    {
        var newTag = new QuestionTag() { Tag = new Tag() { Name = tag } };
        _context.QuestionTags.Add(newTag);
        questionTags.Add(newTag);

        anyNewTags = true;
    }
    else
    {
        questionTags.Add(tagExists); // ERROR OCCURS HERE
    }

}
if (anyNewTags) _context.SaveChanges();
return questionTags;

}

Body:
You tagExists query hasn't yielded a result yet, hence the error. In order to make it yield, use either .ToList(), First() or FirstOrDefault().

Assuming it results in a list, then use:

questionTags.AddRange(tagExists.ToList());

Assuming it results in a single object, then use:

questionTags.Add(tagExists.First());

====== Edit =======

Your questionTags is of type List<QuestionTag>, but when you add tagExists, this is of type Tags.

So change this,

var tagExists = _context.Tags.Where(x => x.Name == tag).Select(x => new QuestionTag { Tag = new Tag { Name = x.Name} }).FirstOrDefault();


问:
Get the next date/time at which a daylight savings time transition occurs
I would like to write (or use if it already exits) a function in C# that returns the date/time of the next DST transition given a System.TimeZoneInfo object and a particular "as of" time in that time zone.  The time returned should be in the provided time zone.  The function I want has this signature:

```<code>public DateTime GetNextTransition(DateTime asOfTime, TimeZoneInfo timeZone)
{
    // Implement me!
}
</code>```

For example, if I pass in the "Eastern Standard Time" TimeZoneInfo object, and 1/21/2011@17:00 as the "asOfTime", I expect this function to return 3/13/2011@2:00.

The System.TimeZoneInfo.TransitionTime structure appears to have all the information I need, but ideally there would be some sort of built-in mechanism to convert the rule into an actual date.  Anyone have any suggestions?

答: System.TimeZoneInfo.TransitionTime looks like a structure that can hold such time transition data, not a function that figures out the actual values.  To create such a function, I would find the data online somewhere, then create values using the static   CreateFloatingDateRule or CreateFixedDateRule methods.

ContentLicense: CC BY-SA 2.5

Body:
I would like to write (or use if it already exits) a function in C# that returns the date/time of the next DST transition given a System.TimeZoneInfo object and a particular "as of" time in that time zone.  The time returned should be in the provided time zone.  The function I want has this signature:

public DateTime GetNextTransition(DateTime asOfTime, TimeZoneInfo timeZone)
{
    // Implement me!
}

For example, if I pass in the "Eastern Standard Time" TimeZoneInfo object, and 1/21/2011@17:00 as the "asOfTime", I expect this function to return 3/13/2011@2:00.

The System.TimeZoneInfo.TransitionTime structure appears to have all the information I need, but ideally there would be some sort of built-in mechanism to convert the rule into an actual date.  Anyone have any suggestions?


问:
This move constructor of Microsoft example appears to have redundant code
The MSDN page for developers has this code snippet:

```<code>// Move constructor.
MemoryBlock(MemoryBlock&& other) : _data(nullptr), _length(0)
{
   std::cout << "In MemoryBlock(MemoryBlock&&). length = "
             << other._length << ". Moving resource." << std::endl;

   // Copy the data pointer and its length from source object.
   _data = other._data;      // Assginment 1
   _length = other._length;  // Assignment 2

   // Release the data pointer from the source object so that
   // the destructor does not free the memory multiple times.
   other._data = nullptr;
   other._length = 0;
}
</code>```

What's the use of _data(nullptr), _length(0), when the instructions labelled Assignment 1 and Assignment 2 over-write the values of _data and _length?

答:
For safety.

Let's say that for some reason, other._data and/or other._length fail to access their value (most probably the pointer other._data though).

An example could be that the pointer is pointing to invalid memory and produce a Segmentation Fault (since you may access memory that is not own by your program), and the program to crash at that point. Another possibility is that other is *nullptr, and so on... What are the values of _data and _length then? Undefined.

It would be nice for these two to have their initial value, since that might help debugging, since the programmer can think that since these two have their initial values, maybe there is something wrong in the assignment.

Body:
The MSDN page for developers has this code snippet:

// Move constructor.
MemoryBlock(MemoryBlock&& other) : _data(nullptr), _length(0)
{
   std::cout << "In MemoryBlock(MemoryBlock&&). length = "
             << other._length << ". Moving resource." << std::endl;

   // Copy the data pointer and its length from source object.
   _data = other._data;      // Assginment 1
   _length = other._length;  // Assignment 2

   // Release the data pointer from the source object so that
   // the destructor does not free the memory multiple times.
   other._data = nullptr;
   other._length = 0;
}

What's the use of _data(nullptr), _length(0), when the instructions labelled Assignment 1 and Assignment 2 over-write the values of _data and _length?


问:
Python Selenium - finding elements which contain any text
I am trying to process all elements which have text. I know I can iterate over the list and process only those which contain text:

```<code>from selenium import webdriver
driver = webdriver.Chrome()
my_elelements = driver.find_elements_by_xpath("//*")
for elm in my_elements:
    if elm.text!=""
    'processing of text
</code>```

but is there a quicker way only find elements with text, with selenium's driver.find_elements_by_ without finding all elements and then filtering only those with text...? Is there a wildcard that can be used here ?

答:
You can use the following x-paths to get all elements with text.

//*[text()]  -- it will returns all element with text including parent nodes

//*[text()][count(*)=0] -- it returns all element with text only child nodes

or you can use the following x-path to get the all elements without text.

//*[not(text())]  -- it will returns all element without text including parent nodes

//*[not(text())][count(*)=0] -- it returns all element without text only child nodes

Body:
I am trying to process all elements which have text. I know I can iterate over the list and process only those which contain text:

from selenium import webdriver
driver = webdriver.Chrome()
my_elelements = driver.find_elements_by_xpath("//*")
for elm in my_elements:
    if elm.text!=""
    'processing of text

but is there a quicker way only find elements with text, with selenium's driver.find_elements_by_ without finding all elements and then filtering only those with text...? Is there a wildcard that can be used here ?


问:
sessionStorage is not passing string
First page

```<code>sessionStorage.myvar=no;
</code>```

Second page

```<code>var display=sessionStorage.myvar;
</code>```

Here I am trying to pass a session variable through pages. The sessionvariable is only supporting numbers, if I try to send string, it is saying error.

First error comes if it starts with number and Second error comes if it starts with alphabet

Snapshot:

答:
You have to pass string with quotes. like below

```<code>sessionStorage.myvar='no';
</code>```

or

```<code>sessionStorage.myvar="no";
</code>```

Title: sessionStorage is not passing string

Body:
First page

sessionStorage.myvar=no;

Second page

var display=sessionStorage.myvar;

Here I am trying to pass a session variable through pages. The sessionvariable is only supporting numbers, if I try to send string, it is saying error.

First error comes if it starts with number and Second error comes if it starts with alphabet

Snapshot:

Body:
You have to pass string with quotes. like below

sessionStorage.myvar='no';

or

sessionStorage.myvar="no";


问:
Combine multiple row to single row for unique values in multiple column

I am trying to get unique rows based on unique values on multiple columns in SQL Server 2012.

Source Data:

UserId  ---- P1 ---- P2 ------ P3

101  ------- NO ---- NO ------- YES

101  ------- NO ---- YES ------ NO

101  ------- YES ---- NO ------- NO

102 -------- NO ----- NO ------- NO

My source data has 'YES' in single columns for multiple rows.

I'm trying to get the result as follows:

Desired Output:

UserId  ---- P1 ---- P2 ------ P3

101  ------- YES ---- YES ----- YES

102 -------- NO ----- NO ------- NO

Any ideas or code-sample will be greatly appreciated.

答:
In SQL Server 2012 and higher you can use this construction:

```<code>SELECT  UserId,
        IIF(SUM(IIF(P1 = 'YES',1,0)) > 0,'YES','NO') as P1,
        IIF(SUM(IIF(P2 = 'YES',1,0)) > 0,'YES','NO') as P2,
        IIF(SUM(IIF(P3 = 'YES',1,0)) > 0,'YES','NO') as P3
FROM YourTable
GROUP BY UserId
</code>```

Or, instead of IIF use CASE (SQL Server 2008 or higher):

```<code>SELECT  UserId,
        CASE WHEN SUM(CASE WHEN P1 = 'YES' THEN 1 ELSE 0 END) > 0 THEN 'YES' ELSE 'NO' END as P1,
        CASE WHEN SUM(CASE WHEN P2 = 'YES' THEN 1 ELSE 0 END) > 0 THEN 'YES' ELSE 'NO' END as P2,
        CASE WHEN SUM(CASE WHEN P3 = 'YES' THEN 1 ELSE 0 END) > 0 THEN 'YES' ELSE 'NO' END as P3
FROM YourTable
GROUP BY UserId
</code>```

Output:

```<code>UserId  P1  P2  P3
101     YES YES YES
102     NO  NO  NO
</code>```

Body:
In SQL Server 2012 and higher you can use this construction:

SELECT  UserId,
        IIF(SUM(IIF(P1 = 'YES',1,0)) > 0,'YES','NO') as P1,
        IIF(SUM(IIF(P2 = 'YES',1,0)) > 0,'YES','NO') as P2,
        IIF(SUM(IIF(P3 = 'YES',1,0)) > 0,'YES','NO') as P3
FROM YourTable
GROUP BY UserId

Or, instead of IIF use CASE (SQL Server 2008 or higher):

SELECT  UserId,
        CASE WHEN SUM(CASE WHEN P1 = 'YES' THEN 1 ELSE 0 END) > 0 THEN 'YES' ELSE 'NO' END as P1,
        CASE WHEN SUM(CASE WHEN P2 = 'YES' THEN 1 ELSE 0 END) > 0 THEN 'YES' ELSE 'NO' END as P2,
        CASE WHEN SUM(CASE WHEN P3 = 'YES' THEN 1 ELSE 0 END) > 0 THEN 'YES' ELSE 'NO' END as P3
FROM YourTable
GROUP BY UserId

Output:

UserId  P1  P2  P3
101     YES YES YES
102     NO  NO  NO


问:
Java - can you create a helper class with methods with same name but possibly can take diff arguments
looking for some help...
In Java - i am trying to find if i can have a helper class which basically has several methods:

```<code> class helper{
method1(){doing something}
method2(){doing something}
method_important(String a, String b){doing something}
method_important(String a, int b, String b){doing something}
}
</code>```

Notably i want to call helper class with method_important from other classes but want a flexiblity to pass desired arguments as i it can be two strings or i may have to pass String, int, String....
is it even possible? if no? what is best way to achieve it?
Problem is from my other methods i need to pass different type of variables..

答:
Although, the best way and suitable to you is using Method Overloading (specially in case where arguments have different data types).
But in case and just in case , if you have several methods where type of arguments is same but the number of arguments different (which can be a probable case), Why not use Varags https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html

You can use a combination of both Method overloading and varags in you helper class.

Body:
looking for some help...
In Java - i am trying to find if i can have a helper class which basically has several methods:

 class helper{
method1(){doing something}
method2(){doing something}
method_important(String a, String b){doing something}
method_important(String a, int b, String b){doing something}
}

Notably i want to call helper class with method_important from other classes but want a flexiblity to pass desired arguments as i it can be two strings or i may have to pass String, int, String....
is it even possible? if no? what is best way to achieve it?
Problem is from my other methods i need to pass different type of variables..


问:
Duplicate column name error using UNION query on the world table
I am trying to do a full join on the Mysql built in World database's three tables by the country code. I want to count the number of row returned.

Here is what I wrote:

```<code>    SELECT * From city
 LEFT JOIN country
        ON city.CountryCode = country.Code
 LEFT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode
     UNION
    SELECT * from city
RIGHT JOIN country
        ON city.CountryCode = country.Code
RIGHT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode;
</code>```

This returned 30671 rows.
If I wrap the COUNT(*) clause outside,

```<code>    SELECT COUNT(*) FROM (
    SELECT * from city
 LEFT JOIN country
        ON city.CountryCode = country.Code
 LEFT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode
     UNION
    SELECT * from city
RIGHT JOIN country
        ON city.CountryCode = country.Code
RIGHT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode) AS B;
</code>```

it rises
Error Code: 1060. Duplicate column name 'Name'.

I try to do it the other way:

```<code>    SELECT COUNT(*) from (
    SELECT c1.* from city AS c1
 LEFT JOIN country AS co1
        ON c1.CountryCode = co1.Code
 LEFT JOIN countrylanguage AS cl1
        ON co1.Code = cl1.CountryCode
     UNION
    SELECT c2.* from city AS c2
RIGHT JOIN country AS co2
        ON c2.CountryCode = co2.Code
RIGHT JOIN countrylanguage AS cl2
        ON co2.Code = cl2.CountryCode) AS B;
</code>```

Only has 4080 rows.

I am not sure which one is the correct way?

Thank you

答:
You get error

Duplicate column name 'Name'

because in your joins are multiple times column name

In normal query it is not a problem but with count(*) it matters. You must provide aliases for name columns, something like

```<code>city.name AS city_name
country.name AS country_name
countrylanguage.name AS countrylanguage_name
</code>```

See also this Duplicate column name on JOIN in mysql.

Alternatively if you need only count you could remove the unneeded columns from select, for example changing

```<code>SELECT *
</code>```

to

```<code>SELECT id -- or any appropriate column
</code>```

and then get count(id) or count(*).

Body:
I am trying to do a full join on the Mysql built in World database's three tables by the country code. I want to count the number of row returned.

Here is what I wrote:

    SELECT * From city
 LEFT JOIN country
        ON city.CountryCode = country.Code
 LEFT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode
     UNION
    SELECT * from city
RIGHT JOIN country
        ON city.CountryCode = country.Code
RIGHT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode;

This returned 30671 rows.
If I wrap the COUNT(*) clause outside,

    SELECT COUNT(*) FROM (
    SELECT * from city
 LEFT JOIN country
        ON city.CountryCode = country.Code
 LEFT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode
     UNION
    SELECT * from city
RIGHT JOIN country
        ON city.CountryCode = country.Code
RIGHT JOIN countrylanguage
        ON country.Code = countrylanguage.CountryCode) AS B;

it rises
Error Code: 1060. Duplicate column name 'Name'.

I try to do it the other way:

    SELECT COUNT(*) from (
    SELECT c1.* from city AS c1
 LEFT JOIN country AS co1
        ON c1.CountryCode = co1.Code
 LEFT JOIN countrylanguage AS cl1
        ON co1.Code = cl1.CountryCode
     UNION
    SELECT c2.* from city AS c2
RIGHT JOIN country AS co2
        ON c2.CountryCode = co2.Code
RIGHT JOIN countrylanguage AS cl2
        ON co2.Code = cl2.CountryCode) AS B;

Only has 4080 rows.

I am not sure which one is the correct way?

Thank you

Body:
You get error

Duplicate column name 'Name'

because in your joins are multiple times column name

In normal query it is not a problem but with count(*) it matters. You must provide aliases for name columns, something like

city.name AS city_name
country.name AS country_name
countrylanguage.name AS countrylanguage_name

See also this Duplicate column name on JOIN in mysql.

Alternatively if you need only count you could remove the unneeded columns from select, for example changing

SELECT *

to

SELECT id -- or any appropriate column

and then get count(id) or count(*).


问:
How to convert a DBNULL to double?
im getting a value from the database. it came out an error saying "Conversion from DBNULL to Double is not Valid." anyone, pls help me?

Public Function Total() As Double
        Dim Total As Double

```<code>    Dim strConn As String
    strConn = ConfigurationManager.ConnectionStrings("***").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT SUM (p.Price * c.Quantity) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID "

    Dim cmd As New SqlCommand(strSql, conn)

    cmd.Parameters.AddWithValue("@CartID", CartID)

    Dim da As New SqlDataAdapter(cmd)

    Dim ds As New DataSet

    conn.Open()

    da.Fill(ds, "CartItem")

    conn.Close()

    If (ds.Tables("CartItem").Rows.Count) <> 0 Then
        **Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
    Else
        Total = 0.0
    End If
    Return Total
End Function
</code>```

答: If it's possible for the value to be null, your return type needs to be double? (nullable double).</p>

Title: How to convert a DBNULL to double?

Body:
im getting a value from the database. it came out an error saying "Conversion from DBNULL to Double is not Valid." anyone, pls help me?

Public Function Total() As Double
        Dim Total As Double

    Dim strConn As String
    strConn = ConfigurationManager.ConnectionStrings("***").ToString
    Dim conn As New SqlConnection(strConn)

    Dim strSql As String
    strSql = "SELECT SUM (p.Price * c.Quantity) as 'Total' " & _
    "FROM CartItem sci INNER JOIN Product p ON c.ProductID=p.ProductID " & _
    "WHERE c.CartID=@CartID "

    Dim cmd As New SqlCommand(strSql, conn)

    cmd.Parameters.AddWithValue("@CartID", CartID)

    Dim da As New SqlDataAdapter(cmd)

    Dim ds As New DataSet

    conn.Open()

    da.Fill(ds, "CartItem")

    conn.Close()

    If (ds.Tables("CartItem").Rows.Count) <> 0 Then
        **Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
    Else
        Total = 0.0
    End If
    Return Total
End Function


问:
Need to hide YouTube Branding with iFrame API
I am using YouTube iFrame API to load videos in my custom player (javascript player). I have a requirement to hide the Youtube branding however on iOS devices, it shows the logo with below parameters:

```<code>playerVars:
{
    'fs':1,
    'autoplay' : 0,
    'showinfo' : 0,
    'rel' : 0,
    'controls' : videoControls,
    'cc_load_policy' : 0,
    'color':'white',
    'modestbranding' : 1,
    'iv_load_policy' : 3,
    'loop':inv_loop,
    'wmode': 'transparent',
    'playlist':playlist,
    'playsinline':1
}
</code>```

If I keep "showinfo" to 1, it hides the logo however it shows the video title, share and watch later icons along with ads.

is there any way to hide both (youtube logo and uploader info with ads) with iFrame API?

Thanks!

答:
You can add modestbranding=1

This parameter lets you use a YouTube player that does not show a YouTube logo. Set the parameter value to 1 to prevent the YouTube logo from displaying in the control bar. Note that a small YouTube text label will still display in the upper-right corner of a paused video when the user's mouse pointer hovers over the player.

showinfo=0 will remove the title bar

Values: 0 or 1. The parameter's default value is 1. If you set the parameter value to 0, then the player will not display information like the video title and uploader before the video starts playing.

Also I don't think YouTube allows you to remove their name/logo completely.

Body:
I am using YouTube iFrame API to load videos in my custom player (javascript player). I have a requirement to hide the Youtube branding however on iOS devices, it shows the logo with below parameters:

playerVars:
{
    'fs':1,
    'autoplay' : 0,
    'showinfo' : 0,
    'rel' : 0,
    'controls' : videoControls,
    'cc_load_policy' : 0,
    'color':'white',
    'modestbranding' : 1,
    'iv_load_policy' : 3,
    'loop':inv_loop,
    'wmode': 'transparent',
    'playlist':playlist,
    'playsinline':1
}

If I keep "showinfo" to 1, it hides the logo however it shows the video title, share and watch later icons along with ads.

is there any way to hide both (youtube logo and uploader info with ads) with iFrame API?

Thanks!


问:
Async Call in $http request
How to wait till the response comes from the $http request, in "angularjs"?
In ajax, a successful method is to set async = false like this,

```<code>jQuery.ajax({
     url: '/Something/Index',
     success: function (result) {
         result;
     },
     async: false
});
</code>```

But Its not working in $http request in angularjs.Is there any method for this?

答:
You can use the promise returned by $http services in AngularJS and use .then function. This ensures that the first function response is received and then only code inside .then function would execute.

A sample code would be as below:

```<code>var app = angular.module("app", []);

app.factory('myService', function ($http) {
    return {
        serverCall: function () {
            return $http.get('/Something/Index').then(function (response) {
                console.log(response);
                return response;
            });
        }
    };
});

app.controller("myController", function ($scope, myService) {

    $scope.GetDataFromServer = function () {

        // make the ajax call
        var myData = myService.serverCall();

        // this executes after that ajax call is completed
        myData.then(function (result) {
            $scope.data = result;
        });

    };
});
</code>```

Title: Async Call in $http request

Body:
How to wait till the response comes from the $http request, in "angularjs"?
In ajax, a successful method is to set async = false like this,

jQuery.ajax({
     url: '/Something/Index',
     success: function (result) {
         result;
     },
     async: false
});

But Its not working in $http request in angularjs.Is there any method for this?

Body:
You can use the promise returned by $http services in AngularJS and use .then function. This ensures that the first function response is received and then only code inside .then function would execute.

A sample code would be as below:

var app = angular.module("app", []);

app.factory('myService', function ($http) {
    return {
        serverCall: function () {
            return $http.get('/Something/Index').then(function (response) {
                console.log(response);
                return response;
            });
        }
    };
});

app.controller("myController", function ($scope, myService) {

    $scope.GetDataFromServer = function () {

        // make the ajax call
        var myData = myService.serverCall();

        // this executes after that ajax call is completed
        myData.then(function (result) {
            $scope.data = result;
        });

    };
});


问:
Specifying which activity to launch dynamically
I am developing a chat application.

Once logged in, the user should be navigated into the main page next time when he start the app. Like WhatsApp, it does not have a splash screen. So, Where do I do the check if the user has logged in or not next time ? I don't want to launch the login screen again if the user is already logged in.

Can I launch a service or something on the first time in which I can check which activity is shown next?

答: Use Shared Preference for store login details and check in Main or loginActivity if user Logged in do what you want other wise print alert/Toast Logged in first. </p>


问:
Can I use a lambda function or std::function object in place of a function pointer?
I've got a library that I need to use that defines the following:

```<code>typedef void CallbackFunction(const int& i);
</code>```

and has a function to register your callback that looks like:

```<code>void registerCallback(CallbackFunction* pCallback);
</code>```

Because I'd like to capture the state of several variables to be used in the callback, I can't simply use a plain function. What I'd prefer to use is a lambda function, but the following doesn't compile:

```<code>auto fCallback = [](const int& i) {
    cout << i << endl;
};
registerCallback(fCallback);
</code>```

instead I get the error:

```<code>error C2664: 'registerCallback' : cannot convert parameter 1 from '`anonymous-namespace'::<lambda0>' to 'CallbackFunction (__cdecl *)'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
</code>```

I've been reading up on this topic a lot, and trying a few different (probably idiotic) approaches, but I can't seem to get this to work. Casting the function allows the code to compile, but (not surprisingly) it crashes. It may be that I've overlooked the solution either here on StackOverflow or elsewhere, so a link will suffice. (Though, since I'm a bit new to some of these techniques, please make sure that the correspondence is clear enough for a newbie. For instance, if this conversation contains my answer, I don't understand. Please simplify or explain the correspondence.) FYI, I'm using Visual C++ 2010.

Please let me know if there is anything I can do to clarify my question. Thanks in advance for the help!

答:
You can't use lambdas, because your registerCallback function expects pointer to non-member function. The only way to pass additional parameter to free standing function is 1) using global (static) data or 2) making it a template taking compile time constants, e.g.

```<code>template<int data> void callback(const int& i)
{ /* can use data */ }

registerCallback(callback<10>);
</code>```

Body:
I've got a library that I need to use that defines the following:

typedef void CallbackFunction(const int& i);

and has a function to register your callback that looks like:

void registerCallback(CallbackFunction* pCallback);

Because I'd like to capture the state of several variables to be used in the callback, I can't simply use a plain function. What I'd prefer to use is a lambda function, but the following doesn't compile:

auto fCallback = [](const int& i) {
    cout << i << endl;
};
registerCallback(fCallback);

instead I get the error:

error C2664: 'registerCallback' : cannot convert parameter 1 from '`anonymous-namespace'::<lambda0>' to 'CallbackFunction (__cdecl *)'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

I've been reading up on this topic a lot, and trying a few different (probably idiotic) approaches, but I can't seem to get this to work. Casting the function allows the code to compile, but (not surprisingly) it crashes. It may be that I've overlooked the solution either here on StackOverflow or elsewhere, so a link will suffice. (Though, since I'm a bit new to some of these techniques, please make sure that the correspondence is clear enough for a newbie. For instance, if this conversation contains my answer, I don't understand. Please simplify or explain the correspondence.) FYI, I'm using Visual C++ 2010.

Please let me know if there is anything I can do to clarify my question. Thanks in advance for the help!

Body:
You can't use lambdas, because your registerCallback function expects pointer to non-member function. The only way to pass additional parameter to free standing function is 1) using global (static) data or 2) making it a template taking compile time constants, e.g.

template<int data> void callback(const int& i)
{ /* can use data */ }

registerCallback(callback<10>);


答:
If you want to use jQuery then,</p>

```<code>function rotateBtn() {
var isRotated = 0; // boolean value
$("signUpBtn").css("transformOrigin","top center");
$("signUpBtn").css("transition","1s ease-in-out");
    if (!isRotated) {
        $("signUpBtn").css("transform", "rotateY(90deg)");
        isRotated = 1;
    }

    if (isRotated) {
        $("signUpBtn").css("transform", "rotateY(0deg)");
        isRotated = 0;
    }
}
</code>```

Title: JavaScript changing CSS not working inside of if statement

Body:
Here is my html :

 Sign up »

Here is the JS... the style changes don't work when I take it out of the if statement. I need the if statement to toggle back and forth between the two rotations.
Doing this to learn, want to use JS and also see how it works with jQuery

function rotateBtn() {
var isRotated = 0;
document.getElementById("signUpBtn").style.transformOrigin = "top center";
document.getElementById("signUpBtn").style.transition = "1s ease-in-out";

if (!isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(90deg)";
    isRotated = 1;
}

if (isRotated) {
    document.getElementById("signUpBtn").style.transform = "rotateY(0deg)";
    isRotated = 0;
}

Body:
If you want to use jQuery then,

function rotateBtn() {
var isRotated = 0; // boolean value
$("signUpBtn").css("transformOrigin","top center");
$("signUpBtn").css("transition","1s ease-in-out");
    if (!isRotated) {
        $("signUpBtn").css("transform", "rotateY(90deg)");
        isRotated = 1;
    }

    if (isRotated) {
        $("signUpBtn").css("transform", "rotateY(0deg)");
        isRotated = 0;
    }
}


答:
The problem is the line

```<code>return digit_sum(n//10) + n%10
</code>```

because if the sum of the digits of n//10 and the last digit becomes a number of two digits no one is reducing it. A possible solution is:

```<code>return digit_sum(digit_sum(n//10) + n%10)
</code>```

Title: Recursive function to add all the digits

Body:
I am trying to get the sum of all digits. The only method allowed to solve this question is recursive function. But, the sum is not supposed to exceed 10. For example, if given n is 38, it should return 2. (3+8 = 11, 1+1 =2)

I made the below code. But, it only returns 11. I approached this question in many different ways such as nested if and while loop, but I could not figure it out. Is there any way that I can solve this question using recursive function?

def digit_sum(n):
    if n//10 <= 0:
        return n%10
    return digit_sum(n//10) + n%10

Body:
The problem is the line

return digit_sum(n//10) + n%10

because if the sum of the digits of n//10 and the last digit becomes a number of two digits no one is reducing it. A possible solution is:

return digit_sum(digit_sum(n//10) + n%10)


问:
Which language should I use for [many reads, few big writes DB] with [many concurrent connections]?
Which language would you recommend for use on a dynamic web-page with many users connected.  I am not using flash or anything like that, interactivity is all Javascript/HTML.

My basic two restrictions are:

plays nicely with mySQL or if you have other specific recommendations for db I am all-ears.

It has to be able to keep up with tons of concurrent connections that are all reading small subsets of all the content (so very cache-able) and occasionally posting plaintext (not very frequently, but voluminous -- say

I am really interested in learning a new language as a personal-programmer-expand-my-horizons initiative, so I don't want to use a java server back-end, because that's something I'm very familiar with (and I would really need something with better thread management than apache).  I'm coding proficient (but not fluent) Javascript, and would be open to JS options in addition to everything else.

Things I have looked into and figure they might be relevant, but I'm not sure how:

Node.js

Thanks for your input!

I also tagged this "web-application-design" and I feel that many programmers neglect to notice that figuring out the basic structure of your program and how the methods and objects will interoperate beforehand is absolutely 100% part of the design phase.

答: In addition to PHP probably being the best choice for primary language, you should also consider (If you have enough control over the server) using MEMCACHE and if you are doing very considerably more reads than writes. That would effectively allow you to cache your data in memory and that access is blazingly faster than Db lookups.</p>


问:
logic of variable in javascript
I have some lines of code :
why print 'undefined' and 'B' on my browser . Can you explain for me? </p>

```<code>var x = 'A';

function func(){
  document.write(x);
  var x = "B";
  document.write(x);
};

func();
</code>```

答:
It's JavaScript Hoisting. In your example x inside that function is hoisted. In JavaScript, variable declarations are only hoisted, NOT their initializations.

Update:

Regarding ES6, const and let declarations are not hoisted.

Title: logic of variable in javascript

Body:
I have some lines of code :
why print 'undefined' and 'B' on my browser . Can you explain for me?

var x = 'A';

function func(){
  document.write(x);
  var x = "B";
  document.write(x);
};

func();


问:
Gradle tries to reach remote repository even though jars are in Maven local
Background: I'm working on a Jenkins box that has no internet access (on the command line browsers work idk why) trying to run a Serenity Gradle script(a fluffy version of this http://thucydides.info/docs/serenity-staging/#_building_serenity_projects_in_gradle). I had this problem on my local machine I was able to resolve it by manually creating a .m2 (downloading jars 1 by one on the browser) and having mavenLocal in the list of repository (as in the example).

Problem: so I copy the .m2 folder to the Jenkins user on the remote box but when running the command Gradle clean test aggregate on the Jenkins box the output says the error is a failure to reach jcenter.

Things I've tried:
1 running with --offline (result says no cache version of artificat)
2 copying the Gradle cache from my local to the Jenkins user on the remote box.( They have a shared folder) Why is it trying to reach when the
3 copy the .gradle folder from one to another.
4 remove jcenter (still fails)

I'm at a lost as to what could possibly be wrong in our project Jenkins anywhere we've been tinkering for over a week

答: The best solution for this sort of problem would probably be to set up a Nexus or Artifactory proxy that your Jenkins box can access directly (the Nexus/Artifactory installation needs to be on a box with internet access, though).</p>


问:
R, dplyr: Looping over a subset of columns by name and applying mutate?
My current setup uses R 3.4.2 and tidyverse 1.1.1.

My aim is to transform data in the manner of this answer but to do so in a way that is extensible, so that I can easily change the set of variables that I wish to perform this operation with.

For the sake of definiteness, let us take the following data:

```<code>library(tidyverse)

df = tibble(
  id = seq(1,8),
  hair.colour = c("red", "blonde", "brown", "black", "red", "blonde", "brown", "black"),
  eye.colour = c("blue", "brown", "blue", "brown", "blue", "brown", "blue", "brown"),
  gender = c("male", "male", "male", "male", "female", "female", "female",
             "female"))
</code>```

Code such as this works as desired:

```<code>df2 = df %>%
  mutate(value = 1,
         hair.colour = paste("hair.colour", hair.colour, sep = ".")) %>%
  spread(hair.colour, value, fill = 0)
</code>```

Naively attempting to wrap this in a loop, e.g.

```<code>factors = c("hair.colour", "eye.colour", "gender")
for (factor in factors) {
    df = df %>%
        mutate(value = 1, factor = paste(toString(factor), factor, sep = ".")) %>%
        spread(factor, value, fill = 0)
}
</code>```

does not work. I imagine there's a clever way using quo(), !!, etc., but I'm new to R, and my searches have yielded nothing that I can use.

Does anyone have any advice, both within the tidyverse (especially if it finds a way to use the same code as in the second block) and outside of it?

答:
Since, as @aosmith pointed out, select_ is deprecated and you might want to have a more flexible solution, you might try

```<code>df %>%
  # make data long
  gather(key = key, value = value, -id) %>%
  # unite columns
  unite(col = new_key, key, value, sep = ".") %>%
  # add column with 1 for indication when back to wide
  mutate(new_value = 1,
         # this is only needed if you want to keep the order of the variables:
         new_key = factor(new_key, levels = unique(new_key))) %>%
  # transform back to wide, fill NAs with 0
  spread(key = new_key, value = new_value, fill = 0)
</code>```

Body:
My current setup uses R 3.4.2 and tidyverse 1.1.1.

My aim is to transform data in the manner of this answer but to do so in a way that is extensible, so that I can easily change the set of variables that I wish to perform this operation with.

For the sake of definiteness, let us take the following data:

library(tidyverse)

df = tibble(
  id = seq(1,8),
  hair.colour = c("red", "blonde", "brown", "black", "red", "blonde", "brown", "black"),
  eye.colour = c("blue", "brown", "blue", "brown", "blue", "brown", "blue", "brown"),
  gender = c("male", "male", "male", "male", "female", "female", "female",
             "female"))

Code such as this works as desired:

df2 = df %>%
  mutate(value = 1,
         hair.colour = paste("hair.colour", hair.colour, sep = ".")) %>%
  spread(hair.colour, value, fill = 0)

Naively attempting to wrap this in a loop, e.g.

factors = c("hair.colour", "eye.colour", "gender")
for (factor in factors) {
    df = df %>%
        mutate(value = 1, factor = paste(toString(factor), factor, sep = ".")) %>%
        spread(factor, value, fill = 0)
}

does not work. I imagine there's a clever way using quo(), !!, etc., but I'm new to R, and my searches have yielded nothing that I can use.

Does anyone have any advice, both within the tidyverse (especially if it finds a way to use the same code as in the second block) and outside of it?

Body:
Since, as @aosmith pointed out, select_ is deprecated and you might want to have a more flexible solution, you might try

df %>%
  # make data long
  gather(key = key, value = value, -id) %>%
  # unite columns
  unite(col = new_key, key, value, sep = ".") %>%
  # add column with 1 for indication when back to wide
  mutate(new_value = 1,
         # this is only needed if you want to keep the order of the variables:
         new_key = factor(new_key, levels = unique(new_key))) %>%
  # transform back to wide, fill NAs with 0
  spread(key = new_key, value = new_value, fill = 0)


答:
You'll need to check that
ds.Tables("ShopCartItem").Rows(0))("Total") = DbNull.Value before you set it.

```<code>If (ds.Tables("CartItem").Rows.Count) <> 0 Then
    If ds.Tables("ShopCartItem").Rows(0))("Total") = DbNull.Value
       Total = 0.0
    else
      Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
Else
    Total = 0.0
End If
</code>```

Title: How to convert a DBNULL to double?

Body:
You'll need to check that
ds.Tables("ShopCartItem").Rows(0))("Total") = DbNull.Value before you set it.

If (ds.Tables("CartItem").Rows.Count) <> 0 Then
    If ds.Tables("ShopCartItem").Rows(0))("Total") = DbNull.Value
       Total = 0.0
    else
      Total = ds.Tables("ShopCartItem").Rows(0)("Total")**
Else
    Total = 0.0
End If


问:
Mysql After insert trigger fails
I am trying a mysql trigger. It is my first time

```<code>DROP TRIGGER IF EXISTS `mega_insert`;
delimiter |

CREATE TRIGGER mega_insert AFTER INSERT ON purchase_master
  FOR EACH ROW
  BEGIN
    INSERT INTO mega_score_genre (test_id,user_id,package_id)
    SELECT p.test_id
    ,:NEW.user_id
    ,:NEW.package_id
    FROM package_master p
    ON p.package_id = :NEW.package_id;
  END;
|

delimiter ;
</code>```

It is not working #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':NEW.user_id.

I tried different things but i could not get it working. If anyone can help me getting this work, I will be helpful.

In this I am trying to populate * mega_score_genre* table whenever something inserted into purchase_master table & get test_id filed from package_master table where package_master.package_id = purchase_master.package_id

答:
https://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html

Within the trigger body, the OLD and NEW keywords enable you to access columns in the rows affected by a trigger. OLD and NEW are MySQL extensions to triggers; they are not case sensitive.

NEW, not :NEW.

Out of curiosity, from what example or reference did you get the idea that you should spell it :NEW?

Second problem: You have only one table in your SELECT. You're not doing a JOIN so you can't have an ON clause. Read about the syntax of SELECT here: https://dev.mysql.com/doc/refman/5.7/en/join.html

The example should use WHERE instead of ON if it wants to select some rows based on a condition.

Title: Mysql After insert trigger fails

Body:
I am trying a mysql trigger. It is my first time

DROP TRIGGER IF EXISTS `mega_insert`;
delimiter |

CREATE TRIGGER mega_insert AFTER INSERT ON purchase_master
  FOR EACH ROW
  BEGIN
    INSERT INTO mega_score_genre (test_id,user_id,package_id)
    SELECT p.test_id
    ,:NEW.user_id
    ,:NEW.package_id
    FROM package_master p
    ON p.package_id = :NEW.package_id;
  END;
|

delimiter ;

It is not working #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':NEW.user_id.

I tried different things but i could not get it working. If anyone can help me getting this work, I will be helpful.

In this I am trying to populate * mega_score_genre* table whenever something inserted into purchase_master table & get test_id filed from package_master table where package_master.package_id = purchase_master.package_id


问:
SAPUI5 : How to create a sideBar in SAPUI5?
SAPUI5 : How to create a sideBar in SAPUI5 ? I have to create a collapseable side bar on the right. please help me here.

Note: I have to do this without using Ux3 or commons libraries.

答:
Is that what you want?
    https://sapui5.hana.ondemand.com/#/sample/sap.ui.layout.sample.DynamicSideContentProduct/preview

if not

html or xml or js

```<code><div id="closeBtn">close</div>
<div id="sideBar">......</div>
</code>```

js (jquery)

```<code>var open = true;

$("#closeBtn").on("click",function(){

   if(open){
         $("#sidebar).animate(    {'height' : '200'},300};
   }
   else{`enter code here`
         $("#sidebar).animate({'height' : '0'},300};
   }
}
</code>```

Body:
Is that what you want?
    https://sapui5.hana.ondemand.com/#/sample/sap.ui.layout.sample.DynamicSideContentProduct/preview

if not

html or xml or js

<div id="closeBtn">close</div>
<div id="sideBar">......</div>

js (jquery)

var open = true;

$("#closeBtn").on("click",function(){

   if(open){
         $("#sidebar).animate(    {'height' : '200'},300};
   }
   else{`enter code here`
         $("#sidebar).animate({'height' : '0'},300};
   }
}


问:
What is the double dash in this bash script excerpt doing
I'm looking at an excerpt of bash and I'm trying to understand what exactly is happening here, particularly in the COMPREPLY assignment:

```<code> case "$cur" in
    -*)
    COMPREPLY=( $( compgen -W '-a -d -f -l -t -h --aoption --debug \
                               --file --log --test --help --' -- $cur ) );;
#   Generate the completion matches and load them into $COMPREPLY array.
#   xx) May add more cases here.
#   yy)
#   zz)
  esac
</code>```

I understand we're assigning a value to COMPREPLY here based on the output of compgen, but what exactly is -- doing in this assignment? Also, why the double semi-colon?

答:
The meaning of -- really depends on the program you are executing. In this example compgen. Check the documentation of this program, it should be explained there.

A common convention that is not necessarily always followed is to treat everything after -- as arguments, and do not try to parse as options or flags. As a concrete example, consider the case of running the GNU ls command to get a detailed listing of a file named -t. Running ls -l -t will treat -t as an option (order output by time), not as a filename argument. The solution is ls -l -- -t, this way ls will not try to parse the arguments after --. This is just a convention and not all programs may follow it. Note also that I wrote GNU ls not just ls, because other implementations may behave differently.

Body:
I'm looking at an excerpt of bash and I'm trying to understand what exactly is happening here, particularly in the COMPREPLY assignment:

 case "$cur" in
    -*)
    COMPREPLY=( $( compgen -W '-a -d -f -l -t -h --aoption --debug \
                               --file --log --test --help --' -- $cur ) );;
#   Generate the completion matches and load them into $COMPREPLY array.
#   xx) May add more cases here.
#   yy)
#   zz)
  esac

I understand we're assigning a value to COMPREPLY here based on the output of compgen, but what exactly is -- doing in this assignment? Also, why the double semi-colon?


问:
JSSC alternatives for getInputStream & getOutPutStream
I'm trying to implement one piece of code in my application and I'm using JSSC communication library. This piece of code that I need to implement is using javax.comm.* library. The problem is in methods .getInputStream() and getOutputStream() which are not present in JSSC. Is there any alternative way in JSSC library that can replace those two methods?</p>

答:
Consider these 2 source codes:
idea 1 and
idea 2
You can write your versions of these streams methods by modifying jssc.</p>


问:
How to use trained model in tensorflow, using CNNs to detect object with bounding box
I have built model in tensorflow use CNNs with accuracy over 90%. It's really worked but I don't know how to use this model to detect object with bounding box which I have trained. My model include many class and once label asociated with name of class. I'd read some way about ssd, it can do that but I don't really understand how it work. My CNNs below :

```<code>def cnn_model_fn(features,labels,mode):
#Input layer
input_layer = tf.reshape(features["x"],[-1,28,28,1])

#Convolutional layer 1
conv1 = tf.layers.conv2d(
inputs=input_layer,
filters=32,
kernel_size=[5,5],
padding="same",
activation=tf.nn.relu)

#Pooling Layer 1
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=[2,2],strides=2)

#Convolutional layer 2
conv2 = tf.layers.conv2d(
    inputs=pool1,
    filters=64,
    kernel_size=[5,5],
    padding="same",
    activation=tf.nn.relu)

#Pooling layer 2
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=[2,2],strides=2)

#Debse layer
pool2_flat = tf.reshape(pool2,[-1,7*7*64])
dense = tf.layers.dense(inputs=pool2_flat,units=1024,activation=tf.nn.relu)

#Dropout
dropout = tf.layers.dropout(inputs=dense,rate=0.4,training=mode == tf.estimator.ModeKeys.TRAIN)

#Logits layer
logits = tf.layers.dense(inputs=dropout,units=10)

predictions = {
"classes":tf.argmax(input=logits,axis=1),
"probabilities":tf.nn.softmax(logits,name="softmax_tensor")
}

if mode == tf.estimator.ModeKeys.PREDICT:
    return tf.estimator.EstimatorSpec(mode=mode,predictions=predictions)

#Calculate Loss
onehot_labels = tf.one_hot(indices=tf.cast(labels,tf.int32),depth=10)
loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels,logits=logits)

if mode == tf.estimator.ModeKeys.TRAIN:
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
    train_op = optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode=mode,loss=loss,train_op=train_op)

eval_metric_ops = {
"accuracy":tf.metrics.accuracy(labels=labels,predictions=predictions["classes"])
}

return tf.estimator.EstimatorSpec(mode=mode,loss=loss,eval_metric_ops=eval_metric_ops)
</code>```

And I run my app with main:

```<code>def main(unused_argv):
# Load training and eval data
train_data_dir = "W:/Projects/AutoDrive/Training"
test_data_dir = "W:/Projects/AutoDrive/Testing"

images,labels = load_data(train_data_dir)
test_images,test_labels = load_data(test_data_dir)

print("Labels: {0} \nImages: {1}".format(len(set(labels)),len(images)))

for image in images[:5]:
    print("shape: {0}, min: {1}, max: {2}".format(image.shape, image.min(), image.max()))

images = [skimage.transform.resize(image,(28,28,1)) for image in images]

for image in images[:5]:
    print("shape: {0}, min: {1}, max: {2}".format(image.shape, image.min(), image.max()))

images = np.asarray(images,dtype=np.float32)
labels = np.asarray(labels,dtype=np.int32)

# Create the Estimator
TSRecognition_classifier = tf.estimator.Estimator(
model_fn=cnn_model_fn, model_dir="/tmp/TSRecognition_convnet_model")

# Set up logging for predictions
# Log the values in the "Softmax" tensor with label "probabilities"
tensors_to_log = {"probabilities": "softmax_tensor"}
logging_hook = tf.train.LoggingTensorHook(
tensors=tensors_to_log, every_n_iter=50)

# Train the model
train_input_fn = tf.estimator.inputs.numpy_input_fn(
                       x={"x": images},
                       y=labels,
                       batch_size=100,
                       num_epochs=None,
                       shuffle=True)

TSRecognition_classifier.train(
         input_fn=train_input_fn,
         steps=20000,
         hooks=[logging_hook])

# Evaluate the model and print results
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
                        x={"x": test_images},
                        y=test_labels,
                        num_epochs=1,
                        shuffle=False)
eval_results = TSRecognition_classifier.evaluate(input_fn=eval_input_fn)
print(eval_results)
</code>```

And this is full code if you want to see:

```<code>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf
import os
import skimage.data
import skimage.transform
import matplotlib
import matplotlib.pyplot as plt

tf.logging.set_verbosity(tf.logging.INFO)

def load_data(data_dir):
    """Load Data and return two lists"""
    directories = [d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir,d))]

    list_labels = []
    list_images = []

    for d in directories:
        label_dir = os.path.join(data_dir,d)
        file_names = [os.path.join(label_dir,f) for f in os.listdir(label_dir) if f.endswith(".ppm")]
        for f in file_names:
            list_images.append(skimage.data.imread(f))
            list_labels.append(int(d))

    return list_images,list_labels

def display_images_and_labels(images,labels):
    unique_labels = set(labels)
    plt.figure(figsize=(15,15))
    i = 1
    for label in unique_labels:
        image = images[labels.index(label)]
        plt.subplot(8,8,i)
        plt.axis('off')
        plt.title("Label {0} ({1})".format(label,labels.count(label)))
        i += 1
        _ = plt.imshow(image)
        plt.show()

def cnn_model_fn(features,labels,mode):
        #Input layer
        input_layer = tf.reshape(features["x"],[-1,28,28,1])

        #Convolutional layer 1
        conv1 = tf.layers.conv2d(
            inputs=input_layer,
            filters=32,
            kernel_size=[5,5],
            padding="same",
            activation=tf.nn.relu)

        #Pooling Layer 1
        pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=[2,2],strides=2)

        #Convolutional layer 2
        conv2 = tf.layers.conv2d(
                   inputs=pool1,
                   filters=64,
                   kernel_size=[5,5],
                   padding="same",
                   activation=tf.nn.relu)

         #Pooling layer 2
         pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=[2,2],strides=2)

         #Debse layer
         pool2_flat = tf.reshape(pool2,[-1,7*7*64])
         dense = tf.layers.dense(inputs=pool2_flat,units=1024,activation=tf.nn.relu)

         #Dropout
         dropout = tf.layers.dropout(inputs=dense,rate=0.4,training=mode == tf.estimator.ModeKeys.TRAIN)

         #Logits layer
         logits = tf.layers.dense(inputs=dropout,units=10)

         predictions = {
              "classes":tf.argmax(input=logits,axis=1),
              "probabilities":tf.nn.softmax(logits,name="softmax_tensor")
               }

         if mode == tf.estimator.ModeKeys.PREDICT:
            return tf.estimator.EstimatorSpec(mode=mode,predictions=predictions)

         #Calculate Loss
         onehot_labels = tf.one_hot(indices=tf.cast(labels,tf.int32),depth=10)
         loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels,logits=logits)

         if mode == tf.estimator.ModeKeys.TRAIN:
            optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
            train_op = optimizer.minimize(
                         loss=loss,
                         global_step=tf.train.get_global_step())
            return tf.estimator.EstimatorSpec(mode=mode,loss=loss,train_op=train_op)

         eval_metric_ops = {"accuracy":tf.metrics.accuracy(labels=labels,predictions=predictions["classes"])
}

          return tf.estimator.EstimatorSpec(mode=mode,loss=loss,eval_metric_ops=eval_metric_ops)

def main(unused_argv):
    # Load training and eval data
    train_data_dir = "W:/Projects/AutoDrive/Training"
    test_data_dir = "W:/Projects/AutoDrive/Testing"

    images,labels = load_data(train_data_dir)
    test_images,test_labels = load_data(test_data_dir)

    print("Labels: {0} \nImages: {1}".format(len(set(labels)),len(images)))

    for image in images[:5]:
        print("shape: {0}, min: {1}, max: {2}".format(image.shape, image.min(), image.max()))

    images = [skimage.transform.resize(image,(28,28,1)) for image in images]

    for image in images[:5]:
        print("shape: {0}, min: {1}, max: {2}".format(image.shape, image.min(), image.max()))

    images = np.asarray(images,dtype=np.float32)
    labels = np.asarray(labels,dtype=np.int32)

    # Create the Estimator
    TSRecognition_classifier = tf.estimator.Estimator(
    model_fn=cnn_model_fn, model_dir="/tmp/TSRecognition_convnet_model")

    # Set up logging for predictions
    # Log the values in the "Softmax" tensor with label "probabilities"
    tensors_to_log = {"probabilities": "softmax_tensor"}
   logging_hook = tf.train.LoggingTensorHook(
                   tensors=tensors_to_log, every_n_iter=50)

    # Train the model
    train_input_fn = tf.estimator.inputs.numpy_input_fn(
                       x={"x": images},
                       y=labels,
                       batch_size=100,
                       num_epochs=None,
                       shuffle=True)

    TSRecognition_classifier.train(
         input_fn=train_input_fn,
         steps=20000,
         hooks=[logging_hook])

    # Evaluate the model and print results
    eval_input_fn = tf.estimator.inputs.numpy_input_fn(
                        x={"x": test_images},
                        y=test_labels,
                        num_epochs=1,
                        shuffle=False)
    eval_results = TSRecognition_classifier.evaluate(input_fn=eval_input_fn)
    print(eval_results)

if __name__ == "__main__":
    tf.app.run()
</code>```

Addtionally, I've seen video which I think it can help me. But they just help me train single object. Any ideas can help me ?

答: There are some CNN that can output bounding boxes, and some CNN that only classify the input images. Yours is the second type. If you want bounding boxes with tensorflow, you can use the object detection API that allows you to build multi-class SSD and faster-rcnn : https://github.com/tensorflow/models/tree/master/research/object_detection</p>

Body:
I have built model in tensorflow use CNNs with accuracy over 90%. It's really worked but I don't know how to use this model to detect object with bounding box which I have trained. My model include many class and once label asociated with name of class. I'd read some way about ssd, it can do that but I don't really understand how it work. My CNNs below :

def cnn_model_fn(features,labels,mode):
#Input layer
input_layer = tf.reshape(features["x"],[-1,28,28,1])

#Convolutional layer 1
conv1 = tf.layers.conv2d(
inputs=input_layer,
filters=32,
kernel_size=[5,5],
padding="same",
activation=tf.nn.relu)

#Pooling Layer 1
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=[2,2],strides=2)

#Convolutional layer 2
conv2 = tf.layers.conv2d(
    inputs=pool1,
    filters=64,
    kernel_size=[5,5],
    padding="same",
    activation=tf.nn.relu)

#Pooling layer 2
pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=[2,2],strides=2)

#Debse layer
pool2_flat = tf.reshape(pool2,[-1,7*7*64])
dense = tf.layers.dense(inputs=pool2_flat,units=1024,activation=tf.nn.relu)

#Dropout
dropout = tf.layers.dropout(inputs=dense,rate=0.4,training=mode == tf.estimator.ModeKeys.TRAIN)

#Logits layer
logits = tf.layers.dense(inputs=dropout,units=10)

predictions = {
"classes":tf.argmax(input=logits,axis=1),
"probabilities":tf.nn.softmax(logits,name="softmax_tensor")
}

if mode == tf.estimator.ModeKeys.PREDICT:
    return tf.estimator.EstimatorSpec(mode=mode,predictions=predictions)

#Calculate Loss
onehot_labels = tf.one_hot(indices=tf.cast(labels,tf.int32),depth=10)
loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels,logits=logits)

if mode == tf.estimator.ModeKeys.TRAIN:
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
    train_op = optimizer.minimize(
        loss=loss,
        global_step=tf.train.get_global_step())
    return tf.estimator.EstimatorSpec(mode=mode,loss=loss,train_op=train_op)

eval_metric_ops = {
"accuracy":tf.metrics.accuracy(labels=labels,predictions=predictions["classes"])
}

return tf.estimator.EstimatorSpec(mode=mode,loss=loss,eval_metric_ops=eval_metric_ops)

And I run my app with main:

def main(unused_argv):
# Load training and eval data
train_data_dir = "W:/Projects/AutoDrive/Training"
test_data_dir = "W:/Projects/AutoDrive/Testing"

images,labels = load_data(train_data_dir)
test_images,test_labels = load_data(test_data_dir)

print("Labels: {0} \nImages: {1}".format(len(set(labels)),len(images)))

for image in images[:5]:
    print("shape: {0}, min: {1}, max: {2}".format(image.shape, image.min(), image.max()))

images = [skimage.transform.resize(image,(28,28,1)) for image in images]

for image in images[:5]:
    print("shape: {0}, min: {1}, max: {2}".format(image.shape, image.min(), image.max()))

images = np.asarray(images,dtype=np.float32)
labels = np.asarray(labels,dtype=np.int32)

# Create the Estimator
TSRecognition_classifier = tf.estimator.Estimator(
model_fn=cnn_model_fn, model_dir="/tmp/TSRecognition_convnet_model")

# Set up logging for predictions
# Log the values in the "Softmax" tensor with label "probabilities"
tensors_to_log = {"probabilities": "softmax_tensor"}
logging_hook = tf.train.LoggingTensorHook(
tensors=tensors_to_log, every_n_iter=50)

# Train the model
train_input_fn = tf.estimator.inputs.numpy_input_fn(
                       x={"x": images},
                       y=labels,
                       batch_size=100,
                       num_epochs=None,
                       shuffle=True)

TSRecognition_classifier.train(
         input_fn=train_input_fn,
         steps=20000,
         hooks=[logging_hook])

# Evaluate the model and print results
eval_input_fn = tf.estimator.inputs.numpy_input_fn(
                        x={"x": test_images},
                        y=test_labels,
                        num_epochs=1,
                        shuffle=False)
eval_results = TSRecognition_classifier.evaluate(input_fn=eval_input_fn)
print(eval_results)

And this is full code if you want to see:

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf
import os
import skimage.data
import skimage.transform
import matplotlib
import matplotlib.pyplot as plt

tf.logging.set_verbosity(tf.logging.INFO)

def load_data(data_dir):
    """Load Data and return two lists"""
    directories = [d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir,d))]

    list_labels = []
    list_images = []

    for d in directories:
        label_dir = os.path.join(data_dir,d)
        file_names = [os.path.join(label_dir,f) for f in os.listdir(label_dir) if f.endswith(".ppm")]
        for f in file_names:
            list_images.append(skimage.data.imread(f))
            list_labels.append(int(d))

    return list_images,list_labels

def display_images_and_labels(images,labels):
    unique_labels = set(labels)
    plt.figure(figsize=(15,15))
    i = 1
    for label in unique_labels:
        image = images[labels.index(label)]
        plt.subplot(8,8,i)
        plt.axis('off')
        plt.title("Label {0} ({1})".format(label,labels.count(label)))
        i += 1
        _ = plt.imshow(image)
        plt.show()

def cnn_model_fn(features,labels,mode):
        #Input layer
        input_layer = tf.reshape(features["x"],[-1,28,28,1])

        #Convolutional layer 1
        conv1 = tf.layers.conv2d(
            inputs=input_layer,
            filters=32,
            kernel_size=[5,5],
            padding="same",
            activation=tf.nn.relu)

        #Pooling Layer 1
        pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=[2,2],strides=2)

        #Convolutional layer 2
        conv2 = tf.layers.conv2d(
                   inputs=pool1,
                   filters=64,
                   kernel_size=[5,5],
                   padding="same",
                   activation=tf.nn.relu)

         #Pooling layer 2
         pool2 = tf.layers.max_pooling2d(inputs=conv2,pool_size=[2,2],strides=2)

         #Debse layer
         pool2_flat = tf.reshape(pool2,[-1,7*7*64])
         dense = tf.layers.dense(inputs=pool2_flat,units=1024,activation=tf.nn.relu)

         #Dropout
         dropout = tf.layers.dropout(inputs=dense,rate=0.4,training=mode == tf.estimator.ModeKeys.TRAIN)

         #Logits layer
         logits = tf.layers.dense(inputs=dropout,units=10)

         predictions = {
              "classes":tf.argmax(input=logits,axis=1),
              "probabilities":tf.nn.softmax(logits,name="softmax_tensor")
               }

         if mode == tf.estimator.ModeKeys.PREDICT:
            return tf.estimator.EstimatorSpec(mode=mode,predictions=predictions)

         #Calculate Loss
         onehot_labels = tf.one_hot(indices=tf.cast(labels,tf.int32),depth=10)
         loss = tf.losses.softmax_cross_entropy(onehot_labels=onehot_labels,logits=logits)

         if mode == tf.estimator.ModeKeys.TRAIN:
            optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
            train_op = optimizer.minimize(
                         loss=loss,
                         global_step=tf.train.get_global_step())
            return tf.estimator.EstimatorSpec(mode=mode,loss=loss,train_op=train_op)

         eval_metric_ops = {"accuracy":tf.metrics.accuracy(labels=labels,predictions=predictions["classes"])
}

          return tf.estimator.EstimatorSpec(mode=mode,loss=loss,eval_metric_ops=eval_metric_ops)

def main(unused_argv):
    # Load training and eval data
    train_data_dir = "W:/Projects/AutoDrive/Training"
    test_data_dir = "W:/Projects/AutoDrive/Testing"

    images,labels = load_data(train_data_dir)
    test_images,test_labels = load_data(test_data_dir)

    print("Labels: {0} \nImages: {1}".format(len(set(labels)),len(images)))

    for image in images[:5]:
        print("shape: {0}, min: {1}, max: {2}".format(image.shape, image.min(), image.max()))

    images = [skimage.transform.resize(image,(28,28,1)) for image in images]

    for image in images[:5]:
        print("shape: {0}, min: {1}, max: {2}".format(image.shape, image.min(), image.max()))

    images = np.asarray(images,dtype=np.float32)
    labels = np.asarray(labels,dtype=np.int32)

    # Create the Estimator
    TSRecognition_classifier = tf.estimator.Estimator(
    model_fn=cnn_model_fn, model_dir="/tmp/TSRecognition_convnet_model")

    # Set up logging for predictions
    # Log the values in the "Softmax" tensor with label "probabilities"
    tensors_to_log = {"probabilities": "softmax_tensor"}
   logging_hook = tf.train.LoggingTensorHook(
                   tensors=tensors_to_log, every_n_iter=50)

    # Train the model
    train_input_fn = tf.estimator.inputs.numpy_input_fn(
                       x={"x": images},
                       y=labels,
                       batch_size=100,
                       num_epochs=None,
                       shuffle=True)

    TSRecognition_classifier.train(
         input_fn=train_input_fn,
         steps=20000,
         hooks=[logging_hook])

    # Evaluate the model and print results
    eval_input_fn = tf.estimator.inputs.numpy_input_fn(
                        x={"x": test_images},
                        y=test_labels,
                        num_epochs=1,
                        shuffle=False)
    eval_results = TSRecognition_classifier.evaluate(input_fn=eval_input_fn)
    print(eval_results)

if __name__ == "__main__":
    tf.app.run()

Addtionally, I've seen video which I think it can help me. But they just help me train single object. Any ideas can help me ?


问:
Highlight changes in code since last commit in Android Studio
Is there any way I can show changes that I made since the last commit in the code editor?</p>

答: On the left side of IDE open "Project" bar and select "Changed Files"


问:
Arrow function (Lambda function) with Angular 4
I know little about lambda, and lambda expression is treated as a function. and we have lots of ways to do that.

This is my simple function on TypeScript file

```<code> byPan(card1,card2){
    return card1.pan == card2.pan;
 }
</code>```

which I am using in HTML file like

```<code> <select [compareWith]="byPan" class="form-control" [(ngModel)]="card">
     <option *ngFor="let cardInfo of cards" [ngValue]="cardInfo">{{cardInfo.pan}}</option>
 </select>
</code>```

If I want to replace this function in lambda then I can write as follows.

```<code>var myFunc2 = (card1, card2) => { return card1.pan == card2.pan};
</code>```

So my question is, Can I use this lambda function directly on any angular property like compareWith or something like?

```<code> <select [compareWith]="(card1,card2)=> { return card1.pan == card2.pan}" class="form-control" [(ngModel)]="card">
     <option *ngFor="let cardInfo of cards" [ngValue]="cardInfo">{{cardInfo.pan}}</option>
 </select>
</code>```

答:
Functions cannot be defined in templates, primarily because this would result in eval in JIT compilation mode. Using component templates to for things that primarily belongs to classes would result in poor quality code that is hard to maintain.

If a function has be defined, it should be defined as component class method. It can be either regular or arrow function.

Body:
I know little about lambda, and lambda expression is treated as a function. and we have lots of ways to do that.

This is my simple function on TypeScript file

 byPan(card1,card2){
    return card1.pan == card2.pan;
 }

which I am using in HTML file like

 <select [compareWith]="byPan" class="form-control" [(ngModel)]="card">
     <option *ngFor="let cardInfo of cards" [ngValue]="cardInfo">{{cardInfo.pan}}</option>
 </select>

If I want to replace this function in lambda then I can write as follows.

var myFunc2 = (card1, card2) => { return card1.pan == card2.pan};

So my question is, Can I use this lambda function directly on any angular property like compareWith or something like?

 <select [compareWith]="(card1,card2)=> { return card1.pan == card2.pan}" class="form-control" [(ngModel)]="card">
     <option *ngFor="let cardInfo of cards" [ngValue]="cardInfo">{{cardInfo.pan}}</option>
 </select>


问:
How do I crop internal HTML elements at CSS3 rounded borders?
I have a div inside another div. The outer div has rounded borders using CSS3. The problem is, if I set a background color on the inner div it bleeds through into the corners. Here's a test page to show what I mean: http://www.webdevout.net/test?0O

I suspect it's not a renderer issue, as the same thing happens in Chrome, FF, and Opera. How do I get the inner div to crop at the rounded borders? Setting border-radius on the inner div to inherit doesn't cut it, the borders don't match up.

EDIT: The inner div is actually a header for more content inside the outer div, so applying the rounded borders to the inner div instead will not work.

答: You can't. Those areas are occupied by the border of the element and that can't be changed. That's not to say you can't without extra markup and css to pull it off but, normally, no.</p>