问:
How can access the angular5 httpclient answer?
export class AppComponent implements OnInit{

userObservable: any = {};

constructor(private httpClient: HttpClient) { }

ngOnInit(): void {

```<code>this.httpClient.get<UserResponse>("http://localhost:9000/home")
    .subscribe(data  => {console.log(data.status);
                         console.log(data.password);
                         this.userObservable = data;
                         console.log('Result ==> ',this.userObservable);
                        },
               error => {}
);
console.log(this.userObservable);
</code>```

}

when the last console statement is executed, the displayed value is null. I need to manipulate the httpclient answer in other components of my application. how can i do that?

答:
It is because your last console.log() statement fire before you get your http answer. What I would suggest is to use a service:

```<code>export class AppComponent implements OnInit {
  constructor(private userService: UserService) {}

  ngOnInit(): void {
    this.userService.getUserData().subscribe(data => {
      console.log("Data :", data, "Data from service :", this.userService.userObservable);
      // DO OTHER STUFF
    });
  }

}

// Service
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable()
  export class UserService {
     userObservable: any = {};

    constructor(private httpClient: HttpClient) {}

    getUserData() {
    this.httpClient.get<UserResponse>("http://localhost:9000/home").subscribe(
      data => {
        this.userObservable = data;
        console.log("Result ==> ", this.userObservable);
        return data;
      },
      error => {
        return error;
      }
    );
  }
}
</code>```

You will be able to get your userData in every component using the service.

Body:
export class AppComponent implements OnInit{

userObservable: any = {};

constructor(private httpClient: HttpClient) { }

ngOnInit(): void {

this.httpClient.get<UserResponse>("http://localhost:9000/home")
    .subscribe(data  => {console.log(data.status);
                         console.log(data.password);
                         this.userObservable = data;
                         console.log('Result ==> ',this.userObservable);
                        },
               error => {}
);
console.log(this.userObservable);

}

when the last console statement is executed, the displayed value is null. I need to manipulate the httpclient answer in other components of my application. how can i do that?

Body:
It is because your last console.log() statement fire before you get your http answer. What I would suggest is to use a service:

export class AppComponent implements OnInit {
  constructor(private userService: UserService) {}

  ngOnInit(): void {
    this.userService.getUserData().subscribe(data => {
      console.log("Data :", data, "Data from service :", this.userService.userObservable);
      // DO OTHER STUFF
    });
  }

}

// Service
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
@Injectable()
  export class UserService {
     userObservable: any = {};

    constructor(private httpClient: HttpClient) {}

    getUserData() {
    this.httpClient.get<UserResponse>("http://localhost:9000/home").subscribe(
      data => {
        this.userObservable = data;
        console.log("Result ==> ", this.userObservable);
        return data;
      },
      error => {
        return error;
      }
    );
  }
}

You will be able to get your userData in every component using the service.


来源: stackexchange

问:
JS tab - paging or tab slider ala Firefox
Not sure how what I am looking for is called so it's making it very hard to find relevant
result.  So my question is really about finding the name for that type of control.

I am looking for a JS tab control plugin that would allow me to slide the tabs of a tab control the same way Firefox does it when you have many tabs open (with a < and > button).

I have found a few examples, the most similar to what I mean being this one but I can't use it to the commercial Ext JS license:
http://dev.sencha.com/deploy/dev/examples/tabs/tabs-adv.html

I've also found this one, which is still under development:
http://www.seyfertdesign.com/jquery/examples.html

Does anyone know of any other or know what you would call that type of control so I can at least focus my search in the right direction?

答: you are looking for the term "tab scrolling" ?</p>

ContentLicense: CC BY-SA 2.5


问:
How to use float in a QML spinbox
I use a QML Spinbox but I have trouble to use floats in it.
If I write something like value: 5.0 , it will be displayed as 5 , so as an int instead of a float.

Do you have any idea of how to proceed ?

Thanks a lot and have a good day !

答:
This is a @eyllanesc fixed version. All other missing properties must be aliased. Please report me bugs, if you find.

DoubleSpinBox.qml

```<code>import QtQuick 2.0
import QtQuick.Controls 2.2
import QmlUtils 1.0

Item
{
    id: doublespinbox
    width: 140
    height: 40
    property int decimals: 1
    property alias value: valuePreview.value
    property real from: 0
    property real to: 99
    property real stepSize: 1
    property alias editable: spinbox.editable
    property alias font: spinbox.font

    SpinBox
    {
        id: spinbox
        property bool init: false
        property real factor: Math.pow(10, decimals)

        function setValue(preview)
        {
            init = true
            value = preview.value * factor
            init = false
            preview.value = value / factor
        }

        DoubleValuePreview
        {
            id: valuePreview
            onValuePreview: spinbox.setValue(preview)
        }

        anchors.fill: parent
        editable: true
        stepSize: doublespinbox.stepSize * factor
        to : doublespinbox.to * factor
        from : doublespinbox.from * factor

        onValueChanged:
        {
            if (init)
                return

            valuePreview.setValueDirect(value / factor)
        }

        validator: DoubleValidator
        {
            bottom: Math.min(spinbox.from, spinbox.to)
            top: Math.max(spinbox.from, spinbox.to)
        }

        textFromValue: function(value, locale)
        {
            return Number(value / factor).toLocaleString(locale, 'f', doublespinbox.decimals)
        }

        valueFromText: function(text, locale)
        {
            doublespinbox.value = Number.fromLocaleString(locale, text)
            return doublespinbox.value * factor
        }
    }
}
</code>```

QmlValuePreview.h

```<code>#pragma once

#include <qobject.h>
#include <qqmlengine.h>

class QDoubleValueArg : public QObject
{
    Q_OBJECT
public:
    QDoubleValueArg(double value) : Value(value)
    {
        QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
    }
public:
    Q_PROPERTY(double value MEMBER Value)
public:
    double Value;
};

class QmlDoubleValuePreview : public QObject
{
    Q_OBJECT
public:
    using QObject::QObject;
public:
    Q_PROPERTY(double value READ getValue WRITE setValue NOTIFY valueChanged)
public:
    Q_INVOKABLE void setValueDirect(double value)
    {
        if (m_value == value)
            return;

        m_value = value;
        emit valueChanged();
    }
public:
    inline double getValue() const { return m_value; }
    inline void setValue(double value)
    {
        if (m_value == value)
            return;

        QDoubleValueArg arg(value);
        emit valuePreview(&arg);
        if (m_value == arg.Value)
            return;

        m_value = arg.Value;
        emit valueChanged();
    }
signals:
    void valueChanged();
    void valuePreview(QDoubleValueArg *preview);
private:
    double m_value = 0;
};
</code>```

Registered with:

```<code>#define URI "QmlUtils"
#define VERSION_MAJOR 1
#define VERSION_MINOR 0

void registerTypes()
{
    qRegisterMetaType<QDoubleValueArg *>("QDoubleValueArg *");
    qmlRegisterType<QmlDoubleValuePreview>(URI, VERSION_MAJOR, VERSION_MINOR, "DoubleValuePreview");
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to use float in a QML spinbox

Body:
This is a @eyllanesc fixed version. All other missing properties must be aliased. Please report me bugs, if you find.

DoubleSpinBox.qml

import QtQuick 2.0
import QtQuick.Controls 2.2
import QmlUtils 1.0

Item
{
    id: doublespinbox
    width: 140
    height: 40
    property int decimals: 1
    property alias value: valuePreview.value
    property real from: 0
    property real to: 99
    property real stepSize: 1
    property alias editable: spinbox.editable
    property alias font: spinbox.font

    SpinBox
    {
        id: spinbox
        property bool init: false
        property real factor: Math.pow(10, decimals)

        function setValue(preview)
        {
            init = true
            value = preview.value * factor
            init = false
            preview.value = value / factor
        }

        DoubleValuePreview
        {
            id: valuePreview
            onValuePreview: spinbox.setValue(preview)
        }

        anchors.fill: parent
        editable: true
        stepSize: doublespinbox.stepSize * factor
        to : doublespinbox.to * factor
        from : doublespinbox.from * factor

        onValueChanged:
        {
            if (init)
                return

            valuePreview.setValueDirect(value / factor)
        }

        validator: DoubleValidator
        {
            bottom: Math.min(spinbox.from, spinbox.to)
            top: Math.max(spinbox.from, spinbox.to)
        }

        textFromValue: function(value, locale)
        {
            return Number(value / factor).toLocaleString(locale, 'f', doublespinbox.decimals)
        }

        valueFromText: function(text, locale)
        {
            doublespinbox.value = Number.fromLocaleString(locale, text)
            return doublespinbox.value * factor
        }
    }
}

QmlValuePreview.h

#pragma once

#include <qobject.h>
#include <qqmlengine.h>

class QDoubleValueArg : public QObject
{
    Q_OBJECT
public:
    QDoubleValueArg(double value) : Value(value)
    {
        QQmlEngine::setObjectOwnership(this, QQmlEngine::CppOwnership);
    }
public:
    Q_PROPERTY(double value MEMBER Value)
public:
    double Value;
};

class QmlDoubleValuePreview : public QObject
{
    Q_OBJECT
public:
    using QObject::QObject;
public:
    Q_PROPERTY(double value READ getValue WRITE setValue NOTIFY valueChanged)
public:
    Q_INVOKABLE void setValueDirect(double value)
    {
        if (m_value == value)
            return;

        m_value = value;
        emit valueChanged();
    }
public:
    inline double getValue() const { return m_value; }
    inline void setValue(double value)
    {
        if (m_value == value)
            return;

        QDoubleValueArg arg(value);
        emit valuePreview(&arg);
        if (m_value == arg.Value)
            return;

        m_value = arg.Value;
        emit valueChanged();
    }
signals:
    void valueChanged();
    void valuePreview(QDoubleValueArg *preview);
private:
    double m_value = 0;
};

Registered with:

#define URI "QmlUtils"
#define VERSION_MAJOR 1
#define VERSION_MINOR 0

void registerTypes()
{
    qRegisterMetaType<QDoubleValueArg *>("QDoubleValueArg *");
    qmlRegisterType<QmlDoubleValuePreview>(URI, VERSION_MAJOR, VERSION_MINOR, "DoubleValuePreview");
}


问:
do an exception on first td with Filter Table
He want to do an input box with a Filter Table options.
My input box is:

```<code><input class="form-control" id="myInput" type="text" placeholder="Search..">
</code>```

and this code to generate a table:

```<code>   $data = '<table class="table table-bordered table-striped">
                                            <tr>
                                                    <th>No.</th>
                                                    <th>Status</th>
                                                    <th>First Name</th>
                                                    <th>Last Name</th>
                                                    <th>Email Address</th>
                                                    <th>Update</th>
                                                    <th>Delete</th>
                                            </tr>';
    $query = "SELECT * FROM users";
</code>```

and my js is:

```<code>$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});
</code>```

is it necessary to use a tbody or anything else to do a Filter Table?
or not’s possible to do an exception for the first  ?

very thanks!

答:
yes, is possible to do an exception for the first. Try something like:

```<code>$('table tr:gt(1)').filter...
</code>```

(Your header has 1 row, so it will work)

Body:
He want to do an input box with a Filter Table options.
My input box is:

<input class="form-control" id="myInput" type="text" placeholder="Search..">

and this code to generate a table:

   $data = '

                                                    No.
                                                    Status
                                                    First Name
                                                    Last Name
                                                    Email Address
                                                    Update
                                                    Delete

';
    $query = "SELECT * FROM users";

and my js is:

$(document).ready(function(){
  $("#myInput").on("keyup", function() {
    var value = $(this).val().toLowerCase();
    $("#myTable tr").filter(function() {
      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
    });
  });
});

is it necessary to use a tbody or anything else to do a Filter Table?
or not’s possible to do an exception for the first  ?

very thanks!

Body:
yes, is possible to do an exception for the first. Try something like:

$('table tr:gt(1)').filter...

(Your header has 1 row, so it will work)


问:
SailsJS : Mysterious null values
my problem is that whenever a new client is created, all the values are null in the database except the id, the name, responsable and the logo. i dont think i did a programmation mistake, so i think it is a case of callbacks race but i cant found the solution.
P.S : the problem occure only if i select and send an image file to be uploaded, in the other case, the client values are stored correctly.
P.S 2 : the problem occure in my remote server only, in local environnement all is ok !

Than you very much !

UPDATE : i included the code for my create.ejs view

This is the code of the store method in my ClientService :

```<code>store: function(req, done) {
  var name = req.param('name'),
    town = req.param('town'),
    adress = req.param('adress'),
    postalCode = req.param('postalCode'),
    telephone = req.param('telephone'),
    email = req.param('email'),
    fax = req.param('fax'),
    responsable = req.param('responsable'),
    website = req.param('website'),
    activity = req.param('activity');
  comments = req.param('comments');

  Client.create({
    name: name,
    town: town,
    adress: adress,
    postalCode: postalCode,
    telephone: telephone,
    fax: fax,
    responsable: responsable,
    website: website,
    activity: activity,
    email: email,
    comments: comments
  }).exec(function(err, client) {
    if (err) console.log(err);
    req.file('logo').upload(
      {
        dirname: sails.config.appPath + sails.config.params.logos
      },
      function(err, logo) {
        if (err) return done(err, null);
        if (logo.length !== 0) {
          client.logo = require('path').basename(logo[0].fd);
        } else {
          client.logo = 'default.png';
        }
        client.save(function(err) {
          return done(null, client);
        });
      }
    );
  });
}
</code>```

And this is the code for the EJS view :

```<code><div class="portlet-body form">
                        <!-- BEGIN FORM-->
                        <form action="store" method="POST" class="form-horizontal" enctype="multipart/form-data">
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="name">
                                                <label for="form_control_1">Nom du Client</label>
                                                <i class="fa fa-institution"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="activity">
                                                <label for="form_control_1">Activité</label>
                                                <i class="icon-star"></i>
                                            </div>
                                        </div>
                                    </div>
                                    </div>
                                <div class="row">
                                    <div class="col-md-6">
                                         <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="responsable">
                                                <label for="form_control_1">Responsable</label>
                                                <i class="icon-user"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                     <div class="form-group" style="margin-left:15px;">
                                        <div class="form-photo-label-form" >
                                                  <i class="icon-picture icon-create"></i>
                                                <label for="form_control_1" class="form-photo-create" >Photo </label>
                                        </div>
                                        <br>
                                        <div class="fileinput fileinput-new" data-provides="fileinput">
                                                    <span class="btn green btn-file">
                                                    <span class="fileinput-new"> Selectionner Fichier </span>
                                                    <span class="fileinput-exists"> Changer </span>
                                                    <input type="file" name="logo"> </span>
                                                    <span class="fileinput-filename"> </span>
                                                     <a href="javascript:;" class="close fileinput-exists" data-dismiss="fileinput"> </a>
                                        </div>
                                    </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                         <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="email">
                                                <label for="form_control_1">Email</label>
                                                <i class="fa fa-inbox"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                         <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="adress">
                                                <label for="form_control_1">Adresse</label>
                                                <i class="icon-home"></i>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                     <div class="col-md-6">
                                        <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="postalCode">
                                                <label for="form_control_1">Code postale</label>
                                                <i class="fa fa-send"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                            <div class="input-icon">
                                                <input type="text" class="form-control" name="town">
                                                <label for="form_control_1">Ville</label>
                                                <i class=" fa fa-map"></i>
                                            </div>
                                        </div>
                                    </div>
                                    <!--/span-->
                                </div>
                                <div class="row">
                                     <div class="col-md-6">
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                                <div class="input-icon">
                                                <textarea class="form-control" rows="3" style="height: 192px; resize:none " name="comments"></textarea>
                                                <label for="form_control_1">Commentaire</label>
                                                <i class=" fa fa-edit"></i>
                                                </div>
                                            </div>
                                            </div>
                                        </div>
                                     </div>
                                     <div class="col-md-6">
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                                    <div class="input-icon">
                                                        <input type="text" class="form-control" name="telephone">
                                                        <label for="form_control_1">Telephone</label>
                                                        <i class="icon-screen-smartphone"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                                    <div class="input-icon">
                                                        <input type="text" class="form-control" name="fax">
                                                        <label for="form_control_1">Fax</label>
                                                    <i class="fa fa-fax"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <div class="form-group form-md-line-input has-success form-md-floating-label form-create">
                                                    <div class="input-icon">
                                                        <input type="text" class="form-control" name="website">
                                                        <label for="form_control_1">Site Internet</label>
                                                        <i class=" fa fa-internet-explorer"></i>
                                                     </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>

                    <div class="form-actions right">
                        <button type="button" class="btn default">Annuler</button>
                        <button type="submit" class="btn green"><i class="fa fa-check"></i> Enregistrer</button>
                    </div>
                </form>
</code>```

答:
Nothing mysterious (:
Your problem is that You use req.param instead of req.body

And Your code is simply should look like this:

```<code>const path = require('path'); // somewhere in same module at the top

store: (req, done) => {

  Client
    .create(req.body)
    .exec((err, client) => {
      if(err) {
        // no need to go further
        // if You cannot create database record
        return done(err);
      }

      const dirname = path.join(sails.config.appPath, sails.config.params.logos); // safely concatenates paths based on OS

      req
        .file('logo')
        .upload({dirname}, (err, logo) => {
          if (err) {
            // we created record (client)
            // but could not save the file
            // it should not be a stopper
            console.error(err);
          }

          client.logo = (logo) ? path.basename(logo[0].fd) : 'default.png';

          client.save((err) => {
            if(err) {
              // just log the error and continue
              console.error(err);
            }
            done(null, client);
          });
        });
    });
}
</code>```

P.S. When You pass req.body (or any other) object to Client.create don't worry about object contents, just define field constrains in You model file, ODM (or ORM) will just handle validation automatically based on constraints and will prevent from creating null valued fields

Example:

```<code>module.exports = {

  attributes: {

    name: {
      // it requires field name:
      //  to be defined (required: true),
      //  to be string (type),
      //  to have at least 2 symbols,
      //  to not exceed 100 symbols
      type: 'string',
      required: true,
      minLength: 2,
      maxLength: 100
    },

    email: {
      // it requires field email:
      //  to be defined (required: true),
      //  to be email (type),
      //  to be unique among documents, records, rows
      type: 'email',
      required: true,
      unique: true
    },
    ... and so on ...
  }
}
</code>```

More about validation here

Title: SailsJS : Mysterious null values

Body:
my problem is that whenever a new client is created, all the values are null in the database except the id, the name, responsable and the logo. i dont think i did a programmation mistake, so i think it is a case of callbacks race but i cant found the solution.
P.S : the problem occure only if i select and send an image file to be uploaded, in the other case, the client values are stored correctly.
P.S 2 : the problem occure in my remote server only, in local environnement all is ok !

Than you very much !

UPDATE : i included the code for my create.ejs view

This is the code of the store method in my ClientService :

store: function(req, done) {
  var name = req.param('name'),
    town = req.param('town'),
    adress = req.param('adress'),
    postalCode = req.param('postalCode'),
    telephone = req.param('telephone'),
    email = req.param('email'),
    fax = req.param('fax'),
    responsable = req.param('responsable'),
    website = req.param('website'),
    activity = req.param('activity');
  comments = req.param('comments');

  Client.create({
    name: name,
    town: town,
    adress: adress,
    postalCode: postalCode,
    telephone: telephone,
    fax: fax,
    responsable: responsable,
    website: website,
    activity: activity,
    email: email,
    comments: comments
  }).exec(function(err, client) {
    if (err) console.log(err);
    req.file('logo').upload(
      {
        dirname: sails.config.appPath + sails.config.params.logos
      },
      function(err, logo) {
        if (err) return done(err, null);
        if (logo.length !== 0) {
          client.logo = require('path').basename(logo[0].fd);
        } else {
          client.logo = 'default.png';
        }
        client.save(function(err) {
          return done(null, client);
        });
      }
    );
  });
}

And this is the code for the EJS view :

                        <form action="store" method="POST" class="form-horizontal" enctype="multipart/form-data">

                                                <input type="text" class="form-control" name="name">
                                                Nom du Client

                                                <input type="text" class="form-control" name="activity">
                                                Activité

                                                <input type="text" class="form-control" name="responsable">
                                                Responsable

                                                Photo

                                                     Selectionner Fichier
                                                     Changer
                                                    <input type="file" name="logo">

                                                <input type="text" class="form-control" name="email">
                                                Email

                                                <input type="text" class="form-control" name="adress">
                                                Adresse

                                                <input type="text" class="form-control" name="postalCode">
                                                Code postale

                                                <input type="text" class="form-control" name="town">
                                                Ville

                                                <textarea class="form-control" rows="3" style="height: 192px; resize:none " name="comments"></textarea>
                                                Commentaire

                                                        <input type="text" class="form-control" name="telephone">
                                                        Telephone

                                                        <input type="text" class="form-control" name="fax">
                                                        Fax

                                                        <input type="text" class="form-control" name="website">
                                                        Site Internet

                        <button type="button" class="btn default">Annuler</button>
                        <button type="submit" class="btn green"> Enregistrer</button>

                </form>

Body:
Nothing mysterious (:
Your problem is that You use req.param instead of req.body

And Your code is simply should look like this:

const path = require('path'); // somewhere in same module at the top

store: (req, done) => {

  Client
    .create(req.body)
    .exec((err, client) => {
      if(err) {
        // no need to go further
        // if You cannot create database record
        return done(err);
      }

      const dirname = path.join(sails.config.appPath, sails.config.params.logos); // safely concatenates paths based on OS

      req
        .file('logo')
        .upload({dirname}, (err, logo) => {
          if (err) {
            // we created record (client)
            // but could not save the file
            // it should not be a stopper
            console.error(err);
          }

          client.logo = (logo) ? path.basename(logo[0].fd) : 'default.png';

          client.save((err) => {
            if(err) {
              // just log the error and continue
              console.error(err);
            }
            done(null, client);
          });
        });
    });
}

P.S. When You pass req.body (or any other) object to Client.create don't worry about object contents, just define field constrains in You model file, ODM (or ORM) will just handle validation automatically based on constraints and will prevent from creating null valued fields

Example:

module.exports = {

  attributes: {

    name: {
      // it requires field name:
      //  to be defined (required: true),
      //  to be string (type),
      //  to have at least 2 symbols,
      //  to not exceed 100 symbols
      type: 'string',
      required: true,
      minLength: 2,
      maxLength: 100
    },

    email: {
      // it requires field email:
      //  to be defined (required: true),
      //  to be email (type),
      //  to be unique among documents, records, rows
      type: 'email',
      required: true,
      unique: true
    },
    ... and so on ...
  }
}

More about validation here


问:
Lambda times out without error when querying RDS
I have a lambda function that runs successfully the first time I run it (after a new deploy), but times out each subsequent time I try to run it. It definitely has something to do with RDS (MySql) because if I take the query call out, it works normally. I can console.log whatever I like out to CloudWatch, either before or after the query to RDS and all the logs make it into CloudWatch, but no errors are thrown. It's clearly executing the entire lambda, just not returning. It's also not the lambda callback code, because, again, I can simply remove the RDS query and I get a response without a hiccup. </p>

答: Turns out, it's because I'm not shutting down the RDS connection. Apparently, lambda will not respond as long as an RDS connection remains open. Of course this makes sense, since you could potentially end up with an unbounded number of connections open (depending on the load of your lambda function). Unfortunately, lambda has no connection pooling feature for RDS. :(  Perhaps this won't be an issue when Aurora Serverless is released?</p>


问:
rmic error: class btc5.Hello not found
Click here to see picture

I have a problem like the picture attached, when I complied file remote class by "rmic remoteclass", It  can't auto create 2 file stub.class and skeleton.class.

答:
It can't auto create 2 file stub.class and skeleton.class.

It doesn't do that. It creates one class, in this case btc5.Hello_stub. rmic hasn't created skeletons by default for fifteen if not twenty years.

```<code>class btc5.Hello not found
</code>```

You haven't compiled it, or you aren't running the command from the directory containing btc5.

Title: rmic error: class btc5.Hello not found

Body:
It can't auto create 2 file stub.class and skeleton.class.

It doesn't do that. It creates one class, in this case btc5.Hello_stub. rmic hasn't created skeletons by default for fifteen if not twenty years.

class btc5.Hello not found

You haven't compiled it, or you aren't running the command from the directory containing btc5.


问:
JDBC batch operations understanding
I use Hibernate ORM and PostgreSQL in my application, and sometimes i use batch operations.
And at first I didn't understand why in the logs with size of the batch =  25, 25 queries are generated, and at first thought that it does not work correctly.
But after that I looked at the source code of the pg driver and found the following lines in the PgStatement class:

```<code> public int[] executeBatch() throws SQLException {
        this.checkClosed();
        this.closeForNextExecution();
        if (this.batchStatements != null && !this.batchStatements.isEmpty()) {
            this.transformQueriesAndParameters();
//confuses next line, because we have array of identical queries
            Query[] queries = (Query[])this.batchStatements.toArray(new Query[0]);
            ParameterList[] parameterLists =
(ParameterList[])this.batchParameters.toArray(new ParameterList[0]);
            this.batchStatements.clear();
            this.batchParameters.clear();
</code>```

and in PgPreparedStatement class

```<code>    public void addBatch() throws SQLException {
        checkClosed();
        if (batchStatements == null) {
          batchStatements = new ArrayList<Query>();
          batchParameters = new ArrayList<ParameterList>();
        }

        batchParameters.add(preparedParameters.copy());
        Query query = preparedQuery.query;
    //confuses next line
        if (!(query instanceof BatchedQuery) || batchStatements.isEmpty()) {
          batchStatements.add(query);
        }
      }
</code>```

I noticed that it turns out that if the size of the batch goes 25,
25 queries are sent with the parameters attached to them.

Logs of the database confirm this, for example:

```<code>2017-12-06 01:22:08.023 MSK [18402] postgres@buzzfactory СООБЩЕНИЕ:  выполнение S_3: BEGIN
2017-12-06 01:22:08.024 MSK [18402] postgres@buzzfactory СООБЩЕНИЕ:  выполнение S_4: select nextval ('tests_id_seq')
2017-12-06 01:22:08.041 MSK [18402] postgres@buzzfactory СООБЩЕНИЕ:  выполнение S_2: insert into tests (name, id) values ($1, $2)
2017-12-06 01:22:08.041 MSK [18402] postgres@buzzfactory ПОДРОБНОСТИ:  параметры: $1 = 'test', $2 = '1'
2017-12-06 01:22:08.041 MSK [18402] postgres@buzzfactory СООБЩЕНИЕ:  выполнение S_2: insert into tests (name, id) values ($1, $2)
2017-12-06 01:22:08.041 MSK [18402] postgres@buzzfactory ПОДРОБНОСТИ:  параметры: $1 = 'test', $2 = '2'
...
x23 queries with parameters
...
2017-12-06 01:22:08.063 MSK [18402] postgres@buzzfactory СООБЩЕНИЕ:  выполнение S_5: COMMIT
</code>```

But i thought one query must be executed with an array of 25 parameters.
Or I don't understand how batch inserts work with a prepared statement?
Why duplicate one query n times?

After all, i tried to debug my queries on this place

```<code>if (!(query instanceof BatchedQuery) || batchStatements.isEmpty()) {
</code>```

and noticed that my queries are always instance of SimpleQuery instead of BatchedQuery. Maybe this is the solution to the problem? Information about BatchedQuery i couldn't find

答:
Batch processing does not collapse or minimize the number of SQL statements done; it is all about optimizing how Hibernate caches and flushes things to the database in its in-memory session.  The importance of batch processing and finding the right batch size for your operation is to find the right balance between app memory used and database performance.

You will run out of app server memory if you do too many queries before committing/flushing a batch

you will not get the best performance if your batch size is too small and you are committing/flushing too often.

More reading here.

https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/batch.html
https://www.tutorialspoint.com/hibernate/hibernate_batch_processing.htm

Title: JDBC batch operations understanding

Body:
I use Hibernate ORM and PostgreSQL in my application, and sometimes i use batch operations.
And at first I didn't understand why in the logs with size of the batch =  25, 25 queries are generated, and at first thought that it does not work correctly.
But after that I looked at the source code of the pg driver and found the following lines in the PgStatement class:

 public int[] executeBatch() throws SQLException {
        this.checkClosed();
        this.closeForNextExecution();
        if (this.batchStatements != null && !this.batchStatements.isEmpty()) {
            this.transformQueriesAndParameters();
//confuses next line, because we have array of identical queries
            Query[] queries = (Query[])this.batchStatements.toArray(new Query[0]);
            ParameterList[] parameterLists =
(ParameterList[])this.batchParameters.toArray(new ParameterList[0]);
            this.batchStatements.clear();
            this.batchParameters.clear();

and in PgPreparedStatement class

    public void addBatch() throws SQLException {
        checkClosed();
        if (batchStatements == null) {
          batchStatements = new ArrayList<Query>();
          batchParameters = new ArrayList<ParameterList>();
        }

        batchParameters.add(preparedParameters.copy());
        Query query = preparedQuery.query;
    //confuses next line
        if (!(query instanceof BatchedQuery) || batchStatements.isEmpty()) {
          batchStatements.add(query);
        }
      }

I noticed that it turns out that if the size of the batch goes 25,
25 queries are sent with the parameters attached to them.

Logs of the database confirm this, for example:

2017-12-06 01:22:08.023 MSK [18402] postgres@buzzfactory СООБЩЕНИЕ:  выполнение S_3: BEGIN
2017-12-06 01:22:08.024 MSK [18402] postgres@buzzfactory СООБЩЕНИЕ:  выполнение S_4: select nextval ('tests_id_seq')
2017-12-06 01:22:08.041 MSK [18402] postgres@buzzfactory СООБЩЕНИЕ:  выполнение S_2: insert into tests (name, id) values ($1, $2)
2017-12-06 01:22:08.041 MSK [18402] postgres@buzzfactory ПОДРОБНОСТИ:  параметры: $1 = 'test', $2 = '1'
2017-12-06 01:22:08.041 MSK [18402] postgres@buzzfactory СООБЩЕНИЕ:  выполнение S_2: insert into tests (name, id) values ($1, $2)
2017-12-06 01:22:08.041 MSK [18402] postgres@buzzfactory ПОДРОБНОСТИ:  параметры: $1 = 'test', $2 = '2'
...
x23 queries with parameters
...
2017-12-06 01:22:08.063 MSK [18402] postgres@buzzfactory СООБЩЕНИЕ:  выполнение S_5: COMMIT

But i thought one query must be executed with an array of 25 parameters.
Or I don't understand how batch inserts work with a prepared statement?
Why duplicate one query n times?

After all, i tried to debug my queries on this place

if (!(query instanceof BatchedQuery) || batchStatements.isEmpty()) {

and noticed that my queries are always instance of SimpleQuery instead of BatchedQuery. Maybe this is the solution to the problem? Information about BatchedQuery i couldn't find


问:
Trace the IPAddress
I like to know the IP address of the system from which user is connected to MSTSC or remote system. Here is my problem:-

I have web application wich run on intranet and when user need to access that webapplication they need to login to their office PC. Now to access their office PC user need to connect thorugh VPN. Now i want to know his IP address from which he has done the VPN when he access the webapplication. Your help is appriciated

Thanks,
Pankaj

答:
That's something technically impossible to achieve solely inside your web application.

Like you mentioned, the HTTP requests come from the machine inside corporate network, not the machine the end user uses outside. If you know networking well, then those requests only contain IP address of the inner machine, not the outer one.

To acquire the outer machine's IP address, you will have to collect information from the inner machine who sends out the requests.

Since the outer machine has a connection to the inner machine, there should be possibility to collect outer machine information on the inner machine (but it still can be hard if VPN is used, as that means there can be network devices in between, who may hide the outer machine's IP address.

Title: Trace the IPAddress


问:
Cannot import my store file into App.js error: 'store' should be listed in the project's dependencies

'store' should be listed in the project's dependencies

For some reason I can't import my store into App.js

Here you can see that App.js and store.js are at the same level:

App.js

```<code>import React from 'react';
import { connect, Provider } from 'react-redux';

import Routes from './config/Routes';
import { setSearch } from './actions';
import localCoins from './coins.json';

// Store
import store from 'store';

class App extends React.Component {
  componentWillMount() {
    this.props.setSearch(localCoins);
  }

  render() {
    return (
      <Provider store={store}>
        <Routes />
      </Provider>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  setSearch: (...args) => { dispatch(setSearch(...args)); }
});

export default connect(null, mapDispatchToProps)(App);
</code>```

store.js

```<code>import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

// Reducers
import reducers from './reducers';

/* eslint-disable no-underscore-dangle */
const reduxDevToolsExtension = window.__REDUX_DEVTOOLS_EXTENSION__;
/* eslint-enable */

const store = createStore(
  combineReducers({
    ...reducers
  }),
  reduxDevToolsExtension && reduxDevToolsExtension(),
  applyMiddleware(
    thunk
  )
);

export default store;
</code>```

答:
you meant import store from './store';

you are missing the ./ that indicates that is a project file not an installed dependency

Body:
'store' should be listed in the project's dependencies

For some reason I can't import my store into App.js

Here you can see that App.js and store.js are at the same level:

App.js

import React from 'react';
import { connect, Provider } from 'react-redux';

import Routes from './config/Routes';
import { setSearch } from './actions';
import localCoins from './coins.json';

// Store
import store from 'store';

class App extends React.Component {
  componentWillMount() {
    this.props.setSearch(localCoins);
  }

  render() {
    return (
      <Provider store={store}>
        <Routes />
      </Provider>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  setSearch: (...args) => { dispatch(setSearch(...args)); }
});

export default connect(null, mapDispatchToProps)(App);

store.js

import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

// Reducers
import reducers from './reducers';

/* eslint-disable no-underscore-dangle */
const reduxDevToolsExtension = window.__REDUX_DEVTOOLS_EXTENSION__;
/* eslint-enable */

const store = createStore(
  combineReducers({
    ...reducers
  }),
  reduxDevToolsExtension && reduxDevToolsExtension(),
  applyMiddleware(
    thunk
  )
);

export default store;


问:
Amazon cloudfront and 403 cost
We host some scripts and content in cloudfront. These are accessible publicly by different consumers as part of their websites. When the scripts are no longer relavant we invalidate the file/content and it is no longer available. The people who use the script/content on their pages are notified but we can't enforce them to remove the script/content which gives 403 status code now. How to avoid or reduce this cost?</p>

答:
Here's one strategy.

Assume your domain name is example.com.

Create a CloudFront distribution with Alternate Domain Name *.example.com.

For each site, or script, or site+script combo, assign a custom "dummy" hostname -- e.g. jozxyqkrd52169.example.com.   Give this to one site only.

In Route 53, maintain only DNS entries for the hostnames that you currently consider valid.  Delete them when the entry is no longer needed.  This can be automated.

Technically, CloudFront would respond to any *.example.com hostname, but with no DNS record pointing there, no requests arrive for hostnames you aren't using.

You'll be paying for Route 53 to handle queries for hostnames with deleted entries, but that's a fraction of the cost of the CloudFronr and S3 request pricing.

Alternately, instead of provisioning Route 53 with records you want to work, you could provision it with a wildcard record pointing to CloudFront and then create specific entries for hostnames that you want to block.  A CNAME record pointing to a target name such as invalid.invalid (.invalid is a top-level domain name that is actually reserved for signifying that a record is in fact invalid) should be usable for overriding specific subdomains and preventing requests for those names from hitting CloudFront.

Note that as long as you don't configure the CloudFront Cache Behavior to forward the Host header to the origin, on a single distribution that answers for multiple hostnames, foo.example.com/cat.js and bar.example.com/cat.js would be considered the same object, so multiple hostnames like this should not have a negative impact on your cache hit ratio.

Title: Amazon cloudfront and 403 cost


问:
Difference between rows of different variables, avoiding macro method
I am trying to find the average time between two processes. Each record is a repair process with an part ID, a start date, and an end date. For a given ID, only one repair process can occur at a time. See sample data below:

```<code>ID  START_DATE  END_DATE
123  1/2/2006   2/3/2006
124  1/3/2006   4/2/2006
123  3/5/2006   3/7/2006
123  6/2/2006   6/4/2006
123  6/8/2006   6/9/2006
124  6/2/2006   6/4/2006
124  6/5/2006   6/9/2006
124  6/10/2006   6/12/2006
</code>```

The information I need is the difference between the END_DATE and START_DATE for a given ID. For example, for ID 123, the time between its first process and the second process is 3/5/2006 - 2/3/2006. If the list were longer, I would then take the all those differences and take the average of them.

The output would be something like this:

```<code>ID  AverageTime
123   4.3
124   2.3
</code>```

My approach is to create a macro based on the following steps:

Create list of unique IDs.

For each ID in list, create table
of just that ID.

Calculate the difference between START_DATE and
END_DATE for that ID using the LAG function.

Average the
difference and append to list of unique IDs.

I think this would work, but may take a long time because there are 400k rows. Is there a way to do this without a macro? How might this process be optimized as the server I am running this on is very slow?

答:
Working off Dom's input and sort, this DOW loop will compute each id's mean gap in a single pass:

```<code>... input ...
... sort ...

data want(keep=id gap_mean);
  do _n_ = 1 by 1 until (last.id);
    set have;
    by id;

    if prior_end then gap_sum = sum ( gap_sum, end_date - prior_end );
    prior_end = end_date;
  end;

  gap_mean = gap_sum / (_n_ - 1);  * number of gaps is the number of iterations less 1;
run;
</code>```

Code items of note:

set and by statement inside loop

loop iterations tracked with _n_ (convenience - reuse of automatic variable)

until (last.id) loop test works because every by group has at least one row and flag is set at last row in group

gap_sum computed with sum() so the first gap can accumulated cleanly.

Alternative ... then gap_sum = gap_sum + end_date-prior_end works, but would cause the LOG to sho NOTE: Missing values were generated as a result of performing an operation on missing values.

Alternative ... then gap_sum + (end_date - prior_date) works without the NOTE, but the + operator would cause gap_sum to be implicitly RETAINed, which means gap_sum would have to be explicitly reset before the do

prior_end is a manual lag for next iter

when a group is finished the mean is computed and implicitly output

when implicit loop returns to top it will be the start of the next group.  Non-retained variables will get reset to missing (.) Those of importance are gap_sum and prior_end

Body:
I am trying to find the average time between two processes. Each record is a repair process with an part ID, a start date, and an end date. For a given ID, only one repair process can occur at a time. See sample data below:

ID  START_DATE  END_DATE
123  1/2/2006   2/3/2006
124  1/3/2006   4/2/2006
123  3/5/2006   3/7/2006
123  6/2/2006   6/4/2006
123  6/8/2006   6/9/2006
124  6/2/2006   6/4/2006
124  6/5/2006   6/9/2006
124  6/10/2006   6/12/2006

The information I need is the difference between the END_DATE and START_DATE for a given ID. For example, for ID 123, the time between its first process and the second process is 3/5/2006 - 2/3/2006. If the list were longer, I would then take the all those differences and take the average of them.

The output would be something like this:

ID  AverageTime
123   4.3
124   2.3

My approach is to create a macro based on the following steps:

Create list of unique IDs.

For each ID in list, create table
of just that ID.

Calculate the difference between START_DATE and
END_DATE for that ID using the LAG function.

Average the
difference and append to list of unique IDs.

I think this would work, but may take a long time because there are 400k rows. Is there a way to do this without a macro? How might this process be optimized as the server I am running this on is very slow?

Body:
Working off Dom's input and sort, this DOW loop will compute each id's mean gap in a single pass:

... input ...
... sort ...

data want(keep=id gap_mean);
  do _n_ = 1 by 1 until (last.id);
    set have;
    by id;

    if prior_end then gap_sum = sum ( gap_sum, end_date - prior_end );
    prior_end = end_date;
  end;

  gap_mean = gap_sum / (_n_ - 1);  * number of gaps is the number of iterations less 1;
run;

Code items of note:

set and by statement inside loop

loop iterations tracked with _n_ (convenience - reuse of automatic variable)

until (last.id) loop test works because every by group has at least one row and flag is set at last row in group

gap_sum computed with sum() so the first gap can accumulated cleanly.

Alternative ... then gap_sum = gap_sum + end_date-prior_end works, but would cause the LOG to sho NOTE: Missing values were generated as a result of performing an operation on missing values.

Alternative ... then gap_sum + (end_date - prior_date) works without the NOTE, but the + operator would cause gap_sum to be implicitly RETAINed, which means gap_sum would have to be explicitly reset before the do

prior_end is a manual lag for next iter

when a group is finished the mean is computed and implicitly output

when implicit loop returns to top it will be the start of the next group.  Non-retained variables will get reset to missing (.) Those of importance are gap_sum and prior_end


问:
Problem with Array Search in PHP
I am not finding what might be the problem in my program.

I am having an array like this

```<code>$arr = array("1", "urgent", "4", "low", "15", "avg");
</code>```

When i am searching this array using

```<code>$key = array_search("4", $arr);// Working
</code>```

Its is giving me the index of that element;

But when i am searching for "1" it is not giving me any index.

```<code>$key = array_search("4", $arr); // Not working here - for searching "1"
</code>```

What might be the problem.

Thank You

答:
http://ideone.com/e1n3r Your code does work fine. It returns key == 0, which is the key, where "1" is stored.

To get the difference between 0 and false you should use === operator, or its contrary !==:

```<code>$arr = array("1", "urgent", "4", "low", "15", "avg");

$key1 = array_search("1", $arr);
var_dump($key1 === false);  // false (value exists)
var_dump($key1 !== false);  // true (value exists)

$key21 = array_search("21", $arr);
var_dump($key21 === false); // true  (value does not exist)
var_dump($key21 !== false); // false (value does not exist)
</code>```

Title: Problem with Array Search in PHP

Body:
I am not finding what might be the problem in my program.

I am having an array like this

$arr = array("1", "urgent", "4", "low", "15", "avg");

When i am searching this array using

$key = array_search("4", $arr);// Working

Its is giving me the index of that element;

But when i am searching for "1" it is not giving me any index.

$key = array_search("4", $arr); // Not working here - for searching "1"

What might be the problem.

Thank You

Body:
http://ideone.com/e1n3r Your code does work fine. It returns key == 0, which is the key, where "1" is stored.

To get the difference between 0 and false you should use === operator, or its contrary !==:

$arr = array("1", "urgent", "4", "low", "15", "avg");

$key1 = array_search("1", $arr);
var_dump($key1 === false);  // false (value exists)
var_dump($key1 !== false);  // true (value exists)

$key21 = array_search("21", $arr);
var_dump($key21 === false); // true  (value does not exist)
var_dump($key21 !== false); // false (value does not exist)


问:
R: Displaying numbers as currency in knitr::kable
I have the following table created using knitr::kable

```<code>Week Cost   Disc    total
Wk1 10000   -4000   6000
Wk2 20000   -3000   17000
Wk3 30000   -2000   28000
Wk4 40000   -1000   39000
</code>```

I would like to display the numbers using an accounting format with a currency. I know you can use the paste function, but I was wondering if there is a cleaner solution. Here is how I would want it to look:

```<code>Week Cost      Disc     total
Wk1 $10,000  ($4,000)  $6,000
Wk2 $20,000  ($3,000)  $17,000
Wk3 $30,000  ($2,000)  $28,000
Wk4 $40,000  ($1,000)  $39,000
</code>```

Any suggestions?

答:
We can use the dollar function the scales package to write a helper function called format_dol_fun that performs this formatting:

```<code>format_dol_fun <- function(x){
  ifelse(x < 0,
         paste0('(', scales::dollar(-x), ')'),
         scales::dollar(x))
  }

dplyr::mutate_if(dat, is.numeric, format_dol_fun)

#   Week    Cost     Disc   total
# 1  Wk1 $10,000 ($4,000)  $6,000
# 2  Wk2 $20,000 ($3,000) $17,000
# 3  Wk3 $30,000 ($2,000) $28,000
# 4  Wk4 $40,000 ($1,000) $39,000
</code>```

Data

```<code>dat <- structure(list(Week = c("Wk1", "Wk2", "Wk3", "Wk4"),
                      Cost = c(10000L, 20000L, 30000L, 40000L),
                      Disc = c(-4000L, -3000L, -2000L, -1000L),
                      total = c(6000L, 17000L, 28000L, 39000L)),
                 .Names = c("Week", "Cost", "Disc", "total"),
                 class = "data.frame",
                 row.names = c(NA, -4L))
</code>```

Body:
I have the following table created using knitr::kable

Week Cost   Disc    total
Wk1 10000   -4000   6000
Wk2 20000   -3000   17000
Wk3 30000   -2000   28000
Wk4 40000   -1000   39000

I would like to display the numbers using an accounting format with a currency. I know you can use the paste function, but I was wondering if there is a cleaner solution. Here is how I would want it to look:

Week Cost      Disc     total
Wk1 $10,000  ($4,000)  $6,000
Wk2 $20,000  ($3,000)  $17,000
Wk3 $30,000  ($2,000)  $28,000
Wk4 $40,000  ($1,000)  $39,000

Any suggestions?

Body:
We can use the dollar function the scales package to write a helper function called format_dol_fun that performs this formatting:

format_dol_fun <- function(x){
  ifelse(x < 0,
         paste0('(', scales::dollar(-x), ')'),
         scales::dollar(x))
  }

dplyr::mutate_if(dat, is.numeric, format_dol_fun)

#   Week    Cost     Disc   total
# 1  Wk1 $10,000 ($4,000)  $6,000
# 2  Wk2 $20,000 ($3,000) $17,000
# 3  Wk3 $30,000 ($2,000) $28,000
# 4  Wk4 $40,000 ($1,000) $39,000

Data

dat <- structure(list(Week = c("Wk1", "Wk2", "Wk3", "Wk4"),
                      Cost = c(10000L, 20000L, 30000L, 40000L),
                      Disc = c(-4000L, -3000L, -2000L, -1000L),
                      total = c(6000L, 17000L, 28000L, 39000L)),
                 .Names = c("Week", "Cost", "Disc", "total"),
                 class = "data.frame",
                 row.names = c(NA, -4L))


问:
Zipkin stream server and client configuration where client is using multiple input/output channels
I have a client application with multiple channels as SOURCE/SINK. I want to send logs to Zipkin server.

According to my understanding, if spring finds spring cloud stream in classpath, Zipkin client defaults to messaging instead of sending logs through HTTP.

At client side:

Q1.
Is there an automatic configuration for zipkin rabbit binding in such scenario? If not, what is default channel name of zipkin SOURCE channel?

Q2.
Do I need to configure defaultSampler to AlwaysSampler()?

At Server side:

Q1.
Do I need to create Zipkin server as a spring boot application for my use case or can I use the jar retrieved using:
wget -O zipkin.jar 'https://search.maven.org/remote_content?g=io.zipkin.java&a=zipkin-server&v=LATEST&c=exec'
...as stated on https://zipkin.io/pages/quickstart.html ?

Q2.
How do I configure zipkin SINK channel to destination?

Spring boot version: 1.5.9.RELEASE
Spring cloud version: Edgware.RELEASE

答:
I have a client application with multiple channels as SOURCE/SINK. I want to send logs to Zipkin server.

Zipkin is not a tool to store logs

According to my understanding, if spring finds spring cloud stream in classpath, Zipkin client defaults to messaging instead of sending logs through HTTP.

No - you need the sleuth-stream dependency on the client side and the zipkin-stream dependency on the server side (which got deprecated and you should start using the inbuilt rabbitmq support from Zipkin).

At client side: Q1. Is there an automatic configuration for zipkin rabbit binding in such scenario? If not, what is default channel name of zipkin SOURCE channel?

Yes, there is. The channel is sleuth

Q2. Do I need to configure defaultSampler to AlwaysSampler()?

No, you have the PercentageBasedSampler (I'm pretty sure it's written in the docs). You can tweak its values.

At Server side: Q1. Do I need to create Zipkin server as a spring boot application for my use case or can I use the jar retrieved using: wget -O zipkin.jar 'https://search.maven.org/remote_content?g=io.zipkin.java&a=zipkin-server&v=LATEST&c=exec' ...as stated on https://zipkin.io/pages/quickstart.html ?

You should do the wget. If you want to use the legacy stream support then you should create a zipkin server yourself.

Q2. How do I configure zipkin SINK channel to destination?

If you're using the legacy zipkin stream app then it's automatically configured to point to proper destination. You can tweak the destination as you please in the standard way Spring Cloud Stream supports it.


问:
Spring Data Elasticsearch - Create keyword field with normalizer
We are using the spring-data-elasticsearch project to interface with our elasticsearch clusters, and have been using it now for around a year. Recently, we moved to elasticsearch 5.x (from 2.x) where we now have the "keyword" datatype.

I would like to index these keywords as lowercase values, which I know can be done with field normalizers. I can't find anywhere in the documentation or online where I can add a normalizer to a field through the annotation based mapping.
E.g

```<code>@Field(type = FieldType.keyword, <some_other_param = some_normalizer>)
</code>```

Is this something that can be done? I know that we can use JSON based mapping definitions as well, so I will fall back to that option if needed, but would like to be able to do it this way if possible.

Any help would be very appreciated!

答:
FYI, for anyone looking at this, the answer is there is not a way to do this at this time.

You can do this, however, by creating your mappings file as JSON in the Elasticsearch format. See:
https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-put-mapping.html

You can then create that JSON file and link it to your Domain model with.

@Mapping(mappingPath = "some/path/mapping.json")

Note that this is not, in my experience, compatible with the provided annotation based mapping for fields.

Body:
We are using the spring-data-elasticsearch project to interface with our elasticsearch clusters, and have been using it now for around a year. Recently, we moved to elasticsearch 5.x (from 2.x) where we now have the "keyword" datatype.

I would like to index these keywords as lowercase values, which I know can be done with field normalizers. I can't find anywhere in the documentation or online where I can add a normalizer to a field through the annotation based mapping.
E.g

@Field(type = FieldType.keyword, <some_other_param = some_normalizer>)

Is this something that can be done? I know that we can use JSON based mapping definitions as well, so I will fall back to that option if needed, but would like to be able to do it this way if possible.

Any help would be very appreciated!


答:
Using currency in formattable library:

```<code>##Your sample df

df <- data.frame(Week = c("Wk1", "Wk2", "Wk3", "Wk4"), Cost = c(10000, 20000, 30000, 40000))

library(formattable)
df$Cost <- currency(df$Cost, digits = 0L)
df
#  Week    Cost
#1  Wk1 $10,000
#2  Wk2 $20,000
#3  Wk3 $30,000
#4  Wk4 $40,000
</code>```

Title: R: Displaying numbers as currency in knitr::kable

Body:
Using currency in formattable library:

##Your sample df

df <- data.frame(Week = c("Wk1", "Wk2", "Wk3", "Wk4"), Cost = c(10000, 20000, 30000, 40000))

library(formattable)
df$Cost <- currency(df$Cost, digits = 0L)
df
#  Week    Cost
#1  Wk1 $10,000
#2  Wk2 $20,000
#3  Wk3 $30,000
#4  Wk4 $40,000


问:
How to do C++ style destructors in C#?
I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away.

The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.

In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.

Is there any way to for a using block to be automatically used in C#?

Many thanks.

UPDATE:

I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.

Here's the bug I found, reduced to the essentials...

```<code>try
{
    PleaseDisposeMe a = new PleaseDisposeMe();
    throw new Exception();
    a.Dispose();
}
catch (Exception ex)
{
    Log(ex);
}

// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();
</code>```

Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?

答:
Where I work we use the following guidelines:

Each IDisposable class must have a finalizer

Whenever using an IDisposable object, it must be used inside a "using" block. The only exception is if the object is a member of another class, in which case the containing class must be IDisposable and must call the member's 'Dispose' method in its own implementation of 'Dispose'. This means 'Dispose' should never be called by the developer except for inside another 'Dispose' method, eliminating the bug described in the question.

The code in each Finalizer must begin with a warning/error log notifying us that the finalizer has been called. This way you have an extremely good chance of spotting such bugs as described above before releasing the code, plus it might be a hint for bugs occuring in your system.

To make our lives easier, we also have a SafeDispose method in our infrastructure, which calls the the Dispose method of its argument within a try-catch block (with error logging), just in case (although Dispose methods are not supposed to throw exceptions).

See also: Chris Lyon's suggestions regarding IDisposable

Edit:
@Quarrelsome: One thing you ought to do is call GC.SuppressFinalize inside 'Dispose', so that if the object was disposed, it wouldn't be "re-disposed".

It is also usually advisable to hold a flag indicating whether the object has already been disposed or not. The follwoing pattern is usually pretty good:

```<code>class MyDisposable: IDisposable {
    public void Dispose() {
        lock(this) {
            if (disposed) {
                return;
            }

            disposed = true;
        }

        GC.SuppressFinalize(this);

        // Do actual disposing here ...
    }

    private bool disposed = false;
}
</code>```

Of course, locking is not always necessary, but if you're not sure if your class would be used in a multi-threaded environment or not, it is advisable to keep it.

OwnerDisplayName: billpg

Title: How to do C++ style destructors in C#?

Body:
I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away.

The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.

In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.

Is there any way to for a using block to be automatically used in C#?

Many thanks.

UPDATE:

I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.

Here's the bug I found, reduced to the essentials...

try
{
    PleaseDisposeMe a = new PleaseDisposeMe();
    throw new Exception();
    a.Dispose();
}
catch (Exception ex)
{
    Log(ex);
}

// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();

Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?

LastEditorDisplayName: billpg

Body:
Where I work we use the following guidelines:

Each IDisposable class must have a finalizer

Whenever using an IDisposable object, it must be used inside a "using" block. The only exception is if the object is a member of another class, in which case the containing class must be IDisposable and must call the member's 'Dispose' method in its own implementation of 'Dispose'. This means 'Dispose' should never be called by the developer except for inside another 'Dispose' method, eliminating the bug described in the question.

The code in each Finalizer must begin with a warning/error log notifying us that the finalizer has been called. This way you have an extremely good chance of spotting such bugs as described above before releasing the code, plus it might be a hint for bugs occuring in your system.

To make our lives easier, we also have a SafeDispose method in our infrastructure, which calls the the Dispose method of its argument within a try-catch block (with error logging), just in case (although Dispose methods are not supposed to throw exceptions).

See also: Chris Lyon's suggestions regarding IDisposable

Edit:
@Quarrelsome: One thing you ought to do is call GC.SuppressFinalize inside 'Dispose', so that if the object was disposed, it wouldn't be "re-disposed".

It is also usually advisable to hold a flag indicating whether the object has already been disposed or not. The follwoing pattern is usually pretty good:

class MyDisposable: IDisposable {
    public void Dispose() {
        lock(this) {
            if (disposed) {
                return;
            }

            disposed = true;
        }

        GC.SuppressFinalize(this);

        // Do actual disposing here ...
    }

    private bool disposed = false;
}

Of course, locking is not always necessary, but if you're not sure if your class would be used in a multi-threaded environment or not, it is advisable to keep it.

OwnerDisplayName: Hershi

LastEditorDisplayName: Hershi


问:
a simple regexp validator
How do a I create a validator, which has these simple rules. An expression is valid if

it must start with a letter

it must end with a letter

it can contain a dash (minus sign), but not at start or end of the expression

答:
xmammoth pretty much got it, with one minor problem.  My solution is:

```<code>^[a-zA-Z]+\-?[a-zA-Z]+$
</code>```

Note that the original question states, it can contain a dash.  The question mark is needed after the dash to make sure that it is optional in the regex.

OwnerDisplayName: new-to-rails

Title: a simple regexp validator

Body:
xmammoth pretty much got it, with one minor problem.  My solution is:

^[a-zA-Z]+\-?[a-zA-Z]+$

Note that the original question states, it can contain a dash.  The question mark is needed after the dash to make sure that it is optional in the regex.

OwnerDisplayName: sqook


问:
Python script running via shell but not working via supervisord
The error that I'm facing is:

```<code> File "/usr/local/lib/python3.5/dist-packages/oauth2client/crypt.py", line 23, in <module>
    from oauth2client import _pure_python_crypt
  File "/usr/local/lib/python3.5/dist-packages/oauth2client/_pure_python_crypt.py", line 24, in <module>
    from pyasn1_modules.rfc2459 import Certificate
  File "/usr/local/lib/python3.5/dist-packages/pyasn1_modules/rfc2459.py", line 20, in <module>
    from pyasn1.type import opentype
ImportError: cannot import name 'opentype'
</code>```

Which I thought was resolved by following the instructions in this stackoverflow answer:

```<code>sudo apt-get --reinstall install python-pyasn1 python-pyasn1-modules
pip3 install --upgrade google-auth-oauthlib
</code>```

When I run my program via supervisorctl, sudo supervisorctl restart at_ussd I get the error above.
However when I run my program via shell sudo python3 at_ussd.py, the program runs smoothly.

Please help me resolve this so that I can continue using supervisor for management!

答:
tl;dr; Search for multiple pyasn1/pyasn1-modules packages installed on your system.

From the traceback it looks like you have the latest pyasn1-modules (0.2.1) and some older (and incompatible) pyasn1 e.g. < 0.4.1 used together when you run it from superuserd.

However, when you run the program from you user shell, a compatible combination of pyasn1-modules/pyasn1 is picked up. It can be either older pyasn1-modules or newer pyasn1.

Body:
The error that I'm facing is:

 File "/usr/local/lib/python3.5/dist-packages/oauth2client/crypt.py", line 23, in <module>
    from oauth2client import _pure_python_crypt
  File "/usr/local/lib/python3.5/dist-packages/oauth2client/_pure_python_crypt.py", line 24, in <module>
    from pyasn1_modules.rfc2459 import Certificate
  File "/usr/local/lib/python3.5/dist-packages/pyasn1_modules/rfc2459.py", line 20, in <module>
    from pyasn1.type import opentype
ImportError: cannot import name 'opentype'

Which I thought was resolved by following the instructions in this stackoverflow answer:

sudo apt-get --reinstall install python-pyasn1 python-pyasn1-modules
pip3 install --upgrade google-auth-oauthlib

When I run my program via supervisorctl, sudo supervisorctl restart at_ussd I get the error above.
However when I run my program via shell sudo python3 at_ussd.py, the program runs smoothly.

Please help me resolve this so that I can continue using supervisor for management!


问:
Generate all sublists of a list in OCAML
What I want to do is generating all sub-lists of a list in OCAML,

for example for

```<code>[1; 2; 3]
</code>```

as a result I want to get this

```<code>[[1]; [2]; [3]; [1; 2]; [1; 3]; [2; 3]; [1; 2; 3]]
</code>```

This is my approach so far:

```<code>let sublist l =
  let rec aux i j max l2 =
    match l with
    | [] -> l
    | h:t ->
      if (i = max && j = max) then l2
      else if (j < max ) then aux i j+1 [h]::tl
      else aux i+1 i+1 l
  in
  aux 0 0 (List.length l) []
</code>```

答:
Use an divide and conquer approach: given a non-empty list, you get a list of all its sublists by removing its first element x and solving the problem for the remaining elements (via a recursion step).

When the recursive call returns, you combine this intermediate result with the element x you previously cut off: you have to return each of the sublist with x added in front of it and unmodified.

```<code>let rec sublists = function
  | []    -> [[]]
  | x::xs -> let ls = sublists xs in
               List.map (fun l -> x::l) ls @ ls;;
</code>```

For your example input this computes:

# sublists [1;2;3];;

- : int list list = [[1; 2; 3]; [1; 2]; [1; 3]; [1]; [2; 3]; [2]; [3]; []]

The computed list can be sorted and filtered, depending on whether you want the empty list in the result or not.

ContentLicense: CC BY-SA 4.0

Body:
What I want to do is generating all sub-lists of a list in OCAML,

for example for

[1; 2; 3]

as a result I want to get this

[[1]; [2]; [3]; [1; 2]; [1; 3]; [2; 3]; [1; 2; 3]]

This is my approach so far:

let sublist l =
  let rec aux i j max l2 =
    match l with
    | [] -> l
    | h:t ->
      if (i = max && j = max) then l2
      else if (j < max ) then aux i j+1 [h]::tl
      else aux i+1 i+1 l
  in
  aux 0 0 (List.length l) []

Body:
Use an divide and conquer approach: given a non-empty list, you get a list of all its sublists by removing its first element x and solving the problem for the remaining elements (via a recursion step).

When the recursive call returns, you combine this intermediate result with the element x you previously cut off: you have to return each of the sublist with x added in front of it and unmodified.

let rec sublists = function
  | []    -> [[]]
  | x::xs -> let ls = sublists xs in
               List.map (fun l -> x::l) ls @ ls;;

For your example input this computes:

# sublists [1;2;3];;

- : int list list = [[1; 2; 3]; [1; 2]; [1; 3]; [1]; [2; 3]; [2]; [3]; []]

The computed list can be sorted and filtered, depending on whether you want the empty list in the result or not.


问:
React-Native I keep getting "Your binary is not optimized for iPhone 5" but I have the correct images?
I keep getting "Your binary is not optimized for iPhone 5,  New iPhone apps and app updates submitted must support the 4-inch display on iPhone 5 and must include a launch image referenced in the Info.plist under UILaunchImages with a UILaunchImageSize value set to {320, 568}" but I have the correct images, really not sure what is going on here.

Here are my images

答: I was able to fix this by deleting everything and reading all the images. It seems if you have duplicates it creates this issue </p>


问:
How to implement a lazy property in Kotlin that requires another property?
I need a rectangle that needs to be initialized on call.

Here is my code;

```<code>class EpheButton private constructor(
    private val text: String,
    private val x: Float,
    private val y: Float,
    private val projectionMatrix: Matrix4) : Disposable {
private val spriteBatch: SpriteBatch = SpriteBatch()
private val bitmapFont: BitmapFont = BitmapFont()
private val shapeRenderer: ShapeRenderer = ShapeRenderer()

private val textWidth: Float
private val textHeight: Float
private val rectangle :Rectangle by lazy { Rectangle(x, y, textWidth, textHeight) }

init {
    bitmapFont.data.setScale(2f)
    bitmapFont.region.texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)
    bitmapFont.color = Color.BLUE
    val layout = GlyphLayout()
    layout.setText(bitmapFont, text)
    textWidth = layout.width
    textHeight = layout.height
}
</code>```

I get errors for the line private val rectangle :Rectangle by lazy { Rectangle(x, y, textWidth, textHeight) } which says that;

Variable 'textWidth' must be initialized
  Variable 'textHeight' must be initialized

But I am already initializing them on the init{} code block.

What am I doing wrong?

答:
In kotlin , you have to initialize a variable before using it, You are using lazy initializer for Rectangle but compiler doesn't know the the status of textWidth and textHeight

So class looks like this

```<code>class EpheButton private constructor(
    private val text: String,
    private val x: Float,
    private val y: Float,
    private val projectionMatrix: Matrix4) : Disposable {
private val spriteBatch: SpriteBatch = SpriteBatch()
private val bitmapFont: BitmapFont = BitmapFont()
private val shapeRenderer: ShapeRenderer = ShapeRenderer()

private val textWidth: Float
private val textHeight: Float
init {
    bitmapFont.data.setScale(2f)
    bitmapFont.region.texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)
    bitmapFont.color = Color.BLUE
    val layout = GlyphLayout()
    layout.setText(bitmapFont, text)
    textWidth = layout.width
    textHeight = layout.height
}
private val rectangle :Rectangle by lazy { Rectangle(x, y, textWidth, textHeight) }
</code>```

Updated :-
Why order of initialization matter's here ?

We can call this weired behavior to Null-Safty of Kotlin. When we change the order of init block and variable declaration , we are breaking this rule.

From Kotlin official documentaion :-

Kotlin's type system is aimed to eliminate NullPointerException's from
  our code. The only possible causes of NPE's may be

An explicit call to throw NullPointerException();

Usage of the !! operator that is described below;

External Java code has caused it;

There's some data inconsistency with regard to initialization (an uninitialized this available in a constructor is used somewhere).

Other than this four conditions , it always ensure that a variable is initialized at compile time . so same with our case it just ensuring that the used variable must be initialized before it used.

Body:
I need a rectangle that needs to be initialized on call.

Here is my code;

class EpheButton private constructor(
    private val text: String,
    private val x: Float,
    private val y: Float,
    private val projectionMatrix: Matrix4) : Disposable {
private val spriteBatch: SpriteBatch = SpriteBatch()
private val bitmapFont: BitmapFont = BitmapFont()
private val shapeRenderer: ShapeRenderer = ShapeRenderer()

private val textWidth: Float
private val textHeight: Float
private val rectangle :Rectangle by lazy { Rectangle(x, y, textWidth, textHeight) }

init {
    bitmapFont.data.setScale(2f)
    bitmapFont.region.texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)
    bitmapFont.color = Color.BLUE
    val layout = GlyphLayout()
    layout.setText(bitmapFont, text)
    textWidth = layout.width
    textHeight = layout.height
}

I get errors for the line private val rectangle :Rectangle by lazy { Rectangle(x, y, textWidth, textHeight) } which says that;

Variable 'textWidth' must be initialized
  Variable 'textHeight' must be initialized

But I am already initializing them on the init{} code block.

What am I doing wrong?

Body:
In kotlin , you have to initialize a variable before using it, You are using lazy initializer for Rectangle but compiler doesn't know the the status of textWidth and textHeight

So class looks like this

class EpheButton private constructor(
    private val text: String,
    private val x: Float,
    private val y: Float,
    private val projectionMatrix: Matrix4) : Disposable {
private val spriteBatch: SpriteBatch = SpriteBatch()
private val bitmapFont: BitmapFont = BitmapFont()
private val shapeRenderer: ShapeRenderer = ShapeRenderer()

private val textWidth: Float
private val textHeight: Float
init {
    bitmapFont.data.setScale(2f)
    bitmapFont.region.texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear)
    bitmapFont.color = Color.BLUE
    val layout = GlyphLayout()
    layout.setText(bitmapFont, text)
    textWidth = layout.width
    textHeight = layout.height
}
private val rectangle :Rectangle by lazy { Rectangle(x, y, textWidth, textHeight) }

Updated :-
Why order of initialization matter's here ?

We can call this weired behavior to Null-Safty of Kotlin. When we change the order of init block and variable declaration , we are breaking this rule.

From Kotlin official documentaion :-

Kotlin's type system is aimed to eliminate NullPointerException's from
  our code. The only possible causes of NPE's may be

An explicit call to throw NullPointerException();

Usage of the !! operator that is described below;

External Java code has caused it;

There's some data inconsistency with regard to initialization (an uninitialized this available in a constructor is used somewhere).

Other than this four conditions , it always ensure that a variable is initialized at compile time . so same with our case it just ensuring that the used variable must be initialized before it used.


问:
Run query against another procedure that returns a cursor
I have a procedure that that has an OUT sys_refcursor:

```<code>CREATE OR REPLACE PROCEDURE get_detail_data(RC1            IN OUT sys_REFCURSOR)
IS ...
</code>```

Now in another a procedure, I'm trying to calculate some statistics against the output of that procedure so I can insert them into a table:

```<code>CREATE OR REPLACE PROCEDURE load_stats
AS
cur_detail  SYS_REFcursor;

BEGIN
  -- Load the data from the "get_detail_data" procedure
  get_detail_data(cur_detail);

  -- Now lets calculate some stats against that detail data and insert
  insert into stats_table (
    select
      id_number, sum(amount)
    from table(cur_detail) -- obviously this is not valid
  )

END;
</code>```

How can I run a query against a sys_refcursor dataset and insert those results into another table?

答:
You can start fetching from an open cursor like this:

```<code>  LOOP  -- Fetches 2 columns into variables
    FETCH cur_detail INTO v_id_number, v_amount;
    EXIT WHEN cv%NOTFOUND;
    [... insert etc ...]
  END LOOP;
</code>```

I'd suggest to do aggregation within the cursor, otherwise you need to order by id_number and aggregate within the loop, breaking by id_number.

Body:
I have a procedure that that has an OUT sys_refcursor:

CREATE OR REPLACE PROCEDURE get_detail_data(RC1            IN OUT sys_REFCURSOR)
IS ...

Now in another a procedure, I'm trying to calculate some statistics against the output of that procedure so I can insert them into a table:

CREATE OR REPLACE PROCEDURE load_stats
AS
cur_detail  SYS_REFcursor;

BEGIN
  -- Load the data from the "get_detail_data" procedure
  get_detail_data(cur_detail);

  -- Now lets calculate some stats against that detail data and insert
  insert into stats_table (
    select
      id_number, sum(amount)
    from table(cur_detail) -- obviously this is not valid
  )

END;

How can I run a query against a sys_refcursor dataset and insert those results into another table?

Body:
You can start fetching from an open cursor like this:

  LOOP  -- Fetches 2 columns into variables
    FETCH cur_detail INTO v_id_number, v_amount;
    EXIT WHEN cv%NOTFOUND;
    [... insert etc ...]
  END LOOP;

I'd suggest to do aggregation within the cursor, otherwise you need to order by id_number and aggregate within the loop, breaking by id_number.


问:
Nokogiri XML Builder creating unexpected output when scraping HTML
I am fairly new to Ruby and the world of programming so please, bear with me.

My goal is to scrape a table and then save the data to an XML file. The simple script that I've written successfully accomplishes both things.  The problem I am having is the way the XML is being saved.  It doesn't match the XML that I am used to seeing.

I've rummaged through quite a bit of examples, tutorials and forums but have yet to arrive at a solution.

I am open to any suggestions on a better way to get the data from the table as well, especially since the first three columns are all I really need. HELP!!!

Here is my script:

```<code>require 'nokogiri'
require 'open-uri'

url = "http://www.covers.com/pageLoader/pageLoader.aspx?page=
/data/nba/team/pastresults/2010-2011/team404085.html"
doc = Nokogiri::HTML(open(url))

builder = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.items {
       doc.css('.data').each do |o|
        xml.item_content = o
       end
    }
  }
end

File.open('ATL.xml','w'){|f| f.write builder.to_xml}

puts "Scrape Completed."
</code>```

Whether it's saved to an .xml file or printed on the screen in Ruby, the XML looks like this:

```<code><?xml version="1.0"?>
<root>
  <items>
    <item_content=><table cellpadding="2" cellspacing="1" class="data">
<tr class="datahead">
<td width="11%">Date</td>
    <td width="21%">Vs</td>
    <td width="18%">Score</td>
    <td width="27%">Type</td>
    <td width="13%">ATL Line</td>
    <td width="10%">O/U</td>
  </tr>
<tr class="datarow">
<td>
        01/18/11</td>
      <td>
        @ <a href="/pageLoader/pageLoader.aspx?page=/data/nba/team/
team404171.html">Miami</a>
        </td>
      <td>
        W <a href="/pageLoader/pageLoader.aspx?page=/data/nba/
results/2010-2011/boxscore795345.html">
        93-89</a> (OT)</td>
      <td>
        Regular Season</td>
      <td>
        W 5.5</td>
      <td>
        U 194</td>
    </tr>
</code>```

The above code is just a snippet as there are multiple rows. (44 Total)

What is the best way to go about doing this?

答:
It's not clear what you want as your output; do you want the HTML from the original included in the XML, or just the contents of the HTML? In the future, it is helpful when you include an example of what you wanted along with an example of the problem. Let us solve both problems. First, we can reproduce your problem more simply like so:

```<code>require 'nokogiri'
doc = Nokogiri::XML <<ENDXML
  <root>
    <p class="foo">42</p>
    <p class="bar">99</p>
    <p class="foo">17</p>
  </root>
ENDXML

builder = Nokogiri::XML::Builder.new do |xml|
  xml.items {
    doc.css('.foo').each{ |o| xml.item_content = o }
  }
end
puts builder.to_xml
#=> <?xml version="1.0"?>
#=> <items>
#=>   <item_content=><p class="foo">42</p></item_content=>
#=>   <item_content=><p class="foo">17</p></item_content=>
#=> </items>
</code>```

If you wanted the contents of your HTML nodes only in the XML, and presuming you didn't want the equals sign to be part of the tag name, then:

```<code>builder = Nokogiri::XML::Builder.new do |xml|
  xml.items {
    doc.css('.foo').each{ |o| xml.item_content( o.text ) }
  }
end
puts builder.to_xml
#=> <?xml version="1.0"?>
#=> <items>
#=>   <item_content>42</item_content>
#=>   <item_content>17</item_content>
#=> </items>
</code>```

If, on the other hand, you did want the raw HTML in your XML, but didn't want all the entities, then make it a CDATA block:

```<code>builder = Nokogiri::XML::Builder.new do |xml|
  xml.items {
    doc.css('.foo').each{ |o| xml.item_content{ xml.cdata o } }
  }
end
puts builder.to_xml
#=> <?xml version="1.0"?>
#=> <items>
#=>   <item_content><![CDATA[<p class="foo">42</p>]]></item_content>
#=>   <item_content><![CDATA[<p class="foo">17</p>]]></item_content>
#=> </items>
</code>```

An XML CDATA block allows you to use characters normally reserved for XML markup without needing to express them as character entities.

Body:
I am fairly new to Ruby and the world of programming so please, bear with me.

My goal is to scrape a table and then save the data to an XML file. The simple script that I've written successfully accomplishes both things.  The problem I am having is the way the XML is being saved.  It doesn't match the XML that I am used to seeing.

I've rummaged through quite a bit of examples, tutorials and forums but have yet to arrive at a solution.

I am open to any suggestions on a better way to get the data from the table as well, especially since the first three columns are all I really need. HELP!!!

Here is my script:

require 'nokogiri'
require 'open-uri'

url = "http://www.covers.com/pageLoader/pageLoader.aspx?page=
/data/nba/team/pastresults/2010-2011/team404085.html"
doc = Nokogiri::HTML(open(url))

builder = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.items {
       doc.css('.data').each do |o|
        xml.item_content = o
       end
    }
  }
end

File.open('ATL.xml','w'){|f| f.write builder.to_xml}

puts "Scrape Completed."

Whether it's saved to an .xml file or printed on the screen in Ruby, the XML looks like this:

<?xml version="1.0"?>
<root>
  <items>
    <item_content=>

Date
    Vs
    Score
    Type
    ATL Line
    O/U

        01/18/11

        @ Miami

        W
        93-89 (OT)

        Regular Season

        W 5.5

        U 194

The above code is just a snippet as there are multiple rows. (44 Total)

What is the best way to go about doing this?

Body:
It's not clear what you want as your output; do you want the HTML from the original included in the XML, or just the contents of the HTML? In the future, it is helpful when you include an example of what you wanted along with an example of the problem. Let us solve both problems. First, we can reproduce your problem more simply like so:

require 'nokogiri'
doc = Nokogiri::XML <<ENDXML
  <root>
    <p class="foo">42</p>
    <p class="bar">99</p>
    <p class="foo">17</p>
  </root>
ENDXML

builder = Nokogiri::XML::Builder.new do |xml|
  xml.items {
    doc.css('.foo').each{ |o| xml.item_content = o }
  }
end
puts builder.to_xml
#=> <?xml version="1.0"?>
#=> <items>
#=>   <item_content=>&lt;p class="foo"&gt;42&lt;/p&gt;</item_content=>
#=>   <item_content=>&lt;p class="foo"&gt;17&lt;/p&gt;</item_content=>
#=> </items>

If you wanted the contents of your HTML nodes only in the XML, and presuming you didn't want the equals sign to be part of the tag name, then:

builder = Nokogiri::XML::Builder.new do |xml|
  xml.items {
    doc.css('.foo').each{ |o| xml.item_content( o.text ) }
  }
end
puts builder.to_xml
#=> <?xml version="1.0"?>
#=> <items>
#=>   <item_content>42</item_content>
#=>   <item_content>17</item_content>
#=> </items>

If, on the other hand, you did want the raw HTML in your XML, but didn't want all the entities, then make it a CDATA block:

builder = Nokogiri::XML::Builder.new do |xml|
  xml.items {
    doc.css('.foo').each{ |o| xml.item_content{ xml.cdata o } }
  }
end
puts builder.to_xml
#=> <?xml version="1.0"?>
#=> <items>
#=>   <item_content><![CDATA[<p class="foo">42</p>]]></item_content>
#=>   <item_content><![CDATA[<p class="foo">17</p>]]></item_content>
#=> </items>

An XML CDATA block allows you to use characters normally reserved for XML markup without needing to express them as character entities.


问:
Socrata - Pagination with $select
I'm using $query= for advance querying, however the results get paginated at 1000. Socrata is not taking the parameter $limit= when used with $query=.

What can I do to move to the next set of data?

Example:

```<code>https://<url>.json?$offset=1000&$limit=1000&$query=select distinct id

{
  "error" : true,
  "message" : "If $query is used, all options - [$limit, $offset] should not be specified in $query."
}
</code>```

答:
You should include your limit and offset within your $query like so:

?$query=SELECT DISTINCT id LIMIT 1000 OFFSET 1000

That should do the trick!

Title: Socrata - Pagination with $select

Body:
I'm using $query= for advance querying, however the results get paginated at 1000. Socrata is not taking the parameter $limit= when used with $query=.

What can I do to move to the next set of data?

Example:

https://<url>.json?$offset=1000&$limit=1000&$query=select distinct id

{
  "error" : true,
  "message" : "If $query is used, all options - [$limit, $offset] should not be specified in $query."
}


问:
Mariadb: Regexp_substr not working with non-matching group regular expression
I am using a query to pull a user ID from a column that contains text. This is for a forum system I am using and want to get the User id portion out of a text field that contains the full message. The query I am using is

SELECT REGEXP_SUBSTR(message,  '(?:member: )(\d+)'
) AS user_id
from posts
where message like '%quote%';

Now ignoring the fact thats ugly SQL and not final I just need to get to the point where it reads the user ID. The following is an example of the text that you would see in the message column

```<code>`QUOTE="Moony, post: 967760, member: 22665"]I'm underwhelmed...[/QUOTE]

Hopefully we aren’t done yet and this is nothing but a depth signing!`
</code>```

Is there something different about the regular expression when used in mariadb REGEXP_SUBST? this should be PCRE and works within regex testers and should read correctly. It should be looking for the group "member: " and then take the numbers after that and have a single match on all those posts.

答:
This is an ugly hack/workaround that works by using a lookahead for the following "] however will not work if there are multiple quotes in a post

(?<=member: )\.+(?="])

Body:
I am using a query to pull a user ID from a column that contains text. This is for a forum system I am using and want to get the User id portion out of a text field that contains the full message. The query I am using is

SELECT REGEXP_SUBSTR(message,  '(?:member: )(\d+)'
) AS user_id
from posts
where message like '%quote%';

Now ignoring the fact thats ugly SQL and not final I just need to get to the point where it reads the user ID. The following is an example of the text that you would see in the message column

`QUOTE="Moony, post: 967760, member: 22665"]I'm underwhelmed...[/QUOTE]

Hopefully we aren’t done yet and this is nothing but a depth signing!`

Is there something different about the regular expression when used in mariadb REGEXP_SUBST? this should be PCRE and works within regex testers and should read correctly. It should be looking for the group "member: " and then take the numbers after that and have a single match on all those posts.