答:
I'm not a 100 percent sure if I understood your question correctly, but in a nutshell, you want to check the following: your model consists of multiple bookings, each of which may or may not have GuaranteePolicy. You want to check that if they are set, then they are all the same, and render the footer only if this is true. You could solve it like the following:

```<code>@{
    string firstGuaranteePolicy = Model.Bookings.Select(b => b.GuaranteePolicy).FirstOrDefault();
    bool areAllTheSame = Model.Bookings.Select(b => b.GuaranteePolicy).All(val => val == firstGuaranteePolicy);
}

@if (areAllTheSame)
{
    <tfoot>
    ...
    </tfoot>
}
</code>```

So simply you extract the first GuaranteePolicy value (I assume you can navigate to them through a property Bookings, modify that according to your model structure), and if all of them are the same as the first one, then all of them are identical.

Title: compare multiple strings in foreach

Body:
I'm not a 100 percent sure if I understood your question correctly, but in a nutshell, you want to check the following: your model consists of multiple bookings, each of which may or may not have GuaranteePolicy. You want to check that if they are set, then they are all the same, and render the footer only if this is true. You could solve it like the following:

@{
    string firstGuaranteePolicy = Model.Bookings.Select(b => b.GuaranteePolicy).FirstOrDefault();
    bool areAllTheSame = Model.Bookings.Select(b => b.GuaranteePolicy).All(val => val == firstGuaranteePolicy);
}

@if (areAllTheSame)
{
    <tfoot>
    ...
    </tfoot>
}

So simply you extract the first GuaranteePolicy value (I assume you can navigate to them through a property Bookings, modify that according to your model structure), and if all of them are the same as the first one, then all of them are identical.


来源: stackexchange

问:
How to access GUI elements in a dynamic user interface
I am trying to develop a dynamic user interface. When the user clicks at a certain indicator a graph of it is instantiated together with some manipulation buttons. See the image for an example. The graph is created in an HBox, together with the buttons and next added to a VBox. The problem I cannot solve is: when a button is clicked, how can I access the corresponding element?

The problem simply boils down to this:

```<code>  Button buttonRemove = new Button ();
  buttonRemove.setMinWidth (80);
  buttonRemove.setText ("Remove");
  buttonMap.getProperties ().put ("--IndicatorRemoveButton", indicator.getName ());
  buttonRemove.setOnAction (e -> buttonRemoveClick ());

   private Object buttonRemoveClick ()
   {
      // Which button clicked me??

      return null;
   } /*** buttonRemoveClick ***/
</code>```

Any help will be greatly appreciated. I'm kind of stuck  with this.

.

答:
It's possible to pass a parameter to the buttonRemoveClick method in the lambda, as long as it's effectively final or a parameter.

```<code>private void buttonRemoveClick (HBox group) {...}
</code>```

```<code>buttonRemove.setOnAction (e -> buttonRemoveClick (theGroup));
</code>```

In this case you could also pass the ActionEvent and get the source to retrieve the Button; this may not be enough to remove the element, but for this you could traverse to the parent until you reach a child of the HBox

```<code>private void buttonRemoveClick (ActionEvent event) {
    Node currentNode = (Node) event.getSource(); // this is the button

    // traverse to HBox of container
    Node p;
    while ((p = currentNode.getParent()) != containerVBox) {
        currentNode = p;
    }
    // remove part including the Button from container
    containerVBox.getChildren().remove(currentNode);
}
</code>```

```<code>buttonRemove.setOnAction (this::buttonRemoveClick);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to develop a dynamic user interface. When the user clicks at a certain indicator a graph of it is instantiated together with some manipulation buttons. See the image for an example. The graph is created in an HBox, together with the buttons and next added to a VBox. The problem I cannot solve is: when a button is clicked, how can I access the corresponding element?

The problem simply boils down to this:

  Button buttonRemove = new Button ();
  buttonRemove.setMinWidth (80);
  buttonRemove.setText ("Remove");
  buttonMap.getProperties ().put ("--IndicatorRemoveButton", indicator.getName ());
  buttonRemove.setOnAction (e -> buttonRemoveClick ());

   private Object buttonRemoveClick ()
   {
      // Which button clicked me??

      return null;
   } /*** buttonRemoveClick ***/

Any help will be greatly appreciated. I'm kind of stuck  with this.

.

Body:
It's possible to pass a parameter to the buttonRemoveClick method in the lambda, as long as it's effectively final or a parameter.

private void buttonRemoveClick (HBox group) {...}

buttonRemove.setOnAction (e -> buttonRemoveClick (theGroup));

In this case you could also pass the ActionEvent and get the source to retrieve the Button; this may not be enough to remove the element, but for this you could traverse to the parent until you reach a child of the HBox

private void buttonRemoveClick (ActionEvent event) {
    Node currentNode = (Node) event.getSource(); // this is the button

    // traverse to HBox of container
    Node p;
    while ((p = currentNode.getParent()) != containerVBox) {
        currentNode = p;
    }
    // remove part including the Button from container
    containerVBox.getChildren().remove(currentNode);
}

buttonRemove.setOnAction (this::buttonRemoveClick);


问:
Questions about Class Instances
So, I have looked into this question and haven't gotten what I see to be a solid answer, or maybe I just am lacking an understanding of this. Essentially I want to know:

A. Is it bad practice to have many instances of the same class?

B. What is a way to get rid of an overwhelming amount of instances without the program exiting?

Let me explain. Say I want to write a Zero Person RPG that is running in the background consistently. So I create an Enemy class for the Hero to slay.

```<code>class Enemy:
    # Attr = Stats held in a dict
    def __init__(self, attr={}):
         self.attr = attr
</code>```

A simple example. Is there an alternative to having to do the following hundreds of times?

```<code>giant = Enemy({'atk': 10, 'def': 5})
poltergeist = Enemy({'atk': 7, 'def' 8})
...
</code>```

Or is this seen as the pythonic way?

答:
No, it is not a bad practice to have many instances of the same class. When working with ORMs, you'll be working with a lot of objects, and it is totally fine as long as you are not being redundant and your use case needs the instances, and deleting the objects when you do not need them anymore.

Various ways of deleting and object are explained in this answer.

This is another answer which showcases use of with statement to manage objects contextually.

Title: Questions about Class Instances

Body:
So, I have looked into this question and haven't gotten what I see to be a solid answer, or maybe I just am lacking an understanding of this. Essentially I want to know:

A. Is it bad practice to have many instances of the same class?

B. What is a way to get rid of an overwhelming amount of instances without the program exiting?

Let me explain. Say I want to write a Zero Person RPG that is running in the background consistently. So I create an Enemy class for the Hero to slay.

class Enemy:
    # Attr = Stats held in a dict
    def __init__(self, attr={}):
         self.attr = attr

A simple example. Is there an alternative to having to do the following hundreds of times?

giant = Enemy({'atk': 10, 'def': 5})
poltergeist = Enemy({'atk': 7, 'def' 8})
...

Or is this seen as the pythonic way?


问:
Getting a date to pull from a parent to a response on creation
So given this code for pre loading fields from a parent record to a new response record.  I can get the ParentUNID and the HolderName values to load no problem, but I am missing something on passing the date values?</p>

```<code><xp:this.beforePageLoad><![CDATA[#{javascript:
var parentDoc = database.getDocumentByUNID(document1.getParentId());
document1.setValue("ParentUNID", parentDoc.getItemValue("DocID"));
document1.setValue("Policy_HolderName", parentDoc.getItemValue("Policy_HolderName"));
document1.setValue("Policy_Eff_Date", parentDoc.getItemValue("Policy_Eff_Date"));}]]></xp:this.beforePageLoad>
</code>```

答:
Copy the item itself and not just item's value. This way you copy all item's properties too:

```<code>...
document1.getDocument().copyItem(parentDoc.getFirstItem("Policy_Eff_Date"));
...
</code>```

Body:
So given this code for pre loading fields from a parent record to a new response record.  I can get the ParentUNID and the HolderName values to load no problem, but I am missing something on passing the date values?

<xp:this.beforePageLoad><![CDATA[#{javascript:
var parentDoc = database.getDocumentByUNID(document1.getParentId());
document1.setValue("ParentUNID", parentDoc.getItemValue("DocID"));
document1.setValue("Policy_HolderName", parentDoc.getItemValue("Policy_HolderName"));
document1.setValue("Policy_Eff_Date", parentDoc.getItemValue("Policy_Eff_Date"));}]]></xp:this.beforePageLoad>

Body:
Copy the item itself and not just item's value. This way you copy all item's properties too:

...
document1.getDocument().copyItem(parentDoc.getFirstItem("Policy_Eff_Date"));
...


问:
Why is bottom-up parsing more common than top-down parsing?
It seems that recursive-descent parsers are not only the simplest to explain, but also the simplest to design and maintain. They aren't limited to LALR(1) grammars, and the code itself can be understood by mere mortals. In contrast, bottom up parsers have limits on the grammars they are able to recognize, and need to be generated by special tools (because the tables that drive them are next-to-impossible to generate by hand).

Why then, is bottom-up (i.e. shift-reduce) parsing more common than top-down (i.e. recursive descent) parsing?

答:
Recursive-descent parsers try to hypothesize the general structure of the input string, which means a lot of trial-and-error occurs before the end of the string is reached. This makes them less efficient than bottom-up parsers, which need no such inference engines.

The performance difference becomes magnified as the complexity of the grammar increases.

ContentLicense: CC BY-SA 2.5


问:
Client certificate: Could not establish secure channel for SSL/TLS with authority (Again!)
Sorry for asking this question, but I couldn't find any answer for my case on Stack.

I developed a client application that talks to an external SOAP api using WCF. To authenticate, the application uses a client certificate. (The client certificate as been installed on the server). When I test on my local machine everything works fine.

The problems occurs when I deploy the application on IIS (on a EC2). The apps cannot communicate with the SOAP api anymore. This is the error:

```<code>"Could not establish secure channel for SSL/TLS with authority".
</code>```

I installed the certificate in Personnal store of both Current User and Local Computer location. When I try to hit the SOAP api with the browser it works (get on wsdl file which also need the client certificate).

Note: the certificate is not self signed. It was created by an authorized CA.

Thanks for the help

答:
Certificate Store can only be accessible to Administrators. local iis user that is IUSER does not have administrator rights and so u were getting that certificate error. Changing application pool identity to LocalSystem solved your problem because LocalSystem can access to Certificate STore.

Another optimum solution to this is to only allow the access of certificate to IUSER. (by doing this you have given a specific access unlike the full administrator access to app pool).

To do that go to the
Certificate console -> Right click on Certificate -> All Tasks -> Manage Private Key -> Add IUSER and click Ok.

Body:
Sorry for asking this question, but I couldn't find any answer for my case on Stack.

I developed a client application that talks to an external SOAP api using WCF. To authenticate, the application uses a client certificate. (The client certificate as been installed on the server). When I test on my local machine everything works fine.

The problems occurs when I deploy the application on IIS (on a EC2). The apps cannot communicate with the SOAP api anymore. This is the error:

"Could not establish secure channel for SSL/TLS with authority".

I installed the certificate in Personnal store of both Current User and Local Computer location. When I try to hit the SOAP api with the browser it works (get on wsdl file which also need the client certificate).

Note: the certificate is not self signed. It was created by an authorized CA.

Thanks for the help


问:
JSON post doesn't work
I have this code :

```<code>[WebMethod]
public List<string> pubss(string gn)
    {
        List<string> onepub = new List<string>();
        iam_dbEntities db = new iam_dbEntities();
        var message = from i in db.Public_MessageSet where
        i.RoomSet.Room_Name == gn select i;
        foreach(var s in message)
        {
            onepub.Add(s.Sender.ToString());
        }
        return onepub;
    }
</code>```

and this Jquery Code :

```<code>$('#addRoom').click(function () {
 $.ajax({
            type: "POST",
            url: "WebService.asmx/pubss",
            data: "gn=Programmers",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                alert(JSON.toString(data));
            }
    });
});
</code>```

When I click the button I expect some alerts contains information about
the senders but nothing showed, not a single alert.

答:
Is there any error in console please mention? what status code for ajax? how eve you can check below precautions:
 1. On success you can try below:

```<code> data = data.hasOwnProperty("d") ? data.d : data;
</code>```

May be d property may cause.
 2. pass your data with JSON.stringify

```<code> JSON.stringify({gn:'Programmers'})
</code>```

3. in your ajax you have  dataType: "json", 2 times.
4. if ajax is succuss then debug you webMthod and check is it returning correct data?

Title: JSON post doesn't work

Body:
I have this code :

[WebMethod]
public List<string> pubss(string gn)
    {
        List<string> onepub = new List<string>();
        iam_dbEntities db = new iam_dbEntities();
        var message = from i in db.Public_MessageSet where
        i.RoomSet.Room_Name == gn select i;
        foreach(var s in message)
        {
            onepub.Add(s.Sender.ToString());
        }
        return onepub;
    }

and this Jquery Code :

$('#addRoom').click(function () {
 $.ajax({
            type: "POST",
            url: "WebService.asmx/pubss",
            data: "gn=Programmers",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                alert(JSON.toString(data));
            }
    });
});

When I click the button I expect some alerts contains information about
the senders but nothing showed, not a single alert.

Body:
Is there any error in console please mention? what status code for ajax? how eve you can check below precautions:
 1. On success you can try below:

 data = data.hasOwnProperty("d") ? data.d : data;

May be d property may cause.
 2. pass your data with JSON.stringify

 JSON.stringify({gn:'Programmers'})

3. in your ajax you have  dataType: "json", 2 times.
4. if ajax is succuss then debug you webMthod and check is it returning correct data?


问:
jQuery oddity in Wordpress
I'm getting started with Wordpress and trying to use jQuery as my JavaScript library of choice. I've got it loading with wp_enqueue_script but for some reason when the page actually loads the $ function it does so with it behaving like it does in Prototype (single dollar sign is "get by Id" and $$ is the CSS selector system).

I'm very confused as to why because I cannot find anywhere in the response from the server where the instruction to load Prototype is coming from; there is no

答:
"Why does Wordpress jQuery differ from normal jQuery?"

WordPress loads jQuery in no conflict mode - another script on the page must've been tinkering with the $ surely?

Title: jQuery oddity in Wordpress


问:
Added Markers on Map from an Array but only one marker is displayed
I'm trying to add multiple markers to the map, the coordinates of the marker are in an array List named locationList but as I run the project, it only displays the last index. I tried to solve this with the some related questions but it does not work. Here is the code.</p>

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
EditText et;
private ArrayList<Location> locationList ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent=getIntent();
    locationList= (ArrayList<Location>) intent.getSerializableExtra("location");

    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);
    et = (EditText) findViewById(R.id.et);
    if (googleServiceAvailable()) {
        Toast.makeText(this, "Perfect", Toast.LENGTH_LONG).show();
    }
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

  /*  MarkerOptions opts = new MarkerOptions();
    opts.position(new LatLng(14.559691260979879,121.02173693084717));
    mMap.addMarker(opts);

    MarkerOptions asd = new MarkerOptions();
    asd.position(new LatLng(14.556659026561825,121.01744539642334));
    mMap.addMarker(asd);*/

    //loop for adding markers. I tried printing the indexes and got the total size

    for(int i=1; i<locationList.size();i++)
    {
      LatLng latlng = new LatLng(locationList.get(i).getLatitude(),locationList.get(i).getLongitude());
      mMap.addMarker(new MarkerOptions().position(latlng));
    }

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);

}

private void goToLocationZoom(double lat,double lng,float zoom){
    LatLng ll= new LatLng(lat,lng);
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
    mMap.moveCamera(update);

}

//Using geoLocate

public void geoLocate(View view) throws IOException {

    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    mgr.hideSoftInputFromWindow(et.getWindowToken(),0);

    String location = et.getText().toString();

    Geocoder gc = new Geocoder(this);
    List<Address> list = gc.getFromLocationName(location,1);
    Address address = list.get(0);
    String locality = address.getLocality();

    Toast.makeText(this,locality,Toast.LENGTH_LONG).show();
    double lat = address.getLatitude();
    double lng = address.getLongitude();
    goToLocationZoom(lat,lng,17);

}
</code>```

答:
If your list is 2 items long, your for loop is only running once and it's picking up the second item on it's first run through.

I think you've mixed up the indexes between 0 and 1. Java Lists are 0-based.

Initialize i to 0 and you should be good.

```<code>for(int i=0; i<locationList.size();i++)
{
  Location l = locationList.get(i);
  LatLng latlng = new LatLng(l.getLatitude(),l.getLongitude());
  mMap.addMarker(new MarkerOptions().position(latlng));
}
</code>```

Body:
I'm trying to add multiple markers to the map, the coordinates of the marker are in an array List named locationList but as I run the project, it only displays the last index. I tried to solve this with the some related questions but it does not work. Here is the code.

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
EditText et;
private ArrayList<Location> locationList ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent=getIntent();
    locationList= (ArrayList<Location>) intent.getSerializableExtra("location");

    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);

    mapFragment.getMapAsync(this);
    et = (EditText) findViewById(R.id.et);
    if (googleServiceAvailable()) {
        Toast.makeText(this, "Perfect", Toast.LENGTH_LONG).show();
    }
}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

  /*  MarkerOptions opts = new MarkerOptions();
    opts.position(new LatLng(14.559691260979879,121.02173693084717));
    mMap.addMarker(opts);

    MarkerOptions asd = new MarkerOptions();
    asd.position(new LatLng(14.556659026561825,121.01744539642334));
    mMap.addMarker(asd);*/

    //loop for adding markers. I tried printing the indexes and got the total size

    for(int i=1; i<locationList.size();i++)
    {
      LatLng latlng = new LatLng(locationList.get(i).getLatitude(),locationList.get(i).getLongitude());
      mMap.addMarker(new MarkerOptions().position(latlng));
    }

    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);

}

private void goToLocationZoom(double lat,double lng,float zoom){
    LatLng ll= new LatLng(lat,lng);
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
    mMap.moveCamera(update);

}

//Using geoLocate

public void geoLocate(View view) throws IOException {

    InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    mgr.hideSoftInputFromWindow(et.getWindowToken(),0);

    String location = et.getText().toString();

    Geocoder gc = new Geocoder(this);
    List<Address> list = gc.getFromLocationName(location,1);
    Address address = list.get(0);
    String locality = address.getLocality();

    Toast.makeText(this,locality,Toast.LENGTH_LONG).show();
    double lat = address.getLatitude();
    double lng = address.getLongitude();
    goToLocationZoom(lat,lng,17);

}

Body:
If your list is 2 items long, your for loop is only running once and it's picking up the second item on it's first run through.

I think you've mixed up the indexes between 0 and 1. Java Lists are 0-based.

Initialize i to 0 and you should be good.

for(int i=0; i<locationList.size();i++)
{
  Location l = locationList.get(i);
  LatLng latlng = new LatLng(l.getLatitude(),l.getLongitude());
  mMap.addMarker(new MarkerOptions().position(latlng));
}


问:
LocationProvider - Detecting highly inaccurate/incorrect locations
So I know you can use getAccuracy() to find the accuracy of a location but if you set up a cut off for the accuracy, can you prevent recording down one of those locations where it's hugely off mark of where the user is? Like if the user is still, most location updates cluster around his area but occasionally the location provider will hiccup and report the location as somewhere miles away.

Do these locations simply appear as "accurate" with getAccuracy? Or would they turn up as some insanely high getAccuracy() result? Programming a cut off point is easy enough but I was wondering if I would have to code extra checks such as if a location is way too different from the previous ones then it's a wayward one.

答:
Accuracy is not the only deciding factor here. You should also look at the age of the location, and the provider if you get it (the Google Play Services location doesn't tell you, but the original Android LocationManager does).

In fact, Google has some useful sample code for maintaining a current best estimate. I have used a variation of this to filter out wild jumps in incoming location data. Essentially a location is not even reported if it doesn't pass this gate.


问:
Combine 2 lists in python such that elements at the corresponding index are together
I have two lists like:

```<code>listone = [1, 2, 3]
listtwo = [4, 5, 6]
</code>```

I would like to combine them to get:

```<code>l = [1, 4, 2, 5, 3, 6]
</code>```

How can I do this without using loops?

答:
You can plus two lists directly .

```<code>list_one=[1,2,3]
list_two=[4,5,6]
list_one=list_one+list_two
print(list_one)

>>>list_one=[1,2,3,4,5,6]
</code>```

you can also change the order of sum ,
then print out [4,5,6,1,2,3].

Body:
I have two lists like:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

I would like to combine them to get:

l = [1, 4, 2, 5, 3, 6]

How can I do this without using loops?

Body:
You can plus two lists directly .

list_one=[1,2,3]
list_two=[4,5,6]
list_one=list_one+list_two
print(list_one)

>>>list_one=[1,2,3,4,5,6]

you can also change the order of sum ,
then print out [4,5,6,1,2,3].


问:
Celery broadcast task not working
I've tried to make a broadcast task but only one of my workers recieve it per each call. Would you please help me? (I'm using rabbitmq and node-celery)

```<code>default_exchange = Exchange('celery', type='direct')
celery.conf.update(
    CELERY_RESULT_BACKEND = "amqp",
    CELERY_RESULT_SERIALIZER='json',
    CELERY_QUEUES = (
        Queue('celery', default_exchange, routing_key='celery'),
        Broadcast('broadcast_tasks'),
    ),
    CELERY_ROUTES = (
        {'my_tasks.sample_broadcast_task': {
            'queue': 'broadcast_tasks',
            }},
        {'my_tasks.sample_normal_task': {
            'queue': 'celery',
            'exchange': 'celery',
            'exchange_type': 'direct',
            'routing_key': 'celery',
            }}
    ),
    )
</code>```

I've also test following configurtion but not working.

```<code>celery.conf.update(
    CELERY_RESULT_BACKEND = "amqp",
    CELERY_RESULT_SERIALIZER='json',
    CELERY_QUEUES=(
        Queue('celery', Exchange('celery'), routing_key='celery'),
        Broadcast('broadcast'),
    ),
    )
@celery.task(ignore_result=True, queue='broadcast',
             options=dict(queue='broadcast'))
def sample_broadcast_task():
    print "test"
</code>```

EDIT

after changing how to run worker by adding -Q broadcast, now i face to this error:

```<code>PreconditionFailed: Exchange.declare: (406) PRECONDITION_FAILED - inequivalent arg 'type' for exchange 'broadcast' in vhost '/': received 'direct' but current is 'fanout'
</code>```

答:
Try this

```<code>   from celery import Celery
   from kombu.common import Broadcast

   BROKER_URL = 'amqp://guest:guest@localhost:5672//'

   class CeleryConf:
   # List of modules to import when celery starts.
   CELERY_ACCEPT_CONTENT = ['json']
   CELERY_IMPORTS = ('main.tasks')
   CELERY_QUEUES = (Broadcast('q1'),)
   CELERY_ROUTES = {
    'tasks.sampletask': {'queue': 'q1'}
   }

   celeryapp = Celery('celeryapp', broker=BROKER_URL)
   celeryapp.config_from_object(CeleryConf())

   @celeryapp.task
   def sampletask(form):
      print form
</code>```

To send the message, do

```<code>    d= sampletask.apply_async(['4c5b678350fc643'],serializer="json", queue='q1')
</code>```

Title: Celery broadcast task not working

Body:
I've tried to make a broadcast task but only one of my workers recieve it per each call. Would you please help me? (I'm using rabbitmq and node-celery)

default_exchange = Exchange('celery', type='direct')
celery.conf.update(
    CELERY_RESULT_BACKEND = "amqp",
    CELERY_RESULT_SERIALIZER='json',
    CELERY_QUEUES = (
        Queue('celery', default_exchange, routing_key='celery'),
        Broadcast('broadcast_tasks'),
    ),
    CELERY_ROUTES = (
        {'my_tasks.sample_broadcast_task': {
            'queue': 'broadcast_tasks',
            }},
        {'my_tasks.sample_normal_task': {
            'queue': 'celery',
            'exchange': 'celery',
            'exchange_type': 'direct',
            'routing_key': 'celery',
            }}
    ),
    )

I've also test following configurtion but not working.

celery.conf.update(
    CELERY_RESULT_BACKEND = "amqp",
    CELERY_RESULT_SERIALIZER='json',
    CELERY_QUEUES=(
        Queue('celery', Exchange('celery'), routing_key='celery'),
        Broadcast('broadcast'),
    ),
    )
@celery.task(ignore_result=True, queue='broadcast',
             options=dict(queue='broadcast'))
def sample_broadcast_task():
    print "test"

EDIT

after changing how to run worker by adding -Q broadcast, now i face to this error:

PreconditionFailed: Exchange.declare: (406) PRECONDITION_FAILED - inequivalent arg 'type' for exchange 'broadcast' in vhost '/': received 'direct' but current is 'fanout'

Body:
Try this

   from celery import Celery
   from kombu.common import Broadcast

   BROKER_URL = 'amqp://guest:guest@localhost:5672//'

   class CeleryConf:
   # List of modules to import when celery starts.
   CELERY_ACCEPT_CONTENT = ['json']
   CELERY_IMPORTS = ('main.tasks')
   CELERY_QUEUES = (Broadcast('q1'),)
   CELERY_ROUTES = {
    'tasks.sampletask': {'queue': 'q1'}
   }

   celeryapp = Celery('celeryapp', broker=BROKER_URL)
   celeryapp.config_from_object(CeleryConf())

   @celeryapp.task
   def sampletask(form):
      print form

To send the message, do

    d= sampletask.apply_async(['4c5b678350fc643'],serializer="json", queue='q1')


问:
Kubernetes: single POD with many container, or many Pod with single container
I've rather a teoretical question which I can't answer  with the reousrces found online. The question is: what's the rule to decide how to compose containers in POD? . Let me explain with an example.

I've these microservices:

Authentication

Authorization

Serving content

(plus) OpenResty to forward the calls form one to the other and orhcestarate the flow. (is there a possibility to do so natively in K8?, it seems to have services base on nginx+lua, but not sure how it works)

For the sake of the example I avoid Databases and co, I assume they are external and not managed by kubernetes

Now, what's the correct way here LEFT or RIGHT of the image?

LEFT : this seems easier to make it working, everything works on "localhost" , the downside is that it looses a bit the benefit of the microservices. For example, if the auth become slows and it would need more instances, I've to duplicate the whole pod and not just that service.

RIGHT seems a bit more complex, need services to expose each POD to the other PODs. Yet, here, I could duplicate auth as I need without duplicating the other containers. On the other hand I'll have a lot of pods since each pod is basically a container.

答:
It is generally recommended to keep different services in different pods or better deployments that will scale independently. The reasons are what is generally discussed as benefits of a microservices architecture.

A more loose coupling allowing the different services to be developed independently in their own languages/technologies,

be deployed and updated independently and

also to scale independently.

The exception are what is considered a "helper application" to assist a "primary application". Examples given in the k8s docs are data pullers, data pushers and proxies. In those cases a share file system or exchange via loopback network interface can help with critical performance use cases. A data puller can be a side-car container for an nginx container pulling a website to serve from a GIT repository for example.


问:
Learn C# on mac?
Is mono the only route , any specific visual studio like editors that you recommend?</p>

答:
Yeah, mono is really your only option, unless some undergrad somewhere has developed some very experimental thing I don't know about. As for an IDE, well I believe the only thing half way stable that will work right now on Mac OS X is Monodevelop:

http://tirania.org/blog/archive/2008/Feb-07-2.html

I mean, you could run Parallels and develop your code on a Windows VM with Visual Studio and as long as you follow certain guidelines about portability, you could use VS to develop your mono apps. Although, you probably might as well get familiar with Monodevelop. It would be interesting to see if SharpDevelop ever gets ported.

Title: Learn C# on mac?

OwnerDisplayName: BobbyShaftoe


问:
How do I get updated row id in ZEND?
I use

```<code>$table->update($data, $where);
</code>```

How do I get updated row id in ZEND?

答: As with working with just the plain ol' SQL, just re-query for the info you want. Use $table->select('rowid')->where($where) to do this.

Title: How do I get updated row id in ZEND?

Body:
I use

$table->update($data, $where);

How do I get updated row id in ZEND?


问:
java.lang.NoClassDefFoundError: javax/json/Json no maven or IDE
I am trying a simple json java program (no maven or IDE).
This is my java file:

```<code>import javax.json.*;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;

class JsonTest {

public static void main(String[] args){
  JsonObject obj = Json.createObjectBuilder()
  .add("name", "foo")
  .add("num", new Integer(100))
  .add("balance", new Double(1000.21))
  .add("is_vip", new Boolean(true)).build();

  System.out.print(obj);
}
}
</code>```

In the same directory of this file, I have the jar file:

```<code>javax.json-1.0.jar
</code>```

I don't get any error in compiling:

```<code>javac -classpath ./javax.json-1.0.jar JsonTest.java
</code>```

But when I run the program I get the error:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: javax/json/Json
    at JsonTest.main(JsonTest.java:10)
Caused by: java.lang.ClassNotFoundException: javax.json.Json
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 1 more
</code>```

Why am I getting this error when there was no error in compilation. I already searched other questions with this error but unlike them I am not using any IDE or maven. Any help will be appreciated.

答:
You are not running it with the JSON JAR file on the classpath.

Try this:

```<code>java -classpath .:./javax.json-1.0.jar JsonTest
</code>```

Change : to ; on Windows ....

Body:
I am trying a simple json java program (no maven or IDE).
This is my java file:

import javax.json.*;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;

class JsonTest {

public static void main(String[] args){
  JsonObject obj = Json.createObjectBuilder()
  .add("name", "foo")
  .add("num", new Integer(100))
  .add("balance", new Double(1000.21))
  .add("is_vip", new Boolean(true)).build();

  System.out.print(obj);
}
}

In the same directory of this file, I have the jar file:

javax.json-1.0.jar

I don't get any error in compiling:

javac -classpath ./javax.json-1.0.jar JsonTest.java

But when I run the program I get the error:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/json/Json
    at JsonTest.main(JsonTest.java:10)
Caused by: java.lang.ClassNotFoundException: javax.json.Json
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 1 more

Why am I getting this error when there was no error in compilation. I already searched other questions with this error but unlike them I am not using any IDE or maven. Any help will be appreciated.

Body:
You are not running it with the JSON JAR file on the classpath.

Try this:

java -classpath .:./javax.json-1.0.jar JsonTest

Change : to ; on Windows ....


问:
Use trigger to determine to implement insert or not
I am a beginner of SQL and Oracle database, and I need a little help about trigger. Here is the question:

I need to create a trigger that before insert a row into table Room, it will check this new row's hotel_id to see if it exists in another table Hotel. If the new hotel_id exists, then do the insert; if not, cancel this insert.

My code:

```<code>CREATE OR REPLACE TRIGGER TRIGGER1
BEFORE INSERT ON ROOM
FOR EACH ROW
BEGIN
  if (:new.hotel_id in (select hotel_id from hotel)) then
    --execute the insert;
    else
      --cancel the insert;
  end if;
END;
</code>```

I'm not sure that SQL has syntax that can be used to continue or cancel an operation. If there is, please teach me or attach the link related to it.

答:
Correct way of doing this is using foreign key constraints.

You can define/alter your room table to refer it in the hotel_id column.

CREATE TABLE:

```<code>create table room (
    . . .,
    hotel_id int not null,
    constraint fk_hotel_id foreign key (hotel_id)
        references hotel(hotel_id)
);
</code>```

ALTER TABLE:

```<code>alter table room
add constraint fk_hotel_id foreign key (hotel_id)
    references hotel(hotel_id);
</code>```

If the two table exists in different databases, then you can use trigger.

You can use raise_application_error proc to abort the execution and throw error.

```<code>create or replace trigger trigger1
before insert or update
on room for each row
declare
    n integer := 0;
begin
    select count(*) into n
    from hotel
    where hotel_id = :new.hotel_id;

    if n = 0 then
        raise_application_error(-20001, 'Hotel ID doesn't exist');
    end if;

end;
</code>```

Body:
I am a beginner of SQL and Oracle database, and I need a little help about trigger. Here is the question:

I need to create a trigger that before insert a row into table Room, it will check this new row's hotel_id to see if it exists in another table Hotel. If the new hotel_id exists, then do the insert; if not, cancel this insert.

My code:

CREATE OR REPLACE TRIGGER TRIGGER1
BEFORE INSERT ON ROOM
FOR EACH ROW
BEGIN
  if (:new.hotel_id in (select hotel_id from hotel)) then
    --execute the insert;
    else
      --cancel the insert;
  end if;
END;

I'm not sure that SQL has syntax that can be used to continue or cancel an operation. If there is, please teach me or attach the link related to it.

Body:
Correct way of doing this is using foreign key constraints.

You can define/alter your room table to refer it in the hotel_id column.

CREATE TABLE:

create table room (
    . . .,
    hotel_id int not null,
    constraint fk_hotel_id foreign key (hotel_id)
        references hotel(hotel_id)
);

ALTER TABLE:

alter table room
add constraint fk_hotel_id foreign key (hotel_id)
    references hotel(hotel_id);

If the two table exists in different databases, then you can use trigger.

You can use raise_application_error proc to abort the execution and throw error.

create or replace trigger trigger1
before insert or update
on room for each row
declare
    n integer := 0;
begin
    select count(*) into n
    from hotel
    where hotel_id = :new.hotel_id;

    if n = 0 then
        raise_application_error(-20001, 'Hotel ID doesn't exist');
    end if;

end;


问:
Formatting date in odoo email template
In odoo 9 i need to format the date_invoice in %d/%m/%Y inside email template:

```<code>Invoice date: ${object.date_invoice}
</code>```

The code above return 2017-03-31 but it is in wrong locale.

How i can format to get 31/03/2017 ?

答:
You can achieve using alternative different way.

${ object.date_invoice and object.date_invoice.split('-')[1] + '/' + object.date_invoice.split('-')[2] + '/' + object.date_invoice.split('-')[0] or ''}

Title: Formatting date in odoo email template

Body:
In odoo 9 i need to format the date_invoice in %d/%m/%Y inside email template:

Invoice date: ${object.date_invoice}

The code above return 2017-03-31 but it is in wrong locale.

How i can format to get 31/03/2017 ?


问:
How to get list of an entity with generic search
I have a generic repository, something like this:

```<code>    public IEnumerable<T> SelectAll()
    {
        return table.ToList();
    }

    public T SelectByID(object id)
    {
        return table.Find(id);
    }

    public void Insert(T obj)
    {
        table.Add(obj);
    }
</code>```

This works fine for the basic CRUD, but now I need to search an entity (table) against an user entered searchterm. Is it at all possible to do it with something like:

```<code>public IEnumerable<T> SelectAll(T obj, string searchText, string   columnName)
{
    // I am not sure what code to write here... It should give me all the records that contain the search term.
    // I was thinking something like this could be made to work...but I need help with it.
    return table.GetType().GetProperty(columnName).GetValue())ToList();
}
</code>```

答:
This is what I am using now:

```<code>        public IEnumerable<T> SelectAll(Expression<Func<T, bool>> predicate)
    {
        IEnumerable<T> searchResult = context.Set<T>().Where(predicate);
        return searchResult;
    }
</code>```

And the method call:

```<code> var lstResult = objRepo.SelectAll(x=>x.ColumnName.Contains(searchText));
</code>```

Body:
I have a generic repository, something like this:

    public IEnumerable<T> SelectAll()
    {
        return table.ToList();
    }

    public T SelectByID(object id)
    {
        return table.Find(id);
    }

    public void Insert(T obj)
    {
        table.Add(obj);
    }

This works fine for the basic CRUD, but now I need to search an entity (table) against an user entered searchterm. Is it at all possible to do it with something like:

public IEnumerable<T> SelectAll(T obj, string searchText, string   columnName)
{
    // I am not sure what code to write here... It should give me all the records that contain the search term.
    // I was thinking something like this could be made to work...but I need help with it.
    return table.GetType().GetProperty(columnName).GetValue())ToList();
}

Body:
This is what I am using now:

        public IEnumerable<T> SelectAll(Expression<Func<T, bool>> predicate)
    {
        IEnumerable<T> searchResult = context.Set<T>().Where(predicate);
        return searchResult;
    }

And the method call:

 var lstResult = objRepo.SelectAll(x=>x.ColumnName.Contains(searchText));


问:
Why this c++ code is giving me segmentation fault error on runtime?
Consider the code below:

```<code>#include <iostream>
using namespace std;

int main()
{
   const int max=500008;
   long long cordx[max],cordy[max];
   char type[max];
   int n;
   cin>>n;
   for(int m=0;m<n;m++)
       cin>>type[m]>>cordx[m]>>cordy[m];
   return 0;
}
</code>```

This code is giving me a Segmentation Fault error on runtime.

But when I change my code like this:

```<code>for(m=0;m<n;m++)
    cin>>cordx[m];
</code>```

It is not giving me any error.

Its giving me error only when I try to input like this:

```<code> cin>>type[m]>>cordx[m]>>cordy[m];
</code>```

答:
A long long is typically 8 bytes. cordx and cordy each request space for 500008 of them in Automatic  storage. That's about 8 MB storage and either far over or coming up on the maximum Automatic storage available. The typical PC uses a stack for Automatic storage and the stack is usually between 1 and 10 MB in size.

Solutions are to use std::vector to allocate storage from the much larger Dynamic storage or define the variables to be allocated in Static storage (make them static or define them globally).

Additionally, the user may specify an n that is greater than 500008 and force access out of bounds.

Body:
Consider the code below:

#include <iostream>
using namespace std;

int main()
{
   const int max=500008;
   long long cordx[max],cordy[max];
   char type[max];
   int n;
   cin>>n;
   for(int m=0;m<n;m++)
       cin>>type[m]>>cordx[m]>>cordy[m];
   return 0;
}

This code is giving me a Segmentation Fault error on runtime.

But when I change my code like this:

for(m=0;m<n;m++)
    cin>>cordx[m];

It is not giving me any error.

Its giving me error only when I try to input like this:

 cin>>type[m]>>cordx[m]>>cordy[m];


问:
Why do I need to use typedef typename in g++ but not VS?
It had been a while since GCC caught me with this one, but it just happened today. But I've never understood why GCC requires typedef typename within templates, while VS and I guess ICC don't. Is the typedef typename thing a "bug" or an overstrict standard, or something that is left up to the compiler writers?

For those who don't know what I mean here is a sample:

```<code>template<typename KEY, typename VALUE>
bool find(const std::map<KEY,VALUE>& container, const KEY& key)
{
    std::map<KEY,VALUE>::const_iterator iter = container.find(key);
    return iter!=container.end();
}
</code>```

The above code compiles in VS (and probably in ICC), but fails in GCC because it wants it like this:

```<code>template<typename KEY, typename VALUE>
bool find(const std::map<KEY,VALUE>& container, const KEY& key)
{
    typedef typename std::map<KEY,VALUE>::const_iterator iterator; //typedef typename
    iterator iter = container.find(key);
    return iter!=container.end();
}
</code>```

Note: This is not an actual function I'm using, but just something silly that demonstrates the problem.

答:
It should be noted that the value/type kinding issue is not the fundamental problem. The primary issue is parsing. Consider

```<code>template<class T>
void f() { (T::x)(1); }
</code>```

There is no way to tell if this is a cast or a function call unless the typename keyword is mandatory. In that case, the above code contains a function call. In general the choice cannot be delayed without forgoing parsing altogether, just consider fragment

```<code>(a)(b)(c)
</code>```

In case you didn't remember, cast has a higher precedence than function call in C, one reason Bjarne wanted function style casts. It is therefore not possible to tell if the above means

```<code>(a)(b)  (c)   // a is a typename
</code>```

or

```<code>(a) (b)(c)    // a is not a typename , b is
</code>```

or

```<code>(a)(b) (c)    // neither a nor b is a typename
</code>```

where I inserted space to indicate grouping.

Note also "templatename" keyword is required for the same reason as "typename", you can't parse things without knowing their kind in C/C++.

OwnerDisplayName: Robert Gould

Body:
It had been a while since GCC caught me with this one, but it just happened today. But I've never understood why GCC requires typedef typename within templates, while VS and I guess ICC don't. Is the typedef typename thing a "bug" or an overstrict standard, or something that is left up to the compiler writers?

For those who don't know what I mean here is a sample:

template<typename KEY, typename VALUE>
bool find(const std::map<KEY,VALUE>& container, const KEY& key)
{
    std::map<KEY,VALUE>::const_iterator iter = container.find(key);
    return iter!=container.end();
}

The above code compiles in VS (and probably in ICC), but fails in GCC because it wants it like this:

template<typename KEY, typename VALUE>
bool find(const std::map<KEY,VALUE>& container, const KEY& key)
{
    typedef typename std::map<KEY,VALUE>::const_iterator iterator; //typedef typename
    iterator iter = container.find(key);
    return iter!=container.end();
}

Note: This is not an actual function I'm using, but just something silly that demonstrates the problem.

LastEditorDisplayName: Robert Gould

Body:
It should be noted that the value/type kinding issue is not the fundamental problem. The primary issue is parsing. Consider

template<class T>
void f() { (T::x)(1); }

There is no way to tell if this is a cast or a function call unless the typename keyword is mandatory. In that case, the above code contains a function call. In general the choice cannot be delayed without forgoing parsing altogether, just consider fragment

(a)(b)(c)

In case you didn't remember, cast has a higher precedence than function call in C, one reason Bjarne wanted function style casts. It is therefore not possible to tell if the above means

(a)(b)  (c)   // a is a typename

or

(a) (b)(c)    // a is not a typename , b is

or

(a)(b) (c)    // neither a nor b is a typename

where I inserted space to indicate grouping.

Note also "templatename" keyword is required for the same reason as "typename", you can't parse things without knowing their kind in C/C++.


问:
sending message in a skype group conversation through vc#
How can I send the message in a group conversation of skype chat through vc#.

Though I have included the skype reference in my application and can get some chats.

Thanks.

答:
You need a reference to an IChat interface.

You can get such a reference using ISkype.Chat property.

Once you have the IChat reference it is just a matter of calling SendMessage() method.

If you like to you can take a look in a Skype plugin I wrote here. (You don't need to understand the whole application of course. Just take a look in Application class defined in Application.cs)

[Edited]

Some sample code

```<code>using System;
using System.Windows.Forms;
using SKYPE4COMLib;

namespace SkypeClient
{
    public partial class Form1 : Form
    {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                 ISkype skype = new SkypeClass();
                 skype.Attach(5, true);

                 int count = skype.Chats.Count;
                 textBox1.Text = "Count: " + count + "\r\n";
                 foreach (IChat chat in skype.Chats)
                 {
                    textBox1.Text +=  "\r\n"  + chat.FriendlyName;
                 }
            }
       }
 }
</code>```

Hope this helps.

Body:
You need a reference to an IChat interface.

You can get such a reference using ISkype.Chat property.

Once you have the IChat reference it is just a matter of calling SendMessage() method.

If you like to you can take a look in a Skype plugin I wrote here. (You don't need to understand the whole application of course. Just take a look in Application class defined in Application.cs)

[Edited]

Some sample code

using System;
using System.Windows.Forms;
using SKYPE4COMLib;

namespace SkypeClient
{
    public partial class Form1 : Form
    {
            public Form1()
            {
                InitializeComponent();
            }

            private void button1_Click(object sender, EventArgs e)
            {
                 ISkype skype = new SkypeClass();
                 skype.Attach(5, true);

                 int count = skype.Chats.Count;
                 textBox1.Text = "Count: " + count + "\r\n";
                 foreach (IChat chat in skype.Chats)
                 {
                    textBox1.Text +=  "\r\n"  + chat.FriendlyName;
                 }
            }
       }
 }

Hope this helps.


问:
Javascript - dumping all global variables
Is there a way in Javascript to get a list or dump the contents of all global variables declared by Javascript/jQuery script on a page? I am particularly interested in arrays. If I can get the array names, it will be enough to me. Seeing its values is a bonus.</p>

答: You can use npm package called get-globals. It compares properties of window with fresh-created iframe to print only variables declared by dev(s), not browser vendor.


问:
Missing IN or OUT parameter at index:: 3
I am new in programming world. I tried to make a simple login however, I  getting this error:

missing IN or OUT parameter at index:: 3

I've tried to find the answer but I still can't recognize the problem in my coding.

Here is my LoginServlet

```<code>package apl;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import apl.LoginDao;

public class LoginServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String i=request.getParameter("sid");
        String n=request.getParameter("sname");
        String p=request.getParameter("sphone");
        String u=request.getParameter("susername");
        String w=request.getParameter("spassword");

        HttpSession session = request.getSession(true);
        if(session!=null)
        session.setAttribute("sid", i);

        if(LoginDao.validate(i,n,p,u,w)){
            RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
            rd.forward(request,response);
        }
        else{
            out.print("<p style=\"color:red\">Sorry username or password incorrect</p>");
            RequestDispatcher rd=request.getRequestDispatcher("login.jsp");
            rd.include(request,response);
        }

        out.close();
    }
}
</code>```

Here is my LoginDao

```<code>package apl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginDao {

        public static boolean validate(String sid, String sname, String sphone, String susername, String spassword) {

            boolean status = false;
            Connection conn = null;
            PreparedStatement pst = null;
            ResultSet rs = null;

            String driver = "oracle.jdbc.driver.OracleDriver";

            try {
                Class.forName(driver).newInstance();
                conn = DriverManager
                        .getConnection("jdbc:oracle:thin:@localhost:1521:xe","apl","system");

                pst = conn.prepareStatement("select * from SELLER where sid=?,sname=?,sphone=?,susername=? and spassword=?");

                pst.setString(1, sid);
                pst.setString(2, sname);
                pst.setString(3, sphone);
                pst.setString(4, susername);
                pst.setString(5, spassword);

                rs = pst.executeQuery();

                status = rs.next();

            } catch (Exception e) {
                System.out.println(e);
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (pst != null) {
                    try {
                        pst.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
            return status;
        }
    }
</code>```

Here is my jsp file

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
</head>
<body>
    <form action="LoginServlet" method="post">
        <fieldset style="width: 300px">
            <legend> Login to App </legend>
            <table>
               <tr>
                    <td>Id</td>
                    <td><input type="text" name="sid" required="required" /></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="text" name="sname" required="required" /></td>
                </tr>
                <tr>
                    <td>Phone</td>
                    <td><input type="text" name="sphone" required="required" /></td>
                </tr>
                <tr>
                    <td>User name</td>
                    <td><input type="text" name="susername" required="required" /></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="spassword" required="required" /></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Login" /></td>
                </tr>
            </table>
        </fieldset>
    </form>
</body>
</html>
</code>```

web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>apl.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</code>```

答:
In your SQL where clause, and operator is missing, so you need to add it as shown below:

```<code>pst = conn.prepareStatement("select * from SELLER where sid=?
 and sname=? and sphone=? and susername=? and spassword=?")
</code>```

Body:
I am new in programming world. I tried to make a simple login however, I  getting this error:

missing IN or OUT parameter at index:: 3

I've tried to find the answer but I still can't recognize the problem in my coding.

Here is my LoginServlet

package apl;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import apl.LoginDao;

public class LoginServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String i=request.getParameter("sid");
        String n=request.getParameter("sname");
        String p=request.getParameter("sphone");
        String u=request.getParameter("susername");
        String w=request.getParameter("spassword");

        HttpSession session = request.getSession(true);
        if(session!=null)
        session.setAttribute("sid", i);

        if(LoginDao.validate(i,n,p,u,w)){
            RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
            rd.forward(request,response);
        }
        else{
            out.print("
Sorry username or password incorrect
");
            RequestDispatcher rd=request.getRequestDispatcher("login.jsp");
            rd.include(request,response);
        }

        out.close();
    }
}

Here is my LoginDao

package apl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginDao {

        public static boolean validate(String sid, String sname, String sphone, String susername, String spassword) {

            boolean status = false;
            Connection conn = null;
            PreparedStatement pst = null;
            ResultSet rs = null;

            String driver = "oracle.jdbc.driver.OracleDriver";

            try {
                Class.forName(driver).newInstance();
                conn = DriverManager
                        .getConnection("jdbc:oracle:thin:@localhost:1521:xe","apl","system");

                pst = conn.prepareStatement("select * from SELLER where sid=?,sname=?,sphone=?,susername=? and spassword=?");

                pst.setString(1, sid);
                pst.setString(2, sname);
                pst.setString(3, sphone);
                pst.setString(4, susername);
                pst.setString(5, spassword);

                rs = pst.executeQuery();

                status = rs.next();

            } catch (Exception e) {
                System.out.println(e);
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (pst != null) {
                    try {
                        pst.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (rs != null) {
                    try {
                        rs.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
            return status;
        }
    }

Here is my jsp file

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>

    <form action="LoginServlet" method="post">
        <fieldset style="width: 300px">
            <legend> Login to App </legend>

                    Id
                    <input type="text" name="sid" required="required" />

                    Password
                    <input type="text" name="sname" required="required" />

                    Phone
                    <input type="text" name="sphone" required="required" />

                    User name
                    <input type="text" name="susername" required="required" />

                    Password
                    <input type="password" name="spassword" required="required" />

                    <input type="submit" value="Login" />

        </fieldset>
    </form>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>apl.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

Body:
In your SQL where clause, and operator is missing, so you need to add it as shown below:

pst = conn.prepareStatement("select * from SELLER where sid=?
 and sname=? and sphone=? and susername=? and spassword=?")


问:
UITextView - Setting max lines hides the cursor
This is what I am doing to set max number of lines :

```<code>self.text_description.textContainer.maximumNumberOfLines = 2
self.text_description.layoutManager.textContainerChangedGeometry(self.text_description.textContainer)
</code>```

When 3rd line is about to get started, the cursor disappears. To put it back I have to tap backspace.

答:
Assuming, in the text view cursor doesn't stays behind the keyboard. I have written a helper method that makes UITextField text scroll to end of text.</p>

```<code>- (void)scrollToCaretInTextView:(UITextView *)textView animated:(BOOL)animated
{
    CGRect rect = [textView caretRectForPosition:textView.selectedTextRange.end]; //Get the content size of textview
    rect.size.height += textView.textContainerInset.bottom;
    [textView scrollRectToVisible:rect animated:animated];
}
</code>```

Body:
This is what I am doing to set max number of lines :

self.text_description.textContainer.maximumNumberOfLines = 2
self.text_description.layoutManager.textContainerChangedGeometry(self.text_description.textContainer)

When 3rd line is about to get started, the cursor disappears. To put it back I have to tap backspace.

Body:
Assuming, in the text view cursor doesn't stays behind the keyboard. I have written a helper method that makes UITextField text scroll to end of text.

- (void)scrollToCaretInTextView:(UITextView *)textView animated:(BOOL)animated
{
    CGRect rect = [textView caretRectForPosition:textView.selectedTextRange.end]; //Get the content size of textview
    rect.size.height += textView.textContainerInset.bottom;
    [textView scrollRectToVisible:rect animated:animated];
}


问:
How to get the background-color value of an  tag with one line of code?
I have variables $e and $x:

```<code>$e="<a class="ui small interactive circular label" style="background-color:#4bbedd;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue">"

$x="<a class="ui small interactive circular label" style="background-color:#F27EB2;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Azalea">"
</code>```

I need the string #4bbedd, not searching by "#4bbedd" in $e and #F27EB2 in $x.

Step by step: First I need to get string before the ;vertical word and that string is "class="ui small interactive circular label" style="background-color:#4bbedd"

Then I need to get string after the color: word and I got my value only  using PHP function and only in one line of code to get from both variables

I need to change only the variable name that contain string like $e then $x, the line logic should be like this:

```<code>$var = $e.functionForFindStringBeforThisWord(";vertical").functionForFindStringAfterThisWord("color:")
</code>```

or is there another way that has only one line code?

答:
Are you expecting this?

PHP code demo

```<code><?php
$e='<a class="ui small interactive circular label" style="background-color:#4bbedd;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue">';
echo $var=  explode(":",explode(";",$e)[0])[1];
</code>```

Title: How to get the background-color value of an <a> tag with one line of code?

Body:
I have variables $e and $x:

$e=""

$x=""

I need the string #4bbedd, not searching by "#4bbedd" in $e and #F27EB2 in $x.

Step by step: First I need to get string before the ;vertical word and that string is "<a class="ui small interactive circular label" style="background-color:#4bbedd"

Then I need to get string after the color: word and I got my value only  using PHP function and only in one line of code to get from both variables

I need to change only the variable name that contain string like $e then $x, the line logic should be like this:

$var = $e.functionForFindStringBeforThisWord(";vertical").functionForFindStringAfterThisWord("color:")

or is there another way that has only one line code?

Body:
Are you expecting this?

PHP code demo

<?php
$e='<a class="ui small interactive circular label" style="background-color:#4bbedd;vertical-align:middle;" data-reactid=".0.1.1.1.3.0.0.1.1.1.1.0.$Aquatic Blue">';
echo $var=  explode(":",explode(";",$e)[0])[1];


问:
Why DATA is COPIED and not MOVED while loading data from local filesystem Hive hadoop
When we use following command:

```<code>Load data local inpath "mypath"
</code>```

why the data is copied from local filesystem into HDFS and not moved?

答:
Since you are moving data between 2 different file systems (sh + HDFS) this cannot be a metadata operation as in non-local load.
The data itself should be copied.

Theoretically this command could also initiate a deletion command of the source file, but what for?

Body:
When we use following command:

Load data local inpath "mypath"

why the data is copied from local filesystem into HDFS and not moved?


问:
Underscore.js - Check if Object Array contains value
I have the following Object and I want to check if Type.ID contains value 6508 :

```<code> {
   "item": {
      "Feature": [
         {
            "ID": 85408,
            "Status": {
                "ID": 65,
             },
             "Type": {
                 "ID": 6508,
                  "Volume": null
              },
              "Manufacturer": null
          },
          {
             "ID": 85409,
             "Status": {
                 "ID": 65,
              },
              "Type": {
                  "ID": 6509,
                   "Volume": null
              },
              "Manufacturer": null
          }
       ],
       "Errors": {
           "Result": 0,
           "Message": ""
        },
       "RecordCount": 2
      }
 }
</code>```

I can muster the following:

```<code>for (i = 0; i < data.item.Feature.length; i++) {
     if (data.item.Feature[i].Type.ID == 6508)
        return true;
}
return false;
</code>```

How can I use underscore.js to do the same? The following doesn't work?

```<code>_.contains(data.item.Feature.Type.ID, 6508)
</code>```

答:
You don't need underscore for this; example in plain JS.</p>

```<code>data.item.Feature.some(function(x) { return x.Type.ID === 6508 });
</code>```

Body:
I have the following Object and I want to check if Type.ID contains value 6508 :

 {
   "item": {
      "Feature": [
         {
            "ID": 85408,
            "Status": {
                "ID": 65,
             },
             "Type": {
                 "ID": 6508,
                  "Volume": null
              },
              "Manufacturer": null
          },
          {
             "ID": 85409,
             "Status": {
                 "ID": 65,
              },
              "Type": {
                  "ID": 6509,
                   "Volume": null
              },
              "Manufacturer": null
          }
       ],
       "Errors": {
           "Result": 0,
           "Message": ""
        },
       "RecordCount": 2
      }
 }

I can muster the following:

for (i = 0; i < data.item.Feature.length; i++) {
     if (data.item.Feature[i].Type.ID == 6508)
        return true;
}
return false;

How can I use underscore.js to do the same? The following doesn't work?

_.contains(data.item.Feature.Type.ID, 6508)

Body:
You don't need underscore for this; example in plain JS.

data.item.Feature.some(function(x) { return x.Type.ID === 6508 });


问:
Sum rows on basis of current and next row
I have an input in following format:

I have to find the difference of the stop of current row and the start of next row, and if the difference is less than 25, i need to sum the values in [TimeDiff_Start_Stop]. If the difference is more than 25 i do not need to do the sum.

As in the above image, difference

between Stop of Row 1 and Start of Row 2 is 13,
between Stop of Row 2 and Start of Row 3 is 2,
between Stop of Row 3 and Start of Row 4 is 1,
between Stop of Row 4 and Start of Row 5 is 3,
between Stop of Row 5 and Start of Row 6 is 8,

but the difference between Stop of Row 6 and Start of Row 7 is 37,
therefore only [TimeDiff_Start_Stop] of first 6 rows is summed up, producing the row 1 in output.

Moving further difference between Stop of Row 7 and Start of Row 8 is 20,
therefore [TimeDiff_Start_Stop] of row 7 and row 8 is summed up, producing the row 2 in output.

Required output

How should i achieve this ?

Please find below scripts for input and output:

Input:

```<code>select 'Sample' as COL1,'1' AS COL2,1 as 'RN','2016-05-09 02:45:18.239669' AS Start,'2016-05-09 02:45:25.837316' as Stop,7 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,2 as 'RN','2016-05-09 02:45:38.809919' AS Start,'2016-05-09 02:46:59.856081' as Stop,81 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,3 as 'RN','2016-05-09 02:47:01.831128' AS Start,'2016-05-09 02:48:55.211807' as Stop,114 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,4 as 'RN','2016-05-09 02:48:56.305736' AS Start,'2016-05-09 02:50:06.107262' as Stop,70 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,5 as 'RN','2016-05-09 02:50:09.269354' AS Start,'2016-05-09 02:50:16.081159' as Stop,7 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,6 as 'RN','2016-05-09 02:50:24.819440' AS Start,'2016-05-09 02:51:04.736300' as Stop,40 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,7 as 'RN','2016-05-09 02:51:41.029165' AS Start,'2016-05-09 02:54:04.186215' as Stop,143 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,8 as 'RN','2016-05-09 02:54:24.537167' AS Start,'2016-05-09 02:55:26.926029' as Stop,62 as TimeDiff_Start_Stop
</code>```

Output:

```<code>select 'Sample' as COL1,'1' AS COL2,'2016-05-09 02:45:18.239669' AS Start,'2016-05-09 02:51:04.736300' as Stop,319 as Time
union
select 'Sample' as COL1,'1' AS COL2,'2016-05-09 02:51:41.029165' AS Start,'2016-05-09 02:55:26.926029' as Stop,205 as Time
</code>```

答:
Here are 2 different approaches - for this, I created a table @t and used your sample data to populate it - thanks for proving those. Here's the table definition:

```<code>declare @t table (col1 varchar(10), col2 int, rn int, start datetime2, stop datetime2, timediff_start_stop int)
insert into @t ... (from the OP)
</code>```

Here's an approach using a CTE. First, it creates a CTE that just adds the diff (using LEAD to get the difference between current row stop/next row start) as a column.

Note the isnull statement in the CTE query gives a value of 26 to a null if there's no following row - this means the last row in the result set with get a value of 26 (> 25, so will match the criteria of a row that should be an end time in the result set).

```<code>;with tdiff (col1, col2, rn, start, stop, timediff_start_stop, diff, timediff)
as
(
select col1, col2, rn, start, stop, timediff_start_stop, isnull(datediff(ss, stop, lead(start) over (order by rn)), 26) as diff, datediff(ss, start, stop)
from @t
)
select t1.col1, t1.col2, t1.start, (select min(stop) from tdiff where stop > t1.start and diff > 25) as stop,
    (select sum(timediff_start_stop) from tdiff where start >= t1.start and stop <= (select min(stop) from tdiff where stop > t1.start and diff > 25)) AS TIME
from tdiff t1
left join tdiff t2 on (t1.rn - 1) = t2.rn
where t1.rn = 1 or t2.diff > 25
</code>```

Next, here's a completely different solution using cursors. Cursors are inefficient and not well suited to frequently-run tasks, but I find them easy to maintain and follow as a developer, and think it may be useful for some who need to run infrequent or one-time tasks that are suitable for cursors:

```<code>declare @outputtable table (start datetime, stop datetime)
declare @curstart datetime, @curstop datetime, @curdiff int
declare @outputstart datetime

DECLARE cur CURSOR FOR
select start, stop, datediff(ss, stop, LEAD(start) over (order by rn))
from @t
OPEN cur

FETCH NEXT FROM cur
INTO @curstart, @curstop, @curdiff

WHILE @@FETCH_STATUS = 0
BEGIN
    if (@outputstart is null)
        set @outputstart = @curstart

    if (@curdiff > 25)
    begin
        insert into @outputtable values (@outputstart, @curstop)
        set @outputstart = null
    end

    FETCH NEXT FROM cur
    INTO @curstart, @curstop, @curdiff
END
CLOSE cur;
DEALLOCATE cur;

insert into @outputtable values (@outputstart, @curstop)

select * from @outputtable
</code>```

Body:
I have an input in following format:

I have to find the difference of the stop of current row and the start of next row, and if the difference is less than 25, i need to sum the values in [TimeDiff_Start_Stop]. If the difference is more than 25 i do not need to do the sum.

As in the above image, difference

between Stop of Row 1 and Start of Row 2 is 13,
between Stop of Row 2 and Start of Row 3 is 2,
between Stop of Row 3 and Start of Row 4 is 1,
between Stop of Row 4 and Start of Row 5 is 3,
between Stop of Row 5 and Start of Row 6 is 8,

but the difference between Stop of Row 6 and Start of Row 7 is 37,
therefore only [TimeDiff_Start_Stop] of first 6 rows is summed up, producing the row 1 in output.

Moving further difference between Stop of Row 7 and Start of Row 8 is 20,
therefore [TimeDiff_Start_Stop] of row 7 and row 8 is summed up, producing the row 2 in output.

Required output

How should i achieve this ?

Please find below scripts for input and output:

Input:

select 'Sample' as COL1,'1' AS COL2,1 as 'RN','2016-05-09 02:45:18.239669' AS Start,'2016-05-09 02:45:25.837316' as Stop,7 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,2 as 'RN','2016-05-09 02:45:38.809919' AS Start,'2016-05-09 02:46:59.856081' as Stop,81 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,3 as 'RN','2016-05-09 02:47:01.831128' AS Start,'2016-05-09 02:48:55.211807' as Stop,114 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,4 as 'RN','2016-05-09 02:48:56.305736' AS Start,'2016-05-09 02:50:06.107262' as Stop,70 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,5 as 'RN','2016-05-09 02:50:09.269354' AS Start,'2016-05-09 02:50:16.081159' as Stop,7 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,6 as 'RN','2016-05-09 02:50:24.819440' AS Start,'2016-05-09 02:51:04.736300' as Stop,40 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,7 as 'RN','2016-05-09 02:51:41.029165' AS Start,'2016-05-09 02:54:04.186215' as Stop,143 as TimeDiff_Start_Stop
union
select 'Sample' as COL1,'1' AS COL2,8 as 'RN','2016-05-09 02:54:24.537167' AS Start,'2016-05-09 02:55:26.926029' as Stop,62 as TimeDiff_Start_Stop

Output:

select 'Sample' as COL1,'1' AS COL2,'2016-05-09 02:45:18.239669' AS Start,'2016-05-09 02:51:04.736300' as Stop,319 as Time
union
select 'Sample' as COL1,'1' AS COL2,'2016-05-09 02:51:41.029165' AS Start,'2016-05-09 02:55:26.926029' as Stop,205 as Time

Body:
Here are 2 different approaches - for this, I created a table @t and used your sample data to populate it - thanks for proving those. Here's the table definition:

declare @t table (col1 varchar(10), col2 int, rn int, start datetime2, stop datetime2, timediff_start_stop int)
insert into @t ... (from the OP)

Here's an approach using a CTE. First, it creates a CTE that just adds the diff (using LEAD to get the difference between current row stop/next row start) as a column.

Note the isnull statement in the CTE query gives a value of 26 to a null if there's no following row - this means the last row in the result set with get a value of 26 (> 25, so will match the criteria of a row that should be an end time in the result set).

;with tdiff (col1, col2, rn, start, stop, timediff_start_stop, diff, timediff)
as
(
select col1, col2, rn, start, stop, timediff_start_stop, isnull(datediff(ss, stop, lead(start) over (order by rn)), 26) as diff, datediff(ss, start, stop)
from @t
)
select t1.col1, t1.col2, t1.start, (select min(stop) from tdiff where stop > t1.start and diff > 25) as stop,
    (select sum(timediff_start_stop) from tdiff where start >= t1.start and stop <= (select min(stop) from tdiff where stop > t1.start and diff > 25)) AS TIME
from tdiff t1
left join tdiff t2 on (t1.rn - 1) = t2.rn
where t1.rn = 1 or t2.diff > 25

Next, here's a completely different solution using cursors. Cursors are inefficient and not well suited to frequently-run tasks, but I find them easy to maintain and follow as a developer, and think it may be useful for some who need to run infrequent or one-time tasks that are suitable for cursors:

declare @outputtable table (start datetime, stop datetime)
declare @curstart datetime, @curstop datetime, @curdiff int
declare @outputstart datetime

DECLARE cur CURSOR FOR
select start, stop, datediff(ss, stop, LEAD(start) over (order by rn))
from @t
OPEN cur

FETCH NEXT FROM cur
INTO @curstart, @curstop, @curdiff

WHILE @@FETCH_STATUS = 0
BEGIN
    if (@outputstart is null)
        set @outputstart = @curstart

    if (@curdiff > 25)
    begin
        insert into @outputtable values (@outputstart, @curstop)
        set @outputstart = null
    end

    FETCH NEXT FROM cur
    INTO @curstart, @curstop, @curdiff
END
CLOSE cur;
DEALLOCATE cur;

insert into @outputtable values (@outputstart, @curstop)

select * from @outputtable


问:
update image on codeigniter

I'm stuck from make a update image from codeigniter, i want replace image when i update it but, the code its doesn't work.
here is my code :

this is Controller :

```<code>public function updatefoto(){
     $this->load->model('model_users');
    $this->model_users->updatefoto();

}
</code>```

This is The Model

```<code>public function updatefoto($userId){

    if($this->input->post('submit')){
         $config['upload_path']    = "./uploads/images/";
         $config['allowed_types']  = 'gif|jpg|png|jpeg';
         $config['max_size']       = '2000';
         $config['max_width']      = '2000';
         $config['max_height']     = '2000';
         $config['file_name']      = 'gambar-'.trim(str_replace(" ","",date('dmYHis')));
         $this->load->library('upload', $config);

        if (!$this->upload->do_upload("gambar")) {
             $error = array('error' => $this->upload->display_errors('<div class="alert alert-danger"><a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>','</div>'));

            $this->load->view('view_ubah_data-profile', $error);
        }else{
           $nama=$this->upload->data('file_name');
           $this->db->where('id', $userId);
           $this->db->update('foto',array('nama_foto'=>$nama));

           redirect('view_ubah_data-profile','refresh');
        }
       }
   }
</code>```

and the last is view

```<code>          <div class="col-md-4 col-sm-6 col-xs-12">
        <form action="users/updatefoto" method="post" id="updateUserImage">
          <div class="text-center">

            <img src="<?php echo base_url();?>uploads/images/<?php echo $userData['nama_foto']  ?>" cclass="img-thumbnail" alt="avatar">
            <h6>Upload a different photo...</h6>
            <input type="file" class="text-center center-block well well-sm" name="gambar" id="files" accept="image/*" required>
            <button type="submit" value="Upload" name="submit" class="btn btn-primary">
            <i class="fa fa-upload" aria-hidden="true"></i>upload
          </button>
          </div>
        </form>
      </div>
</code>```

Thanks I appreciate any help :)

答:
Here is how I do it.

Edit- Class Construct

```<code>class Team extends CI_Controller {
 function __construct()
 {
    parent::__construct();
    $this->load->library('form_validation');
    $this->load->helper(array('form', 'url'));
    $this->load->model('team_model');
 }

 public function do_upload()
 {
    $config['upload_path']          = './uploads/';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['max_size']             = 100;
    $config['max_width']            = 1024;
    $config['max_height']           = 768;

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload('userfile1'))
    {
        $data['errors'] = array('error' => $this->upload->display_errors());
        $data['client_Id']=$this->team_model->getUserId($email);
        $data['pic']=$this->team_model->getImage($data['client_Id']['id']);
        // Here I load my Views
    }
    else
    {
        $upload_data = $this->upload->data();
        $file_name=$upload_data['file_name'];
        $email=$this->session->userdata['email'];
        $data['client_Id']=$this->team_model->getUserId($email);
        $data['pic']=$this->team_model->getImage($data['client_Id']['id']);
        // If there is no image insert one other wise update
        if($data['pic']['image']!=''){
            $this->team_model->updateEmployeeImage($data['pic']['id'],$file_name);
            $data['success']='Congratulations! Image Updated Successfully';
        }else{
            $this->team_model->InsertEmployeeImage($data['client_Id']['id'],$file_name);
            $data = array('upload_data' => $this->upload->data());
            $data['success']='Congratulations! Image Uploaded Successfully';
        }
        $file_name=$upload_data['file_name'];
        $email=$this->session->userdata['email'];
        $data['client_Id']=$this->team_model->getUserId($email);
        $data['pic']=$this->team_model->getImage($data['client_Id']['id']);

        // Here I load my Views
    }
 }
}
</code>```

Edit- Model Functions

```<code>public function InsertEmployeeImage($id,$image){
    $Image=array(
        'id'                    => '',
        'team_id'             => $id,
        'image'                 => $image
    );
    $this->db->insert('teams_image',$Image);
    return ;
}

public function updateEmployeeImage($id,$img){
     $this->deleteOldImage($id);
     $pic=array(
        'image'      =>  $img
    );
    $this->db->WHERE('id',$id)->update('teams_image',$pic);
}
</code>```

Title: update image on codeigniter

Body:
I'm stuck from make a update image from codeigniter, i want replace image when i update it but, the code its doesn't work.
here is my code :

this is Controller :

public function updatefoto(){
     $this->load->model('model_users');
    $this->model_users->updatefoto();

}

This is The Model

public function updatefoto($userId){

    if($this->input->post('submit')){
         $config['upload_path']    = "./uploads/images/";
         $config['allowed_types']  = 'gif|jpg|png|jpeg';
         $config['max_size']       = '2000';
         $config['max_width']      = '2000';
         $config['max_height']     = '2000';
         $config['file_name']      = 'gambar-'.trim(str_replace(" ","",date('dmYHis')));
         $this->load->library('upload', $config);

        if (!$this->upload->do_upload("gambar")) {
             $error = array('error' => $this->upload->display_errors('
×','
'));

            $this->load->view('view_ubah_data-profile', $error);
        }else{
           $nama=$this->upload->data('file_name');
           $this->db->where('id', $userId);
           $this->db->update('foto',array('nama_foto'=>$nama));

           redirect('view_ubah_data-profile','refresh');
        }
       }
   }

and the last is view

        <form action="users/updatefoto" method="post" id="updateUserImage">

            <img src="<?php echo base_url();?>uploads/images/<?php echo $userData['nama_foto']  ?>" cclass="img-thumbnail" alt="avatar">

Upload a different photo...

            <input type="file" class="text-center center-block well well-sm" name="gambar" id="files" accept="image/*" required>
            <button type="submit" value="Upload" name="submit" class="btn btn-primary">
            upload
          </button>

        </form>

Thanks I appreciate any help :)

Body:
Here is how I do it.

Edit- Class Construct

class Team extends CI_Controller {
 function __construct()
 {
    parent::__construct();
    $this->load->library('form_validation');
    $this->load->helper(array('form', 'url'));
    $this->load->model('team_model');
 }

 public function do_upload()
 {
    $config['upload_path']          = './uploads/';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['max_size']             = 100;
    $config['max_width']            = 1024;
    $config['max_height']           = 768;

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload('userfile1'))
    {
        $data['errors'] = array('error' => $this->upload->display_errors());
        $data['client_Id']=$this->team_model->getUserId($email);
        $data['pic']=$this->team_model->getImage($data['client_Id']['id']);
        // Here I load my Views
    }
    else
    {
        $upload_data = $this->upload->data();
        $file_name=$upload_data['file_name'];
        $email=$this->session->userdata['email'];
        $data['client_Id']=$this->team_model->getUserId($email);
        $data['pic']=$this->team_model->getImage($data['client_Id']['id']);
        // If there is no image insert one other wise update
        if($data['pic']['image']!=''){
            $this->team_model->updateEmployeeImage($data['pic']['id'],$file_name);
            $data['success']='Congratulations! Image Updated Successfully';
        }else{
            $this->team_model->InsertEmployeeImage($data['client_Id']['id'],$file_name);
            $data = array('upload_data' => $this->upload->data());
            $data['success']='Congratulations! Image Uploaded Successfully';
        }
        $file_name=$upload_data['file_name'];
        $email=$this->session->userdata['email'];
        $data['client_Id']=$this->team_model->getUserId($email);
        $data['pic']=$this->team_model->getImage($data['client_Id']['id']);

        // Here I load my Views
    }
 }
}

Edit- Model Functions

public function InsertEmployeeImage($id,$image){
    $Image=array(
        'id'                    => '',
        'team_id'             => $id,
        'image'                 => $image
    );
    $this->db->insert('teams_image',$Image);
    return ;
}

public function updateEmployeeImage($id,$img){
     $this->deleteOldImage($id);
     $pic=array(
        'image'      =>  $img
    );
    $this->db->WHERE('id',$id)->update('teams_image',$pic);
}


问:
Debug VSIX created in VS 2017 using the VS 2015 Experimental Instance
I have a VISX package that I compile using VS 2017. The package applies to VS 2015 & 2017 (it happily installs and runs in a production environment on both version of VS).

When I debug the project in VS 2017, it launches the VS 2017 experimental instance. However, I would like to be able to debug it using the VS 2015 experimental instance.

How do I install my VSIX into the VS 2015 experimental instance?

答:
Since once the extension is built it is deployed to the Visual Studio Experimental Instance of the version whose SDK was used to build the project, you need to remove the NuGet package Microsoft.VSSDK.BuildTools version 15.0 and use version 14.0 for Visual Studio 2015.

You need to go to the Properties page of the project, Debug tab, and set the Start external program field to the “C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe” executable of Visual Studio 2015.


问:
Unable to scroll using swipe() in Appium
I am unable to scroll down in Android using Appium.

Code:

```<code>driver.swipe(0, 0, 450, 250, 2000);
</code>```

Environment:

Appium Version: 1.4.16.1

Android Version: 6.1

Java Version: 1.8.0_91

Selenium: selenium-server-standalone-2.48.2

Java Client: java-client-3.2.0

Error:

org.openqa.selenium.WebDriverException: Not yet implemented. Please
  help us: http://appium.io/get-involved.html

Please let me know if there are any alternative ways to scroll.

答:
Do you have a maven project?
Please update appium server: https://github.com/appium/appium-desktop

and your java-client to 4.1.2 (or even 5.0-BETA6)

For correct scrolling like a real user swiping in the middle of the screen, use this function (you can change it according to your needs):

```<code>public void scrollDown() {
        Dimension size = driver.manage().window().getSize();
        int starty = (int) (size.height * 0.7);
        int endy = (int) (size.height * 0.2);
        int startx = size.height / 2;
        driver.swipe(startx, starty, startx, endy, 800);
    }
</code>```

Body:
I am unable to scroll down in Android using Appium.

Code:

driver.swipe(0, 0, 450, 250, 2000);

Environment:

Appium Version: 1.4.16.1

Android Version: 6.1

Java Version: 1.8.0_91

Selenium: selenium-server-standalone-2.48.2

Java Client: java-client-3.2.0

Error:

org.openqa.selenium.WebDriverException: Not yet implemented. Please
  help us: http://appium.io/get-involved.html

Please let me know if there are any alternative ways to scroll.

Body:
Do you have a maven project?
Please update appium server: https://github.com/appium/appium-desktop

and your java-client to 4.1.2 (or even 5.0-BETA6)

For correct scrolling like a real user swiping in the middle of the screen, use this function (you can change it according to your needs):

public void scrollDown() {
        Dimension size = driver.manage().window().getSize();
        int starty = (int) (size.height * 0.7);
        int endy = (int) (size.height * 0.2);
        int startx = size.height / 2;
        driver.swipe(startx, starty, startx, endy, 800);
    }


问:
WPF Binding StringFormat Short Date String
I would like to use Short Date named string format in WPF.

I tried something like:

```<code><TextBlock Text="{Binding Date, StringFormat='Short Date'}" />
</code>```

How to do this?

答:
If you want add a string with the value use this:</p>

```<code><TextBlock Text="{Binding Date, StringFormat= 'Date : {0:d}'}" />
</code>```

Body:
I would like to use Short Date named string format in WPF.

I tried something like:

<TextBlock Text="{Binding Date, StringFormat='Short Date'}" />

How to do this?

Body:
If you want add a string with the value use this:

<TextBlock Text="{Binding Date, StringFormat= 'Date : {0:d}'}" />