问:
Send Messages without reload page using ajax in laravel
I am working on laravel and I want to send personally messages to the users using blade template. But when I press submit button it gets refreshed/reload the page every time. what to do? and please anyone tell me how to use ajax url, type, data

View file

```<code><form action="{{action('MessageController@sendmessagereply')}}" method="post">
            <div class="panel-footer">
                <div class="input-group">
                   <?php if(isset($data)){ ?>
                   <?php for($i=0;$i<count($data);$i++) {?>
                    <input type="hidden" name="_token" value="{{csrf_token()}}">
                    <input type="hidden" name="id" value="<?php echo $data[$i]->receivermsgid;?>">
                    <?php } }?>
                    <input type="text"  name="messages" class="form-control" placeholder="Enter Message" />
                    <span class="input-group-btn">
                       <button class="btn btn-info" type="submit">SEND</button>
                    </span>
                </div>
            </div>
          </form>
</code>```

Controller file

```<code> public function sendmessagereply(Request $request)
      {
            $post=$request->all();
            $id=$post['id'];
            $senderid=Session::get('login_userid');
            $receiverid = $id;
            $data=array(
                        'sendermsgid' => $senderid,
                        'receivermsgid' => $receiverid,
                        'message'=>$post['messages'],
                        'sdate'=> DB::raw('CURRENT_TIMESTAMP')
                        );
            $messages = DB::table('messages')->insert($data);
            if($messages){
                \Session::flash('msg','Your Message Has Been Sent Successfully');
                return redirect('messageschat/'.$id);
            } else {
                \Session::flash('msg','Error In Sending Message');
                return redirect('basicsearch');
            }

        }

  //i get the all messages between two users
  public function messageschat($id)
    {
       $senderid=Session::get('login_userid');
       $result=DB::table('messages')
                  ->join('user_register','messages.sendermsgid','=','user_register.id')
                  ->leftjoin('profilephoto','messages.receivermsgid','=','profilephoto.userid','messages.sendermsgid','=','profilephoto.userid')
                  ->where('sendermsgid', $senderid)->where('receivermsgid',$receivermsgid)
                  ->orwhere('sendermsgid',$receivermsgid)->where('receivermsgid',$senderid)
                  ->select('messages.message','messages.sendermsgid','messages.receivermsgid','user_register.first_name as fname','profilephoto.name')
                  ->orderby('messages.sdate')
                  ->get();

       $chatdata=DB::table('messages')
                     ->select('messages.message','messages.receivermsgid','messages.sendermsgid')
                     ->where('receivermsgid',$receivermsgid)
                     ->where('sendermsgid',$senderid)->get();

       return view('users.messageschat')->with('data',$chatdata)->with('data1',$result);
    }
</code>```

Route file

```<code>Route::any('messageschat/{id}','MessageController@messageschat');
</code>```

Javascript file

```<code><script>
$("#add").click(function() {

    $.ajax({
        type: 'post',
        url: 'messageschat/{id}',
        data: {
            '_token': $('input[name=_token]').val(),
            'messages': $('input[messages=messages]').val(),
            'id':$('input[name=_token]').val()
        },
        success: function(data) {
          alert(data)
            if ((data.errors)) {
                $('.error').removeClass('hidden');
                $('.error').text(data.errors.name);
            } else {
                $('.error').remove();
                $('#table').append("");
            }
        },
    });
    $('#name').val('');
});
    </script>
</code>```

答:
if #add is the submit button ID then i believe you have tto call the preventDefault() function before ajax call `

```<code>$("#add").click(function(e) {
e.preventDefault();
    $.ajax({
        type: 'post',
        url: 'messageschat/{id}',
        data: {
            '_token': $('input[name=_token]').val(),
            'messages': $('input[messages=messages]').val(),
            'id':$('input[name=_token]').val()
        },
        success: function(data) {
          alert(data)
            if ((data.errors)) {
                $('.error').removeClass('hidden');
                $('.error').text(data.errors.name);
            } else {
                $('.error').remove();
                $('#table').append("");
            }
        },
    });
    $('#name').val('');
});
</code>```

plus you forgot to add id to btn

Body:
I am working on laravel and I want to send personally messages to the users using blade template. But when I press submit button it gets refreshed/reload the page every time. what to do? and please anyone tell me how to use ajax url, type, data

View file

<form action="{{action('MessageController@sendmessagereply')}}" method="post">

                   <?php if(isset($data)){ ?>
                   <?php for($i=0;$i<count($data);$i++) {?>
                    <input type="hidden" name="_token" value="{{csrf_token()}}">
                    <input type="hidden" name="id" value="<?php echo $data[$i]->receivermsgid;?>">
                    <?php } }?>
                    <input type="text"  name="messages" class="form-control" placeholder="Enter Message" />

                       <button class="btn btn-info" type="submit">SEND</button>

          </form>

Controller file

 public function sendmessagereply(Request $request)
      {
            $post=$request->all();
            $id=$post['id'];
            $senderid=Session::get('login_userid');
            $receiverid = $id;
            $data=array(
                        'sendermsgid' => $senderid,
                        'receivermsgid' => $receiverid,
                        'message'=>$post['messages'],
                        'sdate'=> DB::raw('CURRENT_TIMESTAMP')
                        );
            $messages = DB::table('messages')->insert($data);
            if($messages){
                \Session::flash('msg','Your Message Has Been Sent Successfully');
                return redirect('messageschat/'.$id);
            } else {
                \Session::flash('msg','Error In Sending Message');
                return redirect('basicsearch');
            }

        }

  //i get the all messages between two users
  public function messageschat($id)
    {
       $senderid=Session::get('login_userid');
       $result=DB::table('messages')
                  ->join('user_register','messages.sendermsgid','=','user_register.id')
                  ->leftjoin('profilephoto','messages.receivermsgid','=','profilephoto.userid','messages.sendermsgid','=','profilephoto.userid')
                  ->where('sendermsgid', $senderid)->where('receivermsgid',$receivermsgid)
                  ->orwhere('sendermsgid',$receivermsgid)->where('receivermsgid',$senderid)
                  ->select('messages.message','messages.sendermsgid','messages.receivermsgid','user_register.first_name as fname','profilephoto.name')
                  ->orderby('messages.sdate')
                  ->get();

       $chatdata=DB::table('messages')
                     ->select('messages.message','messages.receivermsgid','messages.sendermsgid')
                     ->where('receivermsgid',$receivermsgid)
                     ->where('sendermsgid',$senderid)->get();

       return view('users.messageschat')->with('data',$chatdata)->with('data1',$result);
    }

Route file

Route::any('messageschat/{id}','MessageController@messageschat');

Javascript file

Body:
if #add is the submit button ID then i believe you have tto call the preventDefault() function before ajax call `

$("#add").click(function(e) {
e.preventDefault();
    $.ajax({
        type: 'post',
        url: 'messageschat/{id}',
        data: {
            '_token': $('input[name=_token]').val(),
            'messages': $('input[messages=messages]').val(),
            'id':$('input[name=_token]').val()
        },
        success: function(data) {
          alert(data)
            if ((data.errors)) {
                $('.error').removeClass('hidden');
                $('.error').text(data.errors.name);
            } else {
                $('.error').remove();
                $('#table').append("");
            }
        },
    });
    $('#name').val('');
});

plus you forgot to add id to btn


来源: stackexchange

问:
C++: The choices of initializing a member class with no implicit default constructor (more constraints in question body)
boost::posix_time::time_duration has three constructor overloads, and no implicit constructor. I need to make some calculations in a class which has some time_duration members before I can initialize them. All of this implies that without a default constructor I do not have the luxury of preparing input for my class members in my composing class constructor.

The pattern might be described as follows (which is eroneous):

```<code>class X {
public:
    x(int i,int j){}
};

class Y {
  x _x;
public:
    y() {i = 1+1; j=1-1; _x(i,j);}
};

int main()
{
    return 0;
}
</code>```

I would like some relevant ways of constructing Y (with motivation), where

X does not have a default constructor.

X cannot be altered directly (but can be subclassed).

The generated code is deterministic (no unnecesary expensive constructs malloc/vtables etc).

crucial point The class Y has n X members and m possible calculations. Where n >1 and m > 1. So elegance is important.

Unit testing considerations are important.

At this point I am leaning towards either subclassing , or calling functions to do the calculations and calling these functions in the initialization list (if that is even possible). You can comment on these approaches :D.

答:
Sorry if I misunderstood your question, but isn't Boost.Optional a solution to your problem ? That's probably the best way to achieve a default uninitialized state without going for pointers and dynamic allocation.

However, although that would work, it's probably not ideal. My solution of choice would probably be, if possible, to move the calculations in free functions in an anonymous namespace :

```<code>namespace {
    x computeX()
    {
        int i, j = /* ... */;
        return x(i, j);
    }
}

y::y()
  : _x(computeX())
{
    /* ... */
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
boost::posix_time::time_duration has three constructor overloads, and no implicit constructor. I need to make some calculations in a class which has some time_duration members before I can initialize them. All of this implies that without a default constructor I do not have the luxury of preparing input for my class members in my composing class constructor.

The pattern might be described as follows (which is eroneous):

class X {
public:
    x(int i,int j){}
};

class Y {
  x _x;
public:
    y() {i = 1+1; j=1-1; _x(i,j);}
};

int main()
{
    return 0;
}

I would like some relevant ways of constructing Y (with motivation), where

X does not have a default constructor.

X cannot be altered directly (but can be subclassed).

The generated code is deterministic (no unnecesary expensive constructs malloc/vtables etc).

crucial point The class Y has n X members and m possible calculations. Where n >1 and m > 1. So elegance is important.

Unit testing considerations are important.

At this point I am leaning towards either subclassing , or calling functions to do the calculations and calling these functions in the initialization list (if that is even possible). You can comment on these approaches :D.

Body:
Sorry if I misunderstood your question, but isn't Boost.Optional a solution to your problem ? That's probably the best way to achieve a default uninitialized state without going for pointers and dynamic allocation.

However, although that would work, it's probably not ideal. My solution of choice would probably be, if possible, to move the calculations in free functions in an anonymous namespace :

namespace {
    x computeX()
    {
        int i, j = /* ... */;
        return x(i, j);
    }
}

y::y()
  : _x(computeX())
{
    /* ... */
}


问:
How to push array values in one more array using php and json
Here i am selecting the id from  postadvertisement (Table Name),and after that bassed apon id how many images are there i select the images from gallery (Table Name) and also all images i push in same array, it is working fine, but i am not getting exact JSON format, how can make my result to my json format

```<code>    $select = mysql_query("SELECT * FROM postadvertisement WHERE id = '$postadv' AND status != '1'");
    $count = mysql_num_rows($select);
    $farr = array();
    if($count > 0){
    while($fet= mysql_fetch_array($select)) {
      $row['PostId'] = $fet['id'];
      $row['title'] = $fet['title'];
      $row['subcatName'] = Get_subcatName($fet['subcat']);
      $row['minPrice'] = $fet['minPrice'];
      $row['maxPrice'] = $fet['maxPrice'];
      $row['location'] = Get_areaName($fet['location']);
      $row['description'] = $fet['description'];

    $farrs = array();
    $q1 = mysql_query("SELECT * FROM gallery WHERE `postadvId` = '$postadv' AND status != '1'");

    while($fq1 = mysql_fetch_array($q1))
    {
        $rowimg['PostId'] = $fet['id'];
        $rowimg['title'] = $fet['title'];
        $rowimg['imgId'] =$fq1['id'];
        $rowimg['images'] = "http://androidappfirst.com/b2b/app/images/".$fq1['images'];
    array_push($farrs,$rowimg);
    }
      $row['multipleImages'] = $farrs;
      array_push($farr,$row);
    }

    echo json_encode(array("status"=>"success","productList"=>$farr));
 }
 else
 {
    echo json_encode(array("status"=>"Error","response"=>"No Details found"));
 }
</code>```

I am getting response

```<code>    {
  "status": "yes",
  "response": "success",
  "productList": [
    {
      "PostId": "2",
      "title": "Honda activa",
      "subcatName": "Commercial Land",
      "minPrice": "15000",
      "maxPrice": "0",
      "location": "Marathahalli",
      "description": "1 years  old",
      "multipleImages": [
        {
          "PostId": "2",
          "title": "Honda activa",
          "imgId": "1",
          "images": "http://androidappfirst.com/b2b/app/images/33584d27212ddcf24de5f91b3a0d241d.jpg"
        },
        {
          "PostId": "2",
          "title": "Honda activa",
          "imgId": "2",
          "images": "http://androidappfirst.com/b2b/app/images/763e710ee7c7ffdd96a41ca2a682c0a7.jpg"
        }
      ]
    }
  ]
}
</code>```

My Expected JSON OUPUT

```<code> "status": "yes",
"response": "success",
"Details":[
{
"categoryname": "Recently Added",
"categoriid":  "1",
"productList": [
{
    "PostId": "1",
    "title": "Honda activa",
    "subcatName": "Commercial Land",
    "minPrice": "15000",
    "maxPrice": "0",
    "location": "Marathahalli",
    "description": "1 years  old",
    "multipleImages": [
    {
      "PostId": "2",
      "title": "Honda activa",
      "imgId": "1",
      "images": "http://androidappfirst.com/b2b/app/images/33584d27212ddcf24de5f91b3a0d241d.jpg"
    },
    {
      "PostId": "2",
      "title": "Honda activa",
      "imgId": "2",
      "images": "http://androidappfirst.com/b2b/app/images/763e710ee7c7ffdd96a41ca2a682c0a7.jpg"
    }
  ]
}

]

}

]
}
</code>```

Here i want to create Details array in that array i have push the productList array values

答:
As it is unclear where do you take "categoryname" and "categoriid" values, I'll gve you just an example:

```<code>echo json_encode(array(
    "status"=>"success",
    "Details" => array(
        array(
            "categoryname" => $someVariable,
            "categoriid" => $anotherVariable,
            "productList"=>$farr,
        )
    )
));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here i am selecting the id from  postadvertisement (Table Name),and after that bassed apon id how many images are there i select the images from gallery (Table Name) and also all images i push in same array, it is working fine, but i am not getting exact JSON format, how can make my result to my json format

    $select = mysql_query("SELECT * FROM postadvertisement WHERE id = '$postadv' AND status != '1'");
    $count = mysql_num_rows($select);
    $farr = array();
    if($count > 0){
    while($fet= mysql_fetch_array($select)) {
      $row['PostId'] = $fet['id'];
      $row['title'] = $fet['title'];
      $row['subcatName'] = Get_subcatName($fet['subcat']);
      $row['minPrice'] = $fet['minPrice'];
      $row['maxPrice'] = $fet['maxPrice'];
      $row['location'] = Get_areaName($fet['location']);
      $row['description'] = $fet['description'];

    $farrs = array();
    $q1 = mysql_query("SELECT * FROM gallery WHERE `postadvId` = '$postadv' AND status != '1'");

    while($fq1 = mysql_fetch_array($q1))
    {
        $rowimg['PostId'] = $fet['id'];
        $rowimg['title'] = $fet['title'];
        $rowimg['imgId'] =$fq1['id'];
        $rowimg['images'] = "http://androidappfirst.com/b2b/app/images/".$fq1['images'];
    array_push($farrs,$rowimg);
    }
      $row['multipleImages'] = $farrs;
      array_push($farr,$row);
    }

    echo json_encode(array("status"=>"success","productList"=>$farr));
 }
 else
 {
    echo json_encode(array("status"=>"Error","response"=>"No Details found"));
 }

I am getting response

    {
  "status": "yes",
  "response": "success",
  "productList": [
    {
      "PostId": "2",
      "title": "Honda activa",
      "subcatName": "Commercial Land",
      "minPrice": "15000",
      "maxPrice": "0",
      "location": "Marathahalli",
      "description": "1 years  old",
      "multipleImages": [
        {
          "PostId": "2",
          "title": "Honda activa",
          "imgId": "1",
          "images": "http://androidappfirst.com/b2b/app/images/33584d27212ddcf24de5f91b3a0d241d.jpg"
        },
        {
          "PostId": "2",
          "title": "Honda activa",
          "imgId": "2",
          "images": "http://androidappfirst.com/b2b/app/images/763e710ee7c7ffdd96a41ca2a682c0a7.jpg"
        }
      ]
    }
  ]
}

My Expected JSON OUPUT

 "status": "yes",
"response": "success",
"Details":[
{
"categoryname": "Recently Added",
"categoriid":  "1",
"productList": [
{
    "PostId": "1",
    "title": "Honda activa",
    "subcatName": "Commercial Land",
    "minPrice": "15000",
    "maxPrice": "0",
    "location": "Marathahalli",
    "description": "1 years  old",
    "multipleImages": [
    {
      "PostId": "2",
      "title": "Honda activa",
      "imgId": "1",
      "images": "http://androidappfirst.com/b2b/app/images/33584d27212ddcf24de5f91b3a0d241d.jpg"
    },
    {
      "PostId": "2",
      "title": "Honda activa",
      "imgId": "2",
      "images": "http://androidappfirst.com/b2b/app/images/763e710ee7c7ffdd96a41ca2a682c0a7.jpg"
    }
  ]
}

]

}

]
}

Here i want to create Details array in that array i have push the productList array values

Body:
As it is unclear where do you take "categoryname" and "categoriid" values, I'll gve you just an example:

echo json_encode(array(
    "status"=>"success",
    "Details" => array(
        array(
            "categoryname" => $someVariable,
            "categoriid" => $anotherVariable,
            "productList"=>$farr,
        )
    )
));


问:
Ensure database has been updated before returning with Entity Framework and C#
I have a situation where I am caching the contents of a table in the database.  I am using Entity Framework 6 against an SQL Azure back-end. When the data in the table is updated.The process looks a little like this:

Receive data from UI

Insert/Update according to current state of store

Trigger Cache rebuild ( on separate service )

Then on the cache service

Clear cache

Load all entities from the table

Add the collection to the cache

The code on the data service works along these lines- this is obviously a highly abstracted version, but it shows the steps we go through:

```<code>public void UpdateProperty( int newVal )
{
    SetNewPropertyVal(newVal);
    TriggerUpdateEvent( newVal );
}

private void SetNewPropertyVal(int newVal)
{

     using (var context = new MyContext())
     {
         using ( var mySet = context.Set<MyEntityType>();
         {
              var record = mySet.FindRecordToUpdate();
              record.UpdateableFieldValue = newVal;
              context.SaveChanges();
         }
     }
}
</code>```

The problem is that although context.SaveChanges() has been called before the TriggerUpdateEvent is raised, when cache rebuild ( running in a separate, fully independent, thread against a separate instance of the DbContext ) retrieves the collection of entities, it contains the old value for the updated property. This looks like a race condition- if I put a simple Thread.Sleep(1000) in the cache refresh it works consistently, but I can't believe that is a good solution to this problem.

How do I avoid triggering a cache rebuild until the Entity Framework has actually updated the data store? I thought a transaction might do the trick, but SQL Azure doesn't seem to offer them.

答:
In this case @ivan-stoev correctly explained that there is no reason for this code to fail synchronously. That lead me to explore the Cache rebuild process in more detail and there was a reliance on a second cache concealed away in an AutoMapper configuration that was causing the old value to show up in my searches.

So for anyone else who turns up with this problem, the bug isn't in this part of your code.

Body:
I have a situation where I am caching the contents of a table in the database.  I am using Entity Framework 6 against an SQL Azure back-end. When the data in the table is updated.The process looks a little like this:

Receive data from UI

Insert/Update according to current state of store

Trigger Cache rebuild ( on separate service )

Then on the cache service

Clear cache

Load all entities from the table

Add the collection to the cache

The code on the data service works along these lines- this is obviously a highly abstracted version, but it shows the steps we go through:

public void UpdateProperty( int newVal )
{
    SetNewPropertyVal(newVal);
    TriggerUpdateEvent( newVal );
}

private void SetNewPropertyVal(int newVal)
{

     using (var context = new MyContext())
     {
         using ( var mySet = context.Set<MyEntityType>();
         {
              var record = mySet.FindRecordToUpdate();
              record.UpdateableFieldValue = newVal;
              context.SaveChanges();
         }
     }
}

The problem is that although context.SaveChanges() has been called before the TriggerUpdateEvent is raised, when cache rebuild ( running in a separate, fully independent, thread against a separate instance of the DbContext ) retrieves the collection of entities, it contains the old value for the updated property. This looks like a race condition- if I put a simple Thread.Sleep(1000) in the cache refresh it works consistently, but I can't believe that is a good solution to this problem.

How do I avoid triggering a cache rebuild until the Entity Framework has actually updated the data store? I thought a transaction might do the trick, but SQL Azure doesn't seem to offer them.


问:
Can I use data-binding on the Duration of an Animation in a ControlTemplate?
I found a good explanation here on SO of how to bind the Duration property of a ColorAnimation to the Value property of a Slider. One uses a converter to convert the Double value from the slider to a Duration, and a Binding to have that set the Duration of the ColorAnimation. Here, abbreviated, is how that works:

<Window.Resources>
    <local:DoubleToDurationConverter x:Key="DoubleToDurationConverter" />
</Window.Resources>

<Slider x:Name="slider" />

<Button Content="Click me for an animation">
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation To="Green"
                        Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
                        FillBehavior="Stop"
                        Duration="{Binding ElementName=slider,
                                           Path=Value,
                                           Mode=OneWay,
                                           Converter={StaticResource DoubleToDurationConverter}}" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Button.Triggers>
</Button>
```

<p>I tried that and it worked fine for me. But what I want to do is bind the <code>Duration</code> to a dependency property called <code>FadeTime</code> I've added to my custom control. So, in that control's <code>ControlTemplate</code> I have this:</p>

<pre class="lang-xml prettyprint-override"><code><ControlTemplate.Triggers>
    <Trigger Property="IsLit" Value="true">
        <Trigger.EnterActions>
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetName="glow"
                                     Storyboard.TargetProperty="Opacity"
                                     To="1"
                                     Duration="{Binding FadeTime, Mode=OneWay,
                                                RelativeSource={RelativeSource TemplatedParent}}"/>
                </Storyboard>
            </BeginStoryboard>
        </Trigger.EnterActions>
    </Trigger>
</ControlTemplate.Triggers>
</code>```

This compiles, but gives me an error message at run-time:

InvalidOperationException: Cannot freeze this Storyboard timeline tree
  for use across threads.

How can I bind my DoubleAnimation's Duration to a dependency variable in a custom control's ControlTemplate?

Thanks!

UPDATE

Data-binding is actually gross overkill for what I want to do. Real data-binding would allow for the property's value to change at run-time. All I really want is a way for the developer who is using my custom control to be able to set the Duration of the DoubleAnimation at design time, without having to edit the ControlTemplate. It's okay if the value the developer chooses never changes at run time.

答:
Instead of defining the animation in your XAML markup, you could define it programmatically in the PropertyChangedCallback for the IsLit property.

You could simply define another property that lets the consumer of the control specify the duration of the animation.

Here is an example for you.

Control:

```<code>public class MyCustomControl : Control
{
    private UIElement glow;

    public static readonly DependencyProperty DurationProperty =
         DependencyProperty.Register("Duration", typeof(TimeSpan),
         typeof(MyCustomControl), new PropertyMetadata(TimeSpan.FromSeconds(1)));

    public TimeSpan Duration
    {
        get { return (TimeSpan)GetValue(DurationProperty); }
        set { SetValue(DurationProperty, value); }
    }

    public static readonly DependencyProperty IsLitProperty =
         DependencyProperty.Register("IsLit", typeof(bool),
         typeof(MyCustomControl), new PropertyMetadata(false, new PropertyChangedCallback(OnIsLitChanged)));

    public bool IsLit
    {
        get { return (bool)GetValue(IsLitProperty); }
        set { SetValue(IsLitProperty, value); }
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        glow = Template.FindName("glow", this) as UIElement;
        if (glow != null && IsLit)
            Animate(glow);

    }

    private static void OnIsLitChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        bool newValue = (bool)e.NewValue;
        if(newValue)
        {
            MyCustomControl c = d as MyCustomControl;
            if(c != null && c.glow != null)
            {
                c.Animate(c.glow);
            }
        }
    }

    private void Animate(UIElement glow)
    {
        DoubleAnimation animation = new DoubleAnimation();
        animation.To = 1;
        animation.Duration = Duration;
        glow.BeginAnimation(OpacityProperty, animation);
    }
}
</code>```

Template:

```<code><ControlTemplate x:Key="ct" TargetType="local:MyCustomControl">
    <Border x:Name="glow" Width="100" Height="100" Background="Red" Opacity="0.1">
    </Border>
</ControlTemplate>
</code>```

Usage:

```<code><local:MyCustomControl Template="{StaticResource ct}" Duration="0:0:5" IsLit="True" />
</code>```

Body:
I found a good explanation here on SO of how to bind the Duration property of a ColorAnimation to the Value property of a Slider. One uses a converter to convert the Double value from the slider to a Duration, and a Binding to have that set the Duration of the ColorAnimation. Here, abbreviated, is how that works:

<Window.Resources>
    <local:DoubleToDurationConverter x:Key="DoubleToDurationConverter" />
</Window.Resources>

<Slider x:Name="slider" />

<Button Content="Click me for an animation">
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <BeginStoryboard>
                <Storyboard>
                    <ColorAnimation To="Green"
                        Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
                        FillBehavior="Stop"
                        Duration="{Binding ElementName=slider,
                                           Path=Value,
                                           Mode=OneWay,
                                           Converter={StaticResource DoubleToDurationConverter}}" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Button.Triggers>
</Button>

I tried that and it worked fine for me. But what I want to do is bind the Duration to a dependency property called FadeTime I've added to my custom control. So, in that control's ControlTemplate I have this:

<ControlTemplate.Triggers>
    <Trigger Property="IsLit" Value="true">
        <Trigger.EnterActions>
            <BeginStoryboard>
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetName="glow"
                                     Storyboard.TargetProperty="Opacity"
                                     To="1"
                                     Duration="{Binding FadeTime, Mode=OneWay,
                                                RelativeSource={RelativeSource TemplatedParent}}"/>
                </Storyboard>
            </BeginStoryboard>
        </Trigger.EnterActions>
    </Trigger>
</ControlTemplate.Triggers>

This compiles, but gives me an error message at run-time:

InvalidOperationException: Cannot freeze this Storyboard timeline tree
  for use across threads.

How can I bind my DoubleAnimation's Duration to a dependency variable in a custom control's ControlTemplate?

Thanks!

UPDATE

Data-binding is actually gross overkill for what I want to do. Real data-binding would allow for the property's value to change at run-time. All I really want is a way for the developer who is using my custom control to be able to set the Duration of the DoubleAnimation at design time, without having to edit the ControlTemplate. It's okay if the value the developer chooses never changes at run time.

Body:
Instead of defining the animation in your XAML markup, you could define it programmatically in the PropertyChangedCallback for the IsLit property.

You could simply define another property that lets the consumer of the control specify the duration of the animation.

Here is an example for you.

Control:

public class MyCustomControl : Control
{
    private UIElement glow;

    public static readonly DependencyProperty DurationProperty =
         DependencyProperty.Register("Duration", typeof(TimeSpan),
         typeof(MyCustomControl), new PropertyMetadata(TimeSpan.FromSeconds(1)));

    public TimeSpan Duration
    {
        get { return (TimeSpan)GetValue(DurationProperty); }
        set { SetValue(DurationProperty, value); }
    }

    public static readonly DependencyProperty IsLitProperty =
         DependencyProperty.Register("IsLit", typeof(bool),
         typeof(MyCustomControl), new PropertyMetadata(false, new PropertyChangedCallback(OnIsLitChanged)));

    public bool IsLit
    {
        get { return (bool)GetValue(IsLitProperty); }
        set { SetValue(IsLitProperty, value); }
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        glow = Template.FindName("glow", this) as UIElement;
        if (glow != null && IsLit)
            Animate(glow);

    }

    private static void OnIsLitChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        bool newValue = (bool)e.NewValue;
        if(newValue)
        {
            MyCustomControl c = d as MyCustomControl;
            if(c != null && c.glow != null)
            {
                c.Animate(c.glow);
            }
        }
    }

    private void Animate(UIElement glow)
    {
        DoubleAnimation animation = new DoubleAnimation();
        animation.To = 1;
        animation.Duration = Duration;
        glow.BeginAnimation(OpacityProperty, animation);
    }
}

Template:

<ControlTemplate x:Key="ct" TargetType="local:MyCustomControl">
    <Border x:Name="glow" Width="100" Height="100" Background="Red" Opacity="0.1">
    </Border>
</ControlTemplate>

Usage:

<local:MyCustomControl Template="{StaticResource ct}" Duration="0:0:5" IsLit="True" />


问:
How expensive is to copy an std::function?
While std::function is movable, in some cases it's not possible or not convenient. Is there a significant penalty for copying it?

Does it possibly depend on the size of the captured variables (if it was created using a lambda expression)? Is it implementation dependent?

答:
It is indeed implementation-dependent.  It also depends on what exactly you are storing in the std::function.  It is surely not as cheap as simply copying a C-style function pointer.

The best thing would be for you to try writing the code the way you find clear and convenient, then, if it does not run quickly enough, profile it.  If you need ultimate performance, you may find std::function is not suitable at all.


问:
Sorting in SQL Server
I am trying to sort a week column with the datatype varchar because the weeks are in this format 2017_6, 2017_7. As we all know SQL sorts varchar numbers like 2017_1, 2017_10, 2017_11 etc.

How can I get it to sort numerically, without changing the weeks format? I tried nvarchar but that didn't work.

答:
you can also sort by this field length. e.g:</p>

```<code>SELECT ........ order by len(myfield),myfield
</code>```

Title: Sorting in SQL Server

Body:
you can also sort by this field length. e.g:

SELECT ........ order by len(myfield),myfield


问:
How to call a function whenever global variable changes it value?
How can I call a function change_label whenever global variable a changes its value?  With change_variable I am trying to simulate actual changing of the variable (the variable changes on button click).

```<code>from tkinter import *

a = 3

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.button = Button(self.master, text='Change Variable', command=self.change_variable)
        self.button.grid(row=0)
        self.label = Label(self.master, text='Test')
        self.label.grid(row=1)

    def change_label(self):
        self.label.config(bg='Red', fg='Yellow')

    def change_variable(self):
        global a
        a = 1

def main():
    root = Tk()
    Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()
</code>```

答:
If you are using Tk, this might be worth looking into: Tk's "Variable" classes

If that doesn't work for you (because you want to store your own type, or something like that), Shiva's comment is the way to go, and if you want to store multiple variables, this might be a good idea:

```<code>class Storage(dict):
    def __getattribute__(self, name):
        return self[name]

    def __setattr__(self, name, value):
        print(name, value)  # react to the change of name
        self[name] = value

storage = Storage({a: 3, b: 2})

storage.a = 4
print(storage.a)
</code>```

If you don't want to be able to set the variable without triggering some code you put there, good luck. You can override __setitem__ too, but you can always call dict.__setitem__ with the Storage variable as the first argument.

Body:
How can I call a function change_label whenever global variable a changes its value?  With change_variable I am trying to simulate actual changing of the variable (the variable changes on button click).

from tkinter import *

a = 3

class Application(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.master = master
        self.button = Button(self.master, text='Change Variable', command=self.change_variable)
        self.button.grid(row=0)
        self.label = Label(self.master, text='Test')
        self.label.grid(row=1)

    def change_label(self):
        self.label.config(bg='Red', fg='Yellow')

    def change_variable(self):
        global a
        a = 1

def main():
    root = Tk()
    Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Body:
If you are using Tk, this might be worth looking into: Tk's "Variable" classes

If that doesn't work for you (because you want to store your own type, or something like that), Shiva's comment is the way to go, and if you want to store multiple variables, this might be a good idea:

class Storage(dict):
    def __getattribute__(self, name):
        return self[name]

    def __setattr__(self, name, value):
        print(name, value)  # react to the change of name
        self[name] = value

storage = Storage({a: 3, b: 2})

storage.a = 4
print(storage.a)

If you don't want to be able to set the variable without triggering some code you put there, good luck. You can override __setitem__ too, but you can always call dict.__setitem__ with the Storage variable as the first argument.


问:
Wordpress/PHP: Shorten title if title characters are more than 8 characters
I am trying to learn how to shorten a title only if it is over 8 characters long. If it is longer than 8 characters, then echo the first 8 characters and put an ellipse after it.

Here is how I am getting the title:

<?php echo $post->post_title ?>

Any help would be greatly appreciated. This will be a great learning lesson for me so I can replicate this in the future, so again any help would be amazing.

答: You should do this in plugin because if you change the theme the changes will be lost</p>


问:
Simple one dimension array of float with numpy
I want to make a simple one-dimensional array with numpy.

```<code>import numpy as np
arr = np.array()  # how do I initialize a float array?

np.append(arr, "3453.2")
np.append(arr, "1321.3")
np.append(arr, "2003.6")
</code>```

I have tried np.zeros(), np.ones(), np.empty() and so on. But I can't find out how to initialize an empty array.

答:
You shouldn't use empty arrays and append to them because each numpy.append is an O(n) operation making the array creation have O(n**2) performance.

Pythons list would be better because they have (amortized) O(1) appends.

However if you really want an empty array, you could just use an empty list as input for np.array:

```<code>import numpy as np

arr = np.array([], dtype=float)   # dtype specifies the type of the elements
</code>```

In case you meant an empty array to be an array having the correct size but not yet the correct values you should use np.empty:

```<code>arr = np.empty(shape=3, dtype=float)  # 3 element array
arr[0] = 3453.2
arr[1] = 1321.3
arr[2] = 2003.6
</code>```

Body:
I want to make a simple one-dimensional array with numpy.

import numpy as np
arr = np.array()  # how do I initialize a float array?

np.append(arr, "3453.2")
np.append(arr, "1321.3")
np.append(arr, "2003.6")

I have tried np.zeros(), np.ones(), np.empty() and so on. But I can't find out how to initialize an empty array.

Body:
You shouldn't use empty arrays and append to them because each numpy.append is an O(n) operation making the array creation have O(n**2) performance.

Pythons list would be better because they have (amortized) O(1) appends.

However if you really want an empty array, you could just use an empty list as input for np.array:

import numpy as np

arr = np.array([], dtype=float)   # dtype specifies the type of the elements

In case you meant an empty array to be an array having the correct size but not yet the correct values you should use np.empty:

arr = np.empty(shape=3, dtype=float)  # 3 element array
arr[0] = 3453.2
arr[1] = 1321.3
arr[2] = 2003.6


问:
Issues in posting ejs form data to controller

i have gone through "http://tanmaysarkar.com/html-form-with-ejs-template-in-nodejs/" this post but i have written my logic in controller

i am using mean stack with ejs template engine , i want to post ejs form data to ctroller which is under controller folder i dont how to post it to controller please help the following is ejs template, login.ejs is under views folder

```<code><%- include('partials/header') %>
    <div class="form-container">
        <h2>Login</h2>
        <% if(locals.error) { %>
            <div class="alert alert-danger"><%= error %></div>
        <% } %>
        <% if(locals.success) { %>
            <div class="alert alert-success"><%= success %></div>
        <% } %>
        <form method="post" action="">
            <div class="form-group">
                <label for="username">Username</label>
                <input type="text" name="username" id="username" value="<%= locals.username || '' %>" class="form-control" />
            </div>
            <div class="form-group">
                <label for="password">Password</label>
                <input type="password" name="password" id="password" class="form-control" />
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">Login</button>
                <a href="/register" class="btn btn-link">Register</a>
            </div>
        </form>
    </div>
    <%- include('partials/footer') %>
</code>```

on post of this following controller should get called

In controllers/login.controller.js i have written following post req

```<code>router.post('/', function (req, res) {
    // authenticate using api to maintain clean separation between layers
    request.post({
        url: config.apiUrl + '/users/authenticate',
        form: req.body,
        json: true
    }, function (error, response, body) {
        if (error) {
            return res.render('login', { error: 'An error occurred' });
        }

        if (!body.token) {
          //console.log("inside if loop " + body.token + "::" + req.body.username + "::" + body)
            return res.render('login', { error: body, username: req.body.username });
        }

        // save JWT token in the session to make it available to the angular app
        req.session.token = body.token;

        // redirect to returnUrl

        var returnUrl = req.query.returnUrl && decodeURIComponent(req.query.returnUrl) || '/';
        console.log("return url" + returnUrl);
        res.redirect(returnUrl);
        //res.render('register')

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

答:
i just had to add

```<code>    var ejs = require('ejs');
var login = require(__dirname + '/views/login.ejs');//for ejs
var logincontroller = require(__dirname + '/controllers/login.controller.js');//for ejs
</code>```

above three lines in "server.js" which is entry point of my application and when i am actually posting the data mapping was needed like

```<code>app.use('/controllers/login.controller.js', logincontroller);//for ejs
</code>```

and in my ejs file

```<code><form method="post" action="/controllers/login.controller.js">
</code>```

was required

Body:
i have gone through "http://tanmaysarkar.com/html-form-with-ejs-template-in-nodejs/" this post but i have written my logic in controller

i am using mean stack with ejs template engine , i want to post ejs form data to ctroller which is under controller folder i dont how to post it to controller please help the following is ejs template, login.ejs is under views folder

<%- include('partials/header') %>

Login

        <% if(locals.error) { %>

<%= error %>

        <% } %>
        <% if(locals.success) { %>

<%= success %>

        <% } %>
        <form method="post" action="">

                Username
                <input type="text" name="username" id="username" value="<%= locals.username || '' %>" class="form-control" />

                Password
                <input type="password" name="password" id="password" class="form-control" />

                <button type="submit" class="btn btn-primary">Login</button>
                Register

        </form>

    <%- include('partials/footer') %>

on post of this following controller should get called

In controllers/login.controller.js i have written following post req

router.post('/', function (req, res) {
    // authenticate using api to maintain clean separation between layers
    request.post({
        url: config.apiUrl + '/users/authenticate',
        form: req.body,
        json: true
    }, function (error, response, body) {
        if (error) {
            return res.render('login', { error: 'An error occurred' });
        }

        if (!body.token) {
          //console.log("inside if loop " + body.token + "::" + req.body.username + "::" + body)
            return res.render('login', { error: body, username: req.body.username });
        }

        // save JWT token in the session to make it available to the angular app
        req.session.token = body.token;

        // redirect to returnUrl

        var returnUrl = req.query.returnUrl && decodeURIComponent(req.query.returnUrl) || '/';
        console.log("return url" + returnUrl);
        res.redirect(returnUrl);
        //res.render('register')

    });
});

Body:
i just had to add

    var ejs = require('ejs');
var login = require(__dirname + '/views/login.ejs');//for ejs
var logincontroller = require(__dirname + '/controllers/login.controller.js');//for ejs

above three lines in "server.js" which is entry point of my application and when i am actually posting the data mapping was needed like

app.use('/controllers/login.controller.js', logincontroller);//for ejs

and in my ejs file

<form method="post" action="/controllers/login.controller.js">

was required


问:
Containers and divs in CSS
Good day,
I'm not new to CSS or DIVs but have been out of touch for long enough. Trying to work out with Containers and nested DIVs but not getting much success in doing what I'm trying to do. Have already searched enough on SO and Goog but, hopefully you can help me.

Here's the representation of what I wish to achieve.

Screenshot of the layout

And here is what I have done so far ..

.dealsglobal {
    width: 45%;
    display: inline-block;
    float: left;
    margin-right:20px;
    height: auto;
    overflow: auto;
}

.dealsglobal h2 {
    margin-left: 10px;
}

.dealsindia {
    width: 45%;
    height: auto;
    overflow: auto;
}

.dealsindia h2 {
    margin-left: 10px;
}

.dealsleft {
    margin: 0px 25px 10px 0px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    float: left;
    display: inline-block;
    overflow: auto;
}

.dealsleft img {
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

.dealsright {
    margin-bottom: 10px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    display: inline-block;
    overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dealsglobal">
<h2>Global Coupons</h2>
    <div class="dealsleft">
 <img src="thumb-heavengifts.jpg" alt="HeavenGifts.com Web Store" align="middle" />
    </div>
    <div class="dealsright">
    Test
    </div>
</div>

<div class="dealsindia">
<h2>Indian Coupons</h2>
    <div class="dealsleft">
    Test
    </div>
    <div class="dealsright">
 Test
    </div>
</div></code>```

The image just wont center, no matter what I do. I believe, somewhere I have set the property to align left or something. Can anyone please point me to the correct direction? Thanks for your help!

答:
I changed your code a little bit, but you'll get idea :

Here is html :

```<code><div class="container">
  <div class="left">
    <h2 class="inner-text">title</h2>
    <div class="image">
      <img src="http://via.placeholder.com/350x150" />
    </div>
    <h5 class="inner-text">description</h5>
  </div>

  <div class="right">
    <h2 class="inner-text">title</h2>
    <div class="image">
      <img src="http://via.placeholder.com/350x150" />
    </div>
    <h5 class="inner-text">description</h5>
  </div>
  <div style="clear: both" />
</div>
</code>```

And here is the css:

```<code>.container{
  width: 98%;
  border: 2px solid #f00;
  padding: 10px;
}

.left {
    width: 47%;
    float: left;
    margin: 0 1% 0 1%;
    border: 1px solid green;
}

.right {
    width: 47%;
    float: left;
    margin: 0 1% 0 1%;
    border: 1px solid green;
}

.inner-text{
  text-align:center;
}

.image{
  padding: 20px;
}

.image img{
  max-width: 100%;
}
</code>```

Check here jsfiddle.

Title: Containers and divs in CSS

Body:
Good day,
I'm not new to CSS or DIVs but have been out of touch for long enough. Trying to work out with Containers and nested DIVs but not getting much success in doing what I'm trying to do. Have already searched enough on SO and Goog but, hopefully you can help me.

Here's the representation of what I wish to achieve.

Screenshot of the layout

And here is what I have done so far ..

.dealsglobal {
    width: 45%;
    display: inline-block;
    float: left;
    margin-right:20px;
    height: auto;
    overflow: auto;
}

.dealsglobal h2 {
    margin-left: 10px;
}

.dealsindia {
    width: 45%;
    height: auto;
    overflow: auto;
}

.dealsindia h2 {
    margin-left: 10px;
}

.dealsleft {
    margin: 0px 25px 10px 0px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    float: left;
    display: inline-block;
    overflow: auto;
}

.dealsleft img {
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    margin-left: auto;
    margin-right: auto;
    width: 100px;
}

.dealsright {
    margin-bottom: 10px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    display: inline-block;
    overflow: auto;
}

Global Coupons

    Test

Indian Coupons

    Test

 Test

The image just wont center, no matter what I do. I believe, somewhere I have set the property to align left or something. Can anyone please point me to the correct direction? Thanks for your help!

Body:
I changed your code a little bit, but you'll get idea :

Here is html :

<div class="container">
  <div class="left">
    <h2 class="inner-text">title</h2>
    <div class="image">
      <img src="http://via.placeholder.com/350x150" />
    </div>
    <h5 class="inner-text">description</h5>
  </div>

  <div class="right">
    <h2 class="inner-text">title</h2>
    <div class="image">
      <img src="http://via.placeholder.com/350x150" />
    </div>
    <h5 class="inner-text">description</h5>
  </div>
  <div style="clear: both" />
</div>

And here is the css:

.container{
  width: 98%;
  border: 2px solid #f00;
  padding: 10px;
}

.left {
    width: 47%;
    float: left;
    margin: 0 1% 0 1%;
    border: 1px solid green;
}

.right {
    width: 47%;
    float: left;
    margin: 0 1% 0 1%;
    border: 1px solid green;
}

.inner-text{
  text-align:center;
}

.image{
  padding: 20px;
}

.image img{
  max-width: 100%;
}

Check here jsfiddle.


问:
Saferpay Implementation
I am implementing Saferpay gateway. But the problem is whenever I am sending USD 5.25 as the amount it is saying : attribute AMOUNT is not numeric.
I am very confused because of that, can any one help me regarding this ?

Thank You

答:
You'll probably have to convert this amount to cents:

5.25 * 100 = 525.

That's the case with most of the payment gateways...

Title: Saferpay Implementation


答:
You can center elements inside a div by using text-align:center; for all the text elements like: h1, p, h2, a etc. To center an img or a div inside another div you can use margin: 0 auto; the auto is the important part for centering the left and right margins.

More info here

i've updated your code snippet.

.dealsglobal {
    width: 45%;
    display: inline-block;
    float: left;
    margin-right:20px;
    height: auto;
    overflow: auto;
}

.dealsglobal h2 {
    margin-left: 10px;
}

.dealsindia {
    width: 45%;
    height: auto;
    overflow: auto;
}

.dealsindia h2 {
    margin-left: 10px;
}

.dealsleft {
    margin: 0px 25px 10px 0px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    float: left;
    display: inline-block;
    overflow: auto;
    text-align: center;
}

.dealsleft img {
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    margin: 5px auto;
    width: 100px;
}

.dealsright {
    margin-bottom: 10px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    display: inline-block;
    overflow: auto;
    text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="dealsglobal">
<h2>Global Coupons</h2>
    <div class="dealsleft">
 <img src="thumb-heavengifts.jpg" alt="HeavenGifts.com Web Store" align="middle" />
    </div>
    <div class="dealsright">
    Test
    </div>
</div>

<div class="dealsindia">
<h2>Indian Coupons</h2>
    <div class="dealsleft">
    Test
    </div>
    <div class="dealsright">
 Test
    </div>
</div></code>```

Title: Containers and divs in CSS

Body:
You can center elements inside a div by using text-align:center; for all the text elements like: h1, p, h2, a etc. To center an img or a div inside another div you can use margin: 0 auto; the auto is the important part for centering the left and right margins.

More info here

i've updated your code snippet.

.dealsglobal {
    width: 45%;
    display: inline-block;
    float: left;
    margin-right:20px;
    height: auto;
    overflow: auto;
}

.dealsglobal h2 {
    margin-left: 10px;
}

.dealsindia {
    width: 45%;
    height: auto;
    overflow: auto;
}

.dealsindia h2 {
    margin-left: 10px;
}

.dealsleft {
    margin: 0px 25px 10px 0px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    float: left;
    display: inline-block;
    overflow: auto;
    text-align: center;
}

.dealsleft img {
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 4px;
    margin: 5px auto;
    width: 100px;
}

.dealsright {
    margin-bottom: 10px;
    padding: 5px;
    border: 1px solid #ccc;
    height: auto;
    position: relative;
    width: 40%;
    display: inline-block;
    overflow: auto;
    text-align: center;
}

<div class="dealsglobal">
<h2>Global Coupons</h2>
    <div class="dealsleft">
 <img src="thumb-heavengifts.jpg" alt="HeavenGifts.com Web Store" align="middle" />
    </div>
    <div class="dealsright">
    Test
    </div>
</div>

<div class="dealsindia">
<h2>Indian Coupons</h2>
    <div class="dealsleft">
    Test
    </div>
    <div class="dealsright">
 Test
    </div>
</div>


问:
I have a selection box with 5 option values. I want to repeat a table row based on the value I select from it
This is my select box code:

```<code><select class="form-control">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>
</code>```

This is the table row I want to repeat:

```<code><tr>
    <td><input type="text" class="form-control" name="" placeholder="Name"></td>
    <td><input type="text" class="form-control" name="" placeholder="Email"></td>
    <td><input type="text" class="form-control" name="" placeholder="Mobile No."></td>
</tr>
</code>```

答:
I think this code helps you to solve your problem.
https://jsfiddle.net/karanmehta786/orecu2ky/

Change that section of for loop

```<code> for (var i = 0; i < value; i++) {
$('#table').append($('#table').find('tr:nth-child(1)').clone())}
</code>```

Body:
This is my select box code:

<select class="form-control">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
</select>

This is the table row I want to repeat:

    <input type="text" class="form-control" name="" placeholder="Name">
    <input type="text" class="form-control" name="" placeholder="Email">
    <input type="text" class="form-control" name="" placeholder="Mobile No.">

Body:
I think this code helps you to solve your problem.
https://jsfiddle.net/karanmehta786/orecu2ky/

Change that section of for loop

 for (var i = 0; i < value; i++) {
$('#table').append($('#table').find('tr:nth-child(1)').clone())}


问:
Python numpy matrix multiplication with one diagonal matrix
I have two arrays A (4000,4000) of which only the diagonal is filled with data, and B (4000,5), filled with data. Is there a way to multiply (dot) these arrays that is faster than the numpy.dot(a,b) function?

So far I found that (A * B.T).T should be faster (where A is one dimensional (4000,), filled with the diagonal elements), but it turned out to be roughly twice as slow.

is there a faster way to calculate B.dot(A) in the case where A is a diagnal array?

答:
Appears that my initial claim of (A * B.T).T being slower is incorrect.

```<code>from timeit import default_timer as timer
import numpy as np

##### Case 1
a = np.zeros((4000,4000))
np.fill_diagonal(a, 10)
b = np.ones((4000,5))

dot_list = []

def time_dot(a,b):
    start = timer()
    c = np.dot(a,b)
    end = timer()
    return end - start

for i in range(100):
    dot_list.append(time_dot(a,b))

print np.mean(np.asarray(dot_list))

##### Case 2
a = np.ones((4000,))
a = a * 10
b = np.ones((4000,5))

shortcut_list = []

def time_quicker(a,b):
    start = timer()
    c = (a*b.T).T
    end = timer()
    return end - start

for i in range(100):
    shortcut_list.append(time_quicker(a,b))

print np.mean(np.asarray(shortcut_list))

##### Case 3
a = np.zeros((4000,4000)) #diagonal matrix
np.fill_diagonal(a, 10)
b = np.ones((4000,5))

case3_list = []

def function(a,b):
    start = timer()
    np.multiply(b.T,np.diag(a))
    end = timer()
    return end - start

for i in range(100):
    case3_list.append(function(a,b))

print np.mean(np.asarray(case3_list))
</code>```

results in :

0.119120892431

0.00010633951868

0.00214490709662

so the second method is fastest

Body:
Appears that my initial claim of (A * B.T).T being slower is incorrect.

from timeit import default_timer as timer
import numpy as np

##### Case 1
a = np.zeros((4000,4000))
np.fill_diagonal(a, 10)
b = np.ones((4000,5))

dot_list = []

def time_dot(a,b):
    start = timer()
    c = np.dot(a,b)
    end = timer()
    return end - start

for i in range(100):
    dot_list.append(time_dot(a,b))

print np.mean(np.asarray(dot_list))

##### Case 2
a = np.ones((4000,))
a = a * 10
b = np.ones((4000,5))

shortcut_list = []

def time_quicker(a,b):
    start = timer()
    c = (a*b.T).T
    end = timer()
    return end - start

for i in range(100):
    shortcut_list.append(time_quicker(a,b))

print np.mean(np.asarray(shortcut_list))

##### Case 3
a = np.zeros((4000,4000)) #diagonal matrix
np.fill_diagonal(a, 10)
b = np.ones((4000,5))

case3_list = []

def function(a,b):
    start = timer()
    np.multiply(b.T,np.diag(a))
    end = timer()
    return end - start

for i in range(100):
    case3_list.append(function(a,b))

print np.mean(np.asarray(case3_list))

results in :

0.119120892431

0.00010633951868

0.00214490709662

so the second method is fastest


问:
Vertx client gets clientabort exception
I am geting clientabort sockettimeout read exception at server side while invoking a rest service through https client inside vertx application. If i invoke a http setvice, it works fine though.

I get 200 ok in vertx and do not get any data back. And also i get connection was closed error in vertx.

Any idea why it happens. Help appreciated.

Code:

```<code>final HttpClient httpClient1 = vertx.createHttpClient(
    new HttpClientOptions()
    .setDefaultHost("localhost")
    .setDefaultPort(8443)
    .setSsl(true)
    .setKeepAlive(true)
    .setMaxPoolSize(100)
    .setTrustAll(true)
    );
HttpClientRequest req = httpClient1.request(HttpMethod.POST, "/api/test/");
req.headers()
    .set("Content-Length","10000000")
    .set("Content-Type","application/json")
    .set("Cache-Control", "no-transform, max-age=0");
Buffer body=Buffer.buffer("Hello World");
req.write(body);
</code>```

答:
That's not the way to send a request.

Hope working example may help you.

Server:

```<code>    final Vertx vertx = Vertx.vertx();

    vertx.createHttpServer().requestHandler((c) -> {

        c.bodyHandler(b -> {
            System.out.println(b.toString());
        });
        c.response().end("ok");
    }).listen(8443);
</code>```

Client:

```<code>    final HttpClient client = vertx.createHttpClient(
            new HttpClientOptions()
                    .setDefaultHost("localhost")
                    .setDefaultPort(8443));

    client.request(HttpMethod.POST, "/", (r) -> {
        System.out.println("Got response");
    }).putHeader("Content-Length", Integer.toString("Hello".length()))
             .write("Hello").end();
</code>```

Two important notes: you must end .request() with .end() and you must set Content-Length correctly.

Title: Vertx client gets clientabort exception

Body:
I am geting clientabort sockettimeout read exception at server side while invoking a rest service through https client inside vertx application. If i invoke a http setvice, it works fine though.

I get 200 ok in vertx and do not get any data back. And also i get connection was closed error in vertx.

Any idea why it happens. Help appreciated.

Code:

final HttpClient httpClient1 = vertx.createHttpClient(
    new HttpClientOptions()
    .setDefaultHost("localhost")
    .setDefaultPort(8443)
    .setSsl(true)
    .setKeepAlive(true)
    .setMaxPoolSize(100)
    .setTrustAll(true)
    );
HttpClientRequest req = httpClient1.request(HttpMethod.POST, "/api/test/");
req.headers()
    .set("Content-Length","10000000")
    .set("Content-Type","application/json")
    .set("Cache-Control", "no-transform, max-age=0");
Buffer body=Buffer.buffer("Hello World");
req.write(body);

Body:
That's not the way to send a request.

Hope working example may help you.

Server:

    final Vertx vertx = Vertx.vertx();

    vertx.createHttpServer().requestHandler((c) -> {

        c.bodyHandler(b -> {
            System.out.println(b.toString());
        });
        c.response().end("ok");
    }).listen(8443);

Client:

    final HttpClient client = vertx.createHttpClient(
            new HttpClientOptions()
                    .setDefaultHost("localhost")
                    .setDefaultPort(8443));

    client.request(HttpMethod.POST, "/", (r) -> {
        System.out.println("Got response");
    }).putHeader("Content-Length", Integer.toString("Hello".length()))
             .write("Hello").end();

Two important notes: you must end .request() with .end() and you must set Content-Length correctly.


问:
Handling Local vs Remote Database TimeZone Differences in Tests
I have unit test in Java that writes a constant Timestamp to a row in my local test database, reads it back and compares it to what I expected. This works fine on my local laptop which is under the GMT timezone.

When I commit the code to our continuous integration server, the test fails with the different in time being -5 hours. This is no surprise since our integration server is hosted on AWS on the East Coast of US. However, it is causing a problem...

Short of changing my local MySQL server to have the same timezone as the remote server (and having all the developers in my team do so also), can anyone show me how to fix this issue in code without getting too hacky?

```<code>//Fetch actual table contents
IDataSet databaseDataSet = databaseTester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("batch");

// Load expected data from an XML dataset
IDataSet expectedDataSet = new XmlDataSet(getClass().getResourceAsStream("/dbunit/expected_insert_batch.xml"));
ITable expectedTable = expectedDataSet.getTable("batch");

// Assert actual database table match expected table
Assertion.assertEquals(expectedTable, actualTable);
</code>```

Thanks,

答: You can set a timezone for the MySQL server separate from the OS timezone, or even for individual DB sessions. The former is IMO preferable, as is using UTC everywhere except for the UI and when importing data.</p>

Body:
I have unit test in Java that writes a constant Timestamp to a row in my local test database, reads it back and compares it to what I expected. This works fine on my local laptop which is under the GMT timezone.

When I commit the code to our continuous integration server, the test fails with the different in time being -5 hours. This is no surprise since our integration server is hosted on AWS on the East Coast of US. However, it is causing a problem...

Short of changing my local MySQL server to have the same timezone as the remote server (and having all the developers in my team do so also), can anyone show me how to fix this issue in code without getting too hacky?

//Fetch actual table contents
IDataSet databaseDataSet = databaseTester.getConnection().createDataSet();
ITable actualTable = databaseDataSet.getTable("batch");

// Load expected data from an XML dataset
IDataSet expectedDataSet = new XmlDataSet(getClass().getResourceAsStream("/dbunit/expected_insert_batch.xml"));
ITable expectedTable = expectedDataSet.getTable("batch");

// Assert actual database table match expected table
Assertion.assertEquals(expectedTable, actualTable);

Thanks,


问:
Delete file with same name contained in different sub-folders
For some reason, I have a copy of dismhost.exe in a lot of folders, inside temp folder; what I want to do is delete every instance of it, which are inside folders inside temp.

So the structure is as follows:

```<code>/temp
 /folder1
  dismhost.exe
 /folder2
  dismhost.exe
 /folder3
  dismhost.exe
 ...
</code>```

I first tried

```<code>rm ./*/dismhost.exe
</code>```

but then I remembered there is no rm in windows, so I tried with rd with same arguments. That raised an error, saying that the * modifier is not valid.

How can I achieve this?

答:
Or use recursive delete.:</p>

```<code>del /s \temp\dismhost.exe
</code>```

Body:
For some reason, I have a copy of dismhost.exe in a lot of folders, inside temp folder; what I want to do is delete every instance of it, which are inside folders inside temp.

So the structure is as follows:

/temp
 /folder1
  dismhost.exe
 /folder2
  dismhost.exe
 /folder3
  dismhost.exe
 ...

I first tried

rm ./*/dismhost.exe

but then I remembered there is no rm in windows, so I tried with rd with same arguments. That raised an error, saying that the * modifier is not valid.

How can I achieve this?

Body:
Or use recursive delete.:

del /s \temp\dismhost.exe


问:
Basic CSS opacity
I'm using SaaS for building my own webshop. The problem is that i dont know any code. I wish to make my menu bar look more stylish. The SaaS platform offers CSS editing but i can't change the html.
The current menu bar has this css;

```<code>#menu {
  padding: 5px 0 5px 0;
  background: #005775;
  margin: 0 0 8px 0;
}
</code>```

How can I make this better looking. I tried changing the opacity, but every time i add the word opacity the code breaks and the memu disappears.

My current Design looks like this;
http://imgur.com/a/ptSuA
I would really like to make the Menu bar a bit less rough and make it look more friendly.

Sorry for my horrible grammar and lack of knowledge.

答:
Try this. As said by others, this will reduce the opacity of the text in the menu too. </p>

```<code>#menu {
  padding: 5px 0 5px 0;
  background: #005775;
  margin: 0 0 8px 0;
  opacity: 0.5; // Change this value between 0(transparent) -> 1(100% visible);
}
</code>```

Title: Basic CSS opacity

Body:
I'm using SaaS for building my own webshop. The problem is that i dont know any code. I wish to make my menu bar look more stylish. The SaaS platform offers CSS editing but i can't change the html.
The current menu bar has this css;

#menu {
  padding: 5px 0 5px 0;
  background: #005775;
  margin: 0 0 8px 0;
}

How can I make this better looking. I tried changing the opacity, but every time i add the word opacity the code breaks and the memu disappears.

My current Design looks like this;
http://imgur.com/a/ptSuA
I would really like to make the Menu bar a bit less rough and make it look more friendly.

Sorry for my horrible grammar and lack of knowledge.

Body:
Try this. As said by others, this will reduce the opacity of the text in the menu too.

#menu {
  padding: 5px 0 5px 0;
  background: #005775;
  margin: 0 0 8px 0;
  opacity: 0.5; // Change this value between 0(transparent) -> 1(100% visible);
}


问:
Oracle : Materialized View vs Stored Procedure in terms of huge data at referesh time
My Materialized view underlying table is having 6M of records and its going for COMPLETE refresh each time. The MVIEW underlying query is having 18 table join(all table in the same schema). Its blocking the PGA memory each time when refresh happening and I am getting warning. So my question is below.

1) Shall I change the Materialized view to a stored procedure? Stored procedure will have the cursor with having same query as Mview and it will load the data to a new table by using BULK COLLECT and LIMIT 1000 rows at a time. We will write an Autosys job(daily once at non business hour) to call the procedure.

Below is my changed PROC:

```<code>CREATE OR REPLACE PROCEDURE proc_reporting IS

CURSOR cur_rows IS
(Old MVIEW query)

TYPE reporting_type IS TABLE OF reporting_test%ROWTYPE INDEX BY PLS_INTEGER;
l_reporting_type reporting_type;

BEGIN

EXECUTE IMMEDIATE 'TRUNCATE TABLE reporting_test';

OPEN cur_rows;
LOOP
   FETCH cur_rows BULK COLLECT INTO l_reporting_type LIMIT 1000;
   EXIT WHEN l_reporting_type.count = 0;

          BEGIN
            FORALL i IN l_reporting_type.FIRST .. l_reporting_type.LAST SAVE EXCEPTIONS
            INSERT INTO reporting_test VALUES (l_reporting_type(i).column_1 .. l_reporting_type(i).column_n);

          EXCEPTION
            WHEN ex_dml_errors THEN
              l_error_count := SQL%BULK_EXCEPTIONS.count;
              DBMS_OUTPUT.put_line('Number of failures: ' || l_error_count);
              FOR i IN 1 .. l_error_count
              LOOP
                DBMS_OUTPUT.put_line('Error: ' || i ||
                  ' Array Index: ' || SQL%BULK_EXCEPTIONS(i).error_index ||
                  ' Message: ' || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
              END LOOP;
            END;

END LOOP;
CLOSE cur_rows;
END;
</code>```

答: I agree that your first approach should be to examine the MView SQL for tuning.  If you have license for AWR, you can run it through the SQL Tuning Advisor.  Also please specify the PGA error, it may be that your DBA needs to increase pga_aggregate_target and/or pga_aggregate_limit.  In many cases, increasing the PGA and/or SGA provides a significant performance improvement, but I always try SQL tuning first.</p>

Body:
My Materialized view underlying table is having 6M of records and its going for COMPLETE refresh each time. The MVIEW underlying query is having 18 table join(all table in the same schema). Its blocking the PGA memory each time when refresh happening and I am getting warning. So my question is below.

1) Shall I change the Materialized view to a stored procedure? Stored procedure will have the cursor with having same query as Mview and it will load the data to a new table by using BULK COLLECT and LIMIT 1000 rows at a time. We will write an Autosys job(daily once at non business hour) to call the procedure.

Below is my changed PROC:

CREATE OR REPLACE PROCEDURE proc_reporting IS

CURSOR cur_rows IS
(Old MVIEW query)

TYPE reporting_type IS TABLE OF reporting_test%ROWTYPE INDEX BY PLS_INTEGER;
l_reporting_type reporting_type;

BEGIN

EXECUTE IMMEDIATE 'TRUNCATE TABLE reporting_test';

OPEN cur_rows;
LOOP
   FETCH cur_rows BULK COLLECT INTO l_reporting_type LIMIT 1000;
   EXIT WHEN l_reporting_type.count = 0;

          BEGIN
            FORALL i IN l_reporting_type.FIRST .. l_reporting_type.LAST SAVE EXCEPTIONS
            INSERT INTO reporting_test VALUES (l_reporting_type(i).column_1 .. l_reporting_type(i).column_n);

          EXCEPTION
            WHEN ex_dml_errors THEN
              l_error_count := SQL%BULK_EXCEPTIONS.count;
              DBMS_OUTPUT.put_line('Number of failures: ' || l_error_count);
              FOR i IN 1 .. l_error_count
              LOOP
                DBMS_OUTPUT.put_line('Error: ' || i ||
                  ' Array Index: ' || SQL%BULK_EXCEPTIONS(i).error_index ||
                  ' Message: ' || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
              END LOOP;
            END;

END LOOP;
CLOSE cur_rows;
END;


问:
What is use of underScore in Double value in swift?
I just recently look into Apple documentation I found code like below

```<code>extension Double {
    var km: Double { return self * 1_000.0 }
    var m: Double { return self }
    var cm: Double { return self / 100.0 }
    var mm: Double { return self / 1_000.0 }
    var ft: Double { return self / 3.28084 }
}
</code>```

What is the use of "_" in double value? it's working without error why?

答:
Just a way to improve readability. According to Swift documentation:

Numeric literals can contain extra formatting to make them easier to
  read. Both integers and floats can be padded with extra zeros and can
  contain underscores to help with readability. Neither type of
  formatting affects the underlying value of the literal.

Body:
I just recently look into Apple documentation I found code like below

extension Double {
    var km: Double { return self * 1_000.0 }
    var m: Double { return self }
    var cm: Double { return self / 100.0 }
    var mm: Double { return self / 1_000.0 }
    var ft: Double { return self / 3.28084 }
}

What is the use of "_" in double value? it's working without error why?


问:
Can data between android devices be sent just using the phone operating company?
By using just the phone operating company I'm meaning a situation like this:

When you do a phone call, it looks like the only action that happens is "only" the phone call being received by the phone operating company and then it redirects the phone call to the called number so the communication can be stablished.

I think something similar should be possible with sent data, you just send the data with a format that indicates in a similar way that it's trying to connect with another phone, expect it to be received by the phone operating company and have it delivered to that phone.

I know technologies are far from being the same but I think that the comparison still applies.

From what I've read here it looks like it's not possible to do something like that, whatever the case you are going to need a server on the internet that deals with that be it directly or indirectly. Looks like my best option would be using something like PubNub, anyway it looks that it hasn't been explicitly determined that something like that cannot be done, also answers related to sending data between devices were a bit old, so just in case I'd like to know if that's possible.

Thanks for your time.

答:
Data sent between devices needs to use some transport and addressing mechanism and as I am sure you are aware the most common approach these days is to use the IP protocol.

This is a separate protocol stack than the traditional telephony protocol stack and it uses different addressing - the phone number which is uniquely mapped to your phone in the Android world is not a valid form of address in the IP world.

To allow you send data using the telephone number as the destination address you would need a mapping between telephone numbers and IP addresses. You would also need some way to indicate to the receiving device what application should receive the data - the same function the port number provides in the IP stack.

There is nothing to stop you building such a mapping, and, in fact, such mappings do exist in the Voice over IP world (VoIP) for example where a phone number will be translated to an IP address of a destination device.

However, these approaches still require a 'server' to do the mapping between address schemes which I think you are trying to avoid.

The closest thing in the traditional telephony world to what you outline might be SMS, which will send sets of text 'data' directly between SMS capable phones, but I don't think this is what you are looking for.


问:
Gulp error when trying to run in terminal (no syntax errors)
I`m running a tutorial from Lynda.com and i'm trying to run a gulpfile, the syntax is good but I can't understand the error from terminal.

Could anyone provide me help with this one?

Many thanks!

gulpfile.js

```<code>var themename = 'pistol4';

var gulp = require('gulp'),

autoprefixer = require('autoprefixer'),
browserSync = require('browser-sync').create(),
image = require(gulp - image),
jshint = require('gulp-jshint'),
postcss = require('gulp-postcss'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),

//Only work with new or updated files
newer = require('gulp-newer'),

//Name of working theme folder
root = '../' + themename + '/',
scss = root + 'sass/',
js = root + 'js/',
img = root + 'images/',
languages = root + 'languages';

// CSS via Sass and Autoprefixer
gulp.task('css', function () {
return gulp.src(scss + '(style.css,rtl.scss)')
.pipe(sourcemaps.init())
.pipe(sass({
    outputStyle: 'expanded',
    indentType: 'tab',
    indentWidth: '1'
}).on('error', sass.logError))
.pipe(postcss([
    autoprefixer('last 2 versions', '> 1%')
    ]))
.pipe(sourcemaps.write(scss + 'maps'))
.pipe(gulp.dest(root));
});

//Optimize images trough gulp-image
gulp.task('images', function() {
    return gulp.src(img + 'RAW/**/*.(jpg,JPG,png)')
    .pipe(newer(img))
    .pipe(image())
    .pipe(gulp.dest(img));
});

//Javascript

gulp.task('javascript', function() {
    return gulp.src([js + '*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(gulp.dest(js));
});

//Watch everything
gulp.task('watch', function() {
    browserSync.init({
        open: 'external',
        proxy: 'pistol.dev',
        port: '8080'
    });
    gulp.watch([root + '**/*.css', root + '**/*.scss'], ['css']);
    gulp.watch(js + '**/*.js', ['javascript']);
    gulp.watch(img + 'RAW/**/*.{jpg,JPG,png}', ['images']);
    gulp.watch(root + '**/*').on('change', browserSync.reload);
});

//Default task (runs at initiation: gulp --verbose)
gulp.task('default', ['watch']);
</code>```

error log from terminal:

```<code>assert.js:81
throw new assert.AssertionError({
^
AssertionError: missing path
at Module.require (module.js:495:3)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\xampp\htdocs\pistol01.06.17\wp-
content\themes\gulp-dev\gulpfile.js:7:10)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
</code>```

答:
This line: image = require(gulp - image), wont work just like @Juan said. Did you mean: image = require('gulp-image'),?

The next error:

"[BS] Couldn't open browser (if you are using BrowserSync in a
  headless environment, you might want to set the open option to false)
  "

Since I never worked with browser-sync, I can just guess and write stuff i found from googling it.

I have two suggestions:

Go into the 'watch' task and change: browserSync.init({open: 'external',
to:browserSync.init({open: 'false', in short just do what the error said to do.

You need to give browser-sync the exact file you open the browser with. f.e.:  '--browser "chrome.exe"'

Please let us know how you fixed it or if any of this helped.

Body:
I`m running a tutorial from Lynda.com and i'm trying to run a gulpfile, the syntax is good but I can't understand the error from terminal.

Could anyone provide me help with this one?

Many thanks!

gulpfile.js

var themename = 'pistol4';

var gulp = require('gulp'),

autoprefixer = require('autoprefixer'),
browserSync = require('browser-sync').create(),
image = require(gulp - image),
jshint = require('gulp-jshint'),
postcss = require('gulp-postcss'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),

//Only work with new or updated files
newer = require('gulp-newer'),

//Name of working theme folder
root = '../' + themename + '/',
scss = root + 'sass/',
js = root + 'js/',
img = root + 'images/',
languages = root + 'languages';

// CSS via Sass and Autoprefixer
gulp.task('css', function () {
return gulp.src(scss + '(style.css,rtl.scss)')
.pipe(sourcemaps.init())
.pipe(sass({
    outputStyle: 'expanded',
    indentType: 'tab',
    indentWidth: '1'
}).on('error', sass.logError))
.pipe(postcss([
    autoprefixer('last 2 versions', '> 1%')
    ]))
.pipe(sourcemaps.write(scss + 'maps'))
.pipe(gulp.dest(root));
});

//Optimize images trough gulp-image
gulp.task('images', function() {
    return gulp.src(img + 'RAW/**/*.(jpg,JPG,png)')
    .pipe(newer(img))
    .pipe(image())
    .pipe(gulp.dest(img));
});

//Javascript

gulp.task('javascript', function() {
    return gulp.src([js + '*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(gulp.dest(js));
});

//Watch everything
gulp.task('watch', function() {
    browserSync.init({
        open: 'external',
        proxy: 'pistol.dev',
        port: '8080'
    });
    gulp.watch([root + '**/*.css', root + '**/*.scss'], ['css']);
    gulp.watch(js + '**/*.js', ['javascript']);
    gulp.watch(img + 'RAW/**/*.{jpg,JPG,png}', ['images']);
    gulp.watch(root + '**/*').on('change', browserSync.reload);
});

//Default task (runs at initiation: gulp --verbose)
gulp.task('default', ['watch']);

error log from terminal:

assert.js:81
throw new assert.AssertionError({
^
AssertionError: missing path
at Module.require (module.js:495:3)
at require (internal/module.js:20:19)
at Object.<anonymous> (C:\xampp\htdocs\pistol01.06.17\wp-
content\themes\gulp-dev\gulpfile.js:7:10)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)


问:
Handling dynamically created control?
I'm writing simple web browser in c#. For multi tab functionality I added tabcontrol and placed webbrowser1 in it.  I use toolstripbutton to dynamically add tabpages , webbrowsers (and handle its events with webbrowser1 events):

```<code>        TabPage tabpage = new TabPage();
        tabControl1.Controls.Add(tabpage);
        WebBrowser webbrowser = new WebBrowser();
        webbrowser.Parent = tabpage;
        webbrowser.Dock = DockStyle.Fill;
        webbrowser.Navigate("www.google.com");
        webbrowser.DocumentTitleChanged += new EventHandler(webBrowser1_DocumentTitleChanged);
        webbrowser.StatusTextChanged += new EventHandler(webBrowser1_StatusTextChanged);
        webbrowser.ScriptErrorsSuppressed = true;
        webbrowser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted);
        webbrowser.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.webBrowser1_Navigated);
        webbrowser.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(this.webBrowser1_Navigating);
        webbrowser.ProgressChanged += new System.Windows.Forms.WebBrowserProgressChangedEventHandler(this.webBrowser1_ProgressChanged);
</code>```

my issue is I cant handle them properly because I wrote code for webbrowser1 and dont know how to call dynamically created object. I wrote this:

```<code>    private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        foreach (Control c in tabControl1.SelectedTab.Controls)
        {
            if (e.GetType() == typeof(WebBrowser))
            {
                WebBrowser web = new WebBrowser();
                if (e.KeyCode == Keys.Enter)
                    web.Navigate(toolStripTextBox1.Text);
            }
        }

    }
</code>```

but it doesn't work at all ( even for webbrowser1). How should I fix this?

Thanks in advance

答:
I think you are intending to do something like this:

```<code>private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    foreach (Control c in tabControl1.SelectedTab.Controls)
    {
        var web = c as WebBrowser;
        if (c != null && e.KeyCode == Keys.Enter)
        {
            web.Navigate(toolStripTextBox1.Text);
        }
    }
}
</code>```

You are looping through the controls in your TabControl, you need to find the one that is a WebBrowser.  Once you have that control, then you want to perform the navigation with that particular instance of a WebBrowser instead of creating a new browser.  I don't know what other code you have for the key handler, but if you are only performing an action on enter, I would revise this code to check for that first and only walk the collection when I actually need to.  Like this:

```<code>private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode != Keys.Enter) return;

    foreach (Control c in tabControl1.SelectedTab.Controls)
    {
        var web = c as WebBrowser;
        if (c != null)
        {
            web.Navigate(toolStripTextBox1.Text);
        }
    }
}
</code>```

Title: Handling dynamically created control?

Body:
I'm writing simple web browser in c#. For multi tab functionality I added tabcontrol and placed webbrowser1 in it.  I use toolstripbutton to dynamically add tabpages , webbrowsers (and handle its events with webbrowser1 events):

        TabPage tabpage = new TabPage();
        tabControl1.Controls.Add(tabpage);
        WebBrowser webbrowser = new WebBrowser();
        webbrowser.Parent = tabpage;
        webbrowser.Dock = DockStyle.Fill;
        webbrowser.Navigate("www.google.com");
        webbrowser.DocumentTitleChanged += new EventHandler(webBrowser1_DocumentTitleChanged);
        webbrowser.StatusTextChanged += new EventHandler(webBrowser1_StatusTextChanged);
        webbrowser.ScriptErrorsSuppressed = true;
        webbrowser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.webBrowser1_DocumentCompleted);
        webbrowser.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.webBrowser1_Navigated);
        webbrowser.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(this.webBrowser1_Navigating);
        webbrowser.ProgressChanged += new System.Windows.Forms.WebBrowserProgressChangedEventHandler(this.webBrowser1_ProgressChanged);

my issue is I cant handle them properly because I wrote code for webbrowser1 and dont know how to call dynamically created object. I wrote this:

    private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
    {
        foreach (Control c in tabControl1.SelectedTab.Controls)
        {
            if (e.GetType() == typeof(WebBrowser))
            {
                WebBrowser web = new WebBrowser();
                if (e.KeyCode == Keys.Enter)
                    web.Navigate(toolStripTextBox1.Text);
            }
        }

    }

but it doesn't work at all ( even for webbrowser1). How should I fix this?

Thanks in advance

Body:
I think you are intending to do something like this:

private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    foreach (Control c in tabControl1.SelectedTab.Controls)
    {
        var web = c as WebBrowser;
        if (c != null && e.KeyCode == Keys.Enter)
        {
            web.Navigate(toolStripTextBox1.Text);
        }
    }
}

You are looping through the controls in your TabControl, you need to find the one that is a WebBrowser.  Once you have that control, then you want to perform the navigation with that particular instance of a WebBrowser instead of creating a new browser.  I don't know what other code you have for the key handler, but if you are only performing an action on enter, I would revise this code to check for that first and only walk the collection when I actually need to.  Like this:

private void toolStripTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode != Keys.Enter) return;

    foreach (Control c in tabControl1.SelectedTab.Controls)
    {
        var web = c as WebBrowser;
        if (c != null)
        {
            web.Navigate(toolStripTextBox1.Text);
        }
    }
}


问:
What is the form collection in asp.net/html?
Simple question but one i need to clarify for myself. In terms of collections that can be accessed in the request object there is:

```<code>Cookies:    (whats in  a text file in the browser)
Querystring:   (whats passed in the url like [key=value&key=value etc])
Server Variables:  ?
Form Variables:    ?
</code>```

The ones with the ? next to are the ones that I dont really understand where in the http packet/html they are placed. I did a capture using wireshark:

```<code>POST /Security/HelixSessionAuth.aspx HTTP/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 391

ClientIP=192.168.20.31
Url=%2Fflash%2F56553550%5Fhi%2Emp4
Log=SESSIONSTART%20%5B13%2FDec%2F2010%3A16%3A31%3A23%20%2B0000%5D%20%20flash%2F56553550%5Fhi%2Emp4%200%20192%2E168%2E20%2E31%203%20%5B13%2FDec%2F2010%3A16%3A31%3A23%20%2B0000%5D%200%200%200%20%5B0%20No%20Error%5D%20%5B0%20No%20Error%5D%20%5Brtmp%3A%2F%2Fhelix%2Epete%2Evideolibraryserver%2Ecom%2Fflash%2F56553550%5Fhi%2Emp4%5D%0A
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Mon, 13 Dec 2010 16:31:23 GMT
Connection: close
Content-Length: 315

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Not Found</h2>
<hr><p>HTTP Error 404. The requested resource is not found.</p>
</BODY></HTML>
</code>```

Where abouts would they be in the above feed?

答:
The Form collection is the list of controls in the page that are passed to the action page via the POST method. Querystring is a GET, POST adds items to the Form collection. If you know the name of the control in the POST, you can access its value in the action page using:

```<code>Request.Form("myControl")
</code>```

In .Net web forms, this is a little more complicated because .Net injects a specialized ClientID to preserve the ID of the actual control in the code behind.

The server collection is a collection of common server variables identifying information about the client, server, connection, browser, etc. A full list can be found here:

https://msdn.microsoft.com/en-us/library/ms524602(v=vs.90).aspx

Body:
Simple question but one i need to clarify for myself. In terms of collections that can be accessed in the request object there is:

Cookies:    (whats in  a text file in the browser)
Querystring:   (whats passed in the url like [key=value&key=value etc])
Server Variables:  ?
Form Variables:    ?

The ones with the ? next to are the ones that I dont really understand where in the http packet/html they are placed. I did a capture using wireshark:

POST /Security/HelixSessionAuth.aspx HTTP/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 391

ClientIP=192.168.20.31
Url=%2Fflash%2F56553550%5Fhi%2Emp4
Log=SESSIONSTART%20%5B13%2FDec%2F2010%3A16%3A31%3A23%20%2B0000%5D%20%20flash%2F56553550%5Fhi%2Emp4%200%20192%2E168%2E20%2E31%203%20%5B13%2FDec%2F2010%3A16%3A31%3A23%20%2B0000%5D%200%200%200%20%5B0%20No%20Error%5D%20%5B0%20No%20Error%5D%20%5Brtmp%3A%2F%2Fhelix%2Epete%2Evideolibraryserver%2Ecom%2Fflash%2F56553550%5Fhi%2Emp4%5D%0A
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Mon, 13 Dec 2010 16:31:23 GMT
Connection: close
Content-Length: 315

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Not Found</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Not Found

HTTP Error 404. The requested resource is not found.

Where abouts would they be in the above feed?

Body:
The Form collection is the list of controls in the page that are passed to the action page via the POST method. Querystring is a GET, POST adds items to the Form collection. If you know the name of the control in the POST, you can access its value in the action page using:

Request.Form("myControl")

In .Net web forms, this is a little more complicated because .Net injects a specialized ClientID to preserve the ID of the actual control in the code behind.

The server collection is a collection of common server variables identifying information about the client, server, connection, browser, etc. A full list can be found here:

https://msdn.microsoft.com/en-us/library/ms524602(v=vs.90).aspx