问:
Building common dependencies with docker-compose
Assuming I have a set of images which depend on a common base image:

base (this is only a set of common dependencies)

FROM ubuntu:16.04

ENV FOO 1
```</li>
<li><p>child1</p>

<pre class="lang-sh prettyprint-override"><code>FROM mybaseimage  # where mybaseimage corresponds to base

CMD ["bar1_command"]
</code>```

child2

FROM mybaseimage  # where mybaseimage corresponds to base

CMD ["bar2_command"]
```</li>
</ul>

<p>Is it possible to create <code>docker-compose</code> file which would build <code>base</code> without running it? Lets say I have following dependencies:</p>

```version: '2'
services:
    child1:
        build: ./path-to-child1-dockerfile
services:
    child2:
        build: ./path-to-child2-dockerfile
    depends_on:
        - child1
```

<p>I would like <code>base</code> to be build even if it is not explicitly started. Is something like this even possible? Or should I simply use external Makefile to build dependencies?</p>

```build_base:
    docker build -t mybaseimage mybaseimage

build_all: build_base
    docker-compose build
```

答:
It's possible. There's a kind of workaround. You're close, but you were missing explicit image tags (so you had little ability on child images to declare which image you inherited from).

version: '3.2'
services:
  base:
    image: mybaseimage
    build: ./path-to-base-dockerfile
  child1:
    build: ./path-to-child1-dockerfile
    depends_on:
      - base
  child2:
    build: ./path-to-child2-dockerfile
    depends_on:
      - base
```

Let's say you have no images built. You run docker-compose up. The following things will happen:

docker-compose sees that child1 and child2 services depend on base. So it will deploy base first.

docker-compose sees that you have not yet tagged any image as mybaseimage. It knows how to build mybaseimage (you gave it a build path), so it will build it now, and tag it as mybaseimage.

docker-compose deploys the base service.

ideally you should design base so that it quits immediately, or has no entrypoint. since we don't actually want it to run this service.

docker-compose considers deploying child1 and child2

docker-compose sees that you have not yet tagged any image as child1. It knows how to build child1 (you gave it a build path), so it will build it now, and tag it as child1.

docker-compose deploys the child1 service

same sequence of steps for child2

The next docker-compose up will be simpler (we have tagged images available, so we skip all build steps).

If you already have tagged images, and want to rebuild: use docker-compose build to tell it to build all images (yes, base and children will both be rebuilt).

Body:
Assuming I have a set of images which depend on a common base image:

base (this is only a set of common dependencies)

FROM ubuntu:16.04

ENV FOO 1

child1

FROM mybaseimage  # where mybaseimage corresponds to base

CMD ["bar1_command"]

child2

FROM mybaseimage  # where mybaseimage corresponds to base

CMD ["bar2_command"]

Is it possible to create docker-compose file which would build base without running it? Lets say I have following dependencies:

version: '2'
services:
    child1:
        build: ./path-to-child1-dockerfile
services:
    child2:
        build: ./path-to-child2-dockerfile
    depends_on:
        - child1

I would like base to be build even if it is not explicitly started. Is something like this even possible? Or should I simply use external Makefile to build dependencies?

build_base:
    docker build -t mybaseimage mybaseimage

build_all: build_base
    docker-compose build

Body:
It's possible. There's a kind of workaround. You're close, but you were missing explicit image tags (so you had little ability on child images to declare which image you inherited from).

version: '3.2'
services:
  base:
    image: mybaseimage
    build: ./path-to-base-dockerfile
  child1:
    build: ./path-to-child1-dockerfile
    depends_on:
      - base
  child2:
    build: ./path-to-child2-dockerfile
    depends_on:
      - base

Let's say you have no images built. You run docker-compose up. The following things will happen:

docker-compose sees that child1 and child2 services depend on base. So it will deploy base first.

docker-compose sees that you have not yet tagged any image as mybaseimage. It knows how to build mybaseimage (you gave it a build path), so it will build it now, and tag it as mybaseimage.

docker-compose deploys the base service.

ideally you should design base so that it quits immediately, or has no entrypoint. since we don't actually want it to run this service.

docker-compose considers deploying child1 and child2

docker-compose sees that you have not yet tagged any image as child1. It knows how to build child1 (you gave it a build path), so it will build it now, and tag it as child1.

docker-compose deploys the child1 service

same sequence of steps for child2

The next docker-compose up will be simpler (we have tagged images available, so we skip all build steps).

If you already have tagged images, and want to rebuild: use docker-compose build to tell it to build all images (yes, base and children will both be rebuilt).


来源: stackexchange

问:
Send SMS with GPS location using SMS manager
I need help getting GPS location and sending it via Sms along with the relevant message. I have developed an emergency button app which should send a custom message + GPS location. I am struggling with implementing the GPS location function.

Original code without GPS:
/This code funtcions well however it does not contain the GPS location/

```<code>import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText customMessage;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        customMessage=(EditText)findViewById(R.id.customMessage);

    }

    public void sendText(View view)
    {

        String message = "";
        if (view.getId() == R.id.fab)
        {
            message = customMessage.getText().toString();
        }
        else
        {
            Button sender = (Button)view;
            message = sender.getText().toString();
        }
        //Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show();

        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage("6505551212", null,message + "(Location Here)", null, null);
    }

}
</code>```

Code with GPS:
/The problem with the code is that the app just crashes when I click the send button but it has no errors/

```<code>import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText customMessage;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        customMessage=(EditText)findViewById(R.id.customMessage);

    }

    public void sendText (View view, String phoneNumber, Location currentLocation) {

        String message = "";
        if (view.getId() == R.id.fab)
        {
            message = customMessage.getText().toString();
        }
        else
        {
            Button sender = (Button)view;
            message = sender.getText().toString();
        }

        SmsManager smsManager = SmsManager.getDefault();
        StringBuffer smsBody = new StringBuffer();
        smsBody.append("http://maps.google.com?q=");
        smsBody.append(currentLocation.getLatitude());
        smsBody.append(",");
        smsBody.append(currentLocation.getLongitude());
        smsManager.sendTextMessage("6505551212", null, smsBody.toString(), null, null);
    }
}
</code>```

答:
Your previous code working because its message length is <=160. But the another message contains url which is larger than 160 characters. To overcome this you need to send message in multiple parts. Use the code given below :
SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(messageString);
sms.sendMultipartTextMessage(number, null, parts, null, null);

ContentLicense: CC BY-SA 3.0

Body:
I need help getting GPS location and sending it via Sms along with the relevant message. I have developed an emergency button app which should send a custom message + GPS location. I am struggling with implementing the GPS location function.

Original code without GPS:
/This code funtcions well however it does not contain the GPS location/

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText customMessage;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        customMessage=(EditText)findViewById(R.id.customMessage);

    }

    public void sendText(View view)
    {

        String message = "";
        if (view.getId() == R.id.fab)
        {
            message = customMessage.getText().toString();
        }
        else
        {
            Button sender = (Button)view;
            message = sender.getText().toString();
        }
        //Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show();

        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage("6505551212", null,message + "(Location Here)", null, null);
    }

}

Code with GPS:
/The problem with the code is that the app just crashes when I click the send button but it has no errors/

import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText customMessage;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        customMessage=(EditText)findViewById(R.id.customMessage);

    }

    public void sendText (View view, String phoneNumber, Location currentLocation) {

        String message = "";
        if (view.getId() == R.id.fab)
        {
            message = customMessage.getText().toString();
        }
        else
        {
            Button sender = (Button)view;
            message = sender.getText().toString();
        }

        SmsManager smsManager = SmsManager.getDefault();
        StringBuffer smsBody = new StringBuffer();
        smsBody.append("http://maps.google.com?q=");
        smsBody.append(currentLocation.getLatitude());
        smsBody.append(",");
        smsBody.append(currentLocation.getLongitude());
        smsManager.sendTextMessage("6505551212", null, smsBody.toString(), null, null);
    }
}


问:
iOS download and save image inside app
Is it possible for me to download an image from website and save it permanently inside my app? I really have no idea, but it would make a nice feature for my app.</p>

答:
You can download image without blocking UI with using  NSURLSessionDataTask.

```<code>+(void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
 {
 NSURLSessionDataTask*  _sessionTask = [[NSURLSession sharedSession] dataTaskWithRequest:[NSURLRequest requestWithURL:url]
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error != nil)
        {
          if ([error code] == NSURLErrorAppTransportSecurityRequiresSecureConnection)
                {
                    completionBlock(NO,nil);
                }
         }
    else
     {
      [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                        UIImage *image = [[UIImage alloc] initWithData:data];
                        completionBlock(YES,image);

                        });

      }];

     }

                                            }];
    [_sessionTask resume];
}
</code>```

Title: iOS download and save image inside app

Body:
You can download image without blocking UI with using  NSURLSessionDataTask.

+(void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
 {
 NSURLSessionDataTask*  _sessionTask = [[NSURLSession sharedSession] dataTaskWithRequest:[NSURLRequest requestWithURL:url]
                                            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error != nil)
        {
          if ([error code] == NSURLErrorAppTransportSecurityRequiresSecureConnection)
                {
                    completionBlock(NO,nil);
                }
         }
    else
     {
      [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
                        dispatch_async(dispatch_get_main_queue(), ^{
                        UIImage *image = [[UIImage alloc] initWithData:data];
                        completionBlock(YES,image);

                        });

      }];

     }

                                            }];
    [_sessionTask resume];
}


问:
Creating an overlay in CSS?
I have div that I display dynamically when certain conditions arise.

When I display the div, how can I create the effect of the background dimming and my div appearing to be prominent? much like a number of AJAX lightboxes or popups. (Thickbox, ColorBox, PrettyPhoto, etc)

I don;t quite get how they do it. I have everything else working in my own custom code except that piece.

Can anyone help me learn how?

答:
Just use global div of the size of the page to cover any other content:

http://jsfiddle.net/CHkNd/1/

ContentLicense: CC BY-SA 2.5

Title: Creating an overlay in CSS?


问:
SCNGeometry with polygon as primitiveType
Trying to figure out how I create a SCNGeometry with polygon as primitiveType,
My goal is to add polygon shaped node as a child of a sphere node, and make it look like MKPolygon for map kit, like in this example.

My current code is:

```<code>//Take an arbitrary array of vectors
let vertices: [SCNVector3] = [
SCNVector3Make(-0.1304485, 0.551937, 0.8236193),
SCNVector3Make(0.01393811, 0.601815, 0.7985139),
SCNVector3Make(0.2971005, 0.5591929, 0.7739732),
SCNVector3Make(0.4516893, 0.5150381, 0.7285002),
SCNVector3Make(0.4629132, 0.4383712, 0.7704169),
SCNVector3Make(0.1333823, 0.5224985, 0.8421428),
SCNVector3Make(-0.1684743, 0.4694716, 0.8667254)]

//Does polygon shape require indices?
let indices: [Int] = [0,1,2,3,4,5,6]

let vertexSource = SCNGeometrySource(vertices: vertices)
let indexData = Data(bytes: indices, count: indices.count * MemoryLayout<Int>.size)

//Note!!! I get compiler error if primitiveCount is greater than 0
let element = SCNGeometryElement(data: indexData, primitiveType: .polygon, primitiveCount: 0, bytesPerIndex: MemoryLayout<Int>.size)
let geometry = SCNGeometry(sources: [vertexSource], elements: [element])

let material = SCNMaterial()
material.diffuse.contents = UIColor.purple.withAlphaComponent(0.75)
material.isDoubleSided = true
geometry.firstMaterial = material

let node = SCNNode(geometry: geometry)
</code>```

When using SCNGeometryElement like this I get an empty node.

答:
You have two problems:

SceneKit (and Metal) only support 32 bit integers as indices (source).
So the type of your indices array needs to be [Int32].

SceneKit needs two pieces of information for polygons: The number of points in the polygon and the index of the point in the vertex array.
From Apple's documentation on SCNGeometryPrimitiveTypePolygon (which only exists in Objective-C):

The element’s data  property holds two sequences of values.

The first sequence has a number of values equal to the geometry element’s
  primitiveCount  value. Each value in this sequence specifies the number of vertices in a polygon primitive. For example, if the first sequence is [5, 3], the geometry element contains a pentagon followed by a triangle.

The rest of the data is a sequence of vertex indices. Each entry in the first sequence specifies a corresponding number of entries in the second sequence. For example, if the first sequence includes the values [5, 3], the second sequence includes five indices for the pentagon, followed by three indices for the triangle.

You need to change your index array to:

```<code>let indices: [Int32] = [7, /* We have a polygon with seven points */,
                        0,1,2,3,4,5,6 /* The seven indices for our polygon */
                       ]
</code>```

Then, set the primitiveCount to 1 (we have one polygon to draw) and change the size of the buffer:

```<code>let indexData = Data(bytes: indices,
                     count: indices.count * MemoryLayout<Int32>.size)

// Now without runtime error
let element = SCNGeometryElement(data: indexData,
                                 primitiveType: .polygon,
                                 primitiveCount: 1,
                                 bytesPerIndex: MemoryLayout<Int32>.size)
</code>```

Body:
Trying to figure out how I create a SCNGeometry with polygon as primitiveType,
My goal is to add polygon shaped node as a child of a sphere node, and make it look like MKPolygon for map kit, like in this example.

My current code is:

//Take an arbitrary array of vectors
let vertices: [SCNVector3] = [
SCNVector3Make(-0.1304485, 0.551937, 0.8236193),
SCNVector3Make(0.01393811, 0.601815, 0.7985139),
SCNVector3Make(0.2971005, 0.5591929, 0.7739732),
SCNVector3Make(0.4516893, 0.5150381, 0.7285002),
SCNVector3Make(0.4629132, 0.4383712, 0.7704169),
SCNVector3Make(0.1333823, 0.5224985, 0.8421428),
SCNVector3Make(-0.1684743, 0.4694716, 0.8667254)]

//Does polygon shape require indices?
let indices: [Int] = [0,1,2,3,4,5,6]

let vertexSource = SCNGeometrySource(vertices: vertices)
let indexData = Data(bytes: indices, count: indices.count * MemoryLayout<Int>.size)

//Note!!! I get compiler error if primitiveCount is greater than 0
let element = SCNGeometryElement(data: indexData, primitiveType: .polygon, primitiveCount: 0, bytesPerIndex: MemoryLayout<Int>.size)
let geometry = SCNGeometry(sources: [vertexSource], elements: [element])

let material = SCNMaterial()
material.diffuse.contents = UIColor.purple.withAlphaComponent(0.75)
material.isDoubleSided = true
geometry.firstMaterial = material

let node = SCNNode(geometry: geometry)

When using SCNGeometryElement like this I get an empty node.

Body:
You have two problems:

SceneKit (and Metal) only support 32 bit integers as indices (source).
So the type of your indices array needs to be [Int32].

SceneKit needs two pieces of information for polygons: The number of points in the polygon and the index of the point in the vertex array.
From Apple's documentation on SCNGeometryPrimitiveTypePolygon (which only exists in Objective-C):

The element’s data  property holds two sequences of values.

The first sequence has a number of values equal to the geometry element’s
  primitiveCount  value. Each value in this sequence specifies the number of vertices in a polygon primitive. For example, if the first sequence is [5, 3], the geometry element contains a pentagon followed by a triangle.

The rest of the data is a sequence of vertex indices. Each entry in the first sequence specifies a corresponding number of entries in the second sequence. For example, if the first sequence includes the values [5, 3], the second sequence includes five indices for the pentagon, followed by three indices for the triangle.

You need to change your index array to:

let indices: [Int32] = [7, /* We have a polygon with seven points */,
                        0,1,2,3,4,5,6 /* The seven indices for our polygon */
                       ]

Then, set the primitiveCount to 1 (we have one polygon to draw) and change the size of the buffer:

let indexData = Data(bytes: indices,
                     count: indices.count * MemoryLayout<Int32>.size)

// Now without runtime error
let element = SCNGeometryElement(data: indexData,
                                 primitiveType: .polygon,
                                 primitiveCount: 1,
                                 bytesPerIndex: MemoryLayout<Int32>.size)

ContentLicense: CC BY-SA 4.0


问:
Appropriate encryption for financial data
I'm currently building a web application(PHP/MySQL) which saves data from persons. Most of this data is not worth protecting with encryption but some of it is financial information like income and so on. It is not a payment application and does not store information that could be turned into money directly like credit card information but still stuff you don't want to have in a possible leak. This platform has to be sold to customers that want "security", but that can mean anything as the customers themselves do not have any knowledge what they really want, since they are business people and not cryptographers(like me neither).

It is a management platform so the people that have their financial data saved there are not the users of the platform. Users of the platform are merely a login with permissions attached to them. The server itself never has to have access the data. Every operation is done by a user(could also be an admin) that is logged in. Multiple users need to have access to the same data given they have enough permissions.

My question is now how I can protect the financial data from these threats:

Somebody finds an SQL-injection and dumps all tables remotely

Somebody steals the hard drive of the server (database + code)

Where I'm certainly not going: Large scale sniffing attack or compromised servers(like sniffing all traffic on the server itself where SSL doesn't matter) or social engineering/phishing.

I would also like to have a quick summary how much more information(keys, data, etc.) I have to store in comparison to the current system, where there is one simple field for income etc. and a standard login system with username and hashed password.

EDIT: Reformulated question almost entirely following the suggestion of comments/answers

答:
Here are two approaches to this:

1) Use symmetric encryption because you have already arranged a secret with the client, which is their password.

Whenever the user requires access to their sensitive information, they need to provide their password. If you require this, then you can use that password as a basis of generating the encryption key.

You can use the openssl functions in PHP to encrypt the sensitive data, and decrypt it when the client needs it. This will allow you to select an appropriately hard to break algorithm which OpenSSL supports. The drawback of this is that you will need explicit user permission and their password to access that data, which is good if you're only storing it on behalf of that user, but bad if you need to pass it on to someone else.

This way you will not need to store additional information in the database. In case someone steals your hard drive, all they will have is encrypted sensitive data and hashed passwords. The drawback is that it's a single point of failure, if they break the encryption they also get the password and vice-versa however the difficulty of breaking the encryption is not as high as reversing a hash. It also relies on strong passwords, which as we know users often don't tend to use, however that's not a new problem and one we're not likely to solve today.

2) Require the user to generate a private-public key pair and send you the public key. You can then store this public key and encrypt data using it. This generally would work well if you had an app/software that communicates with your server, which can do this on the user's behalf, but is harder to implement in a web application. Perhaps there's JavaScript libraries that can do this but since it's not something that is commonly done you need to be 100% sure the library you're using is secure. However this also requires of the user to store the key somewhere and be able to use it whenever they want access to that data (again JavaScript can do this for the user but saving and loading the key is something that requires user interaction due to security concerns).

In short:

Symmetric encryption would only be secure if the encryption key is not stored on the server but is something that the user can provide whenever it is needed.

Asymmetric encryption is even more secure but unrealistic in a web application targeted to an average user.

So I would suggest symmetric encryption using the user's password as a key.


问:
SQL - HAVING Clause in depth
I'm trying to understand what condition can be placed after the having clause - it is usually a condition, that uses the functions from the select statement, but it also can contain a column, that is typed in the select statement.

Here's an example:

```<code>create table r(a int, b int, c int, d int, e int primary key)

select a, min(b), sum(c)
from r
where b > 5
group by a
having "condition"
</code>```

which of the following can replace the "condition"

```<code>a) b = 5

b) a = sum(e)

c) min(b) >= 6
</code>```

When I execute this in SQL, only a) doesn't work, but what's the logic behind it?

答:
The HAVING clause is applied as a filter after the GROUP BY.

If you keep that in mind, it becomes obvious that:

b=5 fails because you don't GROUP BY b in the query and b is used as-is and not in an aggregation function.

a=SUM(e) succeeds because you GROUP BY a and compare a with an aggregate function.

MIN(b) >= 6 succeeds because you compare an aggregate function with a constant.

Hope this clarifies ...

Title: SQL - HAVING Clause in depth

Body:
I'm trying to understand what condition can be placed after the having clause - it is usually a condition, that uses the functions from the select statement, but it also can contain a column, that is typed in the select statement.

Here's an example:

create table r(a int, b int, c int, d int, e int primary key)

select a, min(b), sum(c)
from r
where b > 5
group by a
having "condition"

which of the following can replace the "condition"

a) b = 5

b) a = sum(e)

c) min(b) >= 6

When I execute this in SQL, only a) doesn't work, but what's the logic behind it?


问:
dropdown navigation link using jquery not loading valid anchor links in mvc
Here's my html code:

```<code>    <div class="wrapper-demo">
      <div id="dd" class="wrapper-dropdown-3" tabindex="1">
         <span>The Dropdown</span>
         <ul class="dropdown">
            <li>@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })</li>
            <li>@Html.ActionLink("Company Information", "Details", "Employer",routeValues: new {id = Model.ID },htmlAttributes: null)</li>
            <li>@Html.ActionLink("Post Opening", "Create", "Opening")</li>
            <li>@Html.ActionLink("View Opening", "Details", "Opening")</li>
            <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
        </ul>
   </div>
</code>```

And my sample jquery code from:

```<code>function DropDown(el) {
      this.dd = el;
      this.placeholder = this.dd.children('span');
      this.opts = this.dd.find('ul.dropdown > li');
      this.val = '';
      this.index = -1;
      this.initEvents();
   }
   DropDown.prototype = {
      initEvents : function() {
          var obj = this;
          //show dropdown items on click
          obj.dd.on('click', function (event) {
          $(this).toggleClass('active');
      });
      obj.opts.on('click', function () {
         var opt = $(this);
         obj.val = opt.text();
         obj.index = opt.index();
         obj.placeholder.text(obj.val);
      });
   },
   getValue : function() {
      return this.val;
   },
   getIndex : function() {
     return this.index;
   }
  }
  $(function() {
    var dd = new DropDown( $('#dd') );
    $(document).click(function() {
    // all dropdowns
       $('.wrapper-dropdown-3').removeClass('active');
    });
  });
</code>```

Question: the code works like a static href code that goes nowhere whereas it has a valid anchor link to navigate to. How can i make it work?

答:
I've been able to get it to work. All that is needed to be done was to add event.stopPropagation().
Here is the only part that needs fixing:

```<code>DropDown.prototype = {
   initEvents: function () {
       var obj = this;
       obj.dd.on('click', function (event) {
          $(this).toggleClass('active');
          event.stopPropagation();
          //return false;
          ...
</code>```

Body:
Here's my html code:

         The Dropdown

@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

@Html.ActionLink("Company Information", "Details", "Employer",routeValues: new {id = Model.ID },htmlAttributes: null)

@Html.ActionLink("Post Opening", "Create", "Opening")

@Html.ActionLink("View Opening", "Details", "Opening")

Log off

And my sample jquery code from:

function DropDown(el) {
      this.dd = el;
      this.placeholder = this.dd.children('span');
      this.opts = this.dd.find('ul.dropdown > li');
      this.val = '';
      this.index = -1;
      this.initEvents();
   }
   DropDown.prototype = {
      initEvents : function() {
          var obj = this;
          //show dropdown items on click
          obj.dd.on('click', function (event) {
          $(this).toggleClass('active');
      });
      obj.opts.on('click', function () {
         var opt = $(this);
         obj.val = opt.text();
         obj.index = opt.index();
         obj.placeholder.text(obj.val);
      });
   },
   getValue : function() {
      return this.val;
   },
   getIndex : function() {
     return this.index;
   }
  }
  $(function() {
    var dd = new DropDown( $('#dd') );
    $(document).click(function() {
    // all dropdowns
       $('.wrapper-dropdown-3').removeClass('active');
    });
  });

Question: the code works like a static href code that goes nowhere whereas it has a valid anchor link to navigate to. How can i make it work?

Body:
I've been able to get it to work. All that is needed to be done was to add event.stopPropagation().
Here is the only part that needs fixing:

DropDown.prototype = {
   initEvents: function () {
       var obj = this;
       obj.dd.on('click', function (event) {
          $(this).toggleClass('active');
          event.stopPropagation();
          //return false;
          ...


问:
MathJax plugin creating error
So we have been using mathjax on our website for over a year. recently we started receiving this message: "WARNING: cdn.mathjax.org has been retired. Check..."

We performed the necessary steps for migration, but now that we are using the new repository, we are getting an error message when trying to load Tex using CKEditor: "Uncaught SyntaxError: Unexpected token }" in: MathJax.js?config=TeX-AMS_HTML:54

looking at the code thats creating an error, it seems to be a syntax error in the config file. (see image http://imgur.com/a/BneL1). By googling i found an old version of this code meant for the migration and it doesnt have the second last semicolon: https://gist.github.com/pkra/b02253d18a7c611fe0ffb4fbd5d6273b

This is creating issues for us, as it means fractions created in Tex doesnt show up in CKEditor

Is this a bug by CDN with their migration or is there a fix that i can use?

答:
I believe the error message is due to an issue in the accessibility-menu extension that should only affect older browsers (in particular, IE8 and below).  If you are using IE and your version is greater than 8, then that probably means your page is triggering one of IE's emulation modes for an older version.  Try adding

```<code><meta http-equiv="X-UA-Compatible" content="IE=Edge">
</code>```

as the first line of the  section of you page to tell IE to use the highest version it can handle.

This issue will be fixed in the next release of MathJax, but if adding the line above doesn't fix it for you, you could request version 2.6.1 from the CDN rather than 2.7.1 (by changing that number in the cdnjs URL).

Title: MathJax plugin creating error

Body:
I believe the error message is due to an issue in the accessibility-menu extension that should only affect older browsers (in particular, IE8 and below).  If you are using IE and your version is greater than 8, then that probably means your page is triggering one of IE's emulation modes for an older version.  Try adding

<meta http-equiv="X-UA-Compatible" content="IE=Edge">

as the first line of the <head> section of you page to tell IE to use the highest version it can handle.

This issue will be fixed in the next release of MathJax, but if adding the line above doesn't fix it for you, you could request version 2.6.1 from the CDN rather than 2.7.1 (by changing that number in the cdnjs URL).


问:
ConvertString to Big Decimal in JAVA
I am trying to store a String into a column with datatype Big Decimal.

```<code>String a = transaction.getBeneAmt();
log.info(a);
tran.setTransAmt(new BigDecimal(transaction.getBeneAmt()));
tranRepository.saveAndFlush(trangloTran); //save into database
</code>```

But I get

```<code>2017-07-05 18:04:19 [http-nio-8080-exec-1] INFO  ApiController - IDR 3,000,000.00
2017-07-05 18:04:19 [http-nio-8080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NumberFormatException] with root cause
java.lang.NumberFormatException: null
    at java.math.BigDecimal.<init>(BigDecimal.java:494)
    at java.math.BigDecimal.<init>(BigDecimal.java:383)
    at java.math.BigDecimal.<init>(BigDecimal.java:806)
</code>```

答:
The problem here is that your String contains alphabetic characters so it won't be possible to convert it to BigDecimal, that's why you got NumberFormatException.

You need to replace these alphabetic characters before trying to convert it:

```<code>String a = transaction.getBeneAmt();
log.info(a);
tran.setTransAmt(new BigDecimal(a.replaceAll("[a-zA-Z,]", "").trim()));
tranRepository.saveAndFlush(trangloTran);
</code>```

Title: ConvertString to Big Decimal in JAVA

Body:
I am trying to store a String into a column with datatype Big Decimal.

String a = transaction.getBeneAmt();
log.info(a);
tran.setTransAmt(new BigDecimal(transaction.getBeneAmt()));
tranRepository.saveAndFlush(trangloTran); //save into database

But I get

2017-07-05 18:04:19 [http-nio-8080-exec-1] INFO  ApiController - IDR 3,000,000.00
2017-07-05 18:04:19 [http-nio-8080-exec-1] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NumberFormatException] with root cause
java.lang.NumberFormatException: null
    at java.math.BigDecimal.<init>(BigDecimal.java:494)
    at java.math.BigDecimal.<init>(BigDecimal.java:383)
    at java.math.BigDecimal.<init>(BigDecimal.java:806)

Body:
The problem here is that your String contains alphabetic characters so it won't be possible to convert it to BigDecimal, that's why you got NumberFormatException.

You need to replace these alphabetic characters before trying to convert it:

String a = transaction.getBeneAmt();
log.info(a);
tran.setTransAmt(new BigDecimal(a.replaceAll("[a-zA-Z,]", "").trim()));
tranRepository.saveAndFlush(trangloTran);


问:
Show/remove classes while scrolling down
I just need to show div while scrolling down and remove another div at same time.
I try with this code and this is working as I expected. The problem is, If I scroll to top I need to show the removed class and hide current class. (opposite side of this)

This is my code.

```<code>    $(window).scroll(function() {
     var scroll = $(window).scrollTop();
     if (scroll >= 0) {
     $(".left-nav").removeClass("white-nav");
    }
  });
</code>```

What is the best solution?

答:
```<code>$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  $(".left-nav").toggleClass("white-nav", scroll <= 0);
});
</code>```

But be aware, that complex code in scroll event handlers can lead to a laggy performance while scrolling the page. Especially DOM manipulation during scrolling can lead to severe performance issues.

Body:
I just need to show div while scrolling down and remove another div at same time.
I try with this code and this is working as I expected. The problem is, If I scroll to top I need to show the removed class and hide current class. (opposite side of this)

This is my code.

    $(window).scroll(function() {
     var scroll = $(window).scrollTop();
     if (scroll >= 0) {
     $(".left-nav").removeClass("white-nav");
    }
  });

What is the best solution?

Body:
$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  $(".left-nav").toggleClass("white-nav", scroll <= 0);
});

But be aware, that complex code in scroll event handlers can lead to a laggy performance while scrolling the page. Especially DOM manipulation during scrolling can lead to severe performance issues.


问:
Using dequeueReusableCell rewrites cells
I'm having issues working with tables and cells on Swift.

I've created a simple UITableViewController, with two sections of static cells.

To recap:

1 table view

2 sections

4 cells, 2 in each section

2 labels per cell

What I'm trying to do is fill them with data that's coming from a JSON (no problem so far).

All the UI was built with storyboards, not coding.

The problem starts when I try to improve my layout UI. What I want to do is convert those cells to have rounded corners, change their background color, etc. I'm able to achieve that, as you'll see in the code below.

I'm doing that with this block of code:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)

        cell.backgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.5) // white color
        cell.selectionStyle = .none

        //Top Left Right Corners
        let maskPathTop = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
        let shapeLayerTop = CAShapeLayer()
        shapeLayerTop.frame = cell.bounds
        shapeLayerTop.path = maskPathTop.cgPath
        shapeLayerTop.fillColor = UIColor.white.cgColor
        shapeLayerTop.strokeColor = UIColor.white.cgColor

        //Bottom Left Right Corners
        let maskPathBottom = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
        let shapeLayerBottom = CAShapeLayer()
        shapeLayerBottom.frame = cell.bounds
        shapeLayerBottom.path = maskPathBottom.cgPath
        shapeLayerBottom.fillColor = UIColor.white.cgColor
        shapeLayerBottom.strokeColor = UIColor.white.cgColor

        //All Corners
        let maskPathAll = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.topLeft, .topRight, .bottomRight, .bottomLeft], cornerRadii: CGSize(width: 10.0, height: 10.0))
        let shapeLayerAll = CAShapeLayer()
        shapeLayerAll.frame = cell.bounds
        shapeLayerAll.path = maskPathAll.cgPath
        shapeLayerAll.fillColor = UIColor.white.cgColor
        shapeLayerAll.strokeColor = UIColor.white.cgColor

        if (indexPath.row == 0 && indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1) {

            cell.layer.mask = shapeLayerAll
        } else if (indexPath.row == 0) {

            cell.layer.mask = shapeLayerTop
        } else if (indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1) {

            cell.layer.mask = shapeLayerBottom
        }

        return cell
    }
</code>```

The problem starts after that code runs, my labels disappear and just the improved layout is preserved, with the colors, cells rounded borders, etc.

What I couldn't find anywhere was a way to preserve those labels no matter the changes over the cells.

Is there a way to achieve that? I'm sure I am missing some theory related to tables here.

I hope someone can help me

Details:

Xcode 8.3.3

Swift 3.1.1

iOS 8.4

答:
Based on @AndréSlotta reply to my question. This is my final code:

```<code>override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    cell.backgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.5) // white color
    cell.selectionStyle = .none

    //Top Left Right Corners
    let maskPathTop = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
    let shapeLayerTop = CAShapeLayer()
    shapeLayerTop.frame = cell.bounds
    shapeLayerTop.path = maskPathTop.cgPath
    shapeLayerTop.fillColor = UIColor.white.cgColor
    shapeLayerTop.strokeColor = UIColor.white.cgColor

    //Bottom Left Right Corners
    let maskPathBottom = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
    let shapeLayerBottom = CAShapeLayer()
    shapeLayerBottom.frame = cell.bounds
    shapeLayerBottom.path = maskPathBottom.cgPath
    shapeLayerBottom.fillColor = UIColor.white.cgColor
    shapeLayerBottom.strokeColor = UIColor.white.cgColor

    //All Corners
    let maskPathAll = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.topLeft, .topRight, .bottomRight, .bottomLeft], cornerRadii: CGSize(width: 10.0, height: 10.0))
    let shapeLayerAll = CAShapeLayer()
    shapeLayerAll.frame = cell.bounds
    shapeLayerAll.path = maskPathAll.cgPath
    shapeLayerAll.fillColor = UIColor.white.cgColor
    shapeLayerAll.strokeColor = UIColor.white.cgColor

    if (indexPath.row == 0 && indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1) {

        cell.layer.mask = shapeLayerAll
    } else if (indexPath.row == 0) {

        cell.layer.mask = shapeLayerTop
    } else if (indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1) {

        cell.layer.mask = shapeLayerBottom
    }
}
</code>```

Hope it helps someone else

Body:
I'm having issues working with tables and cells on Swift.

I've created a simple UITableViewController, with two sections of static cells.

To recap:

1 table view

2 sections

4 cells, 2 in each section

2 labels per cell

What I'm trying to do is fill them with data that's coming from a JSON (no problem so far).

All the UI was built with storyboards, not coding.

The problem starts when I try to improve my layout UI. What I want to do is convert those cells to have rounded corners, change their background color, etc. I'm able to achieve that, as you'll see in the code below.

I'm doing that with this block of code:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)

        cell.backgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.5) // white color
        cell.selectionStyle = .none

        //Top Left Right Corners
        let maskPathTop = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
        let shapeLayerTop = CAShapeLayer()
        shapeLayerTop.frame = cell.bounds
        shapeLayerTop.path = maskPathTop.cgPath
        shapeLayerTop.fillColor = UIColor.white.cgColor
        shapeLayerTop.strokeColor = UIColor.white.cgColor

        //Bottom Left Right Corners
        let maskPathBottom = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
        let shapeLayerBottom = CAShapeLayer()
        shapeLayerBottom.frame = cell.bounds
        shapeLayerBottom.path = maskPathBottom.cgPath
        shapeLayerBottom.fillColor = UIColor.white.cgColor
        shapeLayerBottom.strokeColor = UIColor.white.cgColor

        //All Corners
        let maskPathAll = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.topLeft, .topRight, .bottomRight, .bottomLeft], cornerRadii: CGSize(width: 10.0, height: 10.0))
        let shapeLayerAll = CAShapeLayer()
        shapeLayerAll.frame = cell.bounds
        shapeLayerAll.path = maskPathAll.cgPath
        shapeLayerAll.fillColor = UIColor.white.cgColor
        shapeLayerAll.strokeColor = UIColor.white.cgColor

        if (indexPath.row == 0 && indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1) {

            cell.layer.mask = shapeLayerAll
        } else if (indexPath.row == 0) {

            cell.layer.mask = shapeLayerTop
        } else if (indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1) {

            cell.layer.mask = shapeLayerBottom
        }

        return cell
    }

The problem starts after that code runs, my labels disappear and just the improved layout is preserved, with the colors, cells rounded borders, etc.

What I couldn't find anywhere was a way to preserve those labels no matter the changes over the cells.

Is there a way to achieve that? I'm sure I am missing some theory related to tables here.

I hope someone can help me

Details:

Xcode 8.3.3

Swift 3.1.1

iOS 8.4

Body:
Based on @AndréSlotta reply to my question. This is my final code:

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    cell.backgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 0.5) // white color
    cell.selectionStyle = .none

    //Top Left Right Corners
    let maskPathTop = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
    let shapeLayerTop = CAShapeLayer()
    shapeLayerTop.frame = cell.bounds
    shapeLayerTop.path = maskPathTop.cgPath
    shapeLayerTop.fillColor = UIColor.white.cgColor
    shapeLayerTop.strokeColor = UIColor.white.cgColor

    //Bottom Left Right Corners
    let maskPathBottom = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.bottomLeft, .bottomRight], cornerRadii: CGSize(width: 10.0, height: 10.0))
    let shapeLayerBottom = CAShapeLayer()
    shapeLayerBottom.frame = cell.bounds
    shapeLayerBottom.path = maskPathBottom.cgPath
    shapeLayerBottom.fillColor = UIColor.white.cgColor
    shapeLayerBottom.strokeColor = UIColor.white.cgColor

    //All Corners
    let maskPathAll = UIBezierPath(roundedRect: cell.bounds, byRoundingCorners: [.topLeft, .topRight, .bottomRight, .bottomLeft], cornerRadii: CGSize(width: 10.0, height: 10.0))
    let shapeLayerAll = CAShapeLayer()
    shapeLayerAll.frame = cell.bounds
    shapeLayerAll.path = maskPathAll.cgPath
    shapeLayerAll.fillColor = UIColor.white.cgColor
    shapeLayerAll.strokeColor = UIColor.white.cgColor

    if (indexPath.row == 0 && indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1) {

        cell.layer.mask = shapeLayerAll
    } else if (indexPath.row == 0) {

        cell.layer.mask = shapeLayerTop
    } else if (indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1) {

        cell.layer.mask = shapeLayerBottom
    }
}

Hope it helps someone else


问:
Free HTML TO PDF DLL for c#.net in ASP.net
Is there any free dll that can be used for PDF generation because I have HTML string in which full html string is there containing table and also inline css style on Tr and td along with css classes.. I tried ITextSharp but it is not parsing HTML properly.

Please help me.Thank in advance.

答: There is wkhtmltopdf however this is a executable file (there is we support for Php and Drupal), however you can wrap it and used it using .net diagnostics to execute it from command line. All others are not as good or not free.</p>


问:
Why do string indices (albeit representing integers) work in arrays?
Why does the following enumerate correctly?

```<code>var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';

arr.forEach(v => console.log(v)); // foo, bar
</code>```

Both arr[1] and arr['1'] also work. Is this a feature of Array that strings corresponding to integers are mapped to their integer value?

答:
For those questions, It may be worth taking a look into the specification

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^(32)−1

Thus, because:

```<code>parseInt("1").toString() === "1"
</code>```

"1" is a perfectly valid array index.

See http://www.ecma-international.org/ecma-262/5.1/#sec-15.4

EDIT: One might ask "What's with 1 (a number)", because parseInt(1).toString() is not equal to 1 (but "1", a string). I think the answer to this is the part "(in the form of a String value)", so I believe 1 is first interpreted as "1" before applying those rules.

Body:
Why does the following enumerate correctly?

var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';

arr.forEach(v => console.log(v)); // foo, bar

Both arr[1] and arr['1'] also work. Is this a feature of Array that strings corresponding to integers are mapped to their integer value?

Body:
For those questions, It may be worth taking a look into the specification

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^(32)−1

Thus, because:

parseInt("1").toString() === "1"

"1" is a perfectly valid array index.

See http://www.ecma-international.org/ecma-262/5.1/#sec-15.4

EDIT: One might ask "What's with 1 (a number)", because parseInt(1).toString() is not equal to 1 (but "1", a string). I think the answer to this is the part "(in the form of a String value)", so I believe 1 is first interpreted as "1" before applying those rules.


问:
Struggling to iterate over an object with an array of string
Im' trying to iterate over an object with an an array of string in it but I'm struggling to do it

Output of the var_dump of the object I'm trying to iterate:

```<code>object(fooClass)#88(2) {
    ["property1:protected"]=> string(3) "foo"
    ["property2"]=> array(2) {
                    ["foo1"]=> string(4) "foo1"
                    ["foo2"]=> string(4) "foo2"}
}
</code>```

(Edit)But when I try to use an arrayIterator to iterate over the object with this code:

```<code>$obj = new ArrayObject($value);
$it = $obj->getIterator();
echo "iterating over: " . $obj->count() . " values <br />";
while ($it->valid()){
    echo $it->key() . "=" . $it->current() . "<br />" ;
    $it->next();
}
</code>```

I have this output:

```<code>iterating over: 1 values
*property1=foo
</code>```

Edit: What I'm expecting is something like that:

```<code>iterating over 3 values
*property1=foo
*foo1=foo1
*foo2=foo2
</code>```

答:
```<code>while ($it->valid())
{
    $key = $it->key();
    $value = $it->current();

   // ...

   $it->next();
  }
</code>```

use a loop to iterate and loop will terminate when it->valid() returns false.

Body:
Im' trying to iterate over an object with an an array of string in it but I'm struggling to do it

Output of the var_dump of the object I'm trying to iterate:

object(fooClass)#88(2) {
    ["property1:protected"]=> string(3) "foo"
    ["property2"]=> array(2) {
                    ["foo1"]=> string(4) "foo1"
                    ["foo2"]=> string(4) "foo2"}
}

(Edit)But when I try to use an arrayIterator to iterate over the object with this code:

$obj = new ArrayObject($value);
$it = $obj->getIterator();
echo "iterating over: " . $obj->count() . " values
";
while ($it->valid()){
    echo $it->key() . "=" . $it->current() . "
" ;
    $it->next();
}

I have this output:

iterating over: 1 values
*property1=foo

Edit: What I'm expecting is something like that:

iterating over 3 values
*property1=foo
*foo1=foo1
*foo2=foo2

Body:
while ($it->valid())
{
    $key = $it->key();
    $value = $it->current();

   // ...

   $it->next();
  }

use a loop to iterate and loop will terminate when it->valid() returns false.


问:
Gettinga a syntax error on twilio
I am trying to send an sms to phone using python but when I run the script I am getting an invalid syntax error with highlight on twilio.rest ...
Help would be appreciated..</p>

```<code>import way2sms
import requests

q=way2sms.sms('Arjun','*****')
q.send('94184*****','Hlo')
n=q.msgSentToday()
q.logout()
</code>```

答:
Twilio developer evangelist here.

There are a couple things that might be wrong with your code.

First up, as TheDarkKnight suggests in the comments, the first word From should be from.

You shouldn't include spaces in the phone numbers you are using.

Then, if you have just installed the Twilio Python library, then your code is likely to be out of date too as the way to import the REST client has changed. The updated code should look a bit like this:

```<code>from twilio.rest import Client

accountSid = "your_account_sid"
authToken  = "your_auth_token"

client = Client(account_sid, auth_token)

myTwilioNumber = "+91###"
destCellPhone  = "+91###"

myMessage = client.messages.create(
    body="whatever",
    to=destCellPhone,
    from_=myTwilioNumber)
</code>```

Let me know if that helps at all.

Title: Gettinga a syntax error on twilio

Body:
I am trying to send an sms to phone using python but when I run the script I am getting an invalid syntax error with highlight on twilio.rest ...
Help would be appreciated..

import way2sms
import requests

q=way2sms.sms('Arjun','*****')
q.send('94184*****','Hlo')
n=q.msgSentToday()
q.logout()

Body:
Twilio developer evangelist here.

There are a couple things that might be wrong with your code.

First up, as TheDarkKnight suggests in the comments, the first word From should be from.

You shouldn't include spaces in the phone numbers you are using.

Then, if you have just installed the Twilio Python library, then your code is likely to be out of date too as the way to import the REST client has changed. The updated code should look a bit like this:

from twilio.rest import Client

accountSid = "your_account_sid"
authToken  = "your_auth_token"

client = Client(account_sid, auth_token)

myTwilioNumber = "+91###"
destCellPhone  = "+91###"

myMessage = client.messages.create(
    body="whatever",
    to=destCellPhone,
    from_=myTwilioNumber)

Let me know if that helps at all.


问:
jquery event delegation on static content doesn't work
JQuery event delegation not working on static content but work perfectly on dynamically added element. Alert('test') works perfectly on the dynamically added divs but not on static divs which are already present there.

$(document).ready(function() {
      $('.addPost').on('click', function() {
          console.log("hello");

          var dyanamicdiv =
          '
'+
          '
'+
          '          hello'+
          '
'+
          '
';

          $('.post-container').append(dyanamicdiv);

      });
      $('.post-container').on('click', '.click-delgated-event', function() {
        alert("test");
      });
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post-container">
    <div>
        <div class="click-delgated-event">
            hello
        </div>
    </div>
</div>
<button class="addPost" type="button" name="button"> ADD POST </button></code>```

答:
It's because of the - that you're missing on the static element class(in your code you have the static element with class like: click-delgated event and you're targeting an element with class click-delgated-event in your jQuery code):

$(document).ready(function() {
  $('.addPost').on('click', function() {
    console.log("hello");

    var dyanamicdiv =
      '
' +
      '
' +
      '          hello' +
      '
' +
      '
';

    $('.post-container').append(dyanamicdiv);

  });
  $('.post-container').on('click', '.click-delgated-event', function() {
    alert("test");
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post-container">
  <div>
    <div class="click-delgated-event">
      hello
    </div>
  </div>
</div>
<button class="addPost" type="button" name="button"> ADD POST </button></code>```

Body:
JQuery event delegation not working on static content but work perfectly on dynamically added element. Alert('test') works perfectly on the dynamically added divs but not on static divs which are already present there.

$(document).ready(function() {
      $('.addPost').on('click', function() {
          console.log("hello");

          var dyanamicdiv =
          '
'+
          '
'+
          '          hello'+
          '
'+
          '
';

          $('.post-container').append(dyanamicdiv);

      });
      $('.post-container').on('click', '.click-delgated-event', function() {
        alert("test");
      });
  });

            hello

<button class="addPost" type="button" name="button"> ADD POST </button>

Body:
It's because of the - that you're missing on the static element class(in your code you have the static element with class like: click-delgated event and you're targeting an element with class click-delgated-event in your jQuery code):

$(document).ready(function() {
  $('.addPost').on('click', function() {
    console.log("hello");

    var dyanamicdiv =
      '  <div>' +
      '      <div class="click-delgated-event">' +
      '          hello' +
      '      </div>' +
      '  </div>';

    $('.post-container').append(dyanamicdiv);

  });
  $('.post-container').on('click', '.click-delgated-event', function() {
    alert("test");
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="post-container">
  <div>
    <div class="click-delgated-event">
      hello
    </div>
  </div>
</div>
<button class="addPost" type="button" name="button"> ADD POST </button>


问:
Magento cant make an order
I have an installation of Magento 1.9.2. I am using a custom theme, and anytime I try and place an order it kicks off the Ajax on the page and then stops with no error messages, but does leave a log:

```<code>ERR (3): User Error: Some transactions have not been committed or rolled back  in /html/lib/Varien/Db/Adapter/Pdo/Mysql.php on line 4039
</code>```

I have spent 2 days trying to get to the bottom of this with no joy. It doesn't matter what payment method I use its always the same.

答: I had today the same problem. Magento 1.9.2.4 with a custom theme. Everything worked fine, expect the checkout-process. The custom theme used the PHP short open tag <? php code ?> . After enabling short_open_tag in the php.ini, everything works fine.

Title: Magento cant make an order

Body:
I have an installation of Magento 1.9.2. I am using a custom theme, and anytime I try and place an order it kicks off the Ajax on the page and then stops with no error messages, but does leave a log:

ERR (3): User Error: Some transactions have not been committed or rolled back  in /html/lib/Varien/Db/Adapter/Pdo/Mysql.php on line 4039

I have spent 2 days trying to get to the bottom of this with no joy. It doesn't matter what payment method I use its always the same.


问:
Does Garmin provide Step count of the user in their API?
I went through the Garmin's Connect API documentation here But nowhere it mentions that they provide Step count of the user. This data is critical for my app.

Can someone kindly answer this question, please?

答:
you need to use Health API, you will find all the info there:

https://developer.garmin.com/health-api/overview/


问:
RSpec Active Record Scope
I want to write a scope that requires that the start date of products be less than today.  I wrote the following in rspec

```<code>it "Should not be found with a start date in the future" do
   @product.start_date = Date.tomorrow
   @product.save

   Product.active.find(@product.id).should == nil
end
</code>```

That test fails, obviously.  Then I wrote the scope-

```<code>scope :active, where('start_date <= ?', Date.today)
</code>```

Then I rerun the spec and it fails with-

```<code>2) Product Should not be found with a start date in the future
 Failure/Error: Product.active.find(@product.id).should_not == true
 Couldn't find Product with ID=1 [WHERE (start_date <= '2010-12-20')]
 # ./spec/models/product_spec.rb:168:in `block (2 levels) in <top (required)>'
</code>```

I cannot figure out how to get this code to pass.  I do not want the product to be found.

答: Look at the error: "Couldn't find Product with ID=1", the scope is actually working. Problem is in your test, find raises an exception as usual because no record has been found. You either have to use find_by_id or assert the exception with rspec.

Title: RSpec Active Record Scope

Body:
I want to write a scope that requires that the start date of products be less than today.  I wrote the following in rspec

it "Should not be found with a start date in the future" do
   @product.start_date = Date.tomorrow
   @product.save

   Product.active.find(@product.id).should == nil
end

That test fails, obviously.  Then I wrote the scope-

scope :active, where('start_date <= ?', Date.today)

Then I rerun the spec and it fails with-

2) Product Should not be found with a start date in the future
 Failure/Error: Product.active.find(@product.id).should_not == true
 Couldn't find Product with ID=1 [WHERE (start_date <= '2010-12-20')]
 # ./spec/models/product_spec.rb:168:in `block (2 levels) in <top (required)>'

I cannot figure out how to get this code to pass.  I do not want the product to be found.


答:
You can used toggleClass() to do this
    http://api.jquery.com/toggleclass/</p>

```<code>$(window).scroll(function() {
 var scroll = $(window).scrollTop();
 if (scroll >0) {
 $(".left-nav").toggleClass("white-nav");
}
else{
$(".left-nav").toggleClass("white-nav");
}
});
</code>```

Title: Show/remove classes while scrolling down

Body:
You can used toggleClass() to do this
    http://api.jquery.com/toggleclass/

$(window).scroll(function() {
 var scroll = $(window).scrollTop();
 if (scroll >0) {
 $(".left-nav").toggleClass("white-nav");
}
else{
$(".left-nav").toggleClass("white-nav");
}
});


问:
Why my all xml sitemap contains 50000 links and not last extra pages?
i am trying to build sitemap daily using php + mysqli (mariadb)

when i checked google for submitted sitemap, all i can see is every sitemap subbmitted has 50k urls in it. daily 3k-4k new Posts get added to the DB, so there should be last sitemap with extra URLs. What i am doing wrong ?

sitemap generation logic

```<code><?php
    $subset_count = 50000 ;

    $total_count_query = "SELECT COUNT(*) as total_count FROM links WHERE enabled = '1' " ;

    $total_count = mysqli_query ($conn, $total_count_query);
    $total_count = mysqli_fetch_assoc($total_count);
    $total_count = $total_count['total_count'];
    $total_pages = ceil ($total_count / $subset_count);

    $current_page = 1;
    while($current_page <= $total_pages){
        $from = ($current_page * $subset_count) - $subset_count;

        //$get_mysql_data_query = " SELECT tpb_id, slug FROM links WHERE enabled = '1' ORDER BY tpb_id ASC LIMIT $from , $subset_count"; // this is slow query

        $get_mysql_data_query = " SELECT tpb_id, slug FROM links WHERE enabled = '1' AND id >  $from ORDER BY tpb_id ASC LIMIT 0 , $subset_count";

        if ($result = mysqli_query($conn, $get_mysql_data_query)) {
            while ($row = mysqli_fetch_assoc($result)) {
                    $link = 'https://example.com/post-id/'.$row['tpb_id'].'/'.$row['slug'];
            }

            mysqli_free_result($result);
        }
        $current_page++ ;
    }
</code>```

My table schema

```<code>MariaDB [Db]> describe links;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| tpb_id  | int(11)      | NO   | UNI | 0       |                |
| slug    | varchar(255) | NO   |     |         |                |
| enabled | tinyint(1)   | NO   |     | 1       |                |
+---------+--------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)
</code>```

there are some inactive records in the table which i dont want them to be included in sitemaps, so i mark them as

```<code>enabled = '0'
</code>```

SELECT COUNT(*) as total_count FROM links;

```<code>+-------------+
| total_count |
+-------------+
|     4162840 |
+-------------+
1 row in set (0.00 sec)
</code>```

SELECT COUNT(*) as total_count FROM links WHERE enabled = '1';

```<code>+-------------+
| total_count |
+-------------+
|     4053924 |
+-------------+
1 row in set (0.91 sec)
</code>```

I am trying to build sitemaps without making server unresponsive buy querying 4 mil records in a single query and then using array chunk to split the results.

update 1:

as suggested by Rick James,

On the positive side, I was glad to see id >  $from ORDER BY tpb_id
  ASC LIMIT 0 , $subset_count -- this makes fetching chunks efficient.
  Oh, wait; it is not efficient -- why id versus tpb_id?  Since
  tpb_id is UNIQUE, get rid of id and promote tpb_id to be the
  PRIMARY KEY.  Then use tpb_id in place of id in the SELECT.

i did changes and ran the sitemap script, still the last sitemap had exact 50k URLs.
on further inspection i noticed on sitemap page 82 , which is last sitemap page, i am getting last record whose tpb_id is 4188464 ,

if i do

```<code>SELECT * FROM links WHERE tpb_id <= '4188464' AND enabled = '1'
</code>```

then i get

```<code>334,564 rows
</code>```

this means all sitemap pages included only 334,564 records from the database instead of 4mil+ records.

on further digging i found , sitemap pages 1-65 contains same 50k urls.

It happened because the lowest tpb_id is 3211594

Update 2: undid changes as suggested by Rick James,

i did some tests with 2 types of queries. (this one is slow)

type 1: old mysql query

```<code>MariaDB [db_name]> SELECT * FROM links ORDER BY tpb_id ASC LIMIT 0 , 5 ;
+----+---------+--------------------------------------------------+---------+
| id | tpb_id  | slug                                             | enabled |
+----+---------+--------------------------------------------------+---------+
|  1 | 3211594 | High.Chaparall.S02E02.PDTV.XViD.SWEDiSH-HuBBaTiX |       1 |
|  2 | 3211609 | School.Of.Rock.PROPER.DVDRip.XviD-DMT            |       1 |
|  3 | 3211623 | Gyllene_Tider-Samtliga_Hits-SE-2004-WLM          |       1 |
|  4 | 3211625 | Oz_-_Season_One                                  |       1 |
|  5 | 3211626 | Prince_of_Persia_-_XBOX                          |       1 |
+----+---------+--------------------------------------------------+---------+
5 rows in set (0.01 sec)

MariaDB [db_name]> SELECT * FROM links ORDER BY tpb_id ASC LIMIT 5 , 5 ;
+----+---------+-------------------------------------------+---------+
| id | tpb_id  | slug                                      | enabled |
+----+---------+-------------------------------------------+---------+
|  6 | 3211629 | Welcome.To.Mooseport.DVDSCR.XViD-DVL      |       1 |
|  7 | 3211639 | Top_Secret_Recipes_E-books                |       1 |
|  8 | 3211687 | Italian_Teens_Home_Video                  |       1 |
|  9 | 3211706 | Splinter_Cell_-_PandoraTomorrow_-DEViANCE |       1 |
| 10 | 3211770 | Revolution_OS                             |       1 |
+----+---------+-------------------------------------------+---------+
5 rows in set (0.00 sec)
</code>```

it is able to fetch records as expected.

type 2:new fast query.

```<code>MariaDB [db_name]>  SELECT * FROM links WHERE enabled = '1' AND tpb_id >  0 ORDER BY tpb_id ASC LIMIT 0 , 5 ;
+----+---------+--------------------------------------------------+---------+
| id | tpb_id  | slug                                             | enabled |
+----+---------+--------------------------------------------------+---------+
|  1 | 3211594 | High.Chaparall.S02E02.PDTV.XViD.SWEDiSH-HuBBaTiX |       1 |
|  2 | 3211609 | School.Of.Rock.PROPER.DVDRip.XviD-DMT            |       1 |
|  3 | 3211623 | Gyllene_Tider-Samtliga_Hits-SE-2004-WLM          |       1 |
|  4 | 3211625 | Oz_-_Season_One                                  |       1 |
|  5 | 3211626 | Prince_of_Persia_-_XBOX                          |       1 |
+----+---------+--------------------------------------------------+---------+
5 rows in set (0.00 sec)

MariaDB [db_name]>  SELECT * FROM links WHERE enabled = '1' AND tpb_id >  5 ORDER BY tpb_id ASC LIMIT 0 , 5 ;
+----+---------+--------------------------------------------------+---------+
| id | tpb_id  | slug                                             | enabled |
+----+---------+--------------------------------------------------+---------+
|  1 | 3211594 | High.Chaparall.S02E02.PDTV.XViD.SWEDiSH-HuBBaTiX |       1 |
|  2 | 3211609 | School.Of.Rock.PROPER.DVDRip.XviD-DMT            |       1 |
|  3 | 3211623 | Gyllene_Tider-Samtliga_Hits-SE-2004-WLM          |       1 |
|  4 | 3211625 | Oz_-_Season_One                                  |       1 |
|  5 | 3211626 | Prince_of_Persia_-_XBOX                          |       1 |
+----+---------+--------------------------------------------------+---------+
5 rows in set (0.01 sec)
</code>```

above you can see type 2 is giving same output because of

```<code>tpb_id >  5
</code>```

and tbp_id was not in incremental and had gaps in it.

Conclusion:
While using type 2 query which uses additional condition.
If table has Auto Increment field then we can use it for reference to get more records using type 2 query which is fast.

so the final query which i was looking for (no, order by/ no, where enabled = 1 condition)

```<code>$get_mysql_data_query = " SELECT tpb_id, slug, enabled FROM links WHERE id > $from LIMIT 0 , $subset_count";
</code>```

and then only using those having enabled = 1

```<code>while ($row = mysqli_fetch_assoc($result)) {
    if($row['enabled'] == 1){
        $link = 'https://example.com/post-id/'.$row['tpb_id'].'/'.$row['slug'];
    }
}
</code>```

so now, it will use id for reference as its incremental and dont have gaps in it, and will scan all 4mil+ records, but only create sitemaps of only those which are enabled.

i have updated script as per above , and will update once the script completes the running.

update: the script is working great and making sitemaps of all pages, not all sitemap pages contains 50k because there are many enabled = 0 records, but thats fine as long as all urls are gets included in sitemaps.

here is the final script logic.

```<code><?php
    $subset_count = 50000 ;

    $total_count_query = "SELECT COUNT(*) as total_count FROM links" ;

    $total_count = mysqli_query ($conn, $total_count_query);
    $total_count = mysqli_fetch_assoc($total_count);
    $total_count = $total_count['total_count'];
    $total_pages = ceil ($total_count / $subset_count);

    $current_page = 1;
    while($current_page <= $total_pages){
        $from = ($current_page * $subset_count) - $subset_count;

        $get_mysql_data_query = " SELECT tpb_id, slug, enabled FROM links WHERE id > $from LIMIT 0 , $subset_count";

        if ($result = mysqli_query($conn, $get_mysql_data_query)) {
            while ($row = mysqli_fetch_assoc($result)) {
                if($row['enabled'] == 1){
                    $link = 'https://example.com/post-id/'.$row['tpb_id'].'/'.$row['slug'];
                }
            }

            mysqli_free_result($result);
        }
        $current_page++ ;
    }
</code>```

答:
Sanity check!

Who is going to look at 4 million links?  Or even 50,000 that exist on a single page?

What browser can load a page with 50,000 links in a reasonable length of time?

If you must build a bunch of pages with 4M links, put some structure in it -- alphabetical or categorized or some other logical grouping, not a blind N.

And make the size of each page much less than 50K items.  And make it at two levels deep.  Say, you had 3 levels; then each "page" could be a few hundred items; this is manageable for users and for PHP.

On the positive side, I was glad to see id >  $from ORDER BY tpb_id ASC LIMIT 0 , $subset_count -- this makes fetching chunks efficient.  Oh, wait; it is not efficient -- why id versus tpb_id?  Since tpb_id is UNIQUE, get rid of id and promote tpb_id to be the PRIMARY KEY.  Then use tpb_id in place of id in the SELECT.

Body:
i am trying to build sitemap daily using php + mysqli (mariadb)

when i checked google for submitted sitemap, all i can see is every sitemap subbmitted has 50k urls in it. daily 3k-4k new Posts get added to the DB, so there should be last sitemap with extra URLs. What i am doing wrong ?

sitemap generation logic

<?php
    $subset_count = 50000 ;

    $total_count_query = "SELECT COUNT(*) as total_count FROM links WHERE enabled = '1' " ;

    $total_count = mysqli_query ($conn, $total_count_query);
    $total_count = mysqli_fetch_assoc($total_count);
    $total_count = $total_count['total_count'];
    $total_pages = ceil ($total_count / $subset_count);

    $current_page = 1;
    while($current_page <= $total_pages){
        $from = ($current_page * $subset_count) - $subset_count;

        //$get_mysql_data_query = " SELECT tpb_id, slug FROM links WHERE enabled = '1' ORDER BY tpb_id ASC LIMIT $from , $subset_count"; // this is slow query

        $get_mysql_data_query = " SELECT tpb_id, slug FROM links WHERE enabled = '1' AND id >  $from ORDER BY tpb_id ASC LIMIT 0 , $subset_count";

        if ($result = mysqli_query($conn, $get_mysql_data_query)) {
            while ($row = mysqli_fetch_assoc($result)) {
                    $link = 'https://example.com/post-id/'.$row['tpb_id'].'/'.$row['slug'];
            }

            mysqli_free_result($result);
        }
        $current_page++ ;
    }

My table schema

MariaDB [Db]> describe links;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| tpb_id  | int(11)      | NO   | UNI | 0       |                |
| slug    | varchar(255) | NO   |     |         |                |
| enabled | tinyint(1)   | NO   |     | 1       |                |
+---------+--------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)

there are some inactive records in the table which i dont want them to be included in sitemaps, so i mark them as

enabled = '0'

SELECT COUNT(*) as total_count FROM links;

+-------------+
| total_count |
+-------------+
|     4162840 |
+-------------+
1 row in set (0.00 sec)

SELECT COUNT(*) as total_count FROM links WHERE enabled = '1';

+-------------+
| total_count |
+-------------+
|     4053924 |
+-------------+
1 row in set (0.91 sec)

I am trying to build sitemaps without making server unresponsive buy querying 4 mil records in a single query and then using array chunk to split the results.

update 1:

as suggested by Rick James,

On the positive side, I was glad to see id >  $from ORDER BY tpb_id
  ASC LIMIT 0 , $subset_count -- this makes fetching chunks efficient.
  Oh, wait; it is not efficient -- why id versus tpb_id?  Since
  tpb_id is UNIQUE, get rid of id and promote tpb_id to be the
  PRIMARY KEY.  Then use tpb_id in place of id in the SELECT.

i did changes and ran the sitemap script, still the last sitemap had exact 50k URLs.
on further inspection i noticed on sitemap page 82 , which is last sitemap page, i am getting last record whose tpb_id is 4188464 ,

if i do

SELECT * FROM links WHERE tpb_id <= '4188464' AND enabled = '1'

then i get

334,564 rows

this means all sitemap pages included only 334,564 records from the database instead of 4mil+ records.

on further digging i found , sitemap pages 1-65 contains same 50k urls.

It happened because the lowest tpb_id is 3211594

Update 2: undid changes as suggested by Rick James,

i did some tests with 2 types of queries. (this one is slow)

type 1: old mysql query

MariaDB [db_name]> SELECT * FROM links ORDER BY tpb_id ASC LIMIT 0 , 5 ;
+----+---------+--------------------------------------------------+---------+
| id | tpb_id  | slug                                             | enabled |
+----+---------+--------------------------------------------------+---------+
|  1 | 3211594 | High.Chaparall.S02E02.PDTV.XViD.SWEDiSH-HuBBaTiX |       1 |
|  2 | 3211609 | School.Of.Rock.PROPER.DVDRip.XviD-DMT            |       1 |
|  3 | 3211623 | Gyllene_Tider-Samtliga_Hits-SE-2004-WLM          |       1 |
|  4 | 3211625 | Oz_-_Season_One                                  |       1 |
|  5 | 3211626 | Prince_of_Persia_-_XBOX                          |       1 |
+----+---------+--------------------------------------------------+---------+
5 rows in set (0.01 sec)

MariaDB [db_name]> SELECT * FROM links ORDER BY tpb_id ASC LIMIT 5 , 5 ;
+----+---------+-------------------------------------------+---------+
| id | tpb_id  | slug                                      | enabled |
+----+---------+-------------------------------------------+---------+
|  6 | 3211629 | Welcome.To.Mooseport.DVDSCR.XViD-DVL      |       1 |
|  7 | 3211639 | Top_Secret_Recipes_E-books                |       1 |
|  8 | 3211687 | Italian_Teens_Home_Video                  |       1 |
|  9 | 3211706 | Splinter_Cell_-_PandoraTomorrow_-DEViANCE |       1 |
| 10 | 3211770 | Revolution_OS                             |       1 |
+----+---------+-------------------------------------------+---------+
5 rows in set (0.00 sec)

it is able to fetch records as expected.

type 2:new fast query.

MariaDB [db_name]>  SELECT * FROM links WHERE enabled = '1' AND tpb_id >  0 ORDER BY tpb_id ASC LIMIT 0 , 5 ;
+----+---------+--------------------------------------------------+---------+
| id | tpb_id  | slug                                             | enabled |
+----+---------+--------------------------------------------------+---------+
|  1 | 3211594 | High.Chaparall.S02E02.PDTV.XViD.SWEDiSH-HuBBaTiX |       1 |
|  2 | 3211609 | School.Of.Rock.PROPER.DVDRip.XviD-DMT            |       1 |
|  3 | 3211623 | Gyllene_Tider-Samtliga_Hits-SE-2004-WLM          |       1 |
|  4 | 3211625 | Oz_-_Season_One                                  |       1 |
|  5 | 3211626 | Prince_of_Persia_-_XBOX                          |       1 |
+----+---------+--------------------------------------------------+---------+
5 rows in set (0.00 sec)

MariaDB [db_name]>  SELECT * FROM links WHERE enabled = '1' AND tpb_id >  5 ORDER BY tpb_id ASC LIMIT 0 , 5 ;
+----+---------+--------------------------------------------------+---------+
| id | tpb_id  | slug                                             | enabled |
+----+---------+--------------------------------------------------+---------+
|  1 | 3211594 | High.Chaparall.S02E02.PDTV.XViD.SWEDiSH-HuBBaTiX |       1 |
|  2 | 3211609 | School.Of.Rock.PROPER.DVDRip.XviD-DMT            |       1 |
|  3 | 3211623 | Gyllene_Tider-Samtliga_Hits-SE-2004-WLM          |       1 |
|  4 | 3211625 | Oz_-_Season_One                                  |       1 |
|  5 | 3211626 | Prince_of_Persia_-_XBOX                          |       1 |
+----+---------+--------------------------------------------------+---------+
5 rows in set (0.01 sec)

above you can see type 2 is giving same output because of

tpb_id >  5

and tbp_id was not in incremental and had gaps in it.

Conclusion:
While using type 2 query which uses additional condition.
If table has Auto Increment field then we can use it for reference to get more records using type 2 query which is fast.

so the final query which i was looking for (no, order by/ no, where enabled = 1 condition)

$get_mysql_data_query = " SELECT tpb_id, slug, enabled FROM links WHERE id > $from LIMIT 0 , $subset_count";

and then only using those having enabled = 1

while ($row = mysqli_fetch_assoc($result)) {
    if($row['enabled'] == 1){
        $link = 'https://example.com/post-id/'.$row['tpb_id'].'/'.$row['slug'];
    }
}

so now, it will use id for reference as its incremental and dont have gaps in it, and will scan all 4mil+ records, but only create sitemaps of only those which are enabled.

i have updated script as per above , and will update once the script completes the running.

update: the script is working great and making sitemaps of all pages, not all sitemap pages contains 50k because there are many enabled = 0 records, but thats fine as long as all urls are gets included in sitemaps.

here is the final script logic.

<?php
    $subset_count = 50000 ;

    $total_count_query = "SELECT COUNT(*) as total_count FROM links" ;

    $total_count = mysqli_query ($conn, $total_count_query);
    $total_count = mysqli_fetch_assoc($total_count);
    $total_count = $total_count['total_count'];
    $total_pages = ceil ($total_count / $subset_count);

    $current_page = 1;
    while($current_page <= $total_pages){
        $from = ($current_page * $subset_count) - $subset_count;

        $get_mysql_data_query = " SELECT tpb_id, slug, enabled FROM links WHERE id > $from LIMIT 0 , $subset_count";

        if ($result = mysqli_query($conn, $get_mysql_data_query)) {
            while ($row = mysqli_fetch_assoc($result)) {
                if($row['enabled'] == 1){
                    $link = 'https://example.com/post-id/'.$row['tpb_id'].'/'.$row['slug'];
                }
            }

            mysqli_free_result($result);
        }
        $current_page++ ;
    }


问:
Rails 4: Session Expiry?
I just made the switch from Rails 3.2 to Rails 4. I'm trying to make sure I'm as up-to-speed as possible on security issues, and I'm concerned about sessions right now. It looks like Rails 4 has moved away from supporting really anything EXCEPT cookie-based sessions, but it sounds like it's not possible to prevent cookie-based sessions from living forever. I've been reading several articles, but this one is the most official: http://guides.rubyonrails.org/security.html#session-expiry . Notice how they point out that this is an issue for cookie-based sessions, then they give a fix for it for database-based sessions (which are now deprecated, apparently).

I'm really confused. I want to be able to prevent an attacker from getting a cookie that gives him permanent access to my login-protected site. Obviously I can set :expire_after in initializers/session_store.rb, but unless I'm wrong that simply sets the expiration of the cookie which is client-side and easily altered by an attacker so the session can live forever. Of course I can make things better by forcing SSL, using secure cookies, and forcing HTTP only, but this will never be a complete defence until I can enforce session expiry.

How can I solve this problem when Rails is deprecating the only ways to have server-side sessions?

I know active record sessions has been moved into a gem and is still available, but the fact remains that it has been deprecated. A solution should be possible without introducing more dependencies, or at the very least without using deprecated features.

答:
add this to your application controller:</p>
```<code>before_filter :session_expires, :except => [:login, :logout]
before_filter :update_session_time, :except => [:login, :logout]

def session_expires
  @time_left = (session[:expires_at] - Time.now).to_i
  unless @time_left > 0
    reset_session
    flash[:error] = 'Lorem Ipsum.'
    redirect_to :controller => 'foo', :action => 'bar'
  end
end

def update_session_time
  session[:expires_at] = 60.minutes.from_now
end
</code>```

Title: Rails 4: Session Expiry?

Body:
add this to your application controller:

before_filter :session_expires, :except => [:login, :logout]
before_filter :update_session_time, :except => [:login, :logout]

def session_expires
  @time_left = (session[:expires_at] - Time.now).to_i
  unless @time_left > 0
    reset_session
    flash[:error] = 'Lorem Ipsum.'
    redirect_to :controller => 'foo', :action => 'bar'
  end
end

def update_session_time
  session[:expires_at] = 60.minutes.from_now
end


问:
What is best approach to get sql data from C#
I'm trying to find optimal (fast vs easiest) way to access SQL Server code thru code in C#.

As I was learning from books I've encountered multiple suggestions usually telling me to do it via drag and drop. However since I wanted to do it in code first approach was to get data by column numbers, but any reordering in SQL Query (like adding/removing columns) was pain for me to fix.

For example (don't laugh, some code is like 2 years old), I even coded special function to pass sqlQueryResult and check if it's null or not):

```<code>public static void exampleByColumnNumber(string varValue) {

        string preparedCommand = @"SELECT TOP 1 [SomeColumn],[SomeColumn2]

                                  FROM [Database].[dbo].[Table]
                  WHERE [SomeOtherColumn] = @varValue";
        SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
        sqlQuery.Prepare();
        sqlQuery.Parameters.AddWithValue("@varValue) ", varValue);

        SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
        if (sqlQueryResult != null) {
            while (sqlQueryResult.Read()) {
                string var1 = Locale.checkForNullReturnString(sqlQueryResult, 0);
            string var2 = Locale.checkForNullReturnString(sqlQueryResult, 1);
            }
            sqlQueryResult.Close();
        }
    }
</code>```

Later on I found out it's possible thru column names (which seems easier to read with multiple columns and a lot of changing order etc):

```<code>    public static void exampleByColumnNames(string varValue) {

        string preparedCommand = @"SELECT TOP 1 [SomeColumn],[SomeColumn2]

                                  FROM [Database].[dbo].[Table]
                  WHERE [SomeOtherColumn] = @varValue";
        SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
        sqlQuery.Prepare();
        sqlQuery.Parameters.AddWithValue("@varValue) ", varValue);

        SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
        if (sqlQueryResult != null) {
            while (sqlQueryResult.Read()) {
                string var1 = (string) sqlQueryResult["SomeColumn"];
            string var2 = (string) sqlQueryResult["SomeColumn2"];
            }
            sqlQueryResult.Close();
        }
    }
</code>```

And 3rd example is by doing it by column names but using .ToString()  to make sure it's not null value, or by doing If/else on the null check.

```<code>    public static void exampleByColumnNamesAgain(string varValue) {

        string preparedCommand = @"SELECT TOP 1 [SomeColumn],[SomeColumn2], [SomeColumn3]

                                  FROM [Database].[dbo].[Table]
                  WHERE [SomeOtherColumn] = @varValue";
        SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
        sqlQuery.Prepare();
        sqlQuery.Parameters.AddWithValue("@varValue) ", varValue);

        SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
        if (sqlQueryResult != null) {
            while (sqlQueryResult.Read()) {
                string var1 = (string) sqlQueryResult["SomeColumn"].ToString();
            DateTime var2;
        DateTime.TryParse(sqlQueryResult["SomeColumn2"].ToString());

        int varInt = ((int) sqlQueryResult["SomeColumn3"] == null ? 0 : (int) sqlQueryResult["SomeColumn3"];

            }
            sqlQueryResult.Close();
        }
    }
</code>```

Please bare in mind that I've just created this for sake of this example and there might be some typos or some slight syntax error, but the main question is which approach is best, which is the worst (I know first one is the one that I dislike the most).

I will soon have to start / rewriting some portion of my little 90k lines app which has at least those 3 examples used widely, so i would like to get best method for speed and preferably easiest to maintain (hopefully it will be same approach).

Probably there are some better options out there so please share?

答:
I test the many different ways for get data from sql server database and i faced & found fastest way is following:

First of all create class with "IDataRecord" parameterized method as per your required properties.

```<code>       class emp
        {
            public int empid { get; set; }
            public string name { get; set; }
            public static emp create(IDataRecord record)
            {
                return new emp
                {
                    empid = Convert.ToInt32(record["Pk_HotelId"]),
                    name = record["HotelName"].ToString()
                };
            }
        }
</code>```

Now create method for get data as below:

```<code>public List<S> GetData<S>(string query, Func<IDataRecord, S> selector)
        {
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = query;
                cmd.Connection.Open();
                using (var r = cmd.ExecuteReader())
                {
                    var items = new List<S>();
                    while (r.Read())
                        items.Add(selector(r));
                    return items;
                }
            }
        }
</code>```

And then call function like:

```<code>var data = GetData<emp>("select * from employeeMaster", emp.create);
</code>```

Body:
I'm trying to find optimal (fast vs easiest) way to access SQL Server code thru code in C#.

As I was learning from books I've encountered multiple suggestions usually telling me to do it via drag and drop. However since I wanted to do it in code first approach was to get data by column numbers, but any reordering in SQL Query (like adding/removing columns) was pain for me to fix.

For example (don't laugh, some code is like 2 years old), I even coded special function to pass sqlQueryResult and check if it's null or not):

public static void exampleByColumnNumber(string varValue) {

        string preparedCommand = @"SELECT TOP 1 [SomeColumn],[SomeColumn2]

                                  FROM [Database].[dbo].[Table]
                  WHERE [SomeOtherColumn] = @varValue";
        SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
        sqlQuery.Prepare();
        sqlQuery.Parameters.AddWithValue("@varValue) ", varValue);

        SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
        if (sqlQueryResult != null) {
            while (sqlQueryResult.Read()) {
                string var1 = Locale.checkForNullReturnString(sqlQueryResult, 0);
            string var2 = Locale.checkForNullReturnString(sqlQueryResult, 1);
            }
            sqlQueryResult.Close();
        }
    }

Later on I found out it's possible thru column names (which seems easier to read with multiple columns and a lot of changing order etc):

    public static void exampleByColumnNames(string varValue) {

        string preparedCommand = @"SELECT TOP 1 [SomeColumn],[SomeColumn2]

                                  FROM [Database].[dbo].[Table]
                  WHERE [SomeOtherColumn] = @varValue";
        SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
        sqlQuery.Prepare();
        sqlQuery.Parameters.AddWithValue("@varValue) ", varValue);

        SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
        if (sqlQueryResult != null) {
            while (sqlQueryResult.Read()) {
                string var1 = (string) sqlQueryResult["SomeColumn"];
            string var2 = (string) sqlQueryResult["SomeColumn2"];
            }
            sqlQueryResult.Close();
        }
    }

And 3rd example is by doing it by column names but using .ToString()  to make sure it's not null value, or by doing If/else on the null check.

    public static void exampleByColumnNamesAgain(string varValue) {

        string preparedCommand = @"SELECT TOP 1 [SomeColumn],[SomeColumn2], [SomeColumn3]

                                  FROM [Database].[dbo].[Table]
                  WHERE [SomeOtherColumn] = @varValue";
        SqlCommand sqlQuery = new SqlCommand(preparedCommand, Locale.sqlDataConnection);
        sqlQuery.Prepare();
        sqlQuery.Parameters.AddWithValue("@varValue) ", varValue);

        SqlDataReader sqlQueryResult = sqlQuery.ExecuteReader();
        if (sqlQueryResult != null) {
            while (sqlQueryResult.Read()) {
                string var1 = (string) sqlQueryResult["SomeColumn"].ToString();
            DateTime var2;
        DateTime.TryParse(sqlQueryResult["SomeColumn2"].ToString());

        int varInt = ((int) sqlQueryResult["SomeColumn3"] == null ? 0 : (int) sqlQueryResult["SomeColumn3"];

            }
            sqlQueryResult.Close();
        }
    }

Please bare in mind that I've just created this for sake of this example and there might be some typos or some slight syntax error, but the main question is which approach is best, which is the worst (I know first one is the one that I dislike the most).

I will soon have to start / rewriting some portion of my little 90k lines app which has at least those 3 examples used widely, so i would like to get best method for speed and preferably easiest to maintain (hopefully it will be same approach).

Probably there are some better options out there so please share?

Body:
I test the many different ways for get data from sql server database and i faced & found fastest way is following:

First of all create class with "IDataRecord" parameterized method as per your required properties.

       class emp
        {
            public int empid { get; set; }
            public string name { get; set; }
            public static emp create(IDataRecord record)
            {
                return new emp
                {
                    empid = Convert.ToInt32(record["Pk_HotelId"]),
                    name = record["HotelName"].ToString()
                };
            }
        }

Now create method for get data as below:

public List<S> GetData<S>(string query, Func<IDataRecord, S> selector)
        {
            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandText = query;
                cmd.Connection.Open();
                using (var r = cmd.ExecuteReader())
                {
                    var items = new List<S>();
                    while (r.Read())
                        items.Add(selector(r));
                    return items;
                }
            }
        }

And then call function like:

var data = GetData<emp>("select * from employeeMaster", emp.create);