问:
JSON-Simple causes compiler warning "Type safety: The method put(Object, Object) belongs to the raw type HashMap."
I Just came across a situation where I need to put the data in the JSONObject, while doing that I received a warning from the compiler regarding.

Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap should be parameterized.

I tried to parameterize the JSONObject but it gave me the error.

I am using following code where option is a Object.

```<code>JSONObject additionalDetails = new JSONObject();
additionalDetails.put("showOppo", option.isShowOppo());
additionalDetails.put("showCont", option.isShowCont());
additionalDetails.put("contActionTaken", option.isConActionTaken());
additionalDetails.put("oppoActionTaken", option.isOppoActionTaken());
</code>```

How is this caused and how can I solve it?

答:
I recently face this problem.There are two libraries for JSONObject which is creating confusion for you
You have used wrong json jar that is  json-simple-1.1.jar, package that you imported is org.json.simple.JSONObject, use java-json.jar and import org.json.JSONObject download jar from http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm </p>

Body:
I Just came across a situation where I need to put the data in the JSONObject, while doing that I received a warning from the compiler regarding.

Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap should be parameterized.

I tried to parameterize the JSONObject but it gave me the error.

I am using following code where option is a Object.

JSONObject additionalDetails = new JSONObject();
additionalDetails.put("showOppo", option.isShowOppo());
additionalDetails.put("showCont", option.isShowCont());
additionalDetails.put("contActionTaken", option.isConActionTaken());
additionalDetails.put("oppoActionTaken", option.isOppoActionTaken());

How is this caused and how can I solve it?


来源: stackexchange

问:
Knockout.js Collection of collections
I just started learning knockout and i am looking for some help in figuring the way to implement collection of collections for the view model to build a json result for collections. I have two form lists names and addresses for which user inputs multiple values. When i try with one form it works fine. When i include the address model i am having issues in building the view model. I think i am doing it wrong. I would appreciate if you can guide me in fixing this. Thanks in advance

```<code><div class="row">
  <div class="col-md-12">
    <div class="panel panel-info">
      <div class="panel-heading">
        <h1 class="panel-title">
                    Names
                </h1>
      </div>
      <div class="panel-body">
        <table data-bind="visible: names().length > 0" class="table table-hover table-responsive">
          <thead>
            <tr>
              <th>First</th>
              <th>Middle</th>
              <th>Last</th>
              <th>Suffix</th>
              <th>Gender</th>
            </tr>
          </thead>
          <tbody data-bind="foreach:names">
            <tr>
              <td>
                <input class="form-control" data-bind="value: firstName" />
              </td>
              <td>
                <input class="form-control" data-bind="value: middleName" />
              </td>
              <td>
                <input class="form-control" data-bind="value: lastName" />
              </td>
              <td>
                <input class="form-control" data-bind="value: suffix" />
              </td>
              <td>
                <input class="form-control" data-bind="value: gender" />
              </td>
              <td style="vertical-align: inherit;"><a href="#" data-bind="click:$root.removeName">Delete</a></td>
            </tr>
          </tbody>
        </table>
        <button class="btn btn-success btn-sm" data-bind="click: addName">Add Name</button>
      </div>
    </div>
  </div>
</div>
<div class="row">
  <div class="col-md-12">
    <div class="panel panel-info">
      <div class="panel-heading">
        <h1 class="panel-title">
                    Addresses
                </h1>
      </div>
      <div class="panel-body">
        <table data-bind="visible: addresses().length > 0" class="table table-hover table-responsive">
          <thead>
            <tr>
              <th>street</th>
              <th>city</th>
              <th>state</th>
              <th>country</th>
            </tr>
          </thead>
          <tbody data-bind="foreach:addresses">
            <tr>
              <td>
                <input class="form-control" data-bind="value: street" />
              </td>
              <td>
                <input class="form-control" data-bind="value: city" />
              </td>
              <td>
                <input class="form-control" data-bind="value: state" />
              </td>
              <td>
                <input class="form-control" data-bind="value: country" />
              </td>
              <td style="vertical-align: inherit;"><a href="#" data-bind="click:$root.removeAddress">Delete</a></td>
            </tr>
          </tbody>
        </table>
        <button class="btn btn-success btn-sm" data-bind="click: addAddress">Add Address</button>
      </div>
    </div>
  </div>
</div>

var NameModel = function(names) {
  var self = this;
  self.names = ko.observableArray(names);

  self.addName = function() {
    self.names.push({
      firstName: "",
      middleName: "",
      lastName: "",
      suffix: "",
      gender: "",
      reportingDate: ""
    });
  };
  self.removeName = function(name) {
    self.names.remove(name);
  };
};
var AddressModel = function(addresses) {
  var self = this;
  self.names = ko.observableArray(addresses);

  self.addaddress = function() {
    self.names.push({
      street: "",
      city: "",
      state: "",
      country: ""
    });
  };
  self.removeAddress = function(address) {
    self.names.remove(address);
  };
};
//var viewModel = new NameModel([
//  { firstName: "", middleName: "", lastName: "", suffix: "", gender: "", reportingDate: "" }
//]);
var viewModel = {
  nameModel: new NameModel([{
    firstName: "",
    middleName: "",
    lastName: "",
    suffix: "",
    gender: "",
    reportingDate: ""
  }]),
  addressModel: new AddressModel([{
    street: "",
    city: "",
    state: "",
    country: ""
  }])
};
ko.applyBindings(viewModel);
</code>```

https://jsfiddle.net/iamsrk/9kf41vd7/

答:
See working fiddle now:

https://jsfiddle.net/9kf41vd7/30/

The reason it didn't work is that it didn't build. ApplyBindings was falling over. It was falling over for mulitple reasons including simple ones like addaddress instead of addAddress.

Because its just an example, I am going to ignore the bad naming conventions.

Added withs (better practice and allowed your add name button to be simplified from nameModel.addName -> addName) Also this is a function so should of been nameModel(). Withs help you from making this mistake.

```<code>data-bind="with: nameModel"
</code>```

Look at my fiddle, and ask any questions if you don't understand why I've done what ive done.

ContentLicense: CC BY-SA 3.0

Title: Knockout.js Collection of collections

Body:
I just started learning knockout and i am looking for some help in figuring the way to implement collection of collections for the view model to build a json result for collections. I have two form lists names and addresses for which user inputs multiple values. When i try with one form it works fine. When i include the address model i am having issues in building the view model. I think i am doing it wrong. I would appreciate if you can guide me in fixing this. Thanks in advance

                    Names

 0" class="table table-hover table-responsive">

              First
              Middle
              Last
              Suffix
              Gender

                <input class="form-control" data-bind="value: firstName" />

                <input class="form-control" data-bind="value: middleName" />

                <input class="form-control" data-bind="value: lastName" />

                <input class="form-control" data-bind="value: suffix" />

                <input class="form-control" data-bind="value: gender" />

              Delete

        <button class="btn btn-success btn-sm" data-bind="click: addName">Add Name</button>

                    Addresses

 0" class="table table-hover table-responsive">

              street
              city
              state
              country

                <input class="form-control" data-bind="value: street" />

                <input class="form-control" data-bind="value: city" />

                <input class="form-control" data-bind="value: state" />

                <input class="form-control" data-bind="value: country" />

              Delete

        <button class="btn btn-success btn-sm" data-bind="click: addAddress">Add Address</button>

var NameModel = function(names) {
  var self = this;
  self.names = ko.observableArray(names);

  self.addName = function() {
    self.names.push({
      firstName: "",
      middleName: "",
      lastName: "",
      suffix: "",
      gender: "",
      reportingDate: ""
    });
  };
  self.removeName = function(name) {
    self.names.remove(name);
  };
};
var AddressModel = function(addresses) {
  var self = this;
  self.names = ko.observableArray(addresses);

  self.addaddress = function() {
    self.names.push({
      street: "",
      city: "",
      state: "",
      country: ""
    });
  };
  self.removeAddress = function(address) {
    self.names.remove(address);
  };
};
//var viewModel = new NameModel([
//  { firstName: "", middleName: "", lastName: "", suffix: "", gender: "", reportingDate: "" }
//]);
var viewModel = {
  nameModel: new NameModel([{
    firstName: "",
    middleName: "",
    lastName: "",
    suffix: "",
    gender: "",
    reportingDate: ""
  }]),
  addressModel: new AddressModel([{
    street: "",
    city: "",
    state: "",
    country: ""
  }])
};
ko.applyBindings(viewModel);

https://jsfiddle.net/iamsrk/9kf41vd7/

Body:
See working fiddle now:

https://jsfiddle.net/9kf41vd7/30/

The reason it didn't work is that it didn't build. ApplyBindings was falling over. It was falling over for mulitple reasons including simple ones like addaddress instead of addAddress.

Because its just an example, I am going to ignore the bad naming conventions.

Added withs (better practice and allowed your add name button to be simplified from nameModel.addName -> addName) Also this is a function so should of been nameModel(). Withs help you from making this mistake.

data-bind="with: nameModel"

Look at my fiddle, and ask any questions if you don't understand why I've done what ive done.


问:
Recommended way for variable scoping
In C and variants, when you have something like this:

```<code>{
  tmp1 <- 5
  tmp2 <- 2
  print(tmp1 + tmp2)
}
</code>```

a 7 will be printed, but the tmp1 and tmp2 variables will be removed from stack once the scope } ends. I sometimes want similar functionality in R so that I do not have to clean up (many) temporary variables after some point in time.

One way to make this work in R is like this:

```<code>(function(){
  tmp1 <- 5
  tmp2 <- 2
  print(tmp1 + tmp2)
})()
</code>```

Now that seems a bit hackish -- or it may be just me.

Are there any better or more concise (i.e. more readable) ways to do this in R?

答:
Within the main code body the variables are global. However, as you found yourself their scope is local within functions:

```<code>addme <- function(){
    tmp1 <- 5;
    tmp2 <- 2;
    return (tmp1+tmp2)
}
</code>```

then call calling addme() will return the sum, but the variable remain inaccessible outside

```<code>> addme()
[1] 7
> tmp1
Error: object 'tmp1' not found
</code>```

Title: Recommended way for variable scoping

Body:
In C and variants, when you have something like this:

{
  tmp1 <- 5
  tmp2 <- 2
  print(tmp1 + tmp2)
}

a 7 will be printed, but the tmp1 and tmp2 variables will be removed from stack once the scope } ends. I sometimes want similar functionality in R so that I do not have to clean up (many) temporary variables after some point in time.

One way to make this work in R is like this:

(function(){
  tmp1 <- 5
  tmp2 <- 2
  print(tmp1 + tmp2)
})()

Now that seems a bit hackish -- or it may be just me.

Are there any better or more concise (i.e. more readable) ways to do this in R?

Body:
Within the main code body the variables are global. However, as you found yourself their scope is local within functions:

addme <- function(){
    tmp1 <- 5;
    tmp2 <- 2;
    return (tmp1+tmp2)
}

then call calling addme() will return the sum, but the variable remain inaccessible outside

> addme()
[1] 7
> tmp1
Error: object 'tmp1' not found


问:
Searching for something in Database - SELECT - Need to search in 2 tables

As you can see in the print screen above, I am wondering, if it is possible to check if there is one thing in two tables at once. Without making 2 queries. I need to look, if "fajne-to-jest" is in table1 or table2. I'm doing it in 2 queries... but question is, is it possible to check this information using one query? Mabye something else? Most efficent way? The best way?

答:
Try UNION ALL to fetch data to two different tables   </p>

```<code>SELECT * FROM table1 WHERE url = 'fajne-to-jest'
UNION ALL
SELECT * FROM table2 WHERE url = 'fajne-to-jest'
</code>```

Body:
Try UNION ALL to fetch data to two different tables

SELECT * FROM table1 WHERE url = 'fajne-to-jest'
UNION ALL
SELECT * FROM table2 WHERE url = 'fajne-to-jest'


问:
How to check Matrics properties are working for hystrix?
my local.properties file hystrix properties are as bellow.

```<code>hystrix.command.FASTSearchPageCommand.execution.isolation.strategy=THREAD
hystrix.command.FASTSearchPageCommand.execution.isolation.semaphore.maxConcurrentRequests=10
hystrix.command.FASTSearchPageCommand.execution.isolation.thread.timeoutInMilliseconds=1000

hystrix.command.FASTSearchPageCommand.execution.timeout.disabled=true
hystrix.command.FASTSearchPageCommand.execution.timeout.enabled=false

hystrix.command.FASTSearchPageCommand.execution.isolation.thread.interruptOnTimeout=true
hystrix.command.FASTSearchPageCommand.fallback.isolation.semaphore.maxConcurrentRequests=10
hystrix.command.FASTSearchPageCommand.fallback.disabled=false
hystrix.command.FASTSearchPageCommand.fallback.enabled=true

hystrix.command.FASTSearchPageCommand.circuitBreaker.disabled=false
hystrix.command.FASTSearchPageCommand.circuitBreaker.enabled=true
hystrix.command.FASTSearchPageCommand.circuitBreaker.requestVolumeThreshold=10
hystrix.command.FASTSearchPageCommand.circuitBreaker.sleepWindowInMilliseconds=8000
hystrix.command.FASTSearchPageCommand.circuitBreaker.errorThresholdPercentage=10
hystrix.command.FASTSearchPageCommand.circuitBreaker.forceOpen=false
hystrix.command.FASTSearchPageCommand.circuitBreaker.forceClosed=false
hystrix.command.FASTSearchPageCommand.metrics.rollingStats.timeInMilliseconds=1000
hystrix.command.FASTSearchPageCommand.metrics.rollingStats.numBuckets=5
hystrix.command.FASTSearchPageCommand.metrics.rollingPercentile.enabled=true
hystrix.command.FASTSearchPageCommand.metrics.rollingPercentile.timeInMilliseconds=100
hystrix.command.FASTSearchPageCommand.metrics.rollingPercentile.bucketSize=10
hystrix.command.FASTSearchPageCommand.metrics.healthSnapshot.intervalInMilliseconds=100
fastSearch.executionTimeout=5000
</code>```

So how can I check all are working. Like how can I notice that my matrics properties are working. If can give me some set of code for run and fallback method.

答:
I think you can find all documentation up here: Hystrix docs

The example taken from their docs is following:

```<code>public class CommandThatFailsSilently extends HystrixCommand<String> {

    private final boolean throwException;

    public CommandThatFailsSilently(boolean throwException) {
        super(HystrixCommandGroupKey.Factory.asKey("FASTSearchPageCommand"));
        this.throwException = throwException;
    }

    @Override
    protected String run() {
        if (throwException) {
            throw new RuntimeException("failure from CommandThatFailsFast");
        } else {
            return "success";
        }
    }

    @Override
    protected String getFallback() {
        return null;
    }
}
</code>```

Body:
my local.properties file hystrix properties are as bellow.

hystrix.command.FASTSearchPageCommand.execution.isolation.strategy=THREAD
hystrix.command.FASTSearchPageCommand.execution.isolation.semaphore.maxConcurrentRequests=10
hystrix.command.FASTSearchPageCommand.execution.isolation.thread.timeoutInMilliseconds=1000

hystrix.command.FASTSearchPageCommand.execution.timeout.disabled=true
hystrix.command.FASTSearchPageCommand.execution.timeout.enabled=false

hystrix.command.FASTSearchPageCommand.execution.isolation.thread.interruptOnTimeout=true
hystrix.command.FASTSearchPageCommand.fallback.isolation.semaphore.maxConcurrentRequests=10
hystrix.command.FASTSearchPageCommand.fallback.disabled=false
hystrix.command.FASTSearchPageCommand.fallback.enabled=true

hystrix.command.FASTSearchPageCommand.circuitBreaker.disabled=false
hystrix.command.FASTSearchPageCommand.circuitBreaker.enabled=true
hystrix.command.FASTSearchPageCommand.circuitBreaker.requestVolumeThreshold=10
hystrix.command.FASTSearchPageCommand.circuitBreaker.sleepWindowInMilliseconds=8000
hystrix.command.FASTSearchPageCommand.circuitBreaker.errorThresholdPercentage=10
hystrix.command.FASTSearchPageCommand.circuitBreaker.forceOpen=false
hystrix.command.FASTSearchPageCommand.circuitBreaker.forceClosed=false
hystrix.command.FASTSearchPageCommand.metrics.rollingStats.timeInMilliseconds=1000
hystrix.command.FASTSearchPageCommand.metrics.rollingStats.numBuckets=5
hystrix.command.FASTSearchPageCommand.metrics.rollingPercentile.enabled=true
hystrix.command.FASTSearchPageCommand.metrics.rollingPercentile.timeInMilliseconds=100
hystrix.command.FASTSearchPageCommand.metrics.rollingPercentile.bucketSize=10
hystrix.command.FASTSearchPageCommand.metrics.healthSnapshot.intervalInMilliseconds=100
fastSearch.executionTimeout=5000

So how can I check all are working. Like how can I notice that my matrics properties are working. If can give me some set of code for run and fallback method.

Body:
I think you can find all documentation up here: Hystrix docs

The example taken from their docs is following:

public class CommandThatFailsSilently extends HystrixCommand<String> {

    private final boolean throwException;

    public CommandThatFailsSilently(boolean throwException) {
        super(HystrixCommandGroupKey.Factory.asKey("FASTSearchPageCommand"));
        this.throwException = throwException;
    }

    @Override
    protected String run() {
        if (throwException) {
            throw new RuntimeException("failure from CommandThatFailsFast");
        } else {
            return "success";
        }
    }

    @Override
    protected String getFallback() {
        return null;
    }
}


答:
You might want to use local in base R for that purpose:

```<code>local({
  tmp1 <- 5
  tmp2 <- 2
  print(tmp1 + tmp2)
})
</code>```

So any variable created within the scope of local will vanish as soon as the scope is left.

From ?local:

local evaluates an expression in a local environment.

See ?local for more details.

Additionally, with (suggested by @Rich Scriven in the comments) also in base R can be used where 1 is just a dummy data:

```<code>with(1, {
    tmp1 <- 5
    tmp2 <- 2
    print(tmp1 + tmp2)
})
</code>```

From ?with:

with is a generic function that evaluates expr in a local environment constructed from data.

Title: Recommended way for variable scoping

Body:
You might want to use local in base R for that purpose:

local({
  tmp1 <- 5
  tmp2 <- 2
  print(tmp1 + tmp2)
})

So any variable created within the scope of local will vanish as soon as the scope is left.

From ?local:

local evaluates an expression in a local environment.

See ?local for more details.

Additionally, with (suggested by @Rich Scriven in the comments) also in base R can be used where 1 is just a dummy data:

with(1, {
    tmp1 <- 5
    tmp2 <- 2
    print(tmp1 + tmp2)
})

From ?with:

with is a generic function that evaluates expr in a local environment constructed from data.


问:
Get Mac address windows mobile device from desktop by activesync
I think I search entire internet bu i cant find any solution for this. I can handle the connection by RAPI (OPENNETCF Remote Apı) I can copy files and start a process but i cant get the mac address by rapi or anything else.</p>

答: I just find my way i find mac address windows ce client and wrote it on registry after this trick i read it from there by accessing registry from windows </p>


问:
Protected External Resource Usage
I'm working with some code where I have the following setup.

```<code>struct data
{
      void change_safe_member(){}
      void read_data(){}
      void change_unsafe_member(){}
};

struct data_processor
{
     std::shared_ptr<data> get_data(){}
     void return_data(std::shared_ptr<data> my_data)
     {
           my_data->change_unsafe_member(); // ONLY data_processor should call this function.
     }
};

struct client
{
     void foo(std::shared_ptr<data_processor>& my_processor)
     {
           auto my_data = my_processor->get_data();
           my_data->change_safe_member();
           //my_data->change_unsafe_member(); SHOULD NOT BE POSSIBLE TO CALL
           my_processor->return_data(my_data);
     }
};
</code>```

The change_unsafe_member should only be used internally by the processor so I would like to hide it or disable it for the client. But I don't know of any nice ways of doing this without resorting to ugly casts...

```<code>struct internal_data
{
      void change_unsafe_member(){}
};

struct data : public internal_data
{
      void change_safe_member(){}
      void read_data(){}
};

struct data_processor
{
     std::shared_ptr<data> get_data(){}
     void return_data(std::shared_ptr<data> my_data)
     {
           auto internal_data = std::static_pointer_cast<internal_data>(my_data);
           internal_data->change_unsafe_member();
     }
};
</code>```

Anyone know of a good pattern to use in situations like this? Maybe visitor pattern or something similar?

EDIT:

As pointed out in the comments one could declare friend classes, there is however one problem... the following will not work.

```<code>struct data
{
      void change_safe_member(){}
      void read_data(){}
private:
      friend class data_processor;
      virtual void change_unsafe_member(){}
};

struct data_decorator : public data
{
      data_decorator(const std::shared_ptr<data>& decoratee) : decoratee_(decoratee){}
      void change_safe_member(){decoratee_->change_safe_member();}
      void read_data(){decoratee_->read_data();}
private:
      virtual void change_unsafe_member()
      {
             std::cout << "Hello!"; // Add functionality
             decoratee_->change_unsafe_member(); // Won't work... compiler error
      }
      std::shared_ptr<data> decoratee_;
};

// Another example
struct data_group_decorator : public data
{
      data_group_decorator (const std::vector<std::shared_ptr<data>>& decoratees) : decoratees_(decoratees){}
      void change_safe_member(){decoratee_->change_safe_member();}
      void read_data(){decoratee_->read_data();}
private:
      virtual void change_unsafe_member()
      {
             for(size_t n = 0; n < decoratees_.size(); ++n)
                   decoratees_[n]->change_unsafe_member(); // Won't work... compiler error
      }
      std::vector<std::shared_ptr<data>> decoratees_;;
};
</code>```

答:
Your last example looks like what you're really asking for is inherited friendship; i.e. you want to have a hierarchy of decorator - derived classes which are all allowed to call the private member function in data. That's answered (with "generally no") elsewhere:

Why does C++ not allow inherited friendship?

Polymorphism might provide some relief in your specific scenario, make class data_decorator an "almost pure" virtual base class, with the only nonvirtual member being a protected change_unsafe_member(), and make that in turn a friend of class data. All decorators would inherit from data_decorator, and call its protected nonvirtual member.

ContentLicense: CC BY-SA 2.5

Title: Protected External Resource Usage

Body:
I'm working with some code where I have the following setup.

struct data
{
      void change_safe_member(){}
      void read_data(){}
      void change_unsafe_member(){}
};

struct data_processor
{
     std::shared_ptr<data> get_data(){}
     void return_data(std::shared_ptr<data> my_data)
     {
           my_data->change_unsafe_member(); // ONLY data_processor should call this function.
     }
};

struct client
{
     void foo(std::shared_ptr<data_processor>& my_processor)
     {
           auto my_data = my_processor->get_data();
           my_data->change_safe_member();
           //my_data->change_unsafe_member(); SHOULD NOT BE POSSIBLE TO CALL
           my_processor->return_data(my_data);
     }
};

The change_unsafe_member should only be used internally by the processor so I would like to hide it or disable it for the client. But I don't know of any nice ways of doing this without resorting to ugly casts...

struct internal_data
{
      void change_unsafe_member(){}
};

struct data : public internal_data
{
      void change_safe_member(){}
      void read_data(){}
};

struct data_processor
{
     std::shared_ptr<data> get_data(){}
     void return_data(std::shared_ptr<data> my_data)
     {
           auto internal_data = std::static_pointer_cast<internal_data>(my_data);
           internal_data->change_unsafe_member();
     }
};

Anyone know of a good pattern to use in situations like this? Maybe visitor pattern or something similar?

EDIT:

As pointed out in the comments one could declare friend classes, there is however one problem... the following will not work.

struct data
{
      void change_safe_member(){}
      void read_data(){}
private:
      friend class data_processor;
      virtual void change_unsafe_member(){}
};

struct data_decorator : public data
{
      data_decorator(const std::shared_ptr<data>& decoratee) : decoratee_(decoratee){}
      void change_safe_member(){decoratee_->change_safe_member();}
      void read_data(){decoratee_->read_data();}
private:
      virtual void change_unsafe_member()
      {
             std::cout << "Hello!"; // Add functionality
             decoratee_->change_unsafe_member(); // Won't work... compiler error
      }
      std::shared_ptr<data> decoratee_;
};

// Another example
struct data_group_decorator : public data
{
      data_group_decorator (const std::vector<std::shared_ptr<data>>& decoratees) : decoratees_(decoratees){}
      void change_safe_member(){decoratee_->change_safe_member();}
      void read_data(){decoratee_->read_data();}
private:
      virtual void change_unsafe_member()
      {
             for(size_t n = 0; n < decoratees_.size(); ++n)
                   decoratees_[n]->change_unsafe_member(); // Won't work... compiler error
      }
      std::vector<std::shared_ptr<data>> decoratees_;;
};


问:
Entering accented characters with notepad++ using only the keyboard
I am new to notepad++ and like it very much, since I can customize how my text documents look more easily than with wordpad. However, I would like to know if it’s possible to enter accented characters like in wordpad (I thought it was a windows thing, but perhaps it isn’t). In wordpad, I can type, for instance, ctrl-’ then i to get an accented í character. Similarly, I can type ctrl-shift-~ then n to get the accented ñ character. It makes it much easier to enter accented characters than copying and pasting from the character map application, or trying to remember code points. When I tried this method in notepad++ I just got the plain character without the accents. I should also mention that when I open documents with such accented characters already present they appear just as expected. Is there a way to enter accented characters like this in notepad++ using only the keyboard? I am using the latest notepad++ under Windows 7.</p>

答:
I think it is configured in the input method. With input method containing the characters you mentioned, you can press key combinations to get special letters.

You can add a keyboard layout preset in Windows. Under "Language and Regions" - "Language" - "Language settings" - "Input method" settings in Control Panel, you can add all what you want. Like this:

Switch keyboard layout with Alt + Shift.


问:
Magento Price Range Filters
I would like to ask a question:

I have a problem with the price ranges filters in the search page, and it shows many un-real ranges that I don’t know why.

check this page for example:

https://znbaq.com/catalogsearch/result/?q=bebe

it seems that it is showing the price ranges for all of the products on my website !

Can you please advise a solution ?

Thank you in advance.

答: Try to reduce range interval from backend and then reindex attributes, index_price and fulltext. Hope it works.</p>

Title: Magento Price Range Filters


问:
Command Injection Vulnerability in Java
I am trying to run Microsoft Rdp application from code.

I have the following pseudo-code and SonarQube complains about Command Injection Vulnerability

```<code>String rdpFilePath = myObject.getRdpFilePath() // get path of .rdp settings file
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("mstsc", rdpFilePath).start();
</code>```

SonarQube Issue explanation is following:

```<code>-Potential Command Injection-
The highlighted API is used to execute a system command.
If unfiltered input is passed to this API, it can lead to arbitrary command execution.
</code>```

How can filter my input and how can i fix this security issue?

答:
Your sample is pretty safe. The one thing you should add here before executing mstsc is checking, that rdpFilePath file exists.

You have security issue in a case, if you put unfiltered user input as a 1st argument of command method (sometimes, next arguments can be vulnerable too, if program you want to run allows to run commands too). In such case user can execute arbitrary command on system.

Title: Command Injection Vulnerability in Java

Body:
I am trying to run Microsoft Rdp application from code.

I have the following pseudo-code and SonarQube complains about Command Injection Vulnerability

String rdpFilePath = myObject.getRdpFilePath() // get path of .rdp settings file
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("mstsc", rdpFilePath).start();

SonarQube Issue explanation is following:

-Potential Command Injection-
The highlighted API is used to execute a system command.
If unfiltered input is passed to this API, it can lead to arbitrary command execution.

How can filter my input and how can i fix this security issue?


问:
For /F: Spaces in both filename and parameter
In a batch file I want to set a variable to the one-line output of a program - a task explained in multiple questions and internet ressources.

In my specific task I want to execute the command

```<code>"D:\__My Program\___My Program\Folder1\Folder2\..\..\FileVersion\FileVersion\bin\Release\FileVersion.exe" /n "D:\__My Program\___My Program\Folder1\Folder2\bin\Deploy\My Program.exe"
</code>```

As you can see, the path for the program I want to execute, FileVersion.exe contains spaces, and the second parameter handed to FileVersion.exe contains a full path with spaces as well.

When I call the above command either directly at the command line or by using CALL in the batch file it correctly executes the program prints out the expected output.

Now, to capture the output of executing the program I use the follow batch command

```<code>FOR /F "usebackq tokens=* delims=" %%i IN (`"D:\__My Program\___My Program\Folder1\Folder2\..\..\FileVersion\FileVersion\bin\Release\FileVersion.exe" /n "D:\__My Program\___My Program\Folder1\Folder2\bin\Deploy\My Program.exe"`) DO (
    echo %%i
)
</code>```

The FOR documentation says

```<code>usebackq     Use the alternate quoting style:
           - Use double quotes for long file names in "filenameset".
           - Use single quotes for 'Text string to process'
           - Use back quotes for `command to process`
</code>```

I think I did this correctly by using back quotes around the command, and using quotes around the filenames.

However, the call fails with the message (translated from German)

```<code>The command "D:\My" is either incorrect or couldn't be found.
</code>```

I think this points to a problem with escaping the spaces.

The weird part: If I either replace the path of the exe to call, or the parameter with a path sans spaces, it works. So both

```<code>FOR /F "usebackq tokens=* delims=" %%i IN (`FileVersion.exe /n "D:\__My Program\___My Program\Folder1\Folder2\bin\Deploy\My Program.exe"`) DO (
    echo %%i
)
</code>```

and

```<code>FOR /F "usebackq tokens=* delims=" %%i IN (`"D:\__My Program\___My Program\Folder1\Folder2\..\..\FileVersion\FileVersion\bin\Release\FileVersion.exe" /n Test.exe`) DO (
    echo %%i
)
</code>```

work.

Why don't two quote-escaped strings work in the same command and how can I fix it?

答:
I wouldn't use usebackq and first resolve the complex path:

```<code>@Echo off
Pushd "D:\__My Program\___My Program\Folder1\Folder2\..\..\FileVersion\FileVersion\bin\Release"
FOR /F "tokens=*" %%i IN (
  ' FileVersion.exe /n "D:\__My Program\___My Program\Folder1\Folder2\bin\Deploy\My Program.exe" '
) DO echo %%i
PopD
</code>```

Body:
In a batch file I want to set a variable to the one-line output of a program - a task explained in multiple questions and internet ressources.

In my specific task I want to execute the command

"D:\__My Program\___My Program\Folder1\Folder2\..\..\FileVersion\FileVersion\bin\Release\FileVersion.exe" /n "D:\__My Program\___My Program\Folder1\Folder2\bin\Deploy\My Program.exe"

As you can see, the path for the program I want to execute, FileVersion.exe contains spaces, and the second parameter handed to FileVersion.exe contains a full path with spaces as well.

When I call the above command either directly at the command line or by using CALL in the batch file it correctly executes the program prints out the expected output.

Now, to capture the output of executing the program I use the follow batch command

FOR /F "usebackq tokens=* delims=" %%i IN (`"D:\__My Program\___My Program\Folder1\Folder2\..\..\FileVersion\FileVersion\bin\Release\FileVersion.exe" /n "D:\__My Program\___My Program\Folder1\Folder2\bin\Deploy\My Program.exe"`) DO (
    echo %%i
)

The FOR documentation says

usebackq     Use the alternate quoting style:
           - Use double quotes for long file names in "filenameset".
           - Use single quotes for 'Text string to process'
           - Use back quotes for `command to process`

I think I did this correctly by using back quotes around the command, and using quotes around the filenames.

However, the call fails with the message (translated from German)

The command "D:\My" is either incorrect or couldn't be found.

I think this points to a problem with escaping the spaces.

The weird part: If I either replace the path of the exe to call, or the parameter with a path sans spaces, it works. So both

FOR /F "usebackq tokens=* delims=" %%i IN (`FileVersion.exe /n "D:\__My Program\___My Program\Folder1\Folder2\bin\Deploy\My Program.exe"`) DO (
    echo %%i
)

and

FOR /F "usebackq tokens=* delims=" %%i IN (`"D:\__My Program\___My Program\Folder1\Folder2\..\..\FileVersion\FileVersion\bin\Release\FileVersion.exe" /n Test.exe`) DO (
    echo %%i
)

work.

Why don't two quote-escaped strings work in the same command and how can I fix it?

Body:
I wouldn't use usebackq and first resolve the complex path:

@Echo off
Pushd "D:\__My Program\___My Program\Folder1\Folder2\..\..\FileVersion\FileVersion\bin\Release"
FOR /F "tokens=*" %%i IN (
  ' FileVersion.exe /n "D:\__My Program\___My Program\Folder1\Folder2\bin\Deploy\My Program.exe" '
) DO echo %%i
PopD


问:
angular-nvd3 line-chart change color of axis
Can anyone tell me how to specify a color or css class for the y axis of an angular-nvd3 lineChart ?

I've been specifying the options:

<nvd3 options="lineChartOptions" data="graphData" ></nvd3>```
</div>
</div>
</p>

<p>and then have all the options in an object:</p>

```$scope.lineChartOptions = {
                    chart: {
                        type: 'lineChart',
                        showLegend:false,
                        forceY:[0,5], // make y axis start at 0 to 5
                        forceX:[1,4],
                        // interpolate:"monotone",
                        height: 400,
                        width: 600,
                        margin : {
                            top: 20,
                            right: 20,
                            bottom: 40,
                            left: 55
                        },
                        x: function(d){ return d.x; },
                        y: function(d){ return d.y; },
                        useInteractiveGuideline: true,
                        tooltip: {
                          contentGenerator: function(d) { return '
HELLO WORLD
'; }
                        },
                        dispatch: {
                            stateChange: function(e){ console.log("stateChange"); },
                            changeState: function(e){ console.log("changeState"); },
                            tooltipShow: function(e){ console.log("tooltipShow"); },
                            tooltipHide: function(e){ console.log("tooltipHide"); }
                        },
                        xAxis: {
                            // axisLabel: 'Week',
                            ticks: 4, // make  x-axis show all 4 weeks,

                            // tickFormat: function(d){
                            //  return "week " + d;
                            // }
                        },
                        showYAxis: true,
                        yAxis: {
                            // axisLabel: 'Score',
                            // tickFormat: function(d){
                            //     return d3.format('.02f')(d);
                            // },
                            ticks: 6,
                            axisLabelDistance: -10
                        },
                        callback: function(chart){
                            //console.log("!!! lineChart callback !!!");
                        }
                    },
                    // title: {
                    //     enable: true,
                    //     text: 'Title for Line Chart'
                    // },
                    // subtitle: {
                    //     enable: true,
                    //     text: 'Subtitle for simple line chart... ',
                    //     css: {
                    //         'text-align': 'center',
                    //         'margin': '10px 13px 0px 7px'
                    //     }
                    // },
                    // caption: {
                    //     enable: true,
                    //     html: 'AND  we can put any sort of html here too...',
                    //     css: {
                    //         'text-align': 'justify',
                    //         'margin': '10px 13px 0px 7px'
                    //     }
                    // }
                };
```

But cannot figure out for the life of me how to specify a color for the axes or how to specify a css class for the tick texts...

Any help would be greatly appreciated...

答:
For the y axis you can do it by css, as follows: </p>

<p>.nvd3 .nv-axis path { fill: #E5E5E5; stroke: #E5E5E5; } </p>

Body:
Can anyone tell me how to specify a color or css class for the y axis of an angular-nvd3 lineChart ?

I've been specifying the options:

<nvd3 options="lineChartOptions" data="graphData" ></nvd3>

and then have all the options in an object:

$scope.lineChartOptions = {
                    chart: {
                        type: 'lineChart',
                        showLegend:false,
                        forceY:[0,5], // make y axis start at 0 to 5
                        forceX:[1,4],
                        // interpolate:"monotone",
                        height: 400,
                        width: 600,
                        margin : {
                            top: 20,
                            right: 20,
                            bottom: 40,
                            left: 55
                        },
                        x: function(d){ return d.x; },
                        y: function(d){ return d.y; },
                        useInteractiveGuideline: true,
                        tooltip: {
                          contentGenerator: function(d) { return '
HELLO WORLD
'; }
                        },
                        dispatch: {
                            stateChange: function(e){ console.log("stateChange"); },
                            changeState: function(e){ console.log("changeState"); },
                            tooltipShow: function(e){ console.log("tooltipShow"); },
                            tooltipHide: function(e){ console.log("tooltipHide"); }
                        },
                        xAxis: {
                            // axisLabel: 'Week',
                            ticks: 4, // make  x-axis show all 4 weeks,

                            // tickFormat: function(d){
                            //  return "week " + d;
                            // }
                        },
                        showYAxis: true,
                        yAxis: {
                            // axisLabel: 'Score',
                            // tickFormat: function(d){
                            //     return d3.format('.02f')(d);
                            // },
                            ticks: 6,
                            axisLabelDistance: -10
                        },
                        callback: function(chart){
                            //console.log("!!! lineChart callback !!!");
                        }
                    },
                    // title: {
                    //     enable: true,
                    //     text: 'Title for Line Chart'
                    // },
                    // subtitle: {
                    //     enable: true,
                    //     text: 'Subtitle for simple line chart... ',
                    //     css: {
                    //         'text-align': 'center',
                    //         'margin': '10px 13px 0px 7px'
                    //     }
                    // },
                    // caption: {
                    //     enable: true,
                    //     html: 'AND  we can put any sort of html here too...',
                    //     css: {
                    //         'text-align': 'justify',
                    //         'margin': '10px 13px 0px 7px'
                    //     }
                    // }
                };

But cannot figure out for the life of me how to specify a color for the axes or how to specify a css class for the tick texts...

Any help would be greatly appreciated...

Body:
For the y axis you can do it by css, as follows:

.nvd3 .nv-axis path { fill: #E5E5E5; stroke: #E5E5E5; }


问:
Check string for multiple words (in any order)
I'm trying to use some VBA code to find if say english and 6 months are in a cell, for example

"Test English, 6 months"

  6 months English

but not

6 months Englishman

I can only find one word, findings two separate strings in a cell

in any order

whole words only

is confusing me.

答:
update - Bulletproofed

```<code>Function StrCheck2(rng1 As Range, str1 As String, str2 As String) As Boolean
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
    .Pattern = "^(?=.*\b" & str1 & "\b)(?=.*\b" & str2 & "\b).*$"
    .ignorecase = True
     StrCheck2 = .test(rng1.Value2)
End With
End Function
</code>```

You could do something like this

```<code>Function StrCheck(rng1 As Range, str1 As String, str2 As String) As Boolean
If InStr(rng1.Value2, str1) > 0 Then
    If InStr(rng1.Value, str2) > 0 Then StrCheck = True
End If
End Function
</code>```

Separating the two IFS allows for an early exit if the first string is not found.

You would call it like
=StrCheck(A1,"English","6 months")

or to avoid partial word matches
=StrCheck(A1," English "," 6 months ")
which would still need tinkering for an edge case of where English could be the first word

A Regexp probably the best step for a bullet-proof check.

Body:
update - Bulletproofed

Function StrCheck2(rng1 As Range, str1 As String, str2 As String) As Boolean
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
    .Pattern = "^(?=.*\b" & str1 & "\b)(?=.*\b" & str2 & "\b).*$"
    .ignorecase = True
     StrCheck2 = .test(rng1.Value2)
End With
End Function

You could do something like this

Function StrCheck(rng1 As Range, str1 As String, str2 As String) As Boolean
If InStr(rng1.Value2, str1) > 0 Then
    If InStr(rng1.Value, str2) > 0 Then StrCheck = True
End If
End Function

Separating the two IFS allows for an early exit if the first string is not found.

You would call it like
=StrCheck(A1,"English","6 months")

or to avoid partial word matches
=StrCheck(A1," English "," 6 months ")
which would still need tinkering for an edge case of where English could be the first word

A Regexp probably the best step for a bullet-proof check.


问:
How to post value from one php page to another using ajax
I am trying to post one value which I got using Jquery, so I have to pass that value to php page using ajax. but when I did this I got Undefined index data error.

Here is my code:

```<code>$("#requirementtable tbody tr").on("click", function(){
                        desc =  $(this).closest("tr").find("td:nth-child(4)").text().trim();
$.ajax({
        type:"POST",
        url:"get_diagnosis.php",
        data: desc,
        success: function (data, textStatus, jqXHR)
        {
            alert(data);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert("some error occured->" + jqXHR.responseJSON);
        }
    })
  })
</code>```

this is my php code:

```<code><?php
    $data = $_POST['data'];
    echo $data;
?>
</code>```

答:
Check the desc variable has some value in it and you have to post data like,

```<code>data: {data:desc},
</code>```

AJAX Code,

```<code>$.ajax({
    type:"POST",
    url:"get_diagnosis.php",
    data: {data:desc},
    success: function (data, textStatus, jqXHR) {
        alert(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert("some error occured->" + jqXHR.responseJSON);
    }
});
</code>```

And in PHP use isset() to prevent undefined errors like,

```<code><?php
    $data = isset($_POST['data']) ? $_POST['data'] : 'Not defined';
    echo $data;
?>
</code>```

If you want JSON response format then use dataType:'json' in $.ajax, and use json_encode() in PHP to respond it.

Body:
I am trying to post one value which I got using Jquery, so I have to pass that value to php page using ajax. but when I did this I got Undefined index data error.

Here is my code:

$("#requirementtable tbody tr").on("click", function(){
                        desc =  $(this).closest("tr").find("td:nth-child(4)").text().trim();
$.ajax({
        type:"POST",
        url:"get_diagnosis.php",
        data: desc,
        success: function (data, textStatus, jqXHR)
        {
            alert(data);
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert("some error occured->" + jqXHR.responseJSON);
        }
    })
  })

this is my php code:

<?php
    $data = $_POST['data'];
    echo $data;
?>

Body:
Check the desc variable has some value in it and you have to post data like,

data: {data:desc},

AJAX Code,

$.ajax({
    type:"POST",
    url:"get_diagnosis.php",
    data: {data:desc},
    success: function (data, textStatus, jqXHR) {
        alert(data);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert("some error occured->" + jqXHR.responseJSON);
    }
});

And in PHP use isset() to prevent undefined errors like,

<?php
    $data = isset($_POST['data']) ? $_POST['data'] : 'Not defined';
    echo $data;
?>

If you want JSON response format then use dataType:'json' in $.ajax, and use json_encode() in PHP to respond it.


问:
rkt networking on ubuntu
I am trying to run a simple rkt container on ubuntu 16.10. I am having some networking problems. Here are the commands I ran.

sudo rkt run --interactive quay.io/coreos/alpine-sh

Then running:

/ # ping google.com
ping: bad address 'google.com'
/ # ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8): 56 data bytes
64 bytes from 8.8.8.8: seq=0 ttl=58 time=6.815 ms

After coming out:
sudo rkt list
UUID        APP     IMAGE NAME          STATE   CREATED     STARTED     NETWORKS
4d35bf55    alpine-sh   quay.io/coreos/alpine-sh:latest exited  40 seconds ago  39 seconds ago

As you can see network tab is empty. Here is my iptables:

sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

ACCEPT     all  --  anywhere             172.16.28.0/24

ACCEPT     all  --  172.16.28.0/24       anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

答:
try adding --dns

sudo rkt run --interactive quay.io/coreos/alpine-sh --dns=8.8.8.8

btw 8.8.8.8 is the address of google's DNS server

Title: rkt networking on ubuntu


问:
Clustering different class
I would like to cluster my dataset which has multiple classes (up to 10). But this clustering problem is different than usual clustering. I need to cluster different classes (as shown in the image;  https://ibb.co/iiNbqv) instead same/similar classes. Which method should I use? what would you recommend?

The problem as follow;
I have several frames/images (up to 10), and each frame has hundred of thousand detections. So, as the data I am processing is the location (x and y coordinates) of the detection. What I am going to do that how much detections are overlapped within these frames with a certain distance threshold. The constraint is that each detection of a frame shouldn't be in the same overlapped cluster more than once as seen in the picture. So basically, I should find the nearest detection of a point from other frames, and put them in same cluster. But once I do that every point in the cluster shouldn't be far each other more than distant threshold

Cheers

答:
Based on your image and the circles you drew, this seems a problem of clustering different data points based on distance between them. A simple euclidian distance based clustering algorithm should provide the results you are looking for.

Something like this would cluster data points according to a measure of distance between them. The only parameter is the distance threshold, which you should set to one that is consistent with your problem.

```<code>#PSEUDO-CODE!
#p is a list of all data points

for i=all points
 if( p(i).used == false)
 {

   #Create new cluster c
   p(i).cluster = c

   for n=1:all_Points
   {
      if ( p(n).used == false)
      {
         if p(n).class not in cluster
         {
             d=dist(p(i),p(n))

             if d<max
             {
                p(n).cluster = c;
                p(n).used = true;
             }
        }
    }
}
</code>```

This basically goes to each point and finds which of them are near it, and assigns them to the same cluster. There are a lot of variations of this clustering routine that achieve different goals.

For example, you can compare the distance between the current centroid of the cluster rather than the point that initialized the cluster, or compare with the last added point to the cluster rather than the first one. Depends on what would work better for the nature of your data.

Title: Clustering different class

Body:
Based on your image and the circles you drew, this seems a problem of clustering different data points based on distance between them. A simple euclidian distance based clustering algorithm should provide the results you are looking for.

Something like this would cluster data points according to a measure of distance between them. The only parameter is the distance threshold, which you should set to one that is consistent with your problem.

#PSEUDO-CODE!
#p is a list of all data points

for i=all points
 if( p(i).used == false)
 {

   #Create new cluster c
   p(i).cluster = c

   for n=1:all_Points
   {
      if ( p(n).used == false)
      {
         if p(n).class not in cluster
         {
             d=dist(p(i),p(n))

             if d<max
             {
                p(n).cluster = c;
                p(n).used = true;
             }
        }
    }
}

This basically goes to each point and finds which of them are near it, and assigns them to the same cluster. There are a lot of variations of this clustering routine that achieve different goals.

For example, you can compare the distance between the current centroid of the cluster rather than the point that initialized the cluster, or compare with the last added point to the cluster rather than the first one. Depends on what would work better for the nature of your data.


问:
How to get data in Angular 2 service with Mlab
```<code>import { Injectable } from '@angular/core';

@Injectable()
export class UserService {

  constructor() {
    console.log("Users service initialized");
  }

  getUsers(){
    //Mlab URL
    //Example: mongodb://user:password@ds129038.mlab.com:29038/database_name
  }

}
</code>```

Hi, i'm looking the way to get users in angular 2 service from a database in MLAB. How could I receive them and iterate results?
Regards,

答:
In your app folder make a new folder and name it "server"

Inside "server" folder make two new folders and name the "models", and "routes"

In models folder create a javascript file and name it same as your collection name in mlab/mongodb. Example "datacollection1.js"

Inside datacollection1.js paste the following code:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const datacollection1Schema = new Schema({
    varone: String,
    vartwo: String,
    varthree: String,
    varfour: String
});

module.exports = mongoose.model('datacollection1', herodataSchema, 'datacollection1class');

Inside "routes" folder create a file and name it "api.js"

Paste the following code in api.js

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Datacollection1class = require('../models/datacollection1');

const db = "mongodb://:@ds155201.mlab.com:<12345>/";
mongoose.Promise = global.Promise;
mongoose.connect(db, function(err){
    if(err) {
        console.log("Error: " + err);
    }
});

//Get all data
router.get('/datacollection1class', function(req, res) {
    console.log("Get request for datacollection1class");
    Datacollection1class.find({})
    .exec(function(err, datacollection1class){
        if(err) {
            console.log("Error retrieving datacollection1class.");
        } else {
            res.json(datacollection1class);
        }
    })
});

//retrieve data by id
router.get('/datacollection1class/:id', function(req, res) {
    console.log("Get request for sigle document");
    Datacollection1class.findById(req.params.id)
    .exec(function(err, datacollection1classsingle){
        if(err) {
            console.log("Error retrieving datacollection1classsingle.");
        }
        else
        {
            res.json(datacollection1classsingle);
        }
    })
});

//Add a single new documemt
router.post('/datacollection1classsingle', function(req, res){
    console.log('Post a data set');
    var newDatacollection1classsingle = new Datacollection1class();
    newDatacollection1classsingle.varone = req.body.varone;
    newDatacollection1classsingle.vartwo = req.body.vartwo;
    newDatacollection1classsingle.varthree = req.body.varthree;
    newDatacollection1classsingle.varfour = req.body.varfour;
    newDatacollection1classsingle.save(function(err, insertedDatacollection1classsingle){
        if (err) {
            console.log('Error saving new hero data: '+err);
        } else {
            res.json(insertedDatacollection1classsingle);
        }
    });
});

//Update existing document
router.put('/hatacollection1class/:id', function(req, res) {
    console.log('Update a video');
    Datacollection1class.findByIdAndUpdate(req.params.id,
    {
        $set: {
            varone: req.body.varone,
            vartwo: req.body.vartwo,
            varthree: req.body.varthree,
            varfour: req.body.varfour
        }
    },
    {
        new:true
    },
    function(err, updatedDatacollection1classsingle) {
        if(err){
            res.send("Error updating Datacollection1class by id : "+err);
        } else {
            res.json(updatedDatacollection1classsingle);
        }
    });
});

// Delete a document
router.delete('/datacollection1class/:id', function(req, res) {
    console.log('Deleting a datacollection1class');
    Datacollection1class.findByIdAndRemove(req.params.id, function(err, deletedDatacollection1classsingle){
        if (err) {
            res.send("Error deleting Datacollection1class by id: "+err);
        } else {
            res.json(deletedDatacollection1classsingle);
        }
    });
});

Go to command prompt and using angular CLI create a class. Make sure Angular CLI is installed on your machine. Type in command prompt in your app folder

ng generate class datacollection1class

and hit enter. This will create a file named "datacollection1class.ts"

Inside datacollection1class.ts type the following code:

export class Datacollection1class {
    _id: string;
    varone: string;
    vartwo: string;
    varthree: string;
    varfour: string;
}

You are all set. Now on your command prompt type:

ng build

Then on your command prompt type:

node server

Go to the browser and run "http://localhost:4200/api/datacollection1class" or if you have the id of the document, then "http://localhost:4200/api/datacollection1class/59305a02734d1d5068f2414e" or tey running it using postman

Feel free to ask questions. upvote if you liked the help.

Body:
import { Injectable } from '@angular/core';

@Injectable()
export class UserService {

  constructor() {
    console.log("Users service initialized");
  }

  getUsers(){
    //Mlab URL
    //Example: mongodb://user:password@ds129038.mlab.com:29038/database_name
  }

}

Hi, i'm looking the way to get users in angular 2 service from a database in MLAB. How could I receive them and iterate results?
Regards,


问:
Mysql using COUNT insde CASE
Is it possible to use count inside CASE, here is my query. gives me an error #1111

```<code>SELECT t1.id,t1.name,t1.date_entered,t1.date_modified, t1.adresse,t1.adresse_state,t1.adresse_city,t1.adresse_postalcode,t1.hausnummer,t1.center_lat,t1.center_long, t3.name as street_name,t3.strasse,t3.primaerstr
FROM hi_haus as t1
LEFT JOIN hi_haus_hi_strasse as t2 ON (t2.hi_haus_id = t1.id)
LEFT JOIN hi_strasse as t3 ON (t3.id = t2.hi_strasse_id)
WHERE t1.adresse !='' AND t1.adresse IS NOT NULL AND t1.adresse NOT LIKE '%bau%' AND t1.id IN ('58e722d6-44f5-4e24-8861-5cd4a6f07cbc','4d0a79ee-decf-49b1-8b4b-a912b278ffec')
AND t3.primaerstr =
CASE
WHEN count(t1.id) > '1' THEN t3.primaerstr='0'
ELSE
t3.primaerstr = '1'
END
GROUP BY t1.id
</code>```

What i need is to get the primaerstr '0' if id is repeating more than once.

答: SELECT t1.id,t1.name,t1.date_entered,t1.date_modified, t1.adresse,t1.adresse_state,t1.adresse_city,t1.adresse_postalcode,t1.hausnummer,t1.center_lat,t1.center_long, t3.name as street_name,t3.id,t3.strasse,t3.primaerstr FROM hi_haus as t1 LEFT JOIN hi_haus_hi_strasse as t2 ON (t2.hi_haus_id = t1.id) LEFT JOIN hi_strasse as t3 ON (t3.id = t2.hi_strasse_id) WHERE t1.adresse !='' AND t1.adresse IS NOT NULL AND t1.adresse NOT LIKE '%bau%' AND t1.id IN ('58e722d6-44f5-4e24-8861-5cd4a6f07cbc','5d492f56-c26e-4c03-b3ec-e1d9b0c6f060','fc87b46a-5fe8-4ed0-b3f4-f6fbb0d6919d')AND t3.primaerstr != (CASE WHEN (SELECT COUNT(hi_haus_id) FROM hi_haus_hi_strasse WHERE hi_haus_id = t1.id) > 1 THEN 1 ELSE '' END)ORDER BY t1.id,t1.date_modified DESC LIMIT 30;</p>

Title: Mysql using COUNT insde CASE

Body:
Is it possible to use count inside CASE, here is my query. gives me an error #1111

SELECT t1.id,t1.name,t1.date_entered,t1.date_modified, t1.adresse,t1.adresse_state,t1.adresse_city,t1.adresse_postalcode,t1.hausnummer,t1.center_lat,t1.center_long, t3.name as street_name,t3.strasse,t3.primaerstr
FROM hi_haus as t1
LEFT JOIN hi_haus_hi_strasse as t2 ON (t2.hi_haus_id = t1.id)
LEFT JOIN hi_strasse as t3 ON (t3.id = t2.hi_strasse_id)
WHERE t1.adresse !='' AND t1.adresse IS NOT NULL AND t1.adresse NOT LIKE '%bau%' AND t1.id IN ('58e722d6-44f5-4e24-8861-5cd4a6f07cbc','4d0a79ee-decf-49b1-8b4b-a912b278ffec')
AND t3.primaerstr =
CASE
WHEN count(t1.id) > '1' THEN t3.primaerstr='0'
ELSE
t3.primaerstr = '1'
END
GROUP BY t1.id

What i need is to get the primaerstr '0' if id is repeating more than once.


答:
here is a simple example that contains your code and solution    </p>

```<code>//Data Object
var obj={
           name:"uneeb",
           city:"gujranwala",
           state: "punjab"
        };
//Data Object

//Ajax Request to Server
     $.ajax({
          type: 'post',
          url: 'someFile.php',
          data:object,
          success: function (data) {
                  //do something here
              }
          });
//Ajax Request to Server

//PHP

echo $_POST['name']; //prints uneeb
echo $_POST['city']; //prints gujranwala
echo $_POST['state']; //prints punjab

//PHP
</code>```

Title: How to post value from one php page to another using ajax

Body:
here is a simple example that contains your code and solution

//Data Object
var obj={
           name:"uneeb",
           city:"gujranwala",
           state: "punjab"
        };
//Data Object

//Ajax Request to Server
     $.ajax({
          type: 'post',
          url: 'someFile.php',
          data:object,
          success: function (data) {
                  //do something here
              }
          });
//Ajax Request to Server

//PHP

echo $_POST['name']; //prints uneeb
echo $_POST['city']; //prints gujranwala
echo $_POST['state']; //prints punjab

//PHP

ContentLicense: CC BY-SA 4.0


问:
Page focus scrolls back to AutoCompleteTextView
Have an autocomplete textView in layout which is in a ScrollView.

```<code>mAutoCompleteTextView.addTextChangedListener(new TextValidator(mAutoCompleteTextView) {
        @Override
        public void validate(TextView textView, String text) {
            if(text == null){
                mAutoCompleteTextView.setError(text);
        }
});
</code>```

This shows a red error icon with a dropdown error message in case text is not valid. While error is visible and page is scrolled, the centre of page returns back to this view instead of scrolling up/down.

How to avoid this while error is still visible?

答:
Try this ..
This will allow you to scroll smoothly, if setEnabled() doesnt work you can also user clearFocus() and requestFocus()

```<code>   scrollLayout.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            Rect rect = new Rect();
            mAutoCompleteTextView.setEnabled(false);
            if (mAutoCompleteTextView.getGlobalVisibleRect(rect)
                    && mAutoCompleteTextView.getHeight() == rect.height()
                    && mAutoCompleteTextView.getWidth() == rect.width() && mAutoCompleteTextView.isShown()) {
                mAutoCompleteTextView.setEnabled(true);
            } else {
                mAutoCompleteTextView.setEnabled(false);
            }
        }
    });
</code>```

Hope this helps

Body:
Have an autocomplete textView in layout which is in a ScrollView.

mAutoCompleteTextView.addTextChangedListener(new TextValidator(mAutoCompleteTextView) {
        @Override
        public void validate(TextView textView, String text) {
            if(text == null){
                mAutoCompleteTextView.setError(text);
        }
});

This shows a red error icon with a dropdown error message in case text is not valid. While error is visible and page is scrolled, the centre of page returns back to this view instead of scrolling up/down.

How to avoid this while error is still visible?

Body:
Try this ..
This will allow you to scroll smoothly, if setEnabled() doesnt work you can also user clearFocus() and requestFocus()

   scrollLayout.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            Rect rect = new Rect();
            mAutoCompleteTextView.setEnabled(false);
            if (mAutoCompleteTextView.getGlobalVisibleRect(rect)
                    && mAutoCompleteTextView.getHeight() == rect.height()
                    && mAutoCompleteTextView.getWidth() == rect.width() && mAutoCompleteTextView.isShown()) {
                mAutoCompleteTextView.setEnabled(true);
            } else {
                mAutoCompleteTextView.setEnabled(false);
            }
        }
    });

Hope this helps


问:
Generate chained setters
I want to create a big Java object with 20 fileds, most of IDE's provide a generate function, wich allows me to generate getters and setters for all the fiels of my object.

The thing is, I am a big fan of method chaining and I am using it on all my objects, but I have to add return this at the end of each setters, which is not very handy.

Is it possible to generate setters with a special plugin form an IDE ?

答: It's generally called "fluent" setters. There is a plugin for Netbeans that does it automatically for you. I'm pretty sure you can find something equivalent in eclipse or IntelliJ.</p>

Title: Generate chained setters


问:
Spring, hibernate entity fields depending on profile
i have something like this:

```<code>@Entity
@Table(name = "schedules")
public class ScheduleDO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;

@Column(name = "begin_time", columnDefinition = "TIMESTAMP WITH TIME ZONE",
nullable = false)
private OffsetDateTime beginTime;
}
</code>```

And i want to be able to change the "beginTime" variable anotation based on active profile. Something like this:

```<code>   @Profile("dev")
   @Column(name = "begin_time_dev", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   @Profile("test")
   @Column(name = "begin_time_test", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   private OffsetDateTime beginTime;
</code>```

is something like that possible?

答:
Actually JPA/Hibernate know nothing about spring so profiles is out of their scope. Moreover entities are not beans so spring don't use them

The only solution I can see is to define a placeholder {profile_begin_time_test} and add an interceptor (see the example).

In the method

```<code>public String onPrepareStatement(String sql)
</code>```

In the sql generated by hibernate replace the {profile_begin_time_test} placeholder with desired real column name. The placeholder replacement can be configured to use value based on spring profiles.

Body:
i have something like this:

@Entity
@Table(name = "schedules")
public class ScheduleDO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;

@Column(name = "begin_time", columnDefinition = "TIMESTAMP WITH TIME ZONE",
nullable = false)
private OffsetDateTime beginTime;
}

And i want to be able to change the "beginTime" variable anotation based on active profile. Something like this:

   @Profile("dev")
   @Column(name = "begin_time_dev", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   @Profile("test")
   @Column(name = "begin_time_test", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   private OffsetDateTime beginTime;

is something like that possible?

Body:
Actually JPA/Hibernate know nothing about spring so profiles is out of their scope. Moreover entities are not beans so spring don't use them

The only solution I can see is to define a placeholder {profile_begin_time_test} and add an interceptor (see the example).

In the method

public String onPrepareStatement(String sql)

In the sql generated by hibernate replace the {profile_begin_time_test} placeholder with desired real column name. The placeholder replacement can be configured to use value based on spring profiles.


问:
Symfony - get access to the method from another file in controller
I am using symfony 3 and trying to get access to the class I declared in

src/AppBundle/Service/ApiEngine.php

```<code>namespace AppBundle\Service;

use DateTime;

class ApiEngine {

    private $api_handler;

    public function __construct($username, bool $repos) {
        $client = new \GuzzleHttp\Client();
        $request = 'https://api.github.com/users/' . $username;
        $request .= ($repos) ?  '/repos' : "";
        $res = $client->request('GET', $request);

        $this->api_handler = json_decode($res->getBody()->getContents(), true);
    }

    public function getProfileData() {
        return [ /*some data*/ ];
    }
}
</code>```

I declared this file in

config/service.yml

```<code>service:
  *
  *
  *
  api:
      class: AppBundle\Service\ApiEngine
      arguments: ["@username", "@repos"]
</code>```

In controller I am trying to use some of the ApiEngine methods like this:

src/AppBundle/Controller/GitApiController.php

```<code>namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class GitApiController extends Controller {

    /**
     * @Route("/{username}", name ="gitapi", defaults={"username": "symfony"})
     */
    public function gitApiAction($username) {
        $api = $this->get('api')->__construct($username, false)->getProfileData();

        return $this->render('gitapi/index.html.twig', $api);
    } }
</code>```

But it gives me this error:

(1/1) ServiceNotFoundException The service "api" has a dependency on a
  non-existent service "username".

答:
I advise you to change your class into this for example:

```<code>private function __construct($username, bool $repos) {
        $client = new \GuzzleHttp\Client();
        $request = 'https://api.github.com/users/' . $username;
        $request .= ($repos) ?  '/repos' : "";
        $res = $client->request('GET', $request);

        $this->api_handler = json_decode($res->getBody()->getContents(), true);
    }

public static function createApiEngine($username, bool $repos)
{
    return new self($username, $bool);
}
</code>```

After inside your controller you can do this:

```<code>$api = ApiEngine::createApiEngine($username, false);
$api->getProfileData();
</code>```

Into your controller you need to insert a use for ApiEngine, in this use case you don't need dependency injection so inside your services.yml remove arguments please

Body:
I am using symfony 3 and trying to get access to the class I declared in

src/AppBundle/Service/ApiEngine.php

namespace AppBundle\Service;

use DateTime;

class ApiEngine {

    private $api_handler;

    public function __construct($username, bool $repos) {
        $client = new \GuzzleHttp\Client();
        $request = 'https://api.github.com/users/' . $username;
        $request .= ($repos) ?  '/repos' : "";
        $res = $client->request('GET', $request);

        $this->api_handler = json_decode($res->getBody()->getContents(), true);
    }

    public function getProfileData() {
        return [ /*some data*/ ];
    }
}

I declared this file in

config/service.yml

service:
  *
  *
  *
  api:
      class: AppBundle\Service\ApiEngine
      arguments: ["@username", "@repos"]

In controller I am trying to use some of the ApiEngine methods like this:

src/AppBundle/Controller/GitApiController.php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class GitApiController extends Controller {

    /**
     * @Route("/{username}", name ="gitapi", defaults={"username": "symfony"})
     */
    public function gitApiAction($username) {
        $api = $this->get('api')->__construct($username, false)->getProfileData();

        return $this->render('gitapi/index.html.twig', $api);
    } }

But it gives me this error:

(1/1) ServiceNotFoundException The service "api" has a dependency on a
  non-existent service "username".

Body:
I advise you to change your class into this for example:

private function __construct($username, bool $repos) {
        $client = new \GuzzleHttp\Client();
        $request = 'https://api.github.com/users/' . $username;
        $request .= ($repos) ?  '/repos' : "";
        $res = $client->request('GET', $request);

        $this->api_handler = json_decode($res->getBody()->getContents(), true);
    }

public static function createApiEngine($username, bool $repos)
{
    return new self($username, $bool);
}

After inside your controller you can do this:

$api = ApiEngine::createApiEngine($username, false);
$api->getProfileData();

Into your controller you need to insert a use for ApiEngine, in this use case you don't need dependency injection so inside your services.yml remove arguments please


答: replace this data: desc, field in your ajax to data:{data: desc},, this is the cause you are not getting data in your php code


问:
Does SQL Azure automatically geo-replication automatically failover?
We have a geo-replicated database in SQL Azure (Premium) and are wondering if we are pointing to the South Central US database that is the master, if that goes down do we have to manually change our connection strings in our code (C# .Net / Entity Framework 6) to point to the new database in say North US?  We are looking for a way to have a single connection string and then Azure do the under the covers to now point to the new database if the master ever goes down.  Is that possible?

Update on method followed:

so I read this that we have to manually go into a web.config file on a production system when a region goes down and change the main database to another replicated database that is working.

I decided to just hard code east, west and south regions in the web config and wrote code to retry and fail over to other regions if the main one couldn't be reached. This means it can only read, not write until Microsoft or we manually failover the master to a Read Only Active slave. Not the best experience to me. Requires human intervention knowing it's down, then flipping it and custom code

答:
Just as an update for someone else who might come looking, this functionality is now available on SQL Azure. It's called auto-failover groups and was announced in May 2017. It is still in preview as of the time of writing -  configuration is currently not supported on the portal and must be done via the API.

More information here: https://azure.microsoft.com/en-us/blog/azure-sql-database-now-supports-transparent-geographic-failover-of-multiple-databases-featuring-automatic-activation/


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

```<code>from tkinter import *

a = 3

class Application(Frame):

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

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

    def change_variable(self):
        global a
        a = 1

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

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

答:
Try running this code it will give you the idea of what you want. </p>

```<code>import tkinter
count = 5
def change_text():
        global count
        if count != 2:
                button.config(text='edit')

frame = tkinter.Frame(height=500,width=500)
button = tkinter.Button(frame,text='save',command=change_text)
button.place(x=0,y=0)
frame.pack()
frame.mainloop()
</code>```

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

from tkinter import *

a = 3

class Application(Frame):

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

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

    def change_variable(self):
        global a
        a = 1

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

if __name__ == '__main__':
    main()

Body:
Try running this code it will give you the idea of what you want.

import tkinter
count = 5
def change_text():
        global count
        if count != 2:
                button.config(text='edit')

frame = tkinter.Frame(height=500,width=500)
button = tkinter.Button(frame,text='save',command=change_text)
button.place(x=0,y=0)
frame.pack()
frame.mainloop()


答:
In the root Layout use this :

```<code>android:descendantFocusability="beforeDescendants"
</code>```

And then in onCreate():

```<code>rootLayout.requestFocus();
</code>```

Hope this helps.

Title: Page focus scrolls back to AutoCompleteTextView

Body:
In the root Layout use this :

android:descendantFocusability="beforeDescendants"

And then in onCreate():

rootLayout.requestFocus();

Hope this helps.


问:
TSQL Code formatter - SQL Server 2005/2008
Is there a free code formatter available for TSQL - SQL Server 2005/2008. I found few most of which asks to copy paste code online in an applet. I am looking for a desktop version. Tried toad for sql server but formatting is not supported in freeware.
If anyone has any work-around please share it. </p>

答:
Check out the SSMS Tools Pack (free addon for SSMS).

One of the features is formatting (http://www.ssmstoolspack.com/Features?f=3), though I don't know what level you want your SQL formatted - maybe you could clarify?


问:
Why does Firefox ignores bottom margin of flex-item?
It respects margin-bottom only when there is enough room for it. Otherwise Firefox behaves as if there is no margin-bottom at all.

Chrome Full:

Chrome Shrinked:

Firefox Shrinked:

Is it correct behaviour of flexbox? How to fix it?

codepen

.container {
  position: fixed;
  display: flex;
  flex-direction: column;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
}

.grow {
  flex-grow: 1;
  flex-shrink: 0;
  background: #8f8;
}

.content {
  width: 500px;
  margin: 20px auto;
  border: 1px solid currentColor;
  background: #f88;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container">
    <div class="grow"></div>
    <div class="content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus, facilis omnis inventore, illum eos quis fuga quos id, labore consectetur quas. Unde sed nemo nobis recusandae saepe ex nulla accusantium?</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias asperiores a enim magnam voluptatem. Ab sint possimus quis odit vero explicabo unde quod rem, quasi voluptatibus cupiditate voluptatem veritatis repudiandae.</p>
    </div>
    <div class="grow"></div>
  </div>
</body></code>```

答:
I think this is what's happening: When the window is too small, the

 elements shrink all the way down to a height of 0 pixels. Now Firefox doesn't even bother rendering them. So you don't have any element underneath the

 element, and therefore the bottom margin of that element doesn't get applied. A page with just one element with bottom margin has the same effect.

I would set up your html/css differently so you don't run into this problem. You can use a container around the content div and apply padding on that for example.

Body:
It respects margin-bottom only when there is enough room for it. Otherwise Firefox behaves as if there is no margin-bottom at all.

Chrome Full:

Chrome Shrinked:

Firefox Shrinked:

Is it correct behaviour of flexbox? How to fix it?

codepen

.container {
  position: fixed;
  display: flex;
  flex-direction: column;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: auto;
}

.grow {
  flex-grow: 1;
  flex-shrink: 0;
  background: #8f8;
}

.content {
  width: 500px;
  margin: 20px auto;
  border: 1px solid currentColor;
  background: #f88;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus, facilis omnis inventore, illum eos quis fuga quos id, labore consectetur quas. Unde sed nemo nobis recusandae saepe ex nulla accusantium?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias asperiores a enim magnam voluptatem. Ab sint possimus quis odit vero explicabo unde quod rem, quasi voluptatibus cupiditate voluptatem veritatis repudiandae.

Body:
I think this is what's happening: When the window is too small, the <div class="grow"></div> elements shrink all the way down to a height of 0 pixels. Now Firefox doesn't even bother rendering them. So you don't have any element underneath the <div class="content"></div> element, and therefore the bottom margin of that element doesn't get applied. A page with just one element with bottom margin has the same effect.

I would set up your html/css differently so you don't run into this problem. You can use a container around the content div and apply padding on that for example.


问:
How to structure a Redux store with interwoven data?
I'm a newbie to React/Redux and I could use your advice on how to structure the following data models in my react app.

I have the following models:

```<code>Users
Skills (id, title)
UserSkills (user_id, skill_id)
</code>```

I want to create a component that shows a User's Skills which I would get from my API /user_skills which would return (user_id, skill_id).

Should I update my API to include the extra fields I need to render the component like Skill.title or should I somehow, with Redux, also store Skills in the Redux store, and the have UserSkills somehow find the Skill.Title from the Redux store and if it doesn't exist, go fetch the title? How can I best structure this in Redux and how can I get started?

答:
So I will start by answering your first question.

Should I update my API to include the extra fields I need to render the component like Skill.title?

Yes you should. Change your API to such that when you provide a user id, it should return all the skills particular to that user. Your API should like something like api/user_skills/:id

Now you have changed your API lets move to Redux. The way Redux works is that you dispatch a certain action and against each action we have a reducer which updates your store and the concerned components are listening to changes in the store via the connect method provided by the react-redux library.

So I will conclude by highlighting the overall flow. In your React component you will dispatch actions (actions can make AJAX requests), against each action you will write a reducer which will update your app's store. On each successful AJAX request, store will be updated and the component(s) which have subscribed to the store will re-render as the entire store will be available to them via props.

Hope I am able to answer your question :)

Body:
I'm a newbie to React/Redux and I could use your advice on how to structure the following data models in my react app.

I have the following models:

Users
Skills (id, title)
UserSkills (user_id, skill_id)

I want to create a component that shows a User's Skills which I would get from my API /user_skills which would return (user_id, skill_id).

Should I update my API to include the extra fields I need to render the component like Skill.title or should I somehow, with Redux, also store Skills in the Redux store, and the have UserSkills somehow find the Skill.Title from the Redux store and if it doesn't exist, go fetch the title? How can I best structure this in Redux and how can I get started?


问:
Mysql CURDATE() -1
Please, I don't understand why this command returns 00 April.

Today is 1st April 2015, and executing:

```<code>mysql> SELECT CURDATE() -1;
</code>```

it returns:

```<code>| 20150400 |

+--------------+
</code>```

Why CURDATE-1 doesn't return 31st March?,

00 April is an error, please it would be great if somebody could explain it.

Next, on 2nd April it works well, also for the rest of the days within the month:

mysql>

```<code>select CURDATE() -1;

|     20150401 |
</code>```

This function seems is not able to operate with +x / -x out of the current month scope.

This should be highlighted in the reference guide.

BTW, I'vereplaced it with this new function:

```<code> SELECT SUBDATE(CURDATE(),1)
</code>```

Thanks.

答:
You can use:

```<code>SELECT SUBDATE(CURDATE(), 1);
</code>```

or

```<code>SELECT CURDATE() - INTERVAL 1 DAY;
</code>```

or

```<code>SELECT SUBDATE(CURDATE(), INTERVAL 1 DAY);
</code>```

or

```<code>SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY);
</code>```

Title: Mysql CURDATE() -1

Body:
Please, I don't understand why this command returns 00 April.

Today is 1st April 2015, and executing:

mysql> SELECT CURDATE() -1;

it returns:

| 20150400 |

+--------------+

Why CURDATE-1 doesn't return 31st March?,

00 April is an error, please it would be great if somebody could explain it.

Next, on 2nd April it works well, also for the rest of the days within the month:

mysql>

select CURDATE() -1;

|     20150401 |

This function seems is not able to operate with +x / -x out of the current month scope.

This should be highlighted in the reference guide.

BTW, I'vereplaced it with this new function:

 SELECT SUBDATE(CURDATE(),1)

Thanks.

Body:
You can use:

SELECT SUBDATE(CURDATE(), 1);

or

SELECT CURDATE() - INTERVAL 1 DAY;

or

SELECT SUBDATE(CURDATE(), INTERVAL 1 DAY);

or

SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY);


问:
How to echo data from Blob which contain image
I am using TinyMCE text editor, In this editor i paste some text and image and save in database. Now i want to echo this data, want to echo image that is store in db using text editor. In Data base column type is blob.

I tried following but failed.

$client_id = mysql_real_escape_string(trim(nl2br($row['test'])));

$client_id = mysql_real_escape_string($row['test']);

$client_id = nl2br($row['test']);

Please help me how i can echo image that is store in blob by using text editor.

Than you

答:
You have to use the base64_encoding function</p>

```<code><img src="data:image/jpeg;base64,'.base64_encode($image->load()) .'" />';
</code>```

Body:
You have to use the base64_encoding function

<img src="data:image/jpeg;base64,'.base64_encode($image->load()) .'" />';


问:
Vue.js passing events up to parents in components
I have a Vue app like this:

```<code><div id="example">

  <event-emitting-component @clicked="methodOnRootInstance"></event-emitting-component>

  <event-emitting-component-parent></event-emitting-component-parent>

  <div v-for="click in clicks">
    {{ click }}
  </div>

</div>
</code>```

And here is the JS for it:

```<code>// Child
Vue.component('event-emitting-component', {
  template: '<div class="event-emitting-component" @click="$emit(\'clicked\')">Event emitter</div>'
});
// Parent
Vue.component('event-emitting-component-parent', {
  template: '<div class="event-emitting-component-parent">' +
  'A custom parent!'+
  '<event-emitting-component></event-emitting-component>' + // <-- Please note child component
  '</div>'
});
// create a root instance
new Vue({
  el: '#example',
  data: {
    clicks : []
  },
  methods : {
    methodOnRootInstance : function(){
      this.clicks.push('Element clicked');
    }
  }
})
</code>```

If you want to play with it it is also here:

https://codepen.io/EightArmsHQ/pen/QgbwPG?editors=1010

When you click the top child component a click is registered on the root element. Perfect.

When the child component is nested inside a parent (the second component in the example), obviously I can't add a @clicked="methodOnRootInstance" as that method doesn't exist inside the component.

What is the best way to pass an event up through a number of nested components?

I've made a stripped back example here, but in reality some components are two or three levels deep. Is the answer (what I think it is) that inside the parent component I would have the following:

```<code>Vue.component('event-emitting-component-parent', {
  template: '<div class="event-emitting-component-parent">' +
  'A custom parent!'+
  '<event-emitting-component @clicked="passClicked"></event-emitting-component>' + // <-- Please note child component
  '</div>',
  'methods': {
    passClicked : function(){
      this.$emit('clicked')
    }
  }
});
</code>```

And then in the html template add the same:

```<code><event-emitting-component-parent @clicked="methodOnRootInstance"></event-emitting-component-parent>
</code>```

I know I can get it to work like this, however it doesn't seem very elegant. I've looked in the docs and there are functions such as sync although I don't think it's what I need, I'm struggling to find the correct approach.

Bonus question: can vuex help with stuff like this?

答:
This is the type of problem vuex is designed to solve, however, before you consider adding an extra layer of complexity to your app, you may be able to get away with a simple global event bus, which is simply an empty Vue object to emit events onto, which can then be listened for by any component in your app, bypassing the parent-child chain:

```<code>const bus = new Vue({});

Vue.component('comp-1', {
  template: `<div>Comp 1 <button @click="emitClick">Click</button></div>`,
  methods: {
     emitClick(){
       bus.$emit('comp-1-click');
     }
  }
})

Vue.component('comp-2', {
  template: `<div><comp-1></comp-1></div>`,
})

new Vue({
  el: '#app',
  created(){
    bus.$on('comp-1-click',() => {
      console.log('Comp 1 clicked');
    });
  }
})
</code>```

Here's the JSFiddle: https://jsfiddle.net/oatLhzLp/

Body:
I have a Vue app like this:

  <event-emitting-component @clicked="methodOnRootInstance"></event-emitting-component>

  <event-emitting-component-parent></event-emitting-component-parent>

    {{ click }}

And here is the JS for it:

// Child
Vue.component('event-emitting-component', {
  template: '
Event emitter
'
});
// Parent
Vue.component('event-emitting-component-parent', {
  template: '
' +
  'A custom parent!'+
  '<event-emitting-component></event-emitting-component>' + // <-- Please note child component
  '
'
});
// create a root instance
new Vue({
  el: '#example',
  data: {
    clicks : []
  },
  methods : {
    methodOnRootInstance : function(){
      this.clicks.push('Element clicked');
    }
  }
})

If you want to play with it it is also here:

https://codepen.io/EightArmsHQ/pen/QgbwPG?editors=1010

When you click the top child component a click is registered on the root element. Perfect.

When the child component is nested inside a parent (the second component in the example), obviously I can't add a @clicked="methodOnRootInstance" as that method doesn't exist inside the component.

What is the best way to pass an event up through a number of nested components?

I've made a stripped back example here, but in reality some components are two or three levels deep. Is the answer (what I think it is) that inside the parent component I would have the following:

Vue.component('event-emitting-component-parent', {
  template: '
' +
  'A custom parent!'+
  '<event-emitting-component @clicked="passClicked"></event-emitting-component>' + // <-- Please note child component
  '
',
  'methods': {
    passClicked : function(){
      this.$emit('clicked')
    }
  }
});

And then in the html template add the same:

<event-emitting-component-parent @clicked="methodOnRootInstance"></event-emitting-component-parent>

I know I can get it to work like this, however it doesn't seem very elegant. I've looked in the docs and there are functions such as sync although I don't think it's what I need, I'm struggling to find the correct approach.

Bonus question: can vuex help with stuff like this?

Body:
This is the type of problem vuex is designed to solve, however, before you consider adding an extra layer of complexity to your app, you may be able to get away with a simple global event bus, which is simply an empty Vue object to emit events onto, which can then be listened for by any component in your app, bypassing the parent-child chain:

const bus = new Vue({});

Vue.component('comp-1', {
  template: `<div>Comp 1 <button @click="emitClick">Click</button></div>`,
  methods: {
     emitClick(){
       bus.$emit('comp-1-click');
     }
  }
})

Vue.component('comp-2', {
  template: `<div><comp-1></comp-1></div>`,
})

new Vue({
  el: '#app',
  created(){
    bus.$on('comp-1-click',() => {
      console.log('Comp 1 clicked');
    });
  }
})

Here's the JSFiddle: https://jsfiddle.net/oatLhzLp/


问:
Searching for something in Database - SELECT - Need to search in 2 tables

As you can see in the print screen above, I am wondering, if it is possible to check if there is one thing in two tables at once. Without making 2 queries. I need to look, if "fajne-to-jest" is in table1 or table2. I'm doing it in 2 queries... but question is, is it possible to check this information using one query? Mabye something else? Most efficent way? The best way?

答:
Please try the below script:

```<code>DECLARE @SearchStr nvarchar(100)

SET @SearchStr  = '%test%'

DECLARE @Results TABLE( TableName nvarchar(256), ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName =
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT DISTINCT ''' + @TableName + ''',''' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END
END

SELECT  TableName, ColumnName, ColumnValue
FROM @Results
</code>```

Put your search string in "@SearchStr".
I got this from this portal itself.

Body:
Please try the below script:

DECLARE @SearchStr nvarchar(100)

SET @SearchStr  = '%test%'

DECLARE @Results TABLE( TableName nvarchar(256), ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName =
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT DISTINCT ''' + @TableName + ''',''' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END
END

SELECT  TableName, ColumnName, ColumnValue
FROM @Results

Put your search string in "@SearchStr".
I got this from this portal itself.