问:
es6 arrow function
I would test this in browser

```<code>let foo = () => ({ bar: 2 })
</code>```

But accidentally typed

```<code>let foo = () => { bar: 2}
</code>```

Why didn't throw an error?

答:
Depends on what bar is. If its a label, that would the key of the object.
But that syntax wont work, if it was a variable.

Some additional syntaxes for the curious mind is shown below:-

```<code>let foo = () => ({ bar: 2}); //works. object is returned
//let foo = () => ({ 'bar': 2}); //works. object is returned

//let foo = () => { let bar = 2; return bar; }; //works
//let foo = (() => { let bar = 2; return bar; }); //works
//let foo = (() => { let bar = 2; return bar}); //works

//let foo = () => ({ let bar = 2; return bar; }); //WONT work
//let foo = (p1=3) => p1 ; //works
let foo = () => 1; //works

console.log(foo());
</code>```

Title: es6 arrow function

Body:
I would test this in browser

let foo = () => ({ bar: 2 })

But accidentally typed

let foo = () => { bar: 2}

Why didn't throw an error?

Body:
Depends on what bar is. If its a label, that would the key of the object.
But that syntax wont work, if it was a variable.

Some additional syntaxes for the curious mind is shown below:-

let foo = () => ({ bar: 2}); //works. object is returned
//let foo = () => ({ 'bar': 2}); //works. object is returned

//let foo = () => { let bar = 2; return bar; }; //works
//let foo = (() => { let bar = 2; return bar; }); //works
//let foo = (() => { let bar = 2; return bar}); //works

//let foo = () => ({ let bar = 2; return bar; }); //WONT work
//let foo = (p1=3) => p1 ; //works
let foo = () => 1; //works

console.log(foo());


来源: stackexchange

问:
Does  have significance to search engines?
The corporate guidlines at my company stipulate that our product names are written in a strange and "wonderful" way [oh how we all love Marketing departments!].

A product name such as "iPhone" is written with the "i" as bold and italic. E.g.

iPhone

I don't want search engines to segment the context of the bold/italic text - for example the above should just be read by a search engine as "iPhone", and not !! I !! Phone.

Just want to check if anyone knows for sure that

```<code><span class="branding">i</span>Phone
</code>```

Would not apply any additional significance to the "i"?

Many thanks

答:
Styling is not the only use of Spans and Divs
http://en.wikipedia.org/wiki/Span_and_div#Semantic_clarity</p>

ContentLicense: CC BY-SA 2.5

Title: Does <span> have significance to search engines?

Body:
The corporate guidlines at my company stipulate that our product names are written in a strange and "wonderful" way [oh how we all love Marketing departments!].

A product name such as "iPhone" is written with the "i" as bold and italic. E.g.

iPhone

I don't want search engines to segment the context of the bold/italic text - for example the above should just be read by a search engine as "iPhone", and not !! I !! Phone.

Just want to check if anyone knows for sure that

iPhone

Would not apply any additional significance to the "i"?

Many thanks


问:
Ruby redirect output to file
How can I redirect the output of this puts method to a file?

```<code>File.open('links.txt').readlines.each do |li|
  puts li if (li['PersonNight'])
end
</code>```

I tried some solutions, but none of them works.

答:
You either can write to a file explicitly (open file and write to it)

```<code>file = File.open('target.file', 'w') do |file|
  File.foreach('links.txt') do |li|
    file.puts(li) if li['PersonNight']
  end
end
</code>```

Or redirect from outside your script, using regular unix machinery

```<code>ruby my_script.rb > target.file
</code>```

ContentLicense: CC BY-SA 3.0

Title: Ruby redirect output to file

Body:
How can I redirect the output of this puts method to a file?

File.open('links.txt').readlines.each do |li|
  puts li if (li['PersonNight'])
end

I tried some solutions, but none of them works.

Body:
You either can write to a file explicitly (open file and write to it)

file = File.open('target.file', 'w') do |file|
  File.foreach('links.txt') do |li|
    file.puts(li) if li['PersonNight']
  end
end

Or redirect from outside your script, using regular unix machinery

ruby my_script.rb > target.file


问:
Javascript execute alert after all events are finished (POST request, Papaparse, Jquery Datatable Insertion)
I'm using Papaparse, and I'm executing this code. I have a counter (errorcounter) that counts how many errors are returned from an asynchronous post request. Problem is that I need to get the value of the errorcounter, and I'm testing it via alert.

I think the alert executes before the post requests of before the parsing completes. How do I execute the alert after all these execution happens: (parsing, sending post request, and displaying results in Jquery datatables.

```<code>function verifyImportComputer() {
  var errorcounter = 0;
  resetImportComputer();
  $('input[id=importFileComputer]').parse({
     config: {
        header: true,
        skipEmptyLines: true,
        step: function(results) {
           $('#importErrorCounter').html(errorcounter);
           $.each(results.data, function(index, data) {
              $.post('com/import/getcomputerimport.cfm', {importData: JSON.stringify(data)}, function(data) {
                 var dataReturn =  $.parseJSON(data);
                 var status = "";
                 jQuery.each(dataReturn.error, function() {
                    status+= "<div class='alert alert-danger'>"+this+"</div>";
                    errorcounter++;
                 });
                 ImportComputerTable.row.add([
                    dataReturn.asset_id,
                    dataReturn.asset_tag,
                    dataReturn.computer_type,
                    dataReturn.computer_name,
                    dataReturn.ip_address,
                    dataReturn.processor,
                    dataReturn.memory,
                    dataReturn.operating_system,
                    dataReturn.office,
                    dataReturn.graphics_card,
                    dataReturn.date_issued,
                    dataReturn.remarks,
                    dataReturn.is_active,
                    status
                 ]).draw(false);
                 $('#importErrorCounter').html(errorcounter);
              });
           });
        }
     }
  });
alert(errorcounter);
}
</code>```

EDIT

I made something like this since someone posted about having callback, but nothing happens.

```<code>function verifyImportComputer() {
    errorcounter = 0;
    resetImportComputer();
    $('input[id=importFileComputer]').parse({
      config: {
         header: true,
         skipEmptyLines: true,
         step: function(results) {
            $('#importErrorCounter').html(errorcounter);
            $.each(results.data, function(index, data) {
               $.post('com/import/getcomputerimport.cfm', {importData: JSON.stringify(data)}, function(data) {
                  var dataReturn =  $.parseJSON(data);
                  var status = "";
                  jQuery.each(dataReturn.error, function() {
                     status+= "<div class='alert alert-danger'>"+this+"</div>";
                     errorcounter++;
                  });
                  ImportComputerTable.row.add([
                     dataReturn.asset_id,
                     dataReturn.asset_tag,
                     dataReturn.computer_type,
                     dataReturn.computer_name,
                     dataReturn.ip_address,
                     dataReturn.processor,
                     dataReturn.memory,
                     dataReturn.operating_system,
                     dataReturn.office,
                     dataReturn.graphics_card,
                     dataReturn.date_issued,
                     dataReturn.remarks,
                     dataReturn.is_active,
                     status
                  ]).draw(false);
                  $('#importErrorCounter').html(errorcounter);
               });
            });
         }
      }
    }, {
      function() {
         alert("haha");
         alert(errorcounter);
      }
    });
}
</code>```

答:
According to the documentation this should work (not tested it though so it might not - perhaps work up a JSFiddle):

```<code>function verifyImportComputer() {
    errorcounter = 0;
    resetImportComputer();
    $('input[id=importFileComputer]').parse({
            config: {
                header: true,
                skipEmptyLines: true,
                step: function(results) {
                    $('#importErrorCounter').html(errorcounter);
                    $.each(results.data, function(index, data) {
                        $.post('com/import/getcomputerimport.cfm', {
                            importData: JSON.stringify(data)
                        }, function(data) {
                            var dataReturn = $.parseJSON(data);
                            var status = "";
                            jQuery.each(dataReturn.error, function() {
                                status += "<div class='alert alert-danger'>" + this + "</div>";
                                errorcounter++;
                            });
                            ImportComputerTable.row.add([
                                dataReturn.asset_id,
                                dataReturn.asset_tag,
                                dataReturn.computer_type,
                                dataReturn.computer_name,
                                dataReturn.ip_address,
                                dataReturn.processor,
                                dataReturn.memory,
                                dataReturn.operating_system,
                                dataReturn.office,
                                dataReturn.graphics_card,
                                dataReturn.date_issued,
                                dataReturn.remarks,
                                dataReturn.is_active,
                                status
                            ]).draw(false);
                            $('#importErrorCounter').html(errorcounter);
                        });
                    });
                }
            }
        },
        complete: function() {
            function() {
                alert("haha");
                alert(errorcounter);
            }
        }
    );
}
</code>```

I think I'd be inclined to add the rows all in one go rather than during each step...

Body:
I'm using Papaparse, and I'm executing this code. I have a counter (errorcounter) that counts how many errors are returned from an asynchronous post request. Problem is that I need to get the value of the errorcounter, and I'm testing it via alert.

I think the alert executes before the post requests of before the parsing completes. How do I execute the alert after all these execution happens: (parsing, sending post request, and displaying results in Jquery datatables.

function verifyImportComputer() {
  var errorcounter = 0;
  resetImportComputer();
  $('input[id=importFileComputer]').parse({
     config: {
        header: true,
        skipEmptyLines: true,
        step: function(results) {
           $('#importErrorCounter').html(errorcounter);
           $.each(results.data, function(index, data) {
              $.post('com/import/getcomputerimport.cfm', {importData: JSON.stringify(data)}, function(data) {
                 var dataReturn =  $.parseJSON(data);
                 var status = "";
                 jQuery.each(dataReturn.error, function() {
                    status+= "
"+this+"
";
                    errorcounter++;
                 });
                 ImportComputerTable.row.add([
                    dataReturn.asset_id,
                    dataReturn.asset_tag,
                    dataReturn.computer_type,
                    dataReturn.computer_name,
                    dataReturn.ip_address,
                    dataReturn.processor,
                    dataReturn.memory,
                    dataReturn.operating_system,
                    dataReturn.office,
                    dataReturn.graphics_card,
                    dataReturn.date_issued,
                    dataReturn.remarks,
                    dataReturn.is_active,
                    status
                 ]).draw(false);
                 $('#importErrorCounter').html(errorcounter);
              });
           });
        }
     }
  });
alert(errorcounter);
}

EDIT

I made something like this since someone posted about having callback, but nothing happens.

function verifyImportComputer() {
    errorcounter = 0;
    resetImportComputer();
    $('input[id=importFileComputer]').parse({
      config: {
         header: true,
         skipEmptyLines: true,
         step: function(results) {
            $('#importErrorCounter').html(errorcounter);
            $.each(results.data, function(index, data) {
               $.post('com/import/getcomputerimport.cfm', {importData: JSON.stringify(data)}, function(data) {
                  var dataReturn =  $.parseJSON(data);
                  var status = "";
                  jQuery.each(dataReturn.error, function() {
                     status+= "
"+this+"
";
                     errorcounter++;
                  });
                  ImportComputerTable.row.add([
                     dataReturn.asset_id,
                     dataReturn.asset_tag,
                     dataReturn.computer_type,
                     dataReturn.computer_name,
                     dataReturn.ip_address,
                     dataReturn.processor,
                     dataReturn.memory,
                     dataReturn.operating_system,
                     dataReturn.office,
                     dataReturn.graphics_card,
                     dataReturn.date_issued,
                     dataReturn.remarks,
                     dataReturn.is_active,
                     status
                  ]).draw(false);
                  $('#importErrorCounter').html(errorcounter);
               });
            });
         }
      }
    }, {
      function() {
         alert("haha");
         alert(errorcounter);
      }
    });
}

Body:
According to the documentation this should work (not tested it though so it might not - perhaps work up a JSFiddle):

function verifyImportComputer() {
    errorcounter = 0;
    resetImportComputer();
    $('input[id=importFileComputer]').parse({
            config: {
                header: true,
                skipEmptyLines: true,
                step: function(results) {
                    $('#importErrorCounter').html(errorcounter);
                    $.each(results.data, function(index, data) {
                        $.post('com/import/getcomputerimport.cfm', {
                            importData: JSON.stringify(data)
                        }, function(data) {
                            var dataReturn = $.parseJSON(data);
                            var status = "";
                            jQuery.each(dataReturn.error, function() {
                                status += "<div class='alert alert-danger'>" + this + "</div>";
                                errorcounter++;
                            });
                            ImportComputerTable.row.add([
                                dataReturn.asset_id,
                                dataReturn.asset_tag,
                                dataReturn.computer_type,
                                dataReturn.computer_name,
                                dataReturn.ip_address,
                                dataReturn.processor,
                                dataReturn.memory,
                                dataReturn.operating_system,
                                dataReturn.office,
                                dataReturn.graphics_card,
                                dataReturn.date_issued,
                                dataReturn.remarks,
                                dataReturn.is_active,
                                status
                            ]).draw(false);
                            $('#importErrorCounter').html(errorcounter);
                        });
                    });
                }
            }
        },
        complete: function() {
            function() {
                alert("haha");
                alert(errorcounter);
            }
        }
    );
}

I think I'd be inclined to add the rows all in one go rather than during each step...


问:
FreeMarker : diplay tag on condition without if block
I am looking for a way to avoid using this in a FreeMarker template :

```<code><#if getName()??>
    <Name>getName()</Name>
</#if>
</code>```

Because I need to test many things.

Is there any way to do it by using, for example, a parameter in the tag?
I don't want the tag to be written at all if the value is null. (So exclamation mark is not enough)

答:
If all your tags follow the same basic structure:

```<code><Tag>value</Tag>
</code>```

you can use a macro, to save yourself some typing:

```<code><#macro optional tag value=[]>
    <#if value?has_content>
         <${tag}>${value}</${tag}>
    </#if>
</#macro>
</code>```

and then apply it like this:

```<code>  <@optional tag='User' value=user/>
  <@optional tag='Name' value=name/>
</code>```

resulting in the following output code:

```<code>  <User>myuser</User>
  <Name>myname</User>
</code>```

if one of the properties is not defined the whole tag will be omitted from the output.

ContentLicense: CC BY-SA 4.0

Body:
I am looking for a way to avoid using this in a FreeMarker template :

<#if getName()??>
    <Name>getName()</Name>
</#if>

Because I need to test many things.

Is there any way to do it by using, for example, a parameter in the tag?
I don't want the tag to be written at all if the value is null. (So exclamation mark is not enough)

Body:
If all your tags follow the same basic structure:

<Tag>value</Tag>

you can use a macro, to save yourself some typing:

<#macro optional tag value=[]>
    <#if value?has_content>
         <${tag}>${value}</${tag}>
    </#if>
</#macro>

and then apply it like this:

  <@optional tag='User' value=user/>
  <@optional tag='Name' value=name/>

resulting in the following output code:

  <User>myuser</User>
  <Name>myname</User>

if one of the properties is not defined the whole tag will be omitted from the output.


问:
Display decimal point with NSString stringWithFormat in Objective C
I'm a complete novice to objective C/iPad development, but I am trying to build a simple four function calculator on the iPad.

My current biggest difficulty is simply displaying a . when the decimal button is pressed. Here is what happens when a button (like two) is pressed.

```<code>-(IBAction)inTwo:(id)sender {
    display = display*10+2;
    [resultfield setText:[NSString stringWithFormat:@"%f",display]];
}
</code>```

Trying to just do

```<code>display = display*10+.
</code>```

Is obviously not working. Any way to append a period to the end of display?

Thanks

答:
I would do it slightly differently to the way you have chosen.  I'd have the buttons update the display directly and only convert to a number when needed for calculation.

e.g.

```<code>-(IBAction)inTwo:(id)sender
{
    NSString* displayedText = [resultField text];
    [resultfield setText:[NSString stringByAppendingString: @"2"]];
}

-(IBAction)inDecimal:(id)sender
{
    if (![self isDecimalAlreadyPressed]) // only allowed one decimal in the number
    {
        NSString* displayedText = [resultField text];
        [resultfield setText:[NSString stringByAppendingString: @"."]]; // actually want the localised character really
        [self setDecimalAlreadyPressed: YES];
    }
}
</code>```

Then when you need to calculate something:

```<code>-(double) displayAsDouble
{
    NSDecimalNumber* displayAsDecimal = [NSDecimalNumber decimalNumberWithString: [resultField text]];
    return [displayAsDecimal doubleValue];
}
</code>```

By the way, consider leaving the number as an NSDecimalNumber.  There are methods on NSDecimalNumber to do simple arithmetic and they work in base 10, so you can use them and avoid a lot of the pesky representation issues with floating point numbers.

Body:
I'm a complete novice to objective C/iPad development, but I am trying to build a simple four function calculator on the iPad.

My current biggest difficulty is simply displaying a . when the decimal button is pressed. Here is what happens when a button (like two) is pressed.

-(IBAction)inTwo:(id)sender {
    display = display*10+2;
    [resultfield setText:[NSString stringWithFormat:@"%f",display]];
}

Trying to just do

display = display*10+.

Is obviously not working. Any way to append a period to the end of display?

Thanks

Body:
I would do it slightly differently to the way you have chosen.  I'd have the buttons update the display directly and only convert to a number when needed for calculation.

e.g.

-(IBAction)inTwo:(id)sender
{
    NSString* displayedText = [resultField text];
    [resultfield setText:[NSString stringByAppendingString: @"2"]];
}

-(IBAction)inDecimal:(id)sender
{
    if (![self isDecimalAlreadyPressed]) // only allowed one decimal in the number
    {
        NSString* displayedText = [resultField text];
        [resultfield setText:[NSString stringByAppendingString: @"."]]; // actually want the localised character really
        [self setDecimalAlreadyPressed: YES];
    }
}

Then when you need to calculate something:

-(double) displayAsDouble
{
    NSDecimalNumber* displayAsDecimal = [NSDecimalNumber decimalNumberWithString: [resultField text]];
    return [displayAsDecimal doubleValue];
}

By the way, consider leaving the number as an NSDecimalNumber.  There are methods on NSDecimalNumber to do simple arithmetic and they work in base 10, so you can use them and avoid a lot of the pesky representation issues with floating point numbers.


问:
Quantize grayscale images
I have grayscale images which I want to quantize to different gray levels.

To be more precise, in the EBImage package, we have a function equalize() which has an argument levels. we can set levels value to 256 or 128 or 64 etc to quantize our grayscale images. (But the equalize() function will perform a histogram equalization of the given grayscale image, which is not preferred for my current situation)

Can somebody suggest a formula or a function which we can use to change the number of gray levels in the given grayscale image.

答:
First convert the format in something continous.
Now pseudocode.

int x = (int) (value / (Quantisation));
(new format) y = x * Quantisation;

It is also possible to compress images that lousy way.

Title: Quantize grayscale images


问:
Retrieve data from three table using join in CodeIgniter
I am trying to get result from three table using CodeIgnitor active record. But I am just getting record who match with second join condition only. But I need all record..

```<code>$uid   = $this->session->userdata('uid');
$codn  = ['stud.uid'=>$uid,'stud.status'=>"ACTIVE"];

$liststudent = $this->db->select('stud.id,stud.studname,stud.mobile1,stud.photo,stud.totalfees,bs.title,SUM(sp.pay_in_digit) AS paidfees')
                        ->from('students as stud')
                        ->join('batchsetting as bs', 'bs.id  = stud.bid')
                        ->join('stud_payment as sp', 'sp.sid = stud.id')
                        ->where($codn)
                        ->get();
return $liststudent->result();
</code>```

Here is the my query.

Concept is: I need batch title from batchsetting who's 'id = stud.bid'. and sum of paidfees from stud_payment who's 'sid=stud.id'.

But in result I am getting only those record of student who's record avail in stud_payment table.

答:
Use full outer join.</p>

```<code>function full_outer_join() {
    $sql = 'SELECT ' . $this->blogs . '.blog_id,comment_id,blog_title,blog_content,blog_date,comment_text,comment_date
            FROM ' . $this->blogs . ' LEFT OUTER JOIN ' . $this->blog_comments . ' ON ' . $this->blog_comments . '.blog_id = ' . $this->blogs . '.blog_id
                UNION
            SELECT ' . $this->blogs . '.blog_id,comment_id,blog_title,blog_content,blog_date,comment_text,comment_date
            FROM ' . $this->blogs . ' RIGHT OUTER JOIN ' . $this->blog_comments . ' ON ' . $this->blog_comments . '.blog_id = ' . $this->blogs . '.blog_id';
    $query = $this->db->query($sql);
    return $query->result();
}
</code>```

Body:
I am trying to get result from three table using CodeIgnitor active record. But I am just getting record who match with second join condition only. But I need all record..

$uid   = $this->session->userdata('uid');
$codn  = ['stud.uid'=>$uid,'stud.status'=>"ACTIVE"];

$liststudent = $this->db->select('stud.id,stud.studname,stud.mobile1,stud.photo,stud.totalfees,bs.title,SUM(sp.pay_in_digit) AS paidfees')
                        ->from('students as stud')
                        ->join('batchsetting as bs', 'bs.id  = stud.bid')
                        ->join('stud_payment as sp', 'sp.sid = stud.id')
                        ->where($codn)
                        ->get();
return $liststudent->result();

Here is the my query.

Concept is: I need batch title from batchsetting who's 'id = stud.bid'. and sum of paidfees from stud_payment who's 'sid=stud.id'.

But in result I am getting only those record of student who's record avail in stud_payment table.

Body:
Use full outer join.

function full_outer_join() {
    $sql = 'SELECT ' . $this->blogs . '.blog_id,comment_id,blog_title,blog_content,blog_date,comment_text,comment_date
            FROM ' . $this->blogs . ' LEFT OUTER JOIN ' . $this->blog_comments . ' ON ' . $this->blog_comments . '.blog_id = ' . $this->blogs . '.blog_id
                UNION
            SELECT ' . $this->blogs . '.blog_id,comment_id,blog_title,blog_content,blog_date,comment_text,comment_date
            FROM ' . $this->blogs . ' RIGHT OUTER JOIN ' . $this->blog_comments . ' ON ' . $this->blog_comments . '.blog_id = ' . $this->blogs . '.blog_id';
    $query = $this->db->query($sql);
    return $query->result();
}


问:
Custom Yii2 TimestampBehavior
I have behavior in my model

```<code>public function behaviors()
{
    return [
        [
            'class' => SluggableBehavior::className(),
            'attribute' => 'title',
            // 'slugAttribute' => 'slug',
        ],
        [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'created_at',
            'updatedAtAttribute' => 'updated_at',
            'value' => time(),
        ],
    ];
}
</code>```

Everything is working. But I need that only in one action does not work.
It is necessary that in actionView did not change "update_at" attribute. My actionView:

```<code>$model = $this->findModel($id);
$model->views++;
$model->save();
</code>```

How can I do this as correctly as possible?

答:
You may just update it with special method ActiveRecord::updateCounters().</p>

```<code>$model = $this->findModel($id);
// Don't forget to check whether the model is null
if ($model !== null) {
    $model->updateCounters(['views' => 1]);
}
</code>```

Title: Custom Yii2 TimestampBehavior

Body:
I have behavior in my model

public function behaviors()
{
    return [
        [
            'class' => SluggableBehavior::className(),
            'attribute' => 'title',
            // 'slugAttribute' => 'slug',
        ],
        [
            'class' => TimestampBehavior::className(),
            'createdAtAttribute' => 'created_at',
            'updatedAtAttribute' => 'updated_at',
            'value' => time(),
        ],
    ];
}

Everything is working. But I need that only in one action does not work.
It is necessary that in actionView did not change "update_at" attribute. My actionView:

$model = $this->findModel($id);
$model->views++;
$model->save();

How can I do this as correctly as possible?

Body:
You may just update it with special method ActiveRecord::updateCounters().

$model = $this->findModel($id);
// Don't forget to check whether the model is null
if ($model !== null) {
    $model->updateCounters(['views' => 1]);
}


问:
when interface method override always use access modifier public why?
```<code> 1.

interface A {
 void display();
 }
class B implements A {
//not use here private,protected,default......
**public** void display(){
  System.out.println("i m interface method");
}
public static void main(String args[]){
 A a1 = new B();
a1.display();
 }

}
</code>```

i am totally confusion please help me....and sorry for my English. Thank u

答:
Interface states that your class should have some methods, you are not allowed to hide them (by making private), if you want to implement interface.

Method is public in Interface by a default, you are now allowed to reduce it visibility area=)

Body:
 1.

interface A {
 void display();
 }
class B implements A {
//not use here private,protected,default......
**public** void display(){
  System.out.println("i m interface method");
}
public static void main(String args[]){
 A a1 = new B();
a1.display();
 }

}

i am totally confusion please help me....and sorry for my English. Thank u


问:
How vlookup between range values?
I have this challenge!!

How can I solve the problem below (picture) using any formula?

答:
Use this formula -1 (without year match)

```<code>=VLOOKUP(B14,$B$3:$D$11,3)
</code>```

formula-2 (with year match)

```<code>=IF(MATCH(A14,$A$3:$A$11,0)>0,VLOOKUP(B14,$B$3:$D$11,3),"Not Matched")
</code>```

Just copy and paste the above formula in C14 and C15. An easy method to get the answer.

Title: How vlookup between range values?

Body:
Use this formula -1 (without year match)

=VLOOKUP(B14,$B$3:$D$11,3)

formula-2 (with year match)

=IF(MATCH(A14,$A$3:$A$11,0)>0,VLOOKUP(B14,$B$3:$D$11,3),"Not Matched")

Just copy and paste the above formula in C14 and C15. An easy method to get the answer.


答:
The reason you must use public in your class, is because your method is implicitly public from the interface. The Java tutorial Defining an Interface says, in part,

All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.

Title: when interface method override always use access modifier public why?


问:
ng-options with array object angularjs
I have data like this :

EDIT

I solved my problem by change to acti[0] . But now I get wrong value in select . How can I solve this

答:
You just miss the , symbol between each element in your object.

$scope.provinces =    [
    {
    00844:"Hà Nội",
    00848:"TPHCM",
    008418:"Hòa Bình",
    008419:"Hà Giang",
    008420:"Lào Cai",
    008422:"Sơn La",
    008425:"Lạng Sơn",
    008426:"Cao Bằng",
    008427:"Tuyên Quang",
    008429:"Yên Bái",
    008430:"Ninh Bình",
    008431:"Hải Phòng"
    }
    ]

Title: ng-options with array object angularjs


问:
Do not trigger UITapGesture in subview
As you can see in the image below I have a video which covers almost the entire screen. I want the video to play/stop whenever one taps on it. The code works almost perfectly fine, the thing is the class in which I call the defInteractions function also contains the booked and comments subview which can also be found below. Consequently, the video also plays/stops when one taps these areas which I don't want.

The UITapGestureRecognizer triggering the function to play/pause the video:

```<code>//set interactions
func defInteractions (){

    //singletap
    let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTapDetected(_:)))
    singleTap.numberOfTapsRequired = 1
    //singleTap.cancelsTouchesInView = false

    //controlsContainerView
    controlsContainerView.addGestureRecognizer(singleTap)
}

//define type
var player: AVPlayer?

//set playing to false
var isPlaying: Bool = false

func singleTapDetected(_ sender: UITapGestureRecognizer) {

    //play or pause
    if(!isPlaying){

        //play
        player?.play()
        isPlaying = true

    }
    else{

        //pause
        player?.pause()
        isPlaying = false

    }

}
</code>```

Each subview looks basically like this:

```<code>//create controls container view
let comments: UIView = {

   //set properties of controls container view
   let commentrect = CGRect(x: viewWidth / 2, y: viewHeight - 110, width: viewWidth / 2, height: 50)
   let entireCommentView = UILabel(frame: commentrect)

   entireCommentView.translatesAutoresizingMaskIntoConstraints = true
   entireCommentView.backgroundColor = .white

   entireCommentView.font = UIFont(name: "HelveticaNeue", size: 20)

   entireCommentView.text = "3 comments"
   entireCommentView.textColor = .black
   entireCommentView.textAlignment = .center

   return entireCommentView

}()
</code>```

In the override they are added as subviews. I tried setting isUserInteractionEnabled to false in the individual subviews (e.g. comments: entireCommentView.isUserInteractionEnabled = false) which didn't work and don't know how to achieve my goal. Can someone help me? Can I exclude these subviews from my target in the UITapGestureRecognizer recognizer.

[

EDIT (Result of first answer):

答: You should define the likes and booked variables as property of the UIView subclass itself, to make them visible to your singleTapDetected(_:) method

Title: Do not trigger UITapGesture in subview

Body:
As you can see in the image below I have a video which covers almost the entire screen. I want the video to play/stop whenever one taps on it. The code works almost perfectly fine, the thing is the class in which I call the defInteractions function also contains the booked and comments subview which can also be found below. Consequently, the video also plays/stops when one taps these areas which I don't want.

The UITapGestureRecognizer triggering the function to play/pause the video:

//set interactions
func defInteractions (){

    //singletap
    let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTapDetected(_:)))
    singleTap.numberOfTapsRequired = 1
    //singleTap.cancelsTouchesInView = false

    //controlsContainerView
    controlsContainerView.addGestureRecognizer(singleTap)
}

//define type
var player: AVPlayer?

//set playing to false
var isPlaying: Bool = false

func singleTapDetected(_ sender: UITapGestureRecognizer) {

    //play or pause
    if(!isPlaying){

        //play
        player?.play()
        isPlaying = true

    }
    else{

        //pause
        player?.pause()
        isPlaying = false

    }

}

Each subview looks basically like this:

//create controls container view
let comments: UIView = {

   //set properties of controls container view
   let commentrect = CGRect(x: viewWidth / 2, y: viewHeight - 110, width: viewWidth / 2, height: 50)
   let entireCommentView = UILabel(frame: commentrect)

   entireCommentView.translatesAutoresizingMaskIntoConstraints = true
   entireCommentView.backgroundColor = .white

   entireCommentView.font = UIFont(name: "HelveticaNeue", size: 20)

   entireCommentView.text = "3 comments"
   entireCommentView.textColor = .black
   entireCommentView.textAlignment = .center

   return entireCommentView

}()

In the override they are added as subviews. I tried setting isUserInteractionEnabled to false in the individual subviews (e.g. comments: entireCommentView.isUserInteractionEnabled = false) which didn't work and don't know how to achieve my goal. Can someone help me? Can I exclude these subviews from my target in the UITapGestureRecognizer recognizer.

[

EDIT (Result of first answer):


问:
ng-repeat get length of array and bind last value of array
```<code>$scope.GetDetails={
  Student:[
      {"id":1,"Name":"Apple","Price":3500}
    ],
  Student:[
      {"id":2,"Name":"Samsung","Price":4000}
     ],
  Student:[
    {"id":3,"Name":"Nokia","Price":1500},
    {"id":3,"Name":"Nokia","Price";7000}
   ]
 }
</code>```

Am binding data using ng-repeat

```<code> <div ng-repeat="As in GetDetails">
         <div ng-repeat="A in As.Student">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>
    </div>
     </div>
</code>```

Result is
    Apple - 3500
Samsung - 4000
Nokia - 1500
Nokia - 7000

Here every thing Ok.But what i want mean , Nokia have two array ,so i have to get name from first array and price from 2nd array Like,

Nokia - 7000,

And Also i need the length of student array.

答:
First, You should change your JSON to achieve your result.

Change JSON to below:

```<code>$scope.GetDetails=[
    {Student:[{"id":1,"Name":"Apple","Price":3500}]},
    {Student:[{"id":2,"Name":"Samsung","Price":4000}]},
    {Student:[{"id":3,"Name":"Nokia","Price":1500},{"id":3,"Name":"Nokia","Price":7000}]}
 ]
</code>```

Please run below code

<!DOCTYPE html>

        {{A.Name}} - {{A.Price}}

```

I used ng-if="$last" to take the last value from array

Here is a working DEMO

Body:
$scope.GetDetails={
  Student:[
      {"id":1,"Name":"Apple","Price":3500}
    ],
  Student:[
      {"id":2,"Name":"Samsung","Price":4000}
     ],
  Student:[
    {"id":3,"Name":"Nokia","Price":1500},
    {"id":3,"Name":"Nokia","Price";7000}
   ]
 }

Am binding data using ng-repeat

        {{A.Name}} - {{A.Price}}

Result is
    Apple - 3500
Samsung - 4000
Nokia - 1500
Nokia - 7000

Here every thing Ok.But what i want mean , Nokia have two array ,so i have to get name from first array and price from 2nd array Like,

Nokia - 7000,

And Also i need the length of student array.

Body:
First, You should change your JSON to achieve your result.

Change JSON to below:

$scope.GetDetails=[
    {Student:[{"id":1,"Name":"Apple","Price":3500}]},
    {Student:[{"id":2,"Name":"Samsung","Price":4000}]},
    {Student:[{"id":3,"Name":"Nokia","Price":1500},{"id":3,"Name":"Nokia","Price":7000}]}
 ]

Please run below code

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

 <div ng-repeat="As in GetDetails">
         <div ng-repeat="A in As.Student" ng-if="$last">
        <span>{{A.Name}}</span> - <span>{{A.Price}}</span>
    </div>
     </div>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.GetDetails=[
    {Student:[{"id":1,"Name":"Apple","Price":3500}]},
    {Student:[{"id":2,"Name":"Samsung","Price":4000}]},
    {Student:[{"id":3,"Name":"Nokia","Price":1500},{"id":3,"Name":"Nokia","Price":7000}]}
 ]

});
</script>

</body>
</html>

I used ng-if="$last" to take the last value from array

Here is a working DEMO


问:
LINQ & Lambda Expressions equivalent of SQL In
Is there a lambda equivalent of IN?  I will like to select all the funds with ids either 4, 5 or 6.  One way of writing it is:

List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId == 5 || fhp.Fund.FundId == 6 || fhp.Fund.FundId == 7).ToList();

However, that quickly becomes unmanageable if I need it to match say 100 different fundIds.  Can I do something like:

List
  fundHistoricalPrices =
  lionContext.FundHistoricalPrices.Where(fhp
  => fhp.Fund.FundId in(5,6,7)).ToList();

答:
You could write an extension method like this :

```<code>public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}
</code>```

Then :

```<code>List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId.In(5,6,7)).ToList();
</code>```

Body:
You could write an extension method like this :

public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}

Then :

List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId.In(5,6,7)).ToList();


问:
Virus Scanning Uploaded files from Azure Web/Worker Role
We are designing an Azure Website which will allow users to Upload content(MP4,Docx...MSOffice Files) which can then be accessed.

Some video content we will encode to provide several differing quality formats, before it will be streamed (using Azure Media Services).

We need to add an intermediate step so we can scan uploaded files for potential virus risk.  Is there functionality built into azure (or third party) which will allow us to call an API to scan content before processing it? We are ideally looking for an API rather than just a background service on a VM, so we can get feedback potentially for use in a web or worker role.

Had a quick look at Symantec Endpoint and Windows Defender but not sure these offer an API

答:
There are a number of options to achieve this:

Firstly you can use ClamAV as already mentioned. ClamAV doesn't always receive the best press for its virus databases but as others have pointed out it's easy to use and is expandable.

You can also install a commercial scanner, such as avg, kaspersky etc. Many of these come with a C API that you can talk to directly, although often getting access to this can be expensive from a licensing point of view.

Alternatively you can make calls to the executable directly using something like the following to capture the output:

```<code>var proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "scanner.exe",
        Arguments = "arguments needed",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};
proc.Start();
while (!proc.StandardOutput.EndOfStream) {
    string line = proc.StandardOutput.ReadLine();
}
</code>```

You would then need to parse the output to get the result and use it within your application.

Finally, now there are some commercial APIs available to do this kind of thing such as attachmentscanner (disclaimer I'm related to this product) or scanii. These will provide you with an API and a more scalable option to scan specific files and receive the response from at least one virus checking engine.

Body:
There are a number of options to achieve this:

Firstly you can use ClamAV as already mentioned. ClamAV doesn't always receive the best press for its virus databases but as others have pointed out it's easy to use and is expandable.

You can also install a commercial scanner, such as avg, kaspersky etc. Many of these come with a C API that you can talk to directly, although often getting access to this can be expensive from a licensing point of view.

Alternatively you can make calls to the executable directly using something like the following to capture the output:

var proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "scanner.exe",
        Arguments = "arguments needed",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};
proc.Start();
while (!proc.StandardOutput.EndOfStream) {
    string line = proc.StandardOutput.ReadLine();
}

You would then need to parse the output to get the result and use it within your application.

Finally, now there are some commercial APIs available to do this kind of thing such as attachmentscanner (disclaimer I'm related to this product) or scanii. These will provide you with an API and a more scalable option to scan specific files and receive the response from at least one virus checking engine.


问:
Sending bulkemails with java mail takes too long
I have to following situation. I want to send bulk emails with java mail client. This means I want to send a lot of emails at once. The opinion to put them all together in the recipient field is out of question because no recipient have to see each other (bcc doesn't work, because you still see the to-recipient).
So what I do is, open a new Transport connection, use sendMessage() for every single recipient and close Transport connection afterwards. Here is the code snippet:

```<code>Session session = Session.getInstance(smtpProps, new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(authUser, authPass);
    }
});

InputStream is = IOUtils.toInputStream(eml, "UTF-8");
MimeMessage message = new MimeMessage(session, is);

Transport transport = session.getTransport("smtp");
transport.connect(smtpServer, smtpPort, smtpUser, smtpPass);

Address[] recipients = message.getRecipients(RecipientType.TO);
for(Address address : recipients) {
    message.setRecipient(RecipientType.TO, address);
    transport.sendMessage(message, new Address[]{ address });
}
transport.close();
</code>```

Remember that the sendMessage() method is an abstract method of the javax.mail.Transport class and so the implementation of the SMTPTransport from the com.sun.mail.smtp is used in my case.

No to my problem: The connection time at transport.connect() takes about 5 seconds, the sending time at sendMessage too. This means, if I send emails to, for example, 10 recipients, it takes 5 + (10*5) = ~55 seconds. This is to long, think about when we have 1000 recipients.

Is this normal and okay? Or do you have any idea what can cause the problem, that it tooks this long time? Is there any other (good) sendMessage() implementation, or is SMTPTransport the default usage for this method?

Information:

The for-loop, respectively, this code snipped runs in a seperate thread, so the emails are send in background. And the whole servlet, which contains this snipped, runs in a docker-container on a servercluster. So if i parallelise this, or use multiple threads, i don't know how the behaviour is in concurence with other servlets on this cluster.

答:
I think i found a solution for my problem.
That the connect takes so much time seems to be normal.
My problem was, that the attachment had to be uploaded to the smtp-server everytime, about 4 seconds. Every single upload sums up to a very large amount of time for the whole request.
So without sending attachments, the requests didn't take so much time. So there is no problem in my implementation, rather than uploading attachments every time.</p>

Body:
I have to following situation. I want to send bulk emails with java mail client. This means I want to send a lot of emails at once. The opinion to put them all together in the recipient field is out of question because no recipient have to see each other (bcc doesn't work, because you still see the to-recipient).
So what I do is, open a new Transport connection, use sendMessage() for every single recipient and close Transport connection afterwards. Here is the code snippet:

Session session = Session.getInstance(smtpProps, new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(authUser, authPass);
    }
});

InputStream is = IOUtils.toInputStream(eml, "UTF-8");
MimeMessage message = new MimeMessage(session, is);

Transport transport = session.getTransport("smtp");
transport.connect(smtpServer, smtpPort, smtpUser, smtpPass);

Address[] recipients = message.getRecipients(RecipientType.TO);
for(Address address : recipients) {
    message.setRecipient(RecipientType.TO, address);
    transport.sendMessage(message, new Address[]{ address });
}
transport.close();

Remember that the sendMessage() method is an abstract method of the javax.mail.Transport class and so the implementation of the SMTPTransport from the com.sun.mail.smtp is used in my case.

No to my problem: The connection time at transport.connect() takes about 5 seconds, the sending time at sendMessage too. This means, if I send emails to, for example, 10 recipients, it takes 5 + (10*5) = ~55 seconds. This is to long, think about when we have 1000 recipients.

Is this normal and okay? Or do you have any idea what can cause the problem, that it tooks this long time? Is there any other (good) sendMessage() implementation, or is SMTPTransport the default usage for this method?

Information:

The for-loop, respectively, this code snipped runs in a seperate thread, so the emails are send in background. And the whole servlet, which contains this snipped, runs in a docker-container on a servercluster. So if i parallelise this, or use multiple threads, i don't know how the behaviour is in concurence with other servlets on this cluster.


问:
Normalize Image Brightness and Saturation
I have a collection of colored/black-white images and most of them have different levels of brightness and saturation.

```<code>How can I normalize those images to make them all at the same "**scale**"?
</code>```

In my case, some of the images might also have a huge amount of white pixels as they are the scans of some old photos.

Thanks

答:
It's hard to suggest anything very concrete without seeing your images, but one idea might be to move to a colourspace that is based on Brightness and Saturation and then to do an auto-gamma correction on the two channels of interest.

It could make a horrible mess so please make backup of your images first!

So, I am suggesting something along the lines of:

```<code>convert Original.jpg -colorspace HSL -channel B -auto-gamma -colorspace sRGB BrightnessNormalised.jpg
</code>```

where I move to "Hue, Saturation and Lightness" colourspace, select the Lightness channel (it is the 3rd one so it is B out of RG&B) and do an auto-gamma of the Lightness and save back as a brightness-corrected, sRGB JPEG.

Likewise, to normalise the saturation, you could do:

```<code>convert Original.jpg -colorspace HSL -channel G -auto-gamma -colorspace sRGB SaturationNormalised.jpg
</code>```

And you could do both at once, by using -channel GB like this:

```<code>convert Original.jpg -colorspace HSL -channel GB -auto-gamma -colorspace sRGB Normalised.jpg
</code>```

Normalising the saturation is probably not a good idea for greyscale images but do some tests.

Normalising the brightness of images is not really a good idea if you have moody, low-key photographs or airy, light, high-key photographs. Hang onto that backup - just make a ZIP/compressed tar-ball and keep it around.

Body:
I have a collection of colored/black-white images and most of them have different levels of brightness and saturation.

How can I normalize those images to make them all at the same "**scale**"?

In my case, some of the images might also have a huge amount of white pixels as they are the scans of some old photos.

Thanks

Body:
It's hard to suggest anything very concrete without seeing your images, but one idea might be to move to a colourspace that is based on Brightness and Saturation and then to do an auto-gamma correction on the two channels of interest.

It could make a horrible mess so please make backup of your images first!

So, I am suggesting something along the lines of:

convert Original.jpg -colorspace HSL -channel B -auto-gamma -colorspace sRGB BrightnessNormalised.jpg

where I move to "Hue, Saturation and Lightness" colourspace, select the Lightness channel (it is the 3rd one so it is B out of RG&B) and do an auto-gamma of the Lightness and save back as a brightness-corrected, sRGB JPEG.

Likewise, to normalise the saturation, you could do:

convert Original.jpg -colorspace HSL -channel G -auto-gamma -colorspace sRGB SaturationNormalised.jpg

And you could do both at once, by using -channel GB like this:

convert Original.jpg -colorspace HSL -channel GB -auto-gamma -colorspace sRGB Normalised.jpg

Normalising the saturation is probably not a good idea for greyscale images but do some tests.

Normalising the brightness of images is not really a good idea if you have moody, low-key photographs or airy, light, high-key photographs. Hang onto that backup - just make a ZIP/compressed tar-ball and keep it around.


问:
Google Plus sharing URL with get parameter (even encoded!) not work
I want to share this URL in Google+:
https://www.tropic.photo/shri-lanka?image=/assets/images/resources/64/shri-lanka-005.jpg

So, I use this link:
https://plus.google.com/share?url=https%3A%2F%2Fwww.tropic.photo%2Fshri-lanka%3Fimage%3D%2Fassets%2Fimages%2Fresources%2F64%2Fshri-lanka-005.jpg

But when I share it, picture sended in '?image=' GET parameter not shown in G+ share window, but it must (Facebook and VK handles GET parameters fine, as is, even without encoding)

How to share link with image specified in '?image=' GET parameter?

答: It's because my URL was contained dot '.' symbol before 'jpg'. I've replaced it with '$' ('%24') and I convert it vice versa on server side</p>


问:
Make a UIBarButtonItem disappear using swift IOS
I have an IBOutlet that I have linked to from the storyboard

```<code>@IBOutlet var creeLigueBouton: UIBarButtonItem!
</code>```

and I want to make it disappear if a condition is true

```<code>if(condition == true)
{
    // Make it disappear
}
</code>```

答:
I have more that 2 menuitems and remove/add menuitem is an overhead. This code snippet worked for me (Using Swift3).

```<code>func showMenuItem(){

    menuItemQuit.customView?.isHidden = false
    menuItemQuit.plainView.isHidden = false
}

func hideMenuItem(){

    menuItemQuit.customView?.isHidden = true
    menuItemQuit.plainView.isHidden = true
}
</code>```

Body:
I have an IBOutlet that I have linked to from the storyboard

@IBOutlet var creeLigueBouton: UIBarButtonItem!

and I want to make it disappear if a condition is true

if(condition == true)
{
    // Make it disappear
}

Body:
I have more that 2 menuitems and remove/add menuitem is an overhead. This code snippet worked for me (Using Swift3).

func showMenuItem(){

    menuItemQuit.customView?.isHidden = false
    menuItemQuit.plainView.isHidden = false
}

func hideMenuItem(){

    menuItemQuit.customView?.isHidden = true
    menuItemQuit.plainView.isHidden = true
}


问:
String concatenation without strcat in C
I am having trouble concatenating strings in C, without strcat library function. Here is my code

```<code>#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}
</code>```

I made corrections to the code. This is working. Now can I do it without strcpy?

答:
It is better to factor out your strcat logic to a separate function. If you make use of pointer arithmetic, you don't need the strlen function:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* To completely get rid of this,
                       implement your our strcpy as well */

static void
my_strcat (char* dest, char* src)
{
  while (*dest) ++dest;
  while (*src) *(dest++) = *(src++);
  *dest = 0;
}

int
main()
{
  char* a1 = malloc(100);
  char* b1 = malloc(100);

  strcpy (a1, "Vivek");
  strcpy (b1, " Ratnavel");

  my_strcat (a1, b1);
  printf ("%s\n", a1); /* => Vivek Ratnavel */

  free (a1);
  free (b1);
  return 0;
}
</code>```

Body:
I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
  char *a1=(char*)malloc(100);
  strcpy(a1,"Vivek");
  char *b1=(char*)malloc(100);
  strcpy(b1,"Ratnavel");
  int i;
  int len=strlen(a1);

  for(i=0;i<strlen(b1);i++)
  {
     a1[i+len]=b1[i];
  }

  a1[i+len]='\0';
  printf("\n\n A: %s",a1);

  return 0;
}

I made corrections to the code. This is working. Now can I do it without strcpy?

Body:
It is better to factor out your strcat logic to a separate function. If you make use of pointer arithmetic, you don't need the strlen function:

#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* To completely get rid of this,
                       implement your our strcpy as well */

static void
my_strcat (char* dest, char* src)
{
  while (*dest) ++dest;
  while (*src) *(dest++) = *(src++);
  *dest = 0;
}

int
main()
{
  char* a1 = malloc(100);
  char* b1 = malloc(100);

  strcpy (a1, "Vivek");
  strcpy (b1, " Ratnavel");

  my_strcat (a1, b1);
  printf ("%s\n", a1); /* => Vivek Ratnavel */

  free (a1);
  free (b1);
  return 0;
}


问:
Left JOIN on DATE field not working in SQL
This is an Order Management System scenario.

I have a [SalesHistory] Table with following fields:

    ItemMasterID varchar(60)

    Qty int

    OrderDate DateTime

(Omitted non relevant fields)

Executing following query on SalesHistory:

```<code>select Cast(OrderDate as Date) 'OrderDate',Sum(Qty) 'Qty'  from SalesHistory
where itemmasterid= '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'
Group by ItemMasterId ,Cast(OrderDate as DAte)
order by OrderDate desc
</code>```

I get the following results (As expected)

As you can see, for the month of 04 there are only 4 records.

What I expect is that all the days of a month be displayed on the left side (Date column) with zeros on the right side (Qty column) if there is no record for that particular date

Here is what I tried:

I created a table [Date_Ref] with field:

    Day DateTime

Then I filled it up with all days of month 04 using the following procedure:

```<code>declare @SD Date = convert(Date,'04/01/2017',101)
declare @ED Date = convert(Date,'04/30/2017',101)
declare @DatePeriod Date = @SD
while (@DatePeriod <= @ED)
begin
    insert into Date_Ref (Day) values (@DatePeriod)
    set @DatePeriod = DATEADD(DD, 1,@DatePeriod)
end
</code>```

Now the Date_Ref table is filled with expected records:

```<code>select Day 'Date' from Date_Ref
</code>```

I tried using LEFT JOIN on this and SalesHistory table expecting to get the result I mentioned above:

```<code>select Cast(d.Day as Date) 'Date',ISNULL (s.Qty,0) 'Qty'
from date_Ref as d
left join
SalesHistory as s on Cast(s.OrderDate as date) = cast(d.Date_Period as date)
where
s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'
</code>```

and I got his result:

Clearly this is not what I EXPECTED.!! I excepected something like:

```<code>+-------------+----+
| Date        | Qty|
+-------------+----+
| 2017-04-01  |   0|
| 2017-04-02  |   0|
| 2017-04-03  |   0|
| 2017-04-04  |   0|
| 2017-04-05  |   0|
| 2017-04-06  |   0|
| 2017-04-07  |   0|
| 2017-04-08  |   0|
| 2017-04-09  |   0|
| 2017-04-10  |   1|
| 2017-04-11  |   1|
....
....
</code>```

Why is the LEFT JOIN behaving like an INNER JOIN? Or is this how SQL returns when you join on DateTime field?

Note:

I also tried removing the Cast.

I also tried all the joins LEFT RIGHT OUTER INNER.

I also tried switching positions of SalesHistory and Date_Ref tables in the query.

Is it that I am doing something wrong? Or is there another approach to this?

Thankyou

Sorry for the lengthy question!! I just had to describe the exact steps what I did

答:
```<code>where s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'
</code>```

turns your join into an inner join. In an outer-joined record s.itemmasterid is null, so the condition is not matched and you dismiss the row.

Conditions on outer-joined tables belong in the ON clause.

```<code>select Cast(d.Day as Date) 'Date', ISNULL (s.Qty,0) 'Qty'
from date_Ref as d
left join SalesHistory as s on cast(s.OrderDate as date) = cast(d.Date_Period as date)
                            and s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'
</code>```

Body:
This is an Order Management System scenario.

I have a [SalesHistory] Table with following fields:

    ItemMasterID varchar(60)

    Qty int

    OrderDate DateTime

(Omitted non relevant fields)

Executing following query on SalesHistory:

select Cast(OrderDate as Date) 'OrderDate',Sum(Qty) 'Qty'  from SalesHistory
where itemmasterid= '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'
Group by ItemMasterId ,Cast(OrderDate as DAte)
order by OrderDate desc

I get the following results (As expected)

As you can see, for the month of 04 there are only 4 records.

What I expect is that all the days of a month be displayed on the left side (Date column) with zeros on the right side (Qty column) if there is no record for that particular date

Here is what I tried:

I created a table [Date_Ref] with field:

    Day DateTime

Then I filled it up with all days of month 04 using the following procedure:

declare @SD Date = convert(Date,'04/01/2017',101)
declare @ED Date = convert(Date,'04/30/2017',101)
declare @DatePeriod Date = @SD
while (@DatePeriod <= @ED)
begin
    insert into Date_Ref (Day) values (@DatePeriod)
    set @DatePeriod = DATEADD(DD, 1,@DatePeriod)
end

Now the Date_Ref table is filled with expected records:

select Day 'Date' from Date_Ref

I tried using LEFT JOIN on this and SalesHistory table expecting to get the result I mentioned above:

select Cast(d.Day as Date) 'Date',ISNULL (s.Qty,0) 'Qty'
from date_Ref as d
left join
SalesHistory as s on Cast(s.OrderDate as date) = cast(d.Date_Period as date)
where
s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'

and I got his result:

Clearly this is not what I EXPECTED.!! I excepected something like:

+-------------+----+
| Date        | Qty|
+-------------+----+
| 2017-04-01  |   0|
| 2017-04-02  |   0|
| 2017-04-03  |   0|
| 2017-04-04  |   0|
| 2017-04-05  |   0|
| 2017-04-06  |   0|
| 2017-04-07  |   0|
| 2017-04-08  |   0|
| 2017-04-09  |   0|
| 2017-04-10  |   1|
| 2017-04-11  |   1|
....
....

Why is the LEFT JOIN behaving like an INNER JOIN? Or is this how SQL returns when you join on DateTime field?

Note:

I also tried removing the Cast.

I also tried all the joins LEFT RIGHT OUTER INNER.

I also tried switching positions of SalesHistory and Date_Ref tables in the query.

Is it that I am doing something wrong? Or is there another approach to this?

Thankyou

Sorry for the lengthy question!! I just had to describe the exact steps what I did

Body:
where s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'

turns your join into an inner join. In an outer-joined record s.itemmasterid is null, so the condition is not matched and you dismiss the row.

Conditions on outer-joined tables belong in the ON clause.

select Cast(d.Day as Date) 'Date', ISNULL (s.Qty,0) 'Qty'
from date_Ref as d
left join SalesHistory as s on cast(s.OrderDate as date) = cast(d.Date_Period as date)
                            and s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'


问:
what is the difference between BFC and stacking context?
these makes me so confuse.

what is the difference between  Block_Formatting_Context and stacking_context ?

thank you !

答:
A block formatting context is a part of a visual CSS rendering of a Web page. It is the region in which the layout of block boxes occurs and in which floats interact with each other.

Read More : https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Block_formatting_context

And

Stacking context is the three-dimensional conceptualization of HTML elements along an imaginary z-axis relative to the user who is assumed to be facing the viewport or the webpage. HTML elements occupy this space in priority order based on element attributes.

read More : https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context


问:
collection view has first cell always empty
I have a custom Collection view in a Viewcontroller , whenever my Collection View is loaded always I get my first cell empty. How to remove this empty cell.

```<code>//CollectionView functions
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return collectionData.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! collectionCell

    let collectionData = self.collectionData[indexPath.row]

    cell.NameLbl.text       = collectionData["name"] as? String

    return cell

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let Info: NSDictionary = self.collectionData[indexPath.item] as! NSDictionary

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "edit") as! editVC
    self.navigationController?.pushViewController(vc, animated: false)

}
</code>```

答:
Depends on what is the case that you should handle hiding the first element, there are tow options that you might want to implement:

1- If it is okay to remove the first object from the data source (collectionData array), then you can simply remove the first element from it:

In your view controller (viewDidLoad()) you could implement:

```<code>override func viewDidLoad() {
    .
    .
    .

    collectionData.remove(at: 0)

    .
    .
    .
}
</code>```

2- if you are required to keep the collectionData as is without removing the first element, but it should not be displayed in the UI, you will need to implement the UICollectionViewDataSource as follows:

```<code>func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // subtract 1
    return collectionData.count - 1
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! collectionCell

    // add 1 to indexPath.row
    let collectionData = self.collectionData[indexPath.row + 1]

    cell.NameLbl.text = collectionData["name"] as? String

    return cell

}
</code>```

That should lead to displaying the collection view as expected without editing the collectionData data source array.

Body:
I have a custom Collection view in a Viewcontroller , whenever my Collection View is loaded always I get my first cell empty. How to remove this empty cell.

//CollectionView functions
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return collectionData.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! collectionCell

    let collectionData = self.collectionData[indexPath.row]

    cell.NameLbl.text       = collectionData["name"] as? String

    return cell

}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    let Info: NSDictionary = self.collectionData[indexPath.item] as! NSDictionary

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "edit") as! editVC
    self.navigationController?.pushViewController(vc, animated: false)

}

Body:
Depends on what is the case that you should handle hiding the first element, there are tow options that you might want to implement:

1- If it is okay to remove the first object from the data source (collectionData array), then you can simply remove the first element from it:

In your view controller (viewDidLoad()) you could implement:

override func viewDidLoad() {
    .
    .
    .

    collectionData.remove(at: 0)

    .
    .
    .
}

2- if you are required to keep the collectionData as is without removing the first element, but it should not be displayed in the UI, you will need to implement the UICollectionViewDataSource as follows:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // subtract 1
    return collectionData.count - 1
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! collectionCell

    // add 1 to indexPath.row
    let collectionData = self.collectionData[indexPath.row + 1]

    cell.NameLbl.text = collectionData["name"] as? String

    return cell

}

That should lead to displaying the collection view as expected without editing the collectionData data source array.


问:
Splitting declaration and initialization using RASCAL
I'm new to Rascal and experimenting with its transformation/term rewriting abilities.

I want to write a script that splits declarations like:

int x = 5;

into declaration/initializations like:

int x;
x = 5;

How might I go about this? Let's say the language I'm trying to transform is Java.

Thanks for any help.

答:
Sketch of a solution

Good question. There are several ways to do this and I will show the most simplistic one. Note that your example is not the simplest possible example since it requires a conversion from a single statement to a list of statements (i.e., it is not type preserving).

Here is without further ado a complete example, the explanation follows below.

```<code>module Decl

import IO;
import ParseTree;

// Decl, a trivial language, to demo simple program trafo

lexical Id  = [a-z][a-z0-9]* !>> [a-z0-9] \ Reserved;
lexical Natural = [0-9]+ ;
lexical String = "\"" ![\"]*  "\"";

layout Layout = WhitespaceAndComment* !>> [\ \t\n];

lexical WhitespaceAndComment
   = [\ \t\n\r]
   ;

keyword Reserved = "int" | "str" | "if" | "then" | "else" | "fi" | "while" | "do" | "od";

start syntax Program
   = {Statement  ";"}* body
   ;

syntax Type
   = "int"
   | "str"
   ;

syntax Statement
   = Type tp Id var
   | Type tp Id var ":=" Expression exp
   | Id var ":=" Expression val
   | "if" Expression cond "then" {Statement ";"}*  thenPart "else" {Statement ";"}* elsePart "fi"
   | "while" Expression cond "do" {Statement ";"}* body "od"
   ;

syntax Expression
   = Id name
   | String string
   | Natural natcon
   | bracket "(" Expression e ")"
   > left ( Expression lhs "+" Expression rhs
          | Expression lhs "-" Expression rhs
          )
   ;

str trafo1 () {
    p = parse(#start[Program], "int x := 1").top;
    newBody = "";
    for(stat <- p.body){
        if((Statement) `<Type tp> <Id var> := <Expression exp>` := stat){
            newBody += "<tp> <var>; <var> := <exp>";
        } else {
            newBody += "<stat>";
        }
    }
    return newBody;
}
</code>```

The major part is a complete grammar of a simple language. The actual transformation is done by trafo1 which does:

Parse the example.

Introduce and initialize newBody (used to build the result).

Iterate over the statements in the given body.

Test for each statement whether it is of the desired form.
If true, append the transformed statement. Note that string templates are used here to build the transformed statement.
If false, append the original statement.

Return the resulting string.

Discussion

The solution style large depends on your goal. Here we just build a string. If desired, you could return the parsed string as result.

Alternatives:

Transform as concrete parse tree (not so easy since some functionality is still lacking but we aim to make this the preferred solution).

First transform to an abstract syntax tree (AST) and perform the transformation on the AST.

Hope this helps you to get started.

Body:
Sketch of a solution

Good question. There are several ways to do this and I will show the most simplistic one. Note that your example is not the simplest possible example since it requires a conversion from a single statement to a list of statements (i.e., it is not type preserving).

Here is without further ado a complete example, the explanation follows below.

module Decl

import IO;
import ParseTree;

// Decl, a trivial language, to demo simple program trafo

lexical Id  = [a-z][a-z0-9]* !>> [a-z0-9] \ Reserved;
lexical Natural = [0-9]+ ;
lexical String = "\"" ![\"]*  "\"";

layout Layout = WhitespaceAndComment* !>> [\ \t\n];

lexical WhitespaceAndComment
   = [\ \t\n\r]
   ;

keyword Reserved = "int" | "str" | "if" | "then" | "else" | "fi" | "while" | "do" | "od";

start syntax Program
   = {Statement  ";"}* body
   ;

syntax Type
   = "int"
   | "str"
   ;

syntax Statement
   = Type tp Id var
   | Type tp Id var ":=" Expression exp
   | Id var ":=" Expression val
   | "if" Expression cond "then" {Statement ";"}*  thenPart "else" {Statement ";"}* elsePart "fi"
   | "while" Expression cond "do" {Statement ";"}* body "od"
   ;

syntax Expression
   = Id name
   | String string
   | Natural natcon
   | bracket "(" Expression e ")"
   > left ( Expression lhs "+" Expression rhs
          | Expression lhs "-" Expression rhs
          )
   ;

str trafo1 () {
    p = parse(#start[Program], "int x := 1").top;
    newBody = "";
    for(stat <- p.body){
        if((Statement) `<Type tp> <Id var> := <Expression exp>` := stat){
            newBody += "<tp> <var>; <var> := <exp>";
        } else {
            newBody += "<stat>";
        }
    }
    return newBody;
}

The major part is a complete grammar of a simple language. The actual transformation is done by trafo1 which does:

Parse the example.

Introduce and initialize newBody (used to build the result).

Iterate over the statements in the given body.

Test for each statement whether it is of the desired form.
If true, append the transformed statement. Note that string templates are used here to build the transformed statement.
If false, append the original statement.

Return the resulting string.

Discussion

The solution style large depends on your goal. Here we just build a string. If desired, you could return the parsed string as result.

Alternatives:

Transform as concrete parse tree (not so easy since some functionality is still lacking but we aim to make this the preferred solution).

First transform to an abstract syntax tree (AST) and perform the transformation on the AST.

Hope this helps you to get started.


问:
Change carousel left/right position - Bootstrap-3/HTML
I have some webviews set within a carousel using bootstrap-3. The Left/Right arrows to move are too big and obstructing certain parts of my pages. How can a trim them down so they are smaller. I have tried with trial and error to change the css but with no luck.

.carousel {
  position: relative;
}

.carousel-inner {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.carousel-inner>.item {
  position: relative;
  display: none;
  -webkit-transition: .30s ease-in-out left;
  -o-transition: .30s ease-in-out left;
  transition: .30s ease-in-out left;
}

.carousel-inner>.item>img,
.carousel-inner>.item>a>img {
  line-height: 1;
}

@media all and (transform-3d),
(-webkit-transform-3d) {
  .carousel-inner>.item {
    -webkit-transition: -webkit-transform .30s ease-in-out;
    -o-transition: -o-transform .30s ease-in-out;
    transition: transform .30s ease-in-out;
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
    -webkit-perspective: 1000px;
    perspective: 1000px;
  }
  .carousel-inner>.item.next,
  .carousel-inner>.item.active.right {
    left: 0;
    -webkit-transform: translate3d(100%, 0, 0);
    transform: translate3d(100%, 0, 0);
  }
  .carousel-inner>.item.prev,
  .carousel-inner>.item.active.left {
    left: 0;
    -webkit-transform: translate3d(-100%, 0, 0);
    transform: translate3d(-100%, 0, 0);
  }
  .carousel-inner>.item.next.left,
  .carousel-inner>.item.prev.right,
  .carousel-inner>.item.active {
    left: 0;
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }
}

.carousel-inner>.active,
.carousel-inner>.next,
.carousel-inner>.prev {
  display: block;
}

.carousel-inner>.active {
  left: 0;
}

.carousel-inner>.next,
.carousel-inner>.prev {
  position: absolute;
  top: 0;
  width: 100%;
}

.carousel-inner>.next {
  left: 100%;
}

.carousel-inner>.prev {
  left: -100%;
}

.carousel-inner>.next.left,
.carousel-inner>.prev.right {
  left: 0;
}

.carousel-inner>.active.left {
  left: -100%;
}

.carousel-inner>.active.right {
  left: 100%;
}

.carousel-control {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 15%;
  font-size: 20px;
  color: #fff;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
  background-color: rgba(0, 0, 0, 0);
  filter: alpha(opacity=50);
  opacity: .5;
}

.carousel-control.left {
  background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
  background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
  background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
  background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
  background-repeat: repeat-x;
}

.carousel-control.right {
  right: 0;
  left: auto;
  background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
  background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
  background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
  background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
  background-repeat: repeat-x;
}

.carousel-control:hover,
.carousel-control:focus {
  color: #fff;
  text-decoration: none;
  filter: alpha(opacity=90);
  outline: 0;
  opacity: .9;
}

.carousel-control .icon-prev,
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
  position: absolute;
  top: 50%;
  z-index: 5;
  display: inline-block;
  margin-top: -10px;
}

.carousel-control .icon-prev,
.carousel-control .glyphicon-chevron-left {
  left: 50%;
  margin-left: -10px;
}

.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-right {
  right: 50%;
  margin-right: -10px;
}

.carousel-control .icon-prev,
.carousel-control .icon-next {
  width: 20px;
  height: 20px;
  font-family: serif;
  line-height: 1;
}

.carousel-control .icon-prev:before {
  content: '\2039';
}

.carousel-control .icon-next:before {
  content: '\203a';
}

.carousel-indicators {
  position: absolute;
  bottom: 10px;
  left: 50%;
  z-index: 15;
  width: 60%;
  padding-left: 0;
  margin-left: -30%;
  text-align: center;
  list-style: none;
}

.carousel-indicators li {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin: 1px;
  text-indent: -999px;
  cursor: pointer;
  background-color: #000 \9;
  background-color: rgba(0, 0, 0, 0);
  border: 1px solid #fff;
  border-radius: 10px;
}

.carousel-indicators .active {
  width: 12px;
  height: 12px;
  margin: 0;
  background-color: #fff;
}

.carousel-caption {
  position: absolute;
  right: 15%;
  bottom: 20px;
  left: 15%;
  z-index: 10;
  padding-top: 20px;
  padding-bottom: 20px;
  color: #fff;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
}

.carousel-caption .btn {
  text-shadow: none;
}

@media screen and (min-width: 768px) {
  .carousel-control .glyphicon-chevron-left,
  .carousel-control .glyphicon-chevron-right,
  .carousel-control .icon-prev,
  .carousel-control .icon-next {
    width: 30px;
    height: 30px;
    margin-top: -10px;
    font-size: 30px;
  }
  .carousel-control .glyphicon-chevron-left,
  .carousel-control .icon-prev {
    margin-left: -10px;
  }
  .carousel-control .glyphicon-chevron-right,
  .carousel-control .icon-next {
    margin-right: -10px;
  }
  .carousel-caption {
    right: 20%;
    left: 20%;
    padding-bottom: 30px;
  }
  .carousel-indicators {
    bottom: 20px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-xs-2 col-md-10 col-md-push-1" style="margin-top:20px; margin-bottom:20px;">
  <div class="carousel slide" data-ride="carousel" id="carousel-example-generic">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li class="active" data-slide-to="0" data-target="#carousel-example-generic"></li>
      <li data-slide-to="1" data-target="#carousel-example-generic"></li>
      <li data-slide-to="2" data-target="#carousel-example-generic"></li>
    </ol>
    <!-- Wrapper for slides -->
    <div class="carousel-inner">
      <div class="item active">
        <div>
          <webview partition="persist:test1" src="www.google.com" style="width:100%; height:1480px"></webview>
        </div>
      </div>
      <div class="item">
        <div>
          <webview partition="persist:test1" src="www.google.com" style="width:100%; height:1480px"></webview>
        </div>
      </div>
      <div class="item">
        <div>
          <webview partition="persist:test1" src="www.google.com" style="width:100%; height:1480px"></webview>
        </div>
      </div>
      <!-- Controls -->
      <span class="glyphicon glyphicon-chevron-left"></span>
      <span class="glyphicon glyphicon-chevron-right"></span>
    </div>
    <!-- Carousel -->
  </div>
</div>
<div class="col-xs-2 col-md-10 col-md-push-1" style="margin-top:20px; margin-bottom:20px;">
  <div class="carousel slide" data-ride="carousel" id="carousel-example-generic1">
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <li class="active" data-slide-to="0" data-target="#carousel-example-generic1"></li>
      <li data-slide-to="1" data-target="#carousel-example-generic1"></li>
      <li data-slide-to="2" data-target="#carousel-example-generic1"></li>
    </ol>
  </div>
</div></code>```

答:
edit the following CSS:

```<code>.carousel-control {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 8%;  /* change this value to required width */
  font-size: 20px;
  color: #fff;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
  background-color: rgba(0, 0, 0, 0);
  filter: alpha(opacity=50);
  opacity: .5;
}
</code>```

Body:
I have some webviews set within a carousel using bootstrap-3. The Left/Right arrows to move are too big and obstructing certain parts of my pages. How can a trim them down so they are smaller. I have tried with trial and error to change the css but with no luck.

.carousel {
  position: relative;
}

.carousel-inner {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.carousel-inner>.item {
  position: relative;
  display: none;
  -webkit-transition: .30s ease-in-out left;
  -o-transition: .30s ease-in-out left;
  transition: .30s ease-in-out left;
}

.carousel-inner>.item>img,
.carousel-inner>.item>a>img {
  line-height: 1;
}

@media all and (transform-3d),
(-webkit-transform-3d) {
  .carousel-inner>.item {
    -webkit-transition: -webkit-transform .30s ease-in-out;
    -o-transition: -o-transform .30s ease-in-out;
    transition: transform .30s ease-in-out;
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
    -webkit-perspective: 1000px;
    perspective: 1000px;
  }
  .carousel-inner>.item.next,
  .carousel-inner>.item.active.right {
    left: 0;
    -webkit-transform: translate3d(100%, 0, 0);
    transform: translate3d(100%, 0, 0);
  }
  .carousel-inner>.item.prev,
  .carousel-inner>.item.active.left {
    left: 0;
    -webkit-transform: translate3d(-100%, 0, 0);
    transform: translate3d(-100%, 0, 0);
  }
  .carousel-inner>.item.next.left,
  .carousel-inner>.item.prev.right,
  .carousel-inner>.item.active {
    left: 0;
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }
}

.carousel-inner>.active,
.carousel-inner>.next,
.carousel-inner>.prev {
  display: block;
}

.carousel-inner>.active {
  left: 0;
}

.carousel-inner>.next,
.carousel-inner>.prev {
  position: absolute;
  top: 0;
  width: 100%;
}

.carousel-inner>.next {
  left: 100%;
}

.carousel-inner>.prev {
  left: -100%;
}

.carousel-inner>.next.left,
.carousel-inner>.prev.right {
  left: 0;
}

.carousel-inner>.active.left {
  left: -100%;
}

.carousel-inner>.active.right {
  left: 100%;
}

.carousel-control {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 15%;
  font-size: 20px;
  color: #fff;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
  background-color: rgba(0, 0, 0, 0);
  filter: alpha(opacity=50);
  opacity: .5;
}

.carousel-control.left {
  background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
  background-image: -o-linear-gradient(left, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
  background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .5)), to(rgba(0, 0, 0, .0001)));
  background-image: linear-gradient(to right, rgba(0, 0, 0, .5) 0%, rgba(0, 0, 0, .0001) 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
  background-repeat: repeat-x;
}

.carousel-control.right {
  right: 0;
  left: auto;
  background-image: -webkit-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
  background-image: -o-linear-gradient(left, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
  background-image: -webkit-gradient(linear, left top, right top, from(rgba(0, 0, 0, .0001)), to(rgba(0, 0, 0, .5)));
  background-image: linear-gradient(to right, rgba(0, 0, 0, .0001) 0%, rgba(0, 0, 0, .5) 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
  background-repeat: repeat-x;
}

.carousel-control:hover,
.carousel-control:focus {
  color: #fff;
  text-decoration: none;
  filter: alpha(opacity=90);
  outline: 0;
  opacity: .9;
}

.carousel-control .icon-prev,
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
  position: absolute;
  top: 50%;
  z-index: 5;
  display: inline-block;
  margin-top: -10px;
}

.carousel-control .icon-prev,
.carousel-control .glyphicon-chevron-left {
  left: 50%;
  margin-left: -10px;
}

.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-right {
  right: 50%;
  margin-right: -10px;
}

.carousel-control .icon-prev,
.carousel-control .icon-next {
  width: 20px;
  height: 20px;
  font-family: serif;
  line-height: 1;
}

.carousel-control .icon-prev:before {
  content: '\2039';
}

.carousel-control .icon-next:before {
  content: '\203a';
}

.carousel-indicators {
  position: absolute;
  bottom: 10px;
  left: 50%;
  z-index: 15;
  width: 60%;
  padding-left: 0;
  margin-left: -30%;
  text-align: center;
  list-style: none;
}

.carousel-indicators li {
  display: inline-block;
  width: 10px;
  height: 10px;
  margin: 1px;
  text-indent: -999px;
  cursor: pointer;
  background-color: #000 \9;
  background-color: rgba(0, 0, 0, 0);
  border: 1px solid #fff;
  border-radius: 10px;
}

.carousel-indicators .active {
  width: 12px;
  height: 12px;
  margin: 0;
  background-color: #fff;
}

.carousel-caption {
  position: absolute;
  right: 15%;
  bottom: 20px;
  left: 15%;
  z-index: 10;
  padding-top: 20px;
  padding-bottom: 20px;
  color: #fff;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
}

.carousel-caption .btn {
  text-shadow: none;
}

@media screen and (min-width: 768px) {
  .carousel-control .glyphicon-chevron-left,
  .carousel-control .glyphicon-chevron-right,
  .carousel-control .icon-prev,
  .carousel-control .icon-next {
    width: 30px;
    height: 30px;
    margin-top: -10px;
    font-size: 30px;
  }
  .carousel-control .glyphicon-chevron-left,
  .carousel-control .icon-prev {
    margin-left: -10px;
  }
  .carousel-control .glyphicon-chevron-right,
  .carousel-control .icon-next {
    margin-right: -10px;
  }
  .carousel-caption {
    right: 20%;
    left: 20%;
    padding-bottom: 30px;
  }
  .carousel-indicators {
    bottom: 20px;
  }
}

          <webview partition="persist:test1" src="www.google.com" style="width:100%; height:1480px"></webview>

          <webview partition="persist:test1" src="www.google.com" style="width:100%; height:1480px"></webview>

          <webview partition="persist:test1" src="www.google.com" style="width:100%; height:1480px"></webview>

Body:
edit the following CSS:

.carousel-control {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 8%;  /* change this value to required width */
  font-size: 20px;
  color: #fff;
  text-align: center;
  text-shadow: 0 1px 2px rgba(0, 0, 0, .6);
  background-color: rgba(0, 0, 0, 0);
  filter: alpha(opacity=50);
  opacity: .5;
}


问:
Automatic post-registration user authentication
We're building a business app from the ground up in Symfony 2, and I've run into a bit of a snag with the user registration flow: after the user creates an account, they should be automatically logged in with those credentials, instead of being immediately forced to provide their credentials again.

Anyone had any experience with this, or able to point me in the right direction?

答:
On Symfony version 2.8.11 (probably working for older and newer versions), if you use FOSUserBundle simply do this :

```<code>try {
    $this->container->get('fos_user.security.login_manager')->loginUser(
    $this->container->getParameter('fos_user.firewall_name'), $user, null);
} catch (AccountStatusException $ex) {
    // We simply do not authenticate users which do not pass the user
    // checker (not enabled, expired, etc.).
}
</code>```

No need to dispatch event as I've seen in other solutions.

inpired from FOS\UserBundle\Controller\RegistrationController::authenticateUser

(from composer.json FOSUserBundle version : "friendsofsymfony/user-bundle": "~1.3")

Body:
On Symfony version 2.8.11 (probably working for older and newer versions), if you use FOSUserBundle simply do this :

try {
    $this->container->get('fos_user.security.login_manager')->loginUser(
    $this->container->getParameter('fos_user.firewall_name'), $user, null);
} catch (AccountStatusException $ex) {
    // We simply do not authenticate users which do not pass the user
    // checker (not enabled, expired, etc.).
}

No need to dispatch event as I've seen in other solutions.

inpired from FOS\UserBundle\Controller\RegistrationController::authenticateUser

(from composer.json FOSUserBundle version : "friendsofsymfony/user-bundle": "~1.3")


问:
How can I shrink an image in HTML whilst maintaining its sharpness?
I have an image that I use many times. In several cases I want to shrink its size, but obviously it loses sharpness when I do this in HTML.

Is there a way to fix this? The image is located elsewhere and I can’t save it locally.

Thanks

答:
There is three way that I know to reduce an image file size in bytes :

Convert the file into a format using lossy compression algorithm such as JPG. Obviously the image will lose sharpness

Convert the file into a format using lossless compression algorithm, like PNG. Only works if the image contains lots of region with flat colors

Resize/resample the image using Photoshop or GIMP. If the new image dimension (width x height) is exactly the same as the displayed image's dimension in HTML, then web users will still see a sharp image


问:
How to add HeaderView in UICollectionView like UITableView's tableHeaderView
How can I add a header view / top view (not section header) at the top of a UICollectionView?

It should act excactly as UITableView's tableHeaderView property.

So it needs to sit on top of the first section header view (before the section at index 0), scroll along with the rest of the content, and have user interaction.

The best I've come up with so far is to make a special XIB (with MyCollectionReusableView subclass of UICollectionReusableView as the File's owner) for the first section header view that is big enough to also contain my subviews in header, it's kind of a hack, I think, and I haven't managed to detect touches.

Not sure if I can make my MyCollectionReusableView subclass to allow touches or there's a better way.

答:
```<code>private var PreviousInsetKey: Void?
extension UIView {

var previousInset:CGFloat {
    get {
        return objc_getAssociatedObject(self, &PreviousInsetKey) as? CGFloat ?? 0.0
    }
    set {
        if newValue == -1{
            objc_setAssociatedObject(self, &PreviousInsetKey, nil, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
        else{
            objc_setAssociatedObject(self, &PreviousInsetKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

func addOnCollectionView(cv: UICollectionView){
    if self.superview == nil{
        var frame = self.frame
        frame.size.width = SCREEN_WIDTH
        cv.frame = frame
        self.addOnView(view: cv)
        let flow = cv.collectionViewLayout as! UICollectionViewFlowLayout
        var inset = flow.sectionInset
        previousInset = inset.top
        inset.top = frame.size.height
        flow.sectionInset = inset
    }

}

func removeFromCollectionView(cv: UICollectionView){
    if self.superview == nil{
        return
    }
    self.removeFromSuperview()
    let flow = cv.collectionViewLayout as! UICollectionViewFlowLayout
    var inset = flow.sectionInset
    inset.top = previousInset
    flow.sectionInset = inset
    previousInset = -1
}

func addOnView(view: UIView){

    view.addSubview(self)

    self.translatesAutoresizingMaskIntoConstraints = false
    let leftConstraint = NSLayoutConstraint(item: self, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0)
    let widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: view.frame.size.width)
    let heightConstraint = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: view.frame.size.height)
    let topConstraint = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0)

    view.addConstraints([leftConstraint, widthConstraint, heightConstraint, topConstraint])
    self.layoutIfNeeded()
    view.layoutIfNeeded()
}
}
</code>```


问:
Remove a string from another string in javascript
I am trying to remove a String from another String.

```<code>var text = "This is a string";
</code>```

I want to remove the word "is" so I will have

```<code>text = "This a string";
</code>```

How do I go about that?

答:
Short way would be

```<code>var text = "This is a string";
var replace = "is";
var text = text.replace(new RegExp('\\b' + replace + '\\b'), "")
</code>```

This would replace whole words and not parts of it. If you want to replace all the occurrences, you can use

```<code>var text = text.split(replace).join("");
</code>```

Body:
I am trying to remove a String from another String.

var text = "This is a string";

I want to remove the word "is" so I will have

text = "This a string";

How do I go about that?

Body:
Short way would be

var text = "This is a string";
var replace = "is";
var text = text.replace(new RegExp('\\b' + replace + '\\b'), "")

This would replace whole words and not parts of it. If you want to replace all the occurrences, you can use

var text = text.split(replace).join("");


问:
SCIM endpoint for Azure User Provisioning
I am trying to implement SCIM auto-provisioning.

I have an endpoint in Java Spring for HTTP method POST with path /User

My site URL is www.SampleScim.com and this endpoint is configured in Azure SCIM provisioning by following the below steps

Creating APP:

launched the Azure management portal at

https://manage.windowsazure.com.

Browse to Active Directory > Directory > My Directory > Applications, and select Add > Add an application from the gallery.

Select the Custom tab on the left, enter a name as SampleSCIM for my application, and clicked the checkmark icon to create an app object.

Configuring endpoint in App:

In the resulting screen, select the second Configure account provisioning button.

In the Provisioning Endpoint URL field, enter the URL SCIM endpoint as www.SampleScim.com/ and left Authentication Token (optional) field blank.

Clicked on Next through to the final step.

My Java Controller is as below.

```<code>    @RequestMapping(value = "/Users", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public ScimUser createSCIMUser(@RequestBody ScimUser user, HttpServletRequest request, HttpServletResponse response) {

         if (LOGGER.isInfoEnabled()) {
                LOGGER.info(requestId + ": ------------------Inside createSCIMUser Entry ----------------------:\n" );
            }

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(requestId + ": ------------------Inside createSCIMUser Exit ----------------------:\n ");
        }
        return user;
    }
</code>```

I am not able to see my endpoint (/Users) is getting triggered whenever I add a user in Azure.

Complete endpoint URL: www.SampleScim.com/Users.

答:
According to the #46 page of the slide Identity Management with Spring Security, it said SCIM is not implemented in Spring. So just via the code you post, I don't know how you implemented SCIM endpoint using Spring, or implement the feature by yourself in other codes.

The code of your Java controller seems to only implement the feature of Creating Resources of the SCIM 2.0 protocol specification. Just as references, I suggested you can refer to the two projects (okta-scim-java-beta and SCIM 2.0 SDK for Java) on GitHub to improve your code.

Hope it helps.

Body:
I am trying to implement SCIM auto-provisioning.

I have an endpoint in Java Spring for HTTP method POST with path /User

My site URL is www.SampleScim.com and this endpoint is configured in Azure SCIM provisioning by following the below steps

Creating APP:

launched the Azure management portal at

https://manage.windowsazure.com.

Browse to Active Directory > Directory > My Directory > Applications, and select Add > Add an application from the gallery.

Select the Custom tab on the left, enter a name as SampleSCIM for my application, and clicked the checkmark icon to create an app object.

Configuring endpoint in App:

In the resulting screen, select the second Configure account provisioning button.

In the Provisioning Endpoint URL field, enter the URL SCIM endpoint as www.SampleScim.com/ and left Authentication Token (optional) field blank.

Clicked on Next through to the final step.

My Java Controller is as below.

    @RequestMapping(value = "/Users", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    @ResponseBody
    public ScimUser createSCIMUser(@RequestBody ScimUser user, HttpServletRequest request, HttpServletResponse response) {

         if (LOGGER.isInfoEnabled()) {
                LOGGER.info(requestId + ": ------------------Inside createSCIMUser Entry ----------------------:\n" );
            }

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(requestId + ": ------------------Inside createSCIMUser Exit ----------------------:\n ");
        }
        return user;
    }

I am not able to see my endpoint (/Users) is getting triggered whenever I add a user in Azure.

Complete endpoint URL: www.SampleScim.com/Users.