问:
java regex problem
Suppose I have a string "July is busy". And I need the string without "July". How can I do it with using regex ?

Thanks.

答:
So you want to remove the first word from a string?

Try

```<code>String resultString = subjectString.replaceAll("^\\s*\\w+\\s*", "");
</code>```

Title: java regex problem

Body:
So you want to remove the first word from a string?

Try

String resultString = subjectString.replaceAll("^\\s*\\w+\\s*", "");


来源: stackexchange

问:
The character encoding of the HTML document was not declared
When I click to the HTML document to open it in browser the fllowing message appears:
"The character encoding of the HTML document was not declared. The document will render with index.html garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.
I don't know how can insert my code here</p>

答:
```<code><meta charset="UTF-8" />
</code>```

Just below

ContentLicense: CC BY-SA 3.0

Body:
<meta charset="UTF-8" />

Just below <head>


问:
want to remove gap in between two label controls
Hi there I have just created a rating control using half stars with fontawesome the problem is a gap in between each half star. I use overflow hidden on the star container like this. codepen the gap is visible in chrome

```<code>label:nth-child(4n+2) {
  width: 12px;
  position: relative;
  display: block;
  margin-right: 3px;
  overflow: hidden;
}

label:nth-child(4n+4)::before {
  content: '\f006';
  display: block;
  width: 11px;
  overflow: hidden;
}
</code>```

How can I have the stars more closely joined so there isn't a gap

答:
You can change the margin on the class

```<code>.rating label:nth-child(4n+2)
{
margin-right: 0px;
}
</code>```

once you do this the stars come together, then you can change the width of the right column to make it a little larger (if you want)

Body:
Hi there I have just created a rating control using half stars with fontawesome the problem is a gap in between each half star. I use overflow hidden on the star container like this. codepen the gap is visible in chrome

label:nth-child(4n+2) {
  width: 12px;
  position: relative;
  display: block;
  margin-right: 3px;
  overflow: hidden;
}

label:nth-child(4n+4)::before {
  content: '\f006';
  display: block;
  width: 11px;
  overflow: hidden;
}

How can I have the stars more closely joined so there isn't a gap

Body:
You can change the margin on the class

.rating label:nth-child(4n+2)
{
margin-right: 0px;
}

once you do this the stars come together, then you can change the width of the right column to make it a little larger (if you want)


问:
Laravel 5.2 API Rest and Angular JS - $HTTP_RAW_POST_DATA is deprecated
I am trying to send an $http.post AJAX data to a route configured in Laravel 5.2, everything works perfect, but the server returns this error:

Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated
  and will be removed in a future version. To avoid this warning set
  'always_populate_raw_post_data' to '-1' in php.ini and use the
  php://input stream instead. in Unknown on line 0

Warning: Cannot modify header information - headers already sent in
  Unknown on line 0

This is my code. PHP:

```<code>public function save(Request $request){
      $input = $request->all();
      try {
        $direccion = urlencode($input['Calle']." ".$input['Numero'].", ".$input['Ciudad']);

        $geocode = "https://maps.googleapis.com/maps/api/geocode/json?address=$direccion&key=APIKEY";
        $datosGoogle = json_decode($this->curl($geocode), true);

        $latitud = $datosGoogle['results'][0]['geometry']['location']['lat'];
        $longitud = $datosGoogle['results'][0]['geometry']['location']['lng'];

        if(is_double($latitud) && is_double($latitud)){
          $input['Latitud'] = $latitud;
          $input['Longitud'] = $longitud;
          $new = MyModel::create($input);
          $data = ["status"=>"ok", "message"=>"Agregado correctamente"];
        }else{
          $data = ["status"=>"fail", "message"=>"Dirección desconocida, compruebe que los datos son correctos para que podamos agregarla al sistema."];
        }
      } catch (Exception $e) {
        $data = ["status"=>"error", "message"=>$e->getMessage()];
      }
      return response()->JSON($data);
    }
</code>```

JS:

```<code>$scope.registrar = function(form, datos) {
      $scope.submitted = true;
      if(form.$valid) {
        var toSendData = JSON.stringify({
          Nombre: datos.nombre,
          Calle: datos.calle,
          Numero: datos.numero,
          Piso: datos.piso,
          Puerta: datos.puerta,
          CP: datos.cp,
          Ciudad: datos.ciudad,
          Email: datos.email,
          Necesidades: datos.necesidades,
          Telefono: datos.telefono
        });
        console.log(toSendData);
        $http.post($rootScope.recibirNuevoUrl, toSendData).then(function(response){
          $scope.hideLoading();
          if(response.data.status == "ok"){
            $state.go('registro');
          }else{
            $scope.$parent.showAlert("Error al introducir los datos", response.data.message);
          }
        })
      }else{
        $scope.$parent.showAlert('Validacion de datos', 'El formulario contiene errores. Por favor revise los campos marcados para comprobar los errores.');
      }
    };
</code>```

How can I fix it?

答:
laravel 5.2

/resource/assets/js/bootstrap.js

window.axios = require('axios');
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
//add default Content-Type
window.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';```
</div>
</div>
</p>

<p><strong>2 data mast be string</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const qs = require('qs')
axios.post('/api/code/create', qs.stringify(this.formItem),)
    .then(function (response) {
        console.log(response)
    })
    .catch(function (error) {
        console.log(error)
    })</code>```

Body:
I am trying to send an $http.post AJAX data to a route configured in Laravel 5.2, everything works perfect, but the server returns this error:

Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated
  and will be removed in a future version. To avoid this warning set
  'always_populate_raw_post_data' to '-1' in php.ini and use the
  php://input stream instead. in Unknown on line 0

Warning: Cannot modify header information - headers already sent in
  Unknown on line 0

This is my code. PHP:

public function save(Request $request){
      $input = $request->all();
      try {
        $direccion = urlencode($input['Calle']." ".$input['Numero'].", ".$input['Ciudad']);

        $geocode = "https://maps.googleapis.com/maps/api/geocode/json?address=$direccion&key=APIKEY";
        $datosGoogle = json_decode($this->curl($geocode), true);

        $latitud = $datosGoogle['results'][0]['geometry']['location']['lat'];
        $longitud = $datosGoogle['results'][0]['geometry']['location']['lng'];

        if(is_double($latitud) && is_double($latitud)){
          $input['Latitud'] = $latitud;
          $input['Longitud'] = $longitud;
          $new = MyModel::create($input);
          $data = ["status"=>"ok", "message"=>"Agregado correctamente"];
        }else{
          $data = ["status"=>"fail", "message"=>"Dirección desconocida, compruebe que los datos son correctos para que podamos agregarla al sistema."];
        }
      } catch (Exception $e) {
        $data = ["status"=>"error", "message"=>$e->getMessage()];
      }
      return response()->JSON($data);
    }

JS:

$scope.registrar = function(form, datos) {
      $scope.submitted = true;
      if(form.$valid) {
        var toSendData = JSON.stringify({
          Nombre: datos.nombre,
          Calle: datos.calle,
          Numero: datos.numero,
          Piso: datos.piso,
          Puerta: datos.puerta,
          CP: datos.cp,
          Ciudad: datos.ciudad,
          Email: datos.email,
          Necesidades: datos.necesidades,
          Telefono: datos.telefono
        });
        console.log(toSendData);
        $http.post($rootScope.recibirNuevoUrl, toSendData).then(function(response){
          $scope.hideLoading();
          if(response.data.status == "ok"){
            $state.go('registro');
          }else{
            $scope.$parent.showAlert("Error al introducir los datos", response.data.message);
          }
        })
      }else{
        $scope.$parent.showAlert('Validacion de datos', 'El formulario contiene errores. Por favor revise los campos marcados para comprobar los errores.');
      }
    };

How can I fix it?

Body:
laravel 5.2

/resource/assets/js/bootstrap.js

window.axios = require('axios');
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
//add default Content-Type
window.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

2 data mast be string

const qs = require('qs')
axios.post('/api/code/create', qs.stringify(this.formItem),)
    .then(function (response) {
        console.log(response)
    })
    .catch(function (error) {
        console.log(error)
    })


问:
How to properly relate items to pricing data, taking price change history into account
Virtually all POS systems record the price of an item directly to the transactions table at the time of the sale since that price may change at a later date, but the price it sold at should remain the same.

I'm wondering how you would setup pricing table(s) that keep a history of price changes, so that you can relate the transactions to that table based on the item and the time it was sold in order to get the correct price?

I think anyone who's ever worked with POS systems will understand what I'm talking about here, but if my question is unclear let me know and I will try to explain better.

I didn't tag a specific database because this question obviously isn't specific to a particular one, but because I know it's the first question I'll be asked: SQL Server 2008.

EDIT:

Here's one solution I just thought of that I would love to get some feedback on...

I'm thinking I could have a price table that has fields like so:
PriceId, ItemId, Price, Date

PriceId would be an autonumber and ItemId relates to the Items table.  Now instead of saving the actual price to the transactions table, I would save the most current PriceId for the given item.

Thoughts?

答:
You'd have to adapt this to your situation, but in mine, I had a lookup table of charge types, and this was how I updated the charge to a new price and retained the original price for reference. The overhead of the view in this is only in terms of however often you query it for generating an invoice. Which is my use case.

You use vwCharge here to get a list of the most current pricing. When update_charge_rate() is used, it adds a new one with the date it was updated, and querying vwCharge will only show the most recent.

The delimiter is set to //

The lookup table:

```<code>CREATE TABLE lkCharge (
  charge_id SMALLINT NOT NULL AUTO_INCREMENT,
  charge_datecreated DATE NOT NULL,
  charge_name VARCHAR(20) NOT NULL,
  charge_rate DECIMAL(10,2) NOT NULL,
  charge_islocked CHAR(1) DEFAULT 'N',
  charge_lockedby VARCHAR(255) DEFAULT NULL,
  charge_lockdate TIMESTAMP NULL,
  charge_isdeleted CHAR(1) DEFAULT 'N',
  CONSTRAINT pkChargeId PRIMARY KEY(charge_id, charge_datecreated)
) ENGINE=InnoDB DEFAULT CHARSET=utf8//
</code>```

The view:

```<code>CREATE VIEW vwCharge AS
  SELECT
    charge_id,
    charge_datecreated,
    charge_name,
    charge_rate,
    charge_islocked,
    charge_lockedby,
    charge_lockdate,
    charge_isdeleted
  FROM lkCharge AS o
  WHERE o.charge_id=o.charge_id AND charge_datecreated=(
    SELECT MAX(charge_datecreated)
      FROM lkCharge AS i
        WHERE i.charge_id=o.charge_id
  )//
</code>```

The update procedure:

```<code>CREATE PROCEDURE update_charge_rate(
  IN p_charge_id SMALLINT,
  IN p_new_charge_rate DECIMAL(10,2)
)
BEGIN
  DECLARE _name VARCHAR(20);

  SELECT charge_name INTO _name
    FROM vwCharge WHERE charge_id=p_charge_id;

  INSERT INTO lkCharge(charge_id, charge_datecreated, charge_name, charge_rate)
    VALUES(p_charge_id, UTC_DATE(), _name, p_new_charge_rate);

  SELECT LAST_INSERT_ID();
END//
</code>```

Body:
You'd have to adapt this to your situation, but in mine, I had a lookup table of charge types, and this was how I updated the charge to a new price and retained the original price for reference. The overhead of the view in this is only in terms of however often you query it for generating an invoice. Which is my use case.

You use vwCharge here to get a list of the most current pricing. When update_charge_rate() is used, it adds a new one with the date it was updated, and querying vwCharge will only show the most recent.

The delimiter is set to //

The lookup table:

CREATE TABLE lkCharge (
  charge_id SMALLINT NOT NULL AUTO_INCREMENT,
  charge_datecreated DATE NOT NULL,
  charge_name VARCHAR(20) NOT NULL,
  charge_rate DECIMAL(10,2) NOT NULL,
  charge_islocked CHAR(1) DEFAULT 'N',
  charge_lockedby VARCHAR(255) DEFAULT NULL,
  charge_lockdate TIMESTAMP NULL,
  charge_isdeleted CHAR(1) DEFAULT 'N',
  CONSTRAINT pkChargeId PRIMARY KEY(charge_id, charge_datecreated)
) ENGINE=InnoDB DEFAULT CHARSET=utf8//

The view:

CREATE VIEW vwCharge AS
  SELECT
    charge_id,
    charge_datecreated,
    charge_name,
    charge_rate,
    charge_islocked,
    charge_lockedby,
    charge_lockdate,
    charge_isdeleted
  FROM lkCharge AS o
  WHERE o.charge_id=o.charge_id AND charge_datecreated=(
    SELECT MAX(charge_datecreated)
      FROM lkCharge AS i
        WHERE i.charge_id=o.charge_id
  )//

The update procedure:

CREATE PROCEDURE update_charge_rate(
  IN p_charge_id SMALLINT,
  IN p_new_charge_rate DECIMAL(10,2)
)
BEGIN
  DECLARE _name VARCHAR(20);

  SELECT charge_name INTO _name
    FROM vwCharge WHERE charge_id=p_charge_id;

  INSERT INTO lkCharge(charge_id, charge_datecreated, charge_name, charge_rate)
    VALUES(p_charge_id, UTC_DATE(), _name, p_new_charge_rate);

  SELECT LAST_INSERT_ID();
END//


问:
Return a value of 0 or 0.00 along with where clause MySQL
While I was debugging and seeing some test with my query, I noticed that some of my results have NULL values. I want to return them or see them as a value of 0 or 0.00 according to their type just like the Senior.

I tried it with a case statement but it didn't get the result I wanted which is 0.

This is determined through where clause according to type.

Here's my query:

```<code>SELECT a.ID as EMPLOYEE, a.DOB as Date, a.AMOUNT as DECLARED,
(SELECT (CASE WHEN

SUM(gndsale.AMOUNT) and gndsale.ID IS NULL then "0" and gndsale.typeid = "10" else
SUM(gndsale.AMOUNT) END)
from gndsale where gndsale.ID= b.ID and
gndsale.typeid = "10" and gndsale.DOB = a.DOB)  as `SENIOR DISCOUNT`

FROM
gndsale a INNER JOIN emp b ON a.ID= b.ID WHERE a.type = "22" and STR_TO_DATE(a.DOB,
'%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-31' GROUP BY DECLARED order by STR_TO_DATE(a.DOB, '%m/%d/%Y')
</code>```

Here is my result:

I want to make that Null Value as 0

答:
One way would be to wrap your subquery with COALESCE() and use zero as a default value:

```<code>SELECT
    a.ID AS EMPLOYEE,
    a.DOB AS Date,
    a.AMOUNT AS DECLARED,
    COALESCE(
        (SELECT
            CASE WHEN SUM(gndsale.AMOUNT) AND gndsale.ID IS NULL AND gndsale.typeid = "10"
                 THEN 0 ELSE SUM(gndsale.AMOUNT) END
        FROM gndsale
        WHERE gndsale.ID = b.ID AND
              gndsale.typeid = "10" AND
              gndsale.DOB = a.DOB), 0) AS `SENIOR DISCOUNT`
FROM gndsale a
INNER JOIN emp b
    ON a.ID = b.ID
WHERE a.type = "22" AND
      STR_TO_DATE(a.DOB, '%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-31'
GROUP BY DECLARED
ORDER BY STR_TO_DATE(a.DOB, '%m/%d/%Y')
</code>```

Body:
While I was debugging and seeing some test with my query, I noticed that some of my results have NULL values. I want to return them or see them as a value of 0 or 0.00 according to their type just like the Senior.

I tried it with a case statement but it didn't get the result I wanted which is 0.

This is determined through where clause according to type.

Here's my query:

SELECT a.ID as EMPLOYEE, a.DOB as Date, a.AMOUNT as DECLARED,
(SELECT (CASE WHEN

SUM(gndsale.AMOUNT) and gndsale.ID IS NULL then "0" and gndsale.typeid = "10" else
SUM(gndsale.AMOUNT) END)
from gndsale where gndsale.ID= b.ID and
gndsale.typeid = "10" and gndsale.DOB = a.DOB)  as `SENIOR DISCOUNT`

FROM
gndsale a INNER JOIN emp b ON a.ID= b.ID WHERE a.type = "22" and STR_TO_DATE(a.DOB,
'%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-31' GROUP BY DECLARED order by STR_TO_DATE(a.DOB, '%m/%d/%Y')

Here is my result:

I want to make that Null Value as 0

Body:
One way would be to wrap your subquery with COALESCE() and use zero as a default value:

SELECT
    a.ID AS EMPLOYEE,
    a.DOB AS Date,
    a.AMOUNT AS DECLARED,
    COALESCE(
        (SELECT
            CASE WHEN SUM(gndsale.AMOUNT) AND gndsale.ID IS NULL AND gndsale.typeid = "10"
                 THEN 0 ELSE SUM(gndsale.AMOUNT) END
        FROM gndsale
        WHERE gndsale.ID = b.ID AND
              gndsale.typeid = "10" AND
              gndsale.DOB = a.DOB), 0) AS `SENIOR DISCOUNT`
FROM gndsale a
INNER JOIN emp b
    ON a.ID = b.ID
WHERE a.type = "22" AND
      STR_TO_DATE(a.DOB, '%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-31'
GROUP BY DECLARED
ORDER BY STR_TO_DATE(a.DOB, '%m/%d/%Y')


问:
How to extract xyz coordinates from 3D point cloud in MATLAB
I am using a Kinect for Windows to import 3D images into MATLAB. I want to be able to find the 3D co-ordinates of objects within the 3D scene.

One simple way to do this is to use the clickA3DPoint function found here, and then click the point I want to know the co-ordinates of.

The problem is clickA3DPoint expects the arguments in a 3 by N matrix, which is the x y and z coordinates of N samples. When I use the Kinect to get a point cloud with depthToPointCloud it returns a 480 * 640 * 3 matrix.

How can I extract the x, y, and z coordinates from this matrix so I can plot it with clickA3DPoint? (or scatter3?)

My attempt so far:

```<code>depthDevice = imaq.VideoDevice('kinect',2)  %this is the kinect depth sensor

depthImage = step(depthDevice);  %this takes a depth image. (A 480 * 640 uint16 array)

xyzPoints = depthToPointCloud(depthImage,depthDevice); %convert the depth image to a point cloud

clickA3DPoint(reshape(xyzPoints,[3,307200])) %I'm guessing each of the 480 * 640 points (307200 points) has an x,y and z coordinate, so this concates the coordinates of all these points.
</code>```

But this just plots the points along a diagonal line in the 3D space. How do I actually extract the x, y and z coordinates from a point cloud in Matlab?

答:
you can use the Property 'Location' of pointCloud to get the x,y,z.
for example:</p>

```<code>moving = movingReg.Location;%movingReg is a pointCloud
scatter(moving(:,1),moving(:,2));
</code>```

Body:
I am using a Kinect for Windows to import 3D images into MATLAB. I want to be able to find the 3D co-ordinates of objects within the 3D scene.

One simple way to do this is to use the clickA3DPoint function found here, and then click the point I want to know the co-ordinates of.

The problem is clickA3DPoint expects the arguments in a 3 by N matrix, which is the x y and z coordinates of N samples. When I use the Kinect to get a point cloud with depthToPointCloud it returns a 480 * 640 * 3 matrix.

How can I extract the x, y, and z coordinates from this matrix so I can plot it with clickA3DPoint? (or scatter3?)

My attempt so far:

depthDevice = imaq.VideoDevice('kinect',2)  %this is the kinect depth sensor

depthImage = step(depthDevice);  %this takes a depth image. (A 480 * 640 uint16 array)

xyzPoints = depthToPointCloud(depthImage,depthDevice); %convert the depth image to a point cloud

clickA3DPoint(reshape(xyzPoints,[3,307200])) %I'm guessing each of the 480 * 640 points (307200 points) has an x,y and z coordinate, so this concates the coordinates of all these points.

But this just plots the points along a diagonal line in the 3D space. How do I actually extract the x, y and z coordinates from a point cloud in Matlab?

Body:
you can use the Property 'Location' of pointCloud to get the x,y,z.
for example:

moving = movingReg.Location;%movingReg is a pointCloud
scatter(moving(:,1),moving(:,2));


问:
How do I return a unsure type?
I have a parent Class named 'Shape' and write a method in it
I want any class extends from it can call the bigger method for other use.
simple logic like this:

```<code>public abstract Class Shape{
    public int size;
    public Shape() {}
    public Class<? extends Shape> bigger() {
        this.size += 1;
        return this; // ← Here,How can I return it with unsure type?
    }
}
</code>```

but how can I return a unsure type in here ?
thanks for any ideas!

====

and if I have a class Square extends Shape;

and I want use it like this:

```<code>Square S = new Square().bigger();
</code>```

And it will return a Shape Class, not a Square Class.

but I don't wanna use: (Square) new Square.bigger();

I hope it can automatic recognize what Class a using this method

And return the correct type.

答:
In Java, when you override a method you can actually be more specific than the interface requires. For example, the interface requires bigger returns a Shape, but a Square class that extends from Shape could return a Square since a Square is a Shape. This means if you assign it to a Square variable, there is no need to cast when you call bigger.

```<code>public abstract class Shape { // class not Class
    public int size;

    public Shape bigger() {
        this.size += 1;
        return this;
    }
}

public class Square extends Shape {
    @Override
    public Square bigger() {
        this.size += 1;
        return this;
    }
}
</code>```

That's one way of doing it, which in this case is a little frustrating because it repeats the code. Another way of doing this, that would work in C# as well, is to use a generic with a restriction that the generic type implement itself. This is called the Curiously Recurring Template Pattern https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

```<code>public abstract class Shape <S extends Shape>{
    public int size;

    public S bigger() {
        this.size += 1;
        return this;
    }
}

public class Square extends Shape<Square>{
}
</code>```

Title: How do I return a unsure type?

Body:
I have a parent Class named 'Shape' and write a method in it
I want any class extends from it can call the bigger method for other use.
simple logic like this:

public abstract Class Shape{
    public int size;
    public Shape() {}
    public Class<? extends Shape> bigger() {
        this.size += 1;
        return this; // ← Here,How can I return it with unsure type?
    }
}

but how can I return a unsure type in here ?
thanks for any ideas!

====

and if I have a class Square extends Shape;

and I want use it like this:

Square S = new Square().bigger();

And it will return a Shape Class, not a Square Class.

but I don't wanna use: (Square) new Square.bigger();

I hope it can automatic recognize what Class a using this method

And return the correct type.

Body:
In Java, when you override a method you can actually be more specific than the interface requires. For example, the interface requires bigger returns a Shape, but a Square class that extends from Shape could return a Square since a Square is a Shape. This means if you assign it to a Square variable, there is no need to cast when you call bigger.

public abstract class Shape { // class not Class
    public int size;

    public Shape bigger() {
        this.size += 1;
        return this;
    }
}

public class Square extends Shape {
    @Override
    public Square bigger() {
        this.size += 1;
        return this;
    }
}

That's one way of doing it, which in this case is a little frustrating because it repeats the code. Another way of doing this, that would work in C# as well, is to use a generic with a restriction that the generic type implement itself. This is called the Curiously Recurring Template Pattern https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

public abstract class Shape <S extends Shape>{
    public int size;

    public S bigger() {
        this.size += 1;
        return this;
    }
}

public class Square extends Shape<Square>{
}


问:
Django's CachedStaticFilesStorage not hashing file urls
I wanted to enabling versioning to some of my javascript and css files as I was getting caching problems when working on the site. I read about CachedStaticFilesStorage in Django 1.6 and it seemed perfect. I modified my settings.py to the following settings:

```<code>STATIC_ROOT = 'staticfiles'

STATIC_URL = ''

# Additional locations of static files
STATICFILES_DIRS = (
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'
</code>```

As a test I then rewrote the most problematic of the css tags to see if it would start hashing the file path. I instead got a 500 error whenever I try and load the page.

Any ideas where I went wrong? Is there an additional step I missed?

The entry in the template:

```<code>{% block cssfiles %}
{% load static%}
<link href="{% static "/static/css/mapmaker.css" %}" media="screen">
{% endblock %}
</code>```

答:
This is fixed in Django 1.10, as explained in the documentation:

In older versions, you also had to use {% load static from staticfiles %} in your template. The static template tag ({% load static %}) now uses django.contrib.staticfiles if it’s installed.

Body:
I wanted to enabling versioning to some of my javascript and css files as I was getting caching problems when working on the site. I read about CachedStaticFilesStorage in Django 1.6 and it seemed perfect. I modified my settings.py to the following settings:

STATIC_ROOT = 'staticfiles'

STATIC_URL = ''

# Additional locations of static files
STATICFILES_DIRS = (
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'

As a test I then rewrote the most problematic of the css tags to see if it would start hashing the file path. I instead got a 500 error whenever I try and load the page.

Any ideas where I went wrong? Is there an additional step I missed?

The entry in the template:

{% block cssfiles %}
{% load static%}
<link href="{% static "/static/css/mapmaker.css" %}" media="screen">
{% endblock %}


问:
angular-ivh-treeview: transmit the on-cb-change callback to my custom template node?
How do I transmit the on-cb-change callback to my custom template node?

Everything is working fine when i'm only using the directive ivh-treeview-on-cb-change. But whenever I want to add a custom template the directive doesn't work.

What can be the problem?

```<code><div ivh-treeview="stuff"
     ivh-treeview-on-cb-change="myfunc(ivhNode, ivhIsSelected, ivhTree)">
         <script type="text/ng-template">
             <span ivh-treeview-toggle>
                 <span ivh-treeview-twistie></span>
             </span>
             <ascii-box></ascii-box>
             <span class="ivh-treeview-node-label"
                   ivh-treeview-toggle>
                       {{trvw.label(node)}}
             </span>
             <div ivh-treeview-children></div>
         </script>
</div>

$scope.myfunc = function (ivhNode, ivhIsSelected, ivhTree) {
    console.log(ivhNode, ivhIsSelected, ivhTree);
}
</code>```

答:
The problem you're running into is that inline templates do not have access to a transcluded scope. I.e. the scope your template has access to does not inherit from the scope you're attaching functions to.

This is being added as a feature in the v2 release of ivh-treeview (currently accessible as an alpha release).

In v1.x of treeview your best bet will be to broadcast/emit events for communication in and out of templates.

Of note:

https://github.com/iVantage/angular-ivh-treeview/pull/158

https://github.com/iVantage/angular-ivh-treeview/issues/81

Body:
How do I transmit the on-cb-change callback to my custom template node?

Everything is working fine when i'm only using the directive ivh-treeview-on-cb-change. But whenever I want to add a custom template the directive doesn't work.

What can be the problem?

$scope.myfunc = function (ivhNode, ivhIsSelected, ivhTree) {
    console.log(ivhNode, ivhIsSelected, ivhTree);
}


问:
Difference between public and private variables
```<code>namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}
</code>```

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?

答:
From the accessibility levels at MSDN:

public Access is not restricted.

protected Access is limited to the containing class or types derived from
  the containing class.

internal Access is limited to the current assembly.

protected internal Access is limited to the current assembly or
  types derived from the containing
  class.

private Access is limited to the containing type.

ContentLicense: CC BY-SA 2.5

Body:
namespace hi
{
    class hithere
    {
         public int numberOne = 12;
         private int numberTwo = 12;

         static void yo()
         {
         }
    }
}

Can someone tell me the difference between the variables numberOne and numberTwo in this code excerpt?


问:
Strategy for securing Azure AD application Client ID and Secret in Azure KeyVault
We are planning to use azure key vault for securing database connection string other secrets e.g. Azure AD application secret and client ID.

But while fetching this values from key-vault we need to provide Azure AD client id and secret to API and we end up setting these values in application.json file.

What is best way to store secure Azure AD clientID and secret in Azure Key-vault? I know we can create separate AD Application and utilize that but I want to avoid creating new application.

答: You are using key-vault to secure clientID/secret , like you create a key(key-vault) to access resources(clientID/secret) in a strongbox ,  but you need another key to use key-vault key .... That seems a infinite loop . If that app is host on azure(app service) , you could store the client ID/secret in App settings in Application settings blade of app service . The Azure Web App configurations in the cloud will be injected into the config system at runtime . You will not set the configurations in system files(web.config) and azure provides basic security protect .


问:
How to use google cloud storage in dataflow pipeline run from datalab
We've been running a Python pipeline in datalab that reads image files from a bucket in google cloud storage (importing google.datalab.storage). Originally we were using DirectRunner and this worked fine, but now we're trying to use DataflowRunner, and we're having import errors. Even if we include "import google.datalab.storage" or any variant thereof inside the function run by the pipeline, we get errors such as "No module named 'datalab.storage'". We've also tried using the save_main_session, requirements_file, and setup_file flags with no luck. How would we correctly access image files in cloud storage buckets in a dataflow pipeline?

EDIT: My original error was due to specifying the requirements_file flag with incorrect syntax (i.e. "--requirements_file ./requirements.txt"). I think I've fixed the syntax there, but now I'm getting a different error. Here's a basic version of the code we're trying to run- we have a pipeline that reads files from a storage bucket in Google Cloud.
We have a datalab notebook with a cell containing the following Python code:

```<code>import apache_beam as beam
from apache_beam.utils.pipeline_options import PipelineOptions
from apache_beam.utils.pipeline_options import GoogleCloudOptions
from apache_beam.utils.pipeline_options import StandardOptions
import google.datalab.storage as storage

bucket = "BUCKET_NAME"
shared_bucket = storage.Bucket(bucket)

# Create and set PipelineOptions.
options = PipelineOptions(flags = ["--requirements_file", "./requirements.txt"])
google_cloud_options = options.view_as(GoogleCloudOptions)
google_cloud_options.project = "PROJECT_NAME"
google_cloud_options.job_name = 'test-pipeline-requirements'
google_cloud_options.staging_location = 'gs://BUCKET_NAME/binaries'
google_cloud_options.temp_location = 'gs://BUCKET_NAME/temp'
options.view_as(StandardOptions).runner = 'DataflowRunner'

def read_file(input_tuple):
  filepath = input_tuple[0]
  shared_object = shared_bucket.object(filepath)
  f = shared_object.read_stream()
  # More processing of f's contents
  return input_tuple

# File paths relative to the bucket
input_tuples = [("FILEPATH_1", "UNUSED_FILEPATH_2")]
p = beam.Pipeline(options = options)
all_files = (p | "Create file path tuple" >> beam.Create(input_tuples))
all_files = (all_files | "Read file" >> beam.FlatMap(read_file))
p.run()
</code>```

Meanwhile there is a file named "requirements.txt" in the same directory as the notebook, with only the line

```<code>datalab==1.0.1
</code>```

This code works fine if I use DirectRunner. However, when I use DataflowRunner, I get a CalledProcessError at "p.run()", with stack trace ending with the following:

/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/internal/dependency.pyc in _populate_requirements_cache(requirements_file, cache_dir)

      224       '--no-binary', ':all:']

      225   logging.info('Executing command: %s', cmd_args)

  --> 226   processes.check_call(cmd_args)

      227

      228

/usr/local/lib/python2.7/dist-packages/apache_beam/utils/processes.pyc in check_call(*args, **kwargs)

       38   if force_shell:

       39     kwargs['shell'] = True

  ---> 40   return subprocess.check_call(*args, **kwargs)

       41

       42

/usr/lib/python2.7/subprocess.pyc in check_call(*popenargs, **kwargs)

      538         if cmd is None:

      539             cmd = popenargs[0]

  --> 540         raise CalledProcessError(retcode, cmd)

      541     return 0

      542

CalledProcessError: Command '['/usr/bin/python', '-m', 'pip', 'install', '--download', '/tmp/dataflow-requirements-cache', '-r', './requirements.txt', '--no-binary', ':all:']' returned non-zero exit status 1

It seems like the "--download" option is deprecated for pip, but that's part of the apache_beam code. I've also tried this with different ways of specifying "requirements.txt", with and without the "--save_main_session" flag, and with and without the "--setup_file" flag, but no dice.

答:
The most likely issue is that you need to have Dataflow install the datalab pypi module.

Typically you would do this by listing "datalab" in the requirements.txt file you upload to Dataflow.  See https://cloud.google.com/dataflow/pipelines/dependencies-python

Body:
We've been running a Python pipeline in datalab that reads image files from a bucket in google cloud storage (importing google.datalab.storage). Originally we were using DirectRunner and this worked fine, but now we're trying to use DataflowRunner, and we're having import errors. Even if we include "import google.datalab.storage" or any variant thereof inside the function run by the pipeline, we get errors such as "No module named 'datalab.storage'". We've also tried using the save_main_session, requirements_file, and setup_file flags with no luck. How would we correctly access image files in cloud storage buckets in a dataflow pipeline?

EDIT: My original error was due to specifying the requirements_file flag with incorrect syntax (i.e. "--requirements_file ./requirements.txt"). I think I've fixed the syntax there, but now I'm getting a different error. Here's a basic version of the code we're trying to run- we have a pipeline that reads files from a storage bucket in Google Cloud.
We have a datalab notebook with a cell containing the following Python code:

import apache_beam as beam
from apache_beam.utils.pipeline_options import PipelineOptions
from apache_beam.utils.pipeline_options import GoogleCloudOptions
from apache_beam.utils.pipeline_options import StandardOptions
import google.datalab.storage as storage

bucket = "BUCKET_NAME"
shared_bucket = storage.Bucket(bucket)

# Create and set PipelineOptions.
options = PipelineOptions(flags = ["--requirements_file", "./requirements.txt"])
google_cloud_options = options.view_as(GoogleCloudOptions)
google_cloud_options.project = "PROJECT_NAME"
google_cloud_options.job_name = 'test-pipeline-requirements'
google_cloud_options.staging_location = 'gs://BUCKET_NAME/binaries'
google_cloud_options.temp_location = 'gs://BUCKET_NAME/temp'
options.view_as(StandardOptions).runner = 'DataflowRunner'

def read_file(input_tuple):
  filepath = input_tuple[0]
  shared_object = shared_bucket.object(filepath)
  f = shared_object.read_stream()
  # More processing of f's contents
  return input_tuple

# File paths relative to the bucket
input_tuples = [("FILEPATH_1", "UNUSED_FILEPATH_2")]
p = beam.Pipeline(options = options)
all_files = (p | "Create file path tuple" >> beam.Create(input_tuples))
all_files = (all_files | "Read file" >> beam.FlatMap(read_file))
p.run()

Meanwhile there is a file named "requirements.txt" in the same directory as the notebook, with only the line

datalab==1.0.1

This code works fine if I use DirectRunner. However, when I use DataflowRunner, I get a CalledProcessError at "p.run()", with stack trace ending with the following:

/usr/local/lib/python2.7/dist-packages/apache_beam/runners/dataflow/internal/dependency.pyc in _populate_requirements_cache(requirements_file, cache_dir)

      224       '--no-binary', ':all:']

      225   logging.info('Executing command: %s', cmd_args)

  --> 226   processes.check_call(cmd_args)

      227

      228

/usr/local/lib/python2.7/dist-packages/apache_beam/utils/processes.pyc in check_call(*args, **kwargs)

       38   if force_shell:

       39     kwargs['shell'] = True

  ---> 40   return subprocess.check_call(*args, **kwargs)

       41

       42

/usr/lib/python2.7/subprocess.pyc in check_call(*popenargs, **kwargs)

      538         if cmd is None:

      539             cmd = popenargs[0]

  --> 540         raise CalledProcessError(retcode, cmd)

      541     return 0

      542

CalledProcessError: Command '['/usr/bin/python', '-m', 'pip', 'install', '--download', '/tmp/dataflow-requirements-cache', '-r', './requirements.txt', '--no-binary', ':all:']' returned non-zero exit status 1

It seems like the "--download" option is deprecated for pip, but that's part of the apache_beam code. I've also tried this with different ways of specifying "requirements.txt", with and without the "--save_main_session" flag, and with and without the "--setup_file" flag, but no dice.


问:
Subquery using Oracle SQL
I am trying to write a query which excludes meter_nos with three of the same date values ie. a 1-3 relationship.

The query must only show meter_nos which have different dates, i.e a 1-1 relationship.

Can anyone help? I am stuck

Heres a sample below:

```<code> ...and a.mtr_id in (select b.mtr_id
                from ci_mtr_config b
                where a.mtr_id=b.mtr_id
                 group by b.mtr_id
                 having count(b.mtr_id)=3)
   and a.mtr_id not in (select f.eff_dttm
                 from ci_mtr_config f
                  where a.mtr_id=f.mtr_id
                   group by f.eff_dttm
                  having count(f.eff_dttm)=3)
</code>```

This does not work.

答:
Try using COUNT(*) OVER(PARTITION BY ....) to count the number of rows sharing the same meter and date. Then filter by that calculation.

```<code>CREATE TABLE CI_MTR_CONFIG
    (MTR_ID INT, EFF_DTTM DATE)
;

INSERT INTO CI_MTR_CONFIG
    (MTR_ID, EFF_DTTM)
    VALUES
    (303, to_date('2017-01-01','yyyy-mm-dd')),
    (303, to_date('2017-01-01','yyyy-mm-dd')),
    (303, to_date('2017-01-01','yyyy-mm-dd')),
    (202, to_date('2017-01-01','yyyy-mm-dd')),
    (202, to_date('2017-01-01','yyyy-mm-dd')),
    (101, to_date('2017-01-01','yyyy-mm-dd'))
;

select
    *
from (
      select
          *, count(*) over(partition by MTR_ID, EFF_DTTM) as count_of
      from CI_MTR_CONFIG
      ) d
where count_of = 1
</code>```

Only meter 101 would be returned from the sample data above.

Note if EFF_DTTM information is more accurate than day use TRUNC()

```<code>count(*) over(partition by MTR_ID, TRUNC(EFF_DTTM)) as count_of
</code>```

Title: Subquery using Oracle SQL

Body:
I am trying to write a query which excludes meter_nos with three of the same date values ie. a 1-3 relationship.

The query must only show meter_nos which have different dates, i.e a 1-1 relationship.

Can anyone help? I am stuck

Heres a sample below:

 ...and a.mtr_id in (select b.mtr_id
                from ci_mtr_config b
                where a.mtr_id=b.mtr_id
                 group by b.mtr_id
                 having count(b.mtr_id)=3)
   and a.mtr_id not in (select f.eff_dttm
                 from ci_mtr_config f
                  where a.mtr_id=f.mtr_id
                   group by f.eff_dttm
                  having count(f.eff_dttm)=3)

This does not work.

Body:
Try using COUNT(*) OVER(PARTITION BY ....) to count the number of rows sharing the same meter and date. Then filter by that calculation.

CREATE TABLE CI_MTR_CONFIG
    (MTR_ID INT, EFF_DTTM DATE)
;

INSERT INTO CI_MTR_CONFIG
    (MTR_ID, EFF_DTTM)
    VALUES
    (303, to_date('2017-01-01','yyyy-mm-dd')),
    (303, to_date('2017-01-01','yyyy-mm-dd')),
    (303, to_date('2017-01-01','yyyy-mm-dd')),
    (202, to_date('2017-01-01','yyyy-mm-dd')),
    (202, to_date('2017-01-01','yyyy-mm-dd')),
    (101, to_date('2017-01-01','yyyy-mm-dd'))
;

select
    *
from (
      select
          *, count(*) over(partition by MTR_ID, EFF_DTTM) as count_of
      from CI_MTR_CONFIG
      ) d
where count_of = 1

Only meter 101 would be returned from the sample data above.

Note if EFF_DTTM information is more accurate than day use TRUNC()

count(*) over(partition by MTR_ID, TRUNC(EFF_DTTM)) as count_of


问:
Swift 4 Codable decoding json
I'm trying to implement the new Codable protocol, so I added Codable to my struct, but am stuck on decoding the JSON.

Here's what I had before:

Struct -

```<code>struct Question {
    var title: String
    var answer: Int
    var question: Int
}
</code>```

Client -

...

```<code>guard let data = data else {
    return
}

do {
    self.jsonResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
    let questionItems = self.jsonResponse?["themes"] as! [[String: Any]]

    questionItems.forEach {
        let item = Question(title: $0["title"] as! String,
                            answer: $0["answer"] as! Int,
                            question: $0["question"] as! Int)
        questionData.append(item)
    }

} catch {
    print("error")
}
</code>```

Here's what I have now, except I can't figure out the decoder part:

Struct -

```<code>struct Question: Codable {
    var title: String
    var answer: Int
    var question: Int
}
</code>```

Client -

...

```<code>let decoder = JSONDecoder()
if let questions = try? decoder.decode([Question].self, from: data) {
    // Can't get past this part
} else {
    print("Not working")
}
</code>```

It prints "Not working" because I can't get past the decoder.decode part. Any ideas? Will post any extra code as needed, thanks!

EDIT:

Sample of API JSON:

```<code>{
  "themes": [
    {
      "answer": 1,
      "question": 44438222,
      "title": "How many letters are in the alphabet?"
    },
    {
      "answer": 0,
      "question": 44438489,
      "title": "This is a random question"
    }
  ]
 }
</code>```

If I print self.jsonResponse I get this:

```<code>Optional(["themes": <__NSArrayI 0x6180002478f0>(
{
    "answer" = 7;
    "question" = 7674790;
    title = "This is the title of the question";
},
{
    "answer_" = 2;
    "question" = 23915741;
    title = "This is the title of the question";
}
</code>```

My new code:

```<code>struct Theme: Codable {
    var themes : [Question]
}

struct Question: Codable {
    var title: String
    var answer: Int
    var question: Int
}
</code>```

...

```<code>if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
    print("decoded:", decoded)
} else {
    print("Not working")
}
</code>```

答:
You're getting this error because your JSON is likely structured as so:

```<code>{
  "themes": [
    { "title": ..., "question": ..., "answer": ... },
    { "title": ..., "question": ..., "answer": ... },
    { ... }
  ],
  ...
}
</code>```

However, the code you wrote expects a [Question] at the top level. What you need is a different top-level type that has a themes property which is a [Question]. When you decode that top-level type, your [Question] will be decoded for the themes key.

Title: Swift 4 Codable decoding json

Body:
I'm trying to implement the new Codable protocol, so I added Codable to my struct, but am stuck on decoding the JSON.

Here's what I had before:

Struct -

struct Question {
    var title: String
    var answer: Int
    var question: Int
}

Client -

...

guard let data = data else {
    return
}

do {
    self.jsonResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
    let questionItems = self.jsonResponse?["themes"] as! [[String: Any]]

    questionItems.forEach {
        let item = Question(title: $0["title"] as! String,
                            answer: $0["answer"] as! Int,
                            question: $0["question"] as! Int)
        questionData.append(item)
    }

} catch {
    print("error")
}

Here's what I have now, except I can't figure out the decoder part:

Struct -

struct Question: Codable {
    var title: String
    var answer: Int
    var question: Int
}

Client -

...

let decoder = JSONDecoder()
if let questions = try? decoder.decode([Question].self, from: data) {
    // Can't get past this part
} else {
    print("Not working")
}

It prints "Not working" because I can't get past the decoder.decode part. Any ideas? Will post any extra code as needed, thanks!

EDIT:

Sample of API JSON:

{
  "themes": [
    {
      "answer": 1,
      "question": 44438222,
      "title": "How many letters are in the alphabet?"
    },
    {
      "answer": 0,
      "question": 44438489,
      "title": "This is a random question"
    }
  ]
 }

If I print self.jsonResponse I get this:

Optional(["themes": <__NSArrayI 0x6180002478f0>(
{
    "answer" = 7;
    "question" = 7674790;
    title = "This is the title of the question";
},
{
    "answer_" = 2;
    "question" = 23915741;
    title = "This is the title of the question";
}

My new code:

struct Theme: Codable {
    var themes : [Question]
}

struct Question: Codable {
    var title: String
    var answer: Int
    var question: Int
}

...

if let decoded = try? JSONDecoder().decode(Theme.self, from: data) {
    print("decoded:", decoded)
} else {
    print("Not working")
}

Body:
You're getting this error because your JSON is likely structured as so:

{
  "themes": [
    { "title": ..., "question": ..., "answer": ... },
    { "title": ..., "question": ..., "answer": ... },
    { ... }
  ],
  ...
}

However, the code you wrote expects a [Question] at the top level. What you need is a different top-level type that has a themes property which is a [Question]. When you decode that top-level type, your [Question] will be decoded for the themes key.


问:
DB2 ZOS Mainframe- Archive Logs Disable
I'm working in DB2 ZOS  Version 10, I have been working under data masking project. For this project I have been executing over 100k DDL statements (delete, update,insert) .

So I need to do disable the transaction logs before the whole SCRAMBLE PROCESS starts.

In DB2 iSeries AS400, I already handle the same issue by calling the procedure which helps to disable the TRANSACTION LOG DISABLE.

Like wise, I need to do in DB2 ZOS.

答:
You can use the NOT LOGGED attribute for all affected tablespaces, specifies that changes that are made to data in the specified tablespace are not recorded in the DB2 log

Take the following steps for your data masking process:

Take an imagecopy so you can recover

ALTER TABLESPACE database-name.table-space-name NOT LOGGED

Execute data masking process

ALTER TABLESPACE database-name.table-space-name LOGGED

Take an imagecopy to establish a recovery point

You will also probably want to lock all tables with exclusive access so that if you have to recover no one else is affected by your changes

N.B. Make sure you're aware of the recovery implications for objects that are not logged!!!

Title: DB2 ZOS Mainframe- Archive Logs Disable


问:
Manage Custom App Offline via VSTS publish in Azure

I want to manage a custom App offline file whilst doing a publish to azure via the Deploy Azure App Service task.

I realise that this task has a property of:take app offline

however this property will use the basic app offline file which is what I would like to avoid.

I figure I need to do something like this.

Option 1

rename file on azure service _App_Offline.htm to App_offline.htm

publish app.

rename file on azure service App_Offline.htm to _App_Offline.htm

however I can't figure out how to do steps 1 or 3.

Option 2

publish file on azure service App_Offline.htm

publish app.

delete file on azure service App_Offline.htm

I can manage steps 1 and 2 of these but how would i do step 3?

any other options i could try?

答:
You can Create/Delete/Rename file on azure app service through kudu REST API, refer to this thread below to get more information about how to use kudu REST API during the build/release.

Remove files and foldes on Azure before a new deploy from VSTS


问:
Querying in mongoexport through python
Can Anyone explain how to export the result of a query with mongoexport inside a program in python ?</p>

```<code>os.system('mongoexport -d fintapp -c portfolio --csv --fields userid,budget --query {"budget":{$exists:True}} -o fulbudg.csv')
</code>```

答:
Use subprocess</p>

```<code>import subprocess

subprocess.call("mongoexport --db db_name --collection collection_name --out output_fileName.csv type csv --fields name_of_columns", shell = True)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Querying in mongoexport through python

Body:
Can Anyone explain how to export the result of a query with mongoexport inside a program in python ?

os.system('mongoexport -d fintapp -c portfolio --csv --fields userid,budget --query {"budget":{$exists:True}} -o fulbudg.csv')

Body:
Use subprocess

import subprocess

subprocess.call("mongoexport --db db_name --collection collection_name --out output_fileName.csv type csv --fields name_of_columns", shell = True)


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
it solves this concrete problem:

you have a, b, c, d of 4 different types. all over your code you have something like:

```<code>a.Process();
b.Process();
c.Process();
d.Process();
</code>```

why not have them implement IProcessable, and then do

```<code>List<IProcessable> list;

foreach(IProcessable p in list)
    p.Process();
</code>```

this will scale much better when you add, say, 50 types of classes that all do the same thing.

Another concrete problem:

Have you ever taken a look at System.Linq.Enumerable? It defines a ton of extension methods that operate on any type that implements IEnumerable. Because anything that implements IEnumerable basically says "I support iteration in a unordered foreach-type pattern", you can define complex behaviors (Count, Max, Where, Select, etc.) for any enumerable type.

LastEditorDisplayName: ALassek

Body:
it solves this concrete problem:

you have a, b, c, d of 4 different types. all over your code you have something like:

a.Process();
b.Process();
c.Process();
d.Process();

why not have them implement IProcessable, and then do

List<IProcessable> list;

foreach(IProcessable p in list)
    p.Process();

this will scale much better when you add, say, 50 types of classes that all do the same thing.

Another concrete problem:

Have you ever taken a look at System.Linq.Enumerable? It defines a ton of extension methods that operate on any type that implements IEnumerable. Because anything that implements IEnumerable basically says "I support iteration in a unordered foreach-type pattern", you can define complex behaviors (Count, Max, Where, Select, etc.) for any enumerable type.

OwnerDisplayName: Jimmy

LastEditorDisplayName: Jimmy


问:
Why does databinding not work?
I have a car-class like this:

```<code>public class car
{
    public String Name {get; private set;}

    public car(string name)
    {
      this.Name = name;
    }
}
</code>```

I also have a userControl:

```<code>public partial class CarListItem : UserControl
{
    private Car car;

    public CarListItem (Car car)
    {
        InitializeComponent();
        this.car= car;
    }

}
</code>```

With xaml:

```<code><Grid>
     <Label Content="{Binding Path=car.Name}" Name="lblCarName"/>
</Grid>
</code>```

but the databinding does not work. What am I doing wrong?

I want to show the name of the car on the userControl.

答:
You should not need to preface the binding expression with car...

```<code><Grid>
     <Label Content="{Binding Name}" Name="lblCarName"/>
</Grid>
</code>```

...in addition you need to set the DataContext of your UserControl

```<code>public partial class CarListItem : UserControl
{
    public CarListItem (Car car)
    {
        InitializeComponent();

        this.DataContext = car;
    }
}
</code>```

Also my assumption is that you are passing a name in to the ctor of car other then an empty string or null.

Title: Why does databinding not work?

Body:
I have a car-class like this:

public class car
{
    public String Name {get; private set;}

    public car(string name)
    {
      this.Name = name;
    }
}

I also have a userControl:

public partial class CarListItem : UserControl
{
    private Car car;

    public CarListItem (Car car)
    {
        InitializeComponent();
        this.car= car;
    }

}

With xaml:

<Grid>

</Grid>

but the databinding does not work. What am I doing wrong?

I want to show the name of the car on the userControl.

Body:
You should not need to preface the binding expression with car...

<Grid>
     <Label Content="{Binding Name}" Name="lblCarName"/>
</Grid>

...in addition you need to set the DataContext of your UserControl

public partial class CarListItem : UserControl
{
    public CarListItem (Car car)
    {
        InitializeComponent();

        this.DataContext = car;
    }
}

Also my assumption is that you are passing a name in to the ctor of car other then an empty string or null.


问:
Error near Where Clause in ASP NET
Below is a code and Visual Studio is raising error that there is syntax error near WHERE. </p>

```<code>SqlCommand cmd2 = new SqlCommand("insert into courses(t_id_fk) values('" + valu3 + "') where c_id=@dr1 ", con);
cmd2.CommandType = CommandType.Text;
                cmd2.Parameters.Add("@dr1", SqlDbType.Int);
                cmd2.Parameters["@dr1"].Value = d1;
                cmd2.ExecuteNonQuery();
                con.Close();
</code>```

答:
remove where clause while inserting:

from:

```<code>"insert into courses(t_id_fk) values('" + valu3 + "') where c_id=@dr1 "
</code>```

to:

```<code>"insert into courses(t_id_fk) values('" + valu3 + "')"
</code>```

But if the sample given above is an update then:

```<code> "update courses set t_id_fk = '" + valu3 + "'  where c_id=@dr1"
</code>```

Title: Error near Where Clause in ASP NET

Body:
Below is a code and Visual Studio is raising error that there is syntax error near WHERE.

SqlCommand cmd2 = new SqlCommand("insert into courses(t_id_fk) values('" + valu3 + "') where c_id=@dr1 ", con);
cmd2.CommandType = CommandType.Text;
                cmd2.Parameters.Add("@dr1", SqlDbType.Int);
                cmd2.Parameters["@dr1"].Value = d1;
                cmd2.ExecuteNonQuery();
                con.Close();

Body:
remove where clause while inserting:

from:

"insert into courses(t_id_fk) values('" + valu3 + "') where c_id=@dr1 "

to:

"insert into courses(t_id_fk) values('" + valu3 + "')"

But if the sample given above is an update then:

 "update courses set t_id_fk = '" + valu3 + "'  where c_id=@dr1"


问:
Why is the big o of this function xn^2?
I have the following function:

```<code>public String joinWords(String[] words) {
  String sentence = "";
  for(String w : words) {
    sentence = sentence + w;
  }
}
</code>```

I am told this is a O(n^2)? Why is that? Is it not O(n) for having one loop?

答:
The loop is, indeed, iterated words.length times.

However, on each iteration the old sentence string is discarded, and a new sentence string is created. In the process of creating the new sentence the previous one is copied into the new one, and then the word is appended. Each act of copying takes O(n), so overall loop takes O(n2).

Title: Why is the big o of this function xn^2?

Body:
I have the following function:

public String joinWords(String[] words) {
  String sentence = "";
  for(String w : words) {
    sentence = sentence + w;
  }
}

I am told this is a O(n^2)? Why is that? Is it not O(n) for having one loop?


问:
How to add a custom field to a layout section in SalesForce via the API
I am creating a Java API integration tool, that on start up will create a new custom filed if it doesn't exist for Lead & Contact. After a bit of searching I have found how to do this.
Now the next bit on the list, is to get the newly created field into the "Lead Information" or "Contact Information" layout.

I have looked in the metadata api docs and cannot find an example, either using Java or plain SOAP messages. I have searched online, in most of the forums, and sample code bases I can find, with no success.

So if anyone one is able to supply an example either through Java or SOAP, that would be fantastic.

答:
You can't just add a field to a layout.  You have to first get the existing layout and then add the field to it and then update the layout.
A layout is a complex object made up of other objects representing the sections and then the rows, etc.
I recommend first retrieving a layout via either the SOAP or Metadata API and once you've looked at the result, it should be clearer on how you can parse it and inject your additional row and field.</p>


问:
Beset with errors trying getting started with react-native.
I'm new to react, and I'm having a lot of trouble getting started. Here's a list of errors I run into in sequence:

Run npm install on a package, then react-native run-ios. Then error:

Command 'run-ios' unrecognized. Make sure that you have run 'npm install' and that you are inside a react-native project.

Run install the latest react-native (according to this question), which solves the problem.

Rerun the simulator. Error:

Cannot find entry file index.ios.js in any of the roots: ["/Users/Dan/ReactApp/node_modules/react-native/packager"

Run kill -9 (process Id of server on 8081) && npm start (according to this question)

Next error:

Cannot read property 'ReactCurrentOwner' of undefined.

I remove node_module, run npm install, yarn add react-navigation (If I use npm to install this module, I'll go back to the first erorr again). according to this.

Back to 1.

I give up and manually copy over my code to a new project.

This is incredibly frustrating. What am I doing wrong?

System Info:

OS: OSX 10.12.6 Beta

Simulator: iOS 10.3

XCode: 8.3.3

Node: 7.4.0

Npm: 5.0.3

React: 15.5.4

React-Native: 0.45.0

React-Native-Cli: 2.0.1

答:
Okay, so first, make sure you're in the correct directory. It sounds silly but it happens. You should be able to ls and see package.json.

If that's the case and it doesn't work, make sure you have react-native-cli installed globally. npm install -g react-native-cli You use which react-native to verify.

Next try killing the packager and xcode and restarting. Try running it again. If it doesn't work, kill xcode and the packager again, open the project with 'open ios/.xcodeproj', hit the run button and see if it works.

All in all I wouldn't reccomend using npm and yarn together. Stick with one or the other. I use npm.

The error Cannot find entry file index.ios.js in any of the roots: ["/Users/Dan/ReactApp/node_modules/react-native/packager"

Leads me to believe you're not in the correct directory.


问:
Internet Explorer 7 & 8 Margin Display Issues
I was having a small problem with center aligning a DIV in IE7 and 8. There are some minor height issues also, but ill cross that bridge when I get to it...

I have always used

```<code>middleAlign {
    width:someAbsWidth;
    margin-right:auto;
    margin-left:auto;
    position:relative;
}
</code>```

to center my DIVS in all browsers, and it has worked fine. But now, I am having problems with this method in IE7 and 8. They do not center the div; rather it acts as if the margin-left is 0. Could it be other CSS rules affecting the margin display in IE?

I have uploaded the page to my server; the page is viewable here: http://drafts.thatcompdude.com/NewSite/

The page renders just fine in FF 3.6; Chrome 8.0.

Thank you;

--Dylan

答: Your page is in quirks mode because of the comment at the top. Remove it and it'll be standards mode and it'll start working.</p>

Body:
I was having a small problem with center aligning a DIV in IE7 and 8. There are some minor height issues also, but ill cross that bridge when I get to it...

I have always used

middleAlign {
    width:someAbsWidth;
    margin-right:auto;
    margin-left:auto;
    position:relative;
}

to center my DIVS in all browsers, and it has worked fine. But now, I am having problems with this method in IE7 and 8. They do not center the div; rather it acts as if the margin-left is 0. Could it be other CSS rules affecting the margin display in IE?

I have uploaded the page to my server; the page is viewable here: http://drafts.thatcompdude.com/NewSite/

The page renders just fine in FF 3.6; Chrome 8.0.

Thank you;

--Dylan


问:
What's the point of throwing an exception?
I'm writing a login class in c#, and I'm trying to be diligent about throwing exceptions for null passwords, insufficiant password characters, etc. The thing that suddenly occured to me was - What do I do with these exception? What/who are they for? Whether I handle the exception or not, the app will still fail at that point. Is the exception for other developers, the customer!? </p>

答:
The nature of exceptions is that they have to be explicitly ignored. Suppose you have this function:

```<code>bool authenticate ( String username, String password )
{
     if ( invalid_password(password) ) {
         return (false);
     }
     // ... perform authentication ...
}
</code>```

Now, consider that this is part of some server, and that the server runs in a highly privileged context. If the calling code (the one that performs authorization) has some error in it's logic, it might unintentionally allow users to perform actions they are not normally allowed.

I would write the following function instead:

```<code>void authenticate ( String username, String password )
{
     if ( invalid_password(password) ) {
         throw new LoginFailed();
     }
     // ... perform authentication ...
}
</code>```

Note that this is purely a defensive programming approach, and it is my preference within this context. This way, an error in login will most likely not allow the operation to keep executing.

Body:
The nature of exceptions is that they have to be explicitly ignored. Suppose you have this function:

bool authenticate ( String username, String password )
{
     if ( invalid_password(password) ) {
         return (false);
     }
     // ... perform authentication ...
}

Now, consider that this is part of some server, and that the server runs in a highly privileged context. If the calling code (the one that performs authorization) has some error in it's logic, it might unintentionally allow users to perform actions they are not normally allowed.

I would write the following function instead:

void authenticate ( String username, String password )
{
     if ( invalid_password(password) ) {
         throw new LoginFailed();
     }
     // ... perform authentication ...
}

Note that this is purely a defensive programming approach, and it is my preference within this context. This way, an error in login will most likely not allow the operation to keep executing.


问:
Why doesn't ${1:r} strip file extension in my zsh script?
I'm writing a zsh script that automates some video encoding. The file to be converted will be the first parameter to the script, which contains this line:

```<code>ffmpeg -i $1 -ac 0 -vcodec libx264 -b:v 500k -crf 20 ${1:r}.mp4
</code>```

I expected ${1:r}.mp4 to create a file with the same name as my .mov input, but with the .mp4 file extension replacing .mov. But instead I get input.mov.mp4. Why isn't the :r modifier stripping the file extension?

答:
I experienced something similar and it seems like zsh doesn't accept :r on the positional arguments. Instead you could do something like this:</p>

```<code>file=${1}
ffmpeg -i $1 -ac 0 -vcodec libx264 -b:v 500k -crf 20 ${file:r}.mp4
</code>```

Body:
I'm writing a zsh script that automates some video encoding. The file to be converted will be the first parameter to the script, which contains this line:

ffmpeg -i $1 -ac 0 -vcodec libx264 -b:v 500k -crf 20 ${1:r}.mp4

I expected ${1:r}.mp4 to create a file with the same name as my .mov input, but with the .mp4 file extension replacing .mov. But instead I get input.mov.mp4. Why isn't the :r modifier stripping the file extension?

Body:
I experienced something similar and it seems like zsh doesn't accept :r on the positional arguments. Instead you could do something like this:

file=${1}
ffmpeg -i $1 -ac 0 -vcodec libx264 -b:v 500k -crf 20 ${file:r}.mp4


问:
VM1052:19 Error: (SystemJS) TypeScript transpilation failed

I am new to angular, I am trying to change color for each li when I click it.

but I am getting an error VM1052:19 Error: (SystemJS) TypeScript transpilation failed

can you guys tell me how to fix it.

providng code below

http://plnkr.co/edit/npNw39aRZVgpqEjI6uLH?open=app%2Fapp.component.ts&p=preview

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  styles: [`
    li {
      color: red;
    }
  `],
  template: `

 {{student}}

`
})
export class AppComponent {
  name = 'Angular';
  liArraycontent = ["testing 1", "testing 2", "testing3"]

  liClicked = function(e1) {
    console.log(e1.target);
    e1.addCss(color: green);
  }

}
```

答:
you just need to add style attribute.

add this line in you click event:

```<code>e1.target.setAttribute("style", "color: green;");
</code>```

link to working plnkr:
http://plnkr.co/edit/w1i9v1fJ02htbDrtkWUy?open=app%2Fapp.component.ts&p=preview

Body:
you just need to add style attribute.

add this line in you click event:

e1.target.setAttribute("style", "color: green;");

link to working plnkr:
http://plnkr.co/edit/w1i9v1fJ02htbDrtkWUy?open=app%2Fapp.component.ts&p=preview


问:
Map column value to table name and join
I have a composite type that looks like

```<code>CREATE TYPE member AS (
    id BIGINT,
    type CHAR(1)
);
</code>```

I have a table that relies on this member type with an array.

```<code>CREATE TABLE relation (
    id BIGINT PRIMARY KEY,
    members member[]
);
</code>```

I have three other tables each with a different schema (but having common id field)

```<code>CREATE TABLE table_x (
    id BIGINT PRIMARY KEY,
    some_text TEXT
);

CREATE TABLE table_y (
    id BIGINT PRIMARY KEY,
    some_int INT
);

CREATE TABLE table_z (
    id BIGINT PRIMARY KEY,
    some_date TIMESTAMP
);
</code>```

type field in member type is just one character to find out table that specific member belongs to. A row in relation table can have a mix of different types.

I have a scenario which requires returning relation ids with at least one member fulfilling a certain condition based on it's type (let's say for x => some_text is not empty or y => some_int is greater than 10 or z => some_date is a week is from now).

I can implement this scenario on the application side by making multiple requests to the database:

unnest relation table

collect member data per relation

make new requests to find out relations

I am wondering if there is a way to map column values to table names and join them.

答:
Assumption

I´m assuming that relation.members array does not have more than one member element of the same type. Correct?

Query to try

```<code>with unnested_members as (
-- Unnest members array
select id, unnest(members) members
from relation
)
, members_joined as (
-- left join on a per type basis with table_x, table_y and table_z.
select r.id, (r.members).id idext, (r.members).type,
       x.some_text, y.some_int, z.some_date -- more types, more columns here
from unnested_members r
  left join table_x x on (x.id = (r.members).id and (r.members).type = 'x')
  left join table_y y on (y.id = (r.members).id and (r.members).type = 'y')
  left join table_z z on (z.id = (r.members).id and (r.members).type = 'z')
  -- More types, more tables to left join
)
select id,
  max(some_text) some_text, -- use max() to get not null value for this id
  max(some_int) some_int, -- use max() to get not null value for this id
  max(some_date) some_date -- use max() to get not null value for this id
  -- more types, more max() columns here
from members_joined
group by id -- get one row per relation.id with data from joined table_* columns
</code>```

If you need to include more tables then you have to include these tables in the left join part, include the column in the select list and in the max() section as well.

Title: Map column value to table name and join

Body:
I have a composite type that looks like

CREATE TYPE member AS (
    id BIGINT,
    type CHAR(1)
);

I have a table that relies on this member type with an array.

CREATE TABLE relation (
    id BIGINT PRIMARY KEY,
    members member[]
);

I have three other tables each with a different schema (but having common id field)

CREATE TABLE table_x (
    id BIGINT PRIMARY KEY,
    some_text TEXT
);

CREATE TABLE table_y (
    id BIGINT PRIMARY KEY,
    some_int INT
);

CREATE TABLE table_z (
    id BIGINT PRIMARY KEY,
    some_date TIMESTAMP
);

type field in member type is just one character to find out table that specific member belongs to. A row in relation table can have a mix of different types.

I have a scenario which requires returning relation ids with at least one member fulfilling a certain condition based on it's type (let's say for x => some_text is not empty or y => some_int is greater than 10 or z => some_date is a week is from now).

I can implement this scenario on the application side by making multiple requests to the database:

unnest relation table

collect member data per relation

make new requests to find out relations

I am wondering if there is a way to map column values to table names and join them.

Body:
Assumption

I´m assuming that relation.members array does not have more than one member element of the same type. Correct?

Query to try

with unnested_members as (
-- Unnest members array
select id, unnest(members) members
from relation
)
, members_joined as (
-- left join on a per type basis with table_x, table_y and table_z.
select r.id, (r.members).id idext, (r.members).type,
       x.some_text, y.some_int, z.some_date -- more types, more columns here
from unnested_members r
  left join table_x x on (x.id = (r.members).id and (r.members).type = 'x')
  left join table_y y on (y.id = (r.members).id and (r.members).type = 'y')
  left join table_z z on (z.id = (r.members).id and (r.members).type = 'z')
  -- More types, more tables to left join
)
select id,
  max(some_text) some_text, -- use max() to get not null value for this id
  max(some_int) some_int, -- use max() to get not null value for this id
  max(some_date) some_date -- use max() to get not null value for this id
  -- more types, more max() columns here
from members_joined
group by id -- get one row per relation.id with data from joined table_* columns

If you need to include more tables then you have to include these tables in the left join part, include the column in the select list and in the max() section as well.


问:
Laravel controller calling database transaction
Does calling a database transaction in the Controller a good practice?
if no where should i proper call a database transaction?</p>

答: Depends upon the size of project and personal preference also. But calling a database transaction outside of controller is a better practice as its makes your code clean and understandable. Also you can use the same function for multiple controllers reducing the pain of redundant coding. You can search for SOA (Service Oriented Architecture) and use it for better practice.</p>


问:
The character encoding of the HTML document was not declared
When I click to the HTML document to open it in browser the fllowing message appears:
"The character encoding of the HTML document was not declared. The document will render with index.html garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol.
I don't know how can insert my code here</p>

答:
Here is the HTML5 basic structure.

```<code><!DOCTYPE html>
<html>
     <head>
        <meta charset="utf-8">
        <title>Title of the document</title>
     </head>
  <body>
    <!--The content of the document......-->
  </body>
</html>
</code>```

Note : UTF-8 is a character encoding capable of encoding all possible Unicode code point.

Here is more details about UTF-8

Body:
Here is the HTML5 basic structure.

<!DOCTYPE html>
<html>
     <head>
        <meta charset="utf-8">
        <title>Title of the document</title>
     </head>
  <body>
    <!--The content of the document......-->
  </body>
</html>

Note : UTF-8 is a character encoding capable of encoding all possible Unicode code point.

Here is more details about UTF-8


问:
is there a way to change case to low or high whole block in visual mode vim?
Want to change case to lower in whole block in visual mode.
If i want to change case of a single character, i can press ~, but what i need to use in visual mode for changing in selected area into low or high case ?</p>

答:
The ~ also works on visual blocks and 'inverts' the casing (lowercase becomes uppercase, uppercase becomes lowercase)

u makes the selection lower case (regardless on the original casing)

U makes the selection upper case (regardless on the original casing)


问:
Geo Library for Amazon DynamoDB Node.js
As we know DynamonDB does not support spatial queries , We can't search by location GPS , but I found a java solution http://aws.typepad.com/aws/2013/09/new-geo-library-for-dynamodb-.html , my question is :

Are there any solution for Node.js ?

答: Found a third party NodeJS port of the official Java library in NPM registry, named dynamodb-geo with useful features.</p>

Title: Geo Library for Amazon DynamoDB Node.js


问:
How to save a tensorflow model trained in google datalab notebook for offline prediction?
I am using Google Cloud Datalab notebook to train my tensorflow model. I want to save the trained model for offline prediction. However, I am clueless on how to save the model. Should I use any tensorflow model saving method or is there any datalab/google cloud storage specific method to do so? Any help in this regard is highly appreciated.</p>

答:
You can use any tensorflow model saving method, but I would suggest that you save it into a Google Cloud Storage bucket and not to local disk.  Most tensorflow methods accept Google Cloud Storage paths in place of file names, using the gs:// prefix.

I would suggest using the SavedModelBuilder as it is currently the most portable.  There is an example here: https://github.com/GoogleCloudPlatform/cloudml-samples/blob/master/flowers/trainer/model.py#L393


问:
Sorting a file based on a field that's not in a fixed position
i am a newbie in unix sort.
I have a set of data..example of lines:
as i tried sort -n command, it is given me this:
it start with 0_0 and the second one is 10_0, how i can make it to start at 0_0 then follow by 1_0 then 2_0 ....9_0...10_0..11_0...19_0...20_0....etc.?

Here is my input:

```<code>reg_0_0/clk
reg_10_0/clk
reg_11_0/clk
reg_12_0/clk
reg_13_0/clk
reg_14_0/clk
reg_15_0/clk
reg_16_0/clk
reg_17_0/clk
reg_18_0/clk
reg_19_0/clk
reg_1_0/clk
reg_20_0/clk
reg_21_0/clk
reg_22_0/clk
reg_23_0/clk
reg_24_0/clk
reg_25_0/clk
reg_26_0/clk
reg_27_0/clk
reg_28_0/clk
reg_29_0/clk
reg_2_0/clk
reg_30_0/clk
reg_31_0/clk
reg_3_0/clk
reg_4_0/clk
reg_5_0/clk
reg_6_0/clk
reg_7_0/clk
reg_8_0/clk
reg_9_0/clk
s_reg_0_0/clk
s_reg_10_0/clk
s_reg_11_0/clk
s_reg_12_0/clk
s_reg_13_0/clk
s_reg_14_0/clk
s_reg_15_0/clk
s_reg_16_0/clk
s_reg_17_0/clk
s_reg_18_0/clk
s_reg_19_0/clk
s_reg_1_0/clk
s_reg_20_0/clk
s_reg_21_0/clk
s_reg_22_0/clk
s_reg_23_0/clk
s_reg_24_0/clk
s_reg_25_0/clk
s_reg_26_0/clk
s_reg_27_0/clk
s_reg_28_0/clk
s_reg_29_0/clk
s_reg_2_0/clk
s_reg_30_0/clk
s_reg_31_0/clk
s_reg_3_0/clk
s_reg_4_0/clk
s_reg_5_0/clk
s_reg_6_0/clk
s_reg_7_0/clk
s_reg_8_0/clk
s_reg_9_0/clk
</code>```

答: I think the bad news is, you can't.  You don't have numbers, you have things that the human eye can discern as numbers, but sort isn't smart enough to parse the number out and sort on it.  You'll have to write some custom software to do it.</p>

Body:
i am a newbie in unix sort.
I have a set of data..example of lines:
as i tried sort -n command, it is given me this:
it start with 0_0 and the second one is 10_0, how i can make it to start at 0_0 then follow by 1_0 then 2_0 ....9_0...10_0..11_0...19_0...20_0....etc.?

Here is my input:

reg_0_0/clk
reg_10_0/clk
reg_11_0/clk
reg_12_0/clk
reg_13_0/clk
reg_14_0/clk
reg_15_0/clk
reg_16_0/clk
reg_17_0/clk
reg_18_0/clk
reg_19_0/clk
reg_1_0/clk
reg_20_0/clk
reg_21_0/clk
reg_22_0/clk
reg_23_0/clk
reg_24_0/clk
reg_25_0/clk
reg_26_0/clk
reg_27_0/clk
reg_28_0/clk
reg_29_0/clk
reg_2_0/clk
reg_30_0/clk
reg_31_0/clk
reg_3_0/clk
reg_4_0/clk
reg_5_0/clk
reg_6_0/clk
reg_7_0/clk
reg_8_0/clk
reg_9_0/clk
s_reg_0_0/clk
s_reg_10_0/clk
s_reg_11_0/clk
s_reg_12_0/clk
s_reg_13_0/clk
s_reg_14_0/clk
s_reg_15_0/clk
s_reg_16_0/clk
s_reg_17_0/clk
s_reg_18_0/clk
s_reg_19_0/clk
s_reg_1_0/clk
s_reg_20_0/clk
s_reg_21_0/clk
s_reg_22_0/clk
s_reg_23_0/clk
s_reg_24_0/clk
s_reg_25_0/clk
s_reg_26_0/clk
s_reg_27_0/clk
s_reg_28_0/clk
s_reg_29_0/clk
s_reg_2_0/clk
s_reg_30_0/clk
s_reg_31_0/clk
s_reg_3_0/clk
s_reg_4_0/clk
s_reg_5_0/clk
s_reg_6_0/clk
s_reg_7_0/clk
s_reg_8_0/clk
s_reg_9_0/clk


问:
How to handle app URLs in a UIWebView?
I recently found that my UIWebView was choking on ITMS links. Specifically, from the UIWebView in my app, if I navigate to a site such as this one and click the "Available on the App Store" link, UIWebView would error out with "Error Domain=WebKitErrorDomain Code=101 The URL can't be shown."

After a bit of Googling, I realized that I needed to catch requests for app links and have iOS handle them. I started out by looking to see if the scheme starts with "itms" in -webView:shouldStartLoadWithRequest:navigationType:, but realized that there might be other kinds of app links that the system can handle. So I came up with this, instead:

```<code>- (void)webView:(UIWebView *)wv didFailLoadWithError:(NSError *)error {
    // Give iOS a chance to open it.
    NSURL *url = [NSURL URLWithString:[error.userInfo objectForKey:@"NSErrorFailingURLStringKey"]];
    if ([error.domain isEqual:@"WebKitErrorDomain"]
        && error.code == 101
        && [[UIApplication sharedApplication]canOpenURL:url])
    {
        [[UIApplication sharedApplication]openURL:url];
        return;
    }

    // Normal error handling…
}
</code>```

I have two questions about this:

Is this sane? I'm specifically checking for the error domain and error code and fetching the URL string from the userInfo. Is that stuff likely to remain?

This does work for the above-linked app store link, but when I switch back to my app, there appears to have been a subsequent failed request that failed with "Frame load interrupted". how can I get rid of that? It doesn't happen when I have the OS handle the request from -webView:shouldStartLoadWithRequest:navigationType:, so it's a bit annoying.

How do you handle such requests?

答:
Here's what I came up with. In webView:shouldStartLoadWithRequest:navigationType:, I ask the OS to handle any non-http and non-https requests that it can, like so:

```<code>- (BOOL)webView:(UIWebView *)wv shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    // Determine if we want the system to handle it.
    NSURL *url = request.URL;
    if (![url.scheme isEqual:@"http"] && ![url.scheme isEqual:@"https"]) {
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url];
            return NO;
        }
    }
    return YES;
}
</code>```

This works very well except for the bloody "Frame Load Interrupted" error. I had thought that by returning false from webView:shouldStartLoadWithRequest:navigationType: that the web view would not load the request and therefore there would be no errors to handle. But even though I return NO above, I still "Frame Load Interrupted" error. Why is that?

Anyway, I'm assuming it can be ignored in -webView:didFailLoadWithError::

```<code>- (void)webView:(UIWebView *)wv didFailLoadWithError:(NSError *)error {
    // Ignore NSURLErrorDomain error -999.
    if (error.code == NSURLErrorCancelled) return;

    // Ignore "Fame Load Interrupted" errors. Seen after app store links.
    if (error.code == 102 && [error.domain isEqual:@"WebKitErrorDomain"]) return;

    // Normal error handling…
}
</code>```

And now iTunes URLs work properly, as do mailto:s and app links.

Title: How to handle app URLs in a UIWebView?

Body:
I recently found that my UIWebView was choking on ITMS links. Specifically, from the UIWebView in my app, if I navigate to a site such as this one and click the "Available on the App Store" link, UIWebView would error out with "Error Domain=WebKitErrorDomain Code=101 The URL can't be shown."

After a bit of Googling, I realized that I needed to catch requests for app links and have iOS handle them. I started out by looking to see if the scheme starts with "itms" in -webView:shouldStartLoadWithRequest:navigationType:, but realized that there might be other kinds of app links that the system can handle. So I came up with this, instead:

- (void)webView:(UIWebView *)wv didFailLoadWithError:(NSError *)error {
    // Give iOS a chance to open it.
    NSURL *url = [NSURL URLWithString:[error.userInfo objectForKey:@"NSErrorFailingURLStringKey"]];
    if ([error.domain isEqual:@"WebKitErrorDomain"]
        && error.code == 101
        && [[UIApplication sharedApplication]canOpenURL:url])
    {
        [[UIApplication sharedApplication]openURL:url];
        return;
    }

    // Normal error handling…
}

I have two questions about this:

Is this sane? I'm specifically checking for the error domain and error code and fetching the URL string from the userInfo. Is that stuff likely to remain?

This does work for the above-linked app store link, but when I switch back to my app, there appears to have been a subsequent failed request that failed with "Frame load interrupted". how can I get rid of that? It doesn't happen when I have the OS handle the request from -webView:shouldStartLoadWithRequest:navigationType:, so it's a bit annoying.

How do you handle such requests?

Body:
Here's what I came up with. In webView:shouldStartLoadWithRequest:navigationType:, I ask the OS to handle any non-http and non-https requests that it can, like so:

- (BOOL)webView:(UIWebView *)wv shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    // Determine if we want the system to handle it.
    NSURL *url = request.URL;
    if (![url.scheme isEqual:@"http"] && ![url.scheme isEqual:@"https"]) {
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url];
            return NO;
        }
    }
    return YES;
}

This works very well except for the bloody "Frame Load Interrupted" error. I had thought that by returning false from webView:shouldStartLoadWithRequest:navigationType: that the web view would not load the request and therefore there would be no errors to handle. But even though I return NO above, I still "Frame Load Interrupted" error. Why is that?

Anyway, I'm assuming it can be ignored in -webView:didFailLoadWithError::

- (void)webView:(UIWebView *)wv didFailLoadWithError:(NSError *)error {
    // Ignore NSURLErrorDomain error -999.
    if (error.code == NSURLErrorCancelled) return;

    // Ignore "Fame Load Interrupted" errors. Seen after app store links.
    if (error.code == 102 && [error.domain isEqual:@"WebKitErrorDomain"]) return;

    // Normal error handling…
}

And now iTunes URLs work properly, as do mailto:s and app links.


问:
Salesforce Validation Rule - Allow certain user & profile to modify record after it's been approved
I've looked for answers and even looked at a lot of our other validation rules but can't quite seem to finish this off.  I feel like I'm almost there but I can't get my syntax correct.

I'm trying to write a Validation Rule that would allow a certain user and profile to modify a certain record once it's been approved.  This is the latest iteration of what I have written (with Record name, userID, and profileID masked):

```<code>AND(

 RecordType.Name = "Example Record",

 ISPICKVAL(Approval_Status__c , "Approved"),

 NOT($User.Id = "xxxxxxxxxxxxxxxx1") ||

 NOT($User.ProfileId = "xxxxxxxxxxxxxxxx2"),

OR(

 ISCHANGED(Status),

 ISCHANGED(Requestor__c),

 ISCHANGED(Department_Owner__c),

 ISCHANGED(Support_Category__c),

 ISCHANGED(Permitting_Approval_Type__c),

 ISCHANGED(State__c),

 ISCHANGED(County__c),

 ISCHANGED(Sites__c),

 ISCHANGED(Priority__c),

 ISCHANGED(Need_by_Date__c),

 ISCHANGED(Days_til_Due__c),

)

)
</code>```

I usually can find an question/answer on this site that will point me in the direction I need to go but this time I haven't had such luck.

Any help is greatly appreciated.

Ryan

答:
I think you were close</p>

```<code>AND(
RecordType.Name = "Example Record",
ISPICKVAL(Approval_Status__c , "Approved"),
NOT($User.Id = "xxxxxxxxxxxxxxxx1"),
NOT($User.ProfileId = "xxxxxxxxxxxxxxxx2"),
OR(
ISCHANGED(Status),
ISCHANGED(Requestor__c),
ISCHANGED(Department_Owner__c),
ISCHANGED(Support_Category__c),
ISCHANGED(Permitting_Approval_Type__c),
ISCHANGED(State__c),
ISCHANGED(County__c),
ISCHANGED(Sites__c),
ISCHANGED(Priority__c),
ISCHANGED(Need_by_Date__c),
ISCHANGED(Days_til_Due__c),
)
)
</code>```

Body:
I've looked for answers and even looked at a lot of our other validation rules but can't quite seem to finish this off.  I feel like I'm almost there but I can't get my syntax correct.

I'm trying to write a Validation Rule that would allow a certain user and profile to modify a certain record once it's been approved.  This is the latest iteration of what I have written (with Record name, userID, and profileID masked):

AND(

 RecordType.Name = "Example Record",

 ISPICKVAL(Approval_Status__c , "Approved"),

 NOT($User.Id = "xxxxxxxxxxxxxxxx1") ||

 NOT($User.ProfileId = "xxxxxxxxxxxxxxxx2"),

OR(

 ISCHANGED(Status),

 ISCHANGED(Requestor__c),

 ISCHANGED(Department_Owner__c),

 ISCHANGED(Support_Category__c),

 ISCHANGED(Permitting_Approval_Type__c),

 ISCHANGED(State__c),

 ISCHANGED(County__c),

 ISCHANGED(Sites__c),

 ISCHANGED(Priority__c),

 ISCHANGED(Need_by_Date__c),

 ISCHANGED(Days_til_Due__c),

)

)

I usually can find an question/answer on this site that will point me in the direction I need to go but this time I haven't had such luck.

Any help is greatly appreciated.

Ryan

Body:
I think you were close

AND(
RecordType.Name = "Example Record",
ISPICKVAL(Approval_Status__c , "Approved"),
NOT($User.Id = "xxxxxxxxxxxxxxxx1"),
NOT($User.ProfileId = "xxxxxxxxxxxxxxxx2"),
OR(
ISCHANGED(Status),
ISCHANGED(Requestor__c),
ISCHANGED(Department_Owner__c),
ISCHANGED(Support_Category__c),
ISCHANGED(Permitting_Approval_Type__c),
ISCHANGED(State__c),
ISCHANGED(County__c),
ISCHANGED(Sites__c),
ISCHANGED(Priority__c),
ISCHANGED(Need_by_Date__c),
ISCHANGED(Days_til_Due__c),
)
)


问:
Retain cookie even after browser is closed
I am setting a cookie in Node-Express JS with JWT token as part of cookie with following code.

```<code>var token = jwt.sign(parsed.data, "token_secret", {expiresIn: "43200m"});

res.setHeader('Set-Cookie', 'token='+token+';expires='+new Date(new Date().getTime()+9940900000).toUTCString());
</code>```

On closing or quitting the browser the cookie is getting deleted.
What is the best way to retain the cookie? Is it storing the token in localStorage in browser and attaching it to header for every http request? Or is there any other way of setting cookie, so that cookie is not deleted after browser is closed.

答:
Maybe this </p>

```<code>    document.cookie = cName + "=" + cValue + "; expires=" + expDate + ";path=/";
</code>```

Body:
I am setting a cookie in Node-Express JS with JWT token as part of cookie with following code.

var token = jwt.sign(parsed.data, "token_secret", {expiresIn: "43200m"});

res.setHeader('Set-Cookie', 'token='+token+';expires='+new Date(new Date().getTime()+9940900000).toUTCString());

On closing or quitting the browser the cookie is getting deleted.
What is the best way to retain the cookie? Is it storing the token in localStorage in browser and attaching it to header for every http request? Or is there any other way of setting cookie, so that cookie is not deleted after browser is closed.

Body:
Maybe this

    document.cookie = cName + "=" + cValue + "; expires=" + expDate + ";path=/";