问:
Chrome app fails to open usb device
I'm trying to connect to a smartcard reader form a chrome app using chrome.usb. The permissions in the manifest are set properly and lsusb recognizes the device.

chrome.usb.getDevices detects the device but when I try to open it using chrome.usb.openDevice I get "Failed to open device". I've tried it on both windows 7 with chrome 43 and ubuntu with chrome 42 and got the same result. I've also installed chrome device-info sample app and got the same message.

Is there anything I should be looking at on the device itself? Could it be related to permissions?

答:
First you need to figure out the vendor and product IDs for your device. If you run lsusb it will list the devices on your system in a format like this:

```<code>~$ lsusb

Bus {Bus number} Device {device id}: ID {vendorid in hexa}:{product id in hexa} Manufacturer Product
</code>```

Once you know this information you can create a file in /etc/udev/rules.d/ with the name {deviceid}.rules. Replace {deviceid} with the value obtained from the output up there.

The content should be the following:

SUBSYSTEM=="usb", ATTRS{idVendor}=="vendorid", ATTR{idProduct}=="productid", MODE="0666", GROUP="plugdev"

Replace vendorid and productid with corresponding hexadecimal values obtained by running the command above.

Title: Chrome app fails to open usb device

Body:
First you need to figure out the vendor and product IDs for your device. If you run lsusb it will list the devices on your system in a format like this:

~$ lsusb

Bus {Bus number} Device {device id}: ID {vendorid in hexa}:{product id in hexa} Manufacturer Product

Once you know this information you can create a file in /etc/udev/rules.d/ with the name {deviceid}.rules. Replace {deviceid} with the value obtained from the output up there.

The content should be the following:

SUBSYSTEM=="usb", ATTRS{idVendor}=="vendorid", ATTR{idProduct}=="productid", MODE="0666", GROUP="plugdev"

Replace vendorid and productid with corresponding hexadecimal values obtained by running the command above.


来源: stackexchange

问:
React map on object then array
This is my object and I want to map this in my component but I have problem, I cant use map on this object. First value is vote and next is array of users. How I cna use map on this in babel ? </p>

```<code>  var ObjVote = {
        '1':['EwaK','Jacek','Jacek'],
        '2':['Anna','Pawel','EwaK'],
        '3':['Anna','EwaK','Jacek'],
        '4':['Jas','Jas','Pawel'],
        '5':['Anna','Jas','Pawel']
        }
</code>```

答:
You can convert it to an array using Array#from, and then you can map it. First you need to convert the object to an array like object, by adding the length property. To add the length property, you can use Object#assign, and Object#keys:

const ObjVote = {
  '1':['EwaK','Jacek','Jacek'],
  '2':['Anna','Pawel','EwaK'],
  '3':['Anna','EwaK','Jacek'],
  '4':['Jas','Jas','Pawel'],
  '5':['Anna','Jas','Pawel']
}

const array = Array.from(
  Object.assign(
    {},
    ObjVote,
    { length: Object.keys(ObjVote).length + 1 } // add the number of keys + 1 (the missing 0 index) as the length property
  ),
  (voters, vote) => ({ vote, voters }) // create the vote object
).slice(1); // remove the 1st empty element

console.log(array);```

ContentLicense: CC BY-SA 3.0

Title: React map on object then array

Body:
This is my object and I want to map this in my component but I have problem, I cant use map on this object. First value is vote and next is array of users. How I cna use map on this in babel ?

  var ObjVote = {
        '1':['EwaK','Jacek','Jacek'],
        '2':['Anna','Pawel','EwaK'],
        '3':['Anna','EwaK','Jacek'],
        '4':['Jas','Jas','Pawel'],
        '5':['Anna','Jas','Pawel']
        }


问:
Avoiding to create the same converters for different beans
I implemented with success the converter for h:selectOneMenu used by one bean but I want to use the same converter from a different bean instead to create the same converter another time.

currently I have:

Converter

```<code>@FacesConverter(value = "csiConverter")
public class CsiConverter implements Converter {

@Override
public Object getAsObject(FacesContext ctx, UIComponent uiComponent, String dcId) {
    ValueExpression vex =
            ctx.getApplication().getExpressionFactory()
                    .createValueExpression(ctx.getELContext(),
                            "#{cfgbean}", CfgDbBean.class);

   ...
}

@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
    return ((Csi) o).getCsi();
}
</code>```

and the xhtml

```<code>     <div class="form-group">
      <label>CSI</label>
     <h:selectOneMenu id="csi" styleClass="form-control" value="#{cfgbean.csi}" converter="csiConverter">
            <f:selectItems var="csival" itemLabel="#{csival.csi} - #{csival.name}" itemValue="${csival}" value="#{cfgbean.csilist}" />
        </h:selectOneMenu>
      </div>
</code>```

this is working all fine.
Now I would like to create in a different xhtml the same selectOneMenu contacting a different bean for the same purpose to show the same content.

Problem is that inside the Converter class is cabled the bean reference and bean class.(createValueExpression(ctx.getELContext(), "#{cfgbean}", CfgDbBean.class);)

How can avoid to cable that references and have a generic csiConverter for all Beans?

thanks

答:
I have a converter where the getAsObject method optionally uses an attribute to pass the bean name. If the attribute is not set I use the component's value attribute to detect the type of object the value is bound to:

```<code>ValueExpression valueExpression = uiComponent.getValueExpression("value");
Class<?> type = valueExpression.getType(ctx.getELContext());
</code>```

From the type I can determine the bean name. This might be an option for you as well.

In my case:

```<code>String beanName = type.getSimpleName() + "Bean";
beanName = beanName.substring(0, 1).toLowerCase() +
           beanName.substring(1);
</code>```

If you are using the same type on different beans, you should be able to get the bean name from:

```<code>valueExpression.getExpressionString()
</code>```

It returns the original string used to create the expression, unmodified. In your case:

```<code>#{cfgbean.csi}
</code>```

Simply remove the .csi part from that string to get the bean. If your beans extends an abstract bean / implements an interface like CsiHolder (or whatever name you gave it), you can can get the bean like:

```<code>ctx.getApplication().evaluateExpressionGet(ctx, "#{cfgbean}", CsiHolder.class)
</code>```

Body:
I implemented with success the converter for h:selectOneMenu used by one bean but I want to use the same converter from a different bean instead to create the same converter another time.

currently I have:

Converter

@FacesConverter(value = "csiConverter")
public class CsiConverter implements Converter {

@Override
public Object getAsObject(FacesContext ctx, UIComponent uiComponent, String dcId) {
    ValueExpression vex =
            ctx.getApplication().getExpressionFactory()
                    .createValueExpression(ctx.getELContext(),
                            "#{cfgbean}", CfgDbBean.class);

   ...
}

@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
    return ((Csi) o).getCsi();
}

and the xhtml

      CSI
     <h:selectOneMenu id="csi" styleClass="form-control" value="#{cfgbean.csi}" converter="csiConverter">
            <f:selectItems var="csival" itemLabel="#{csival.csi} - #{csival.name}" itemValue="${csival}" value="#{cfgbean.csilist}" />
        </h:selectOneMenu>

this is working all fine.
Now I would like to create in a different xhtml the same selectOneMenu contacting a different bean for the same purpose to show the same content.

Problem is that inside the Converter class is cabled the bean reference and bean class.(createValueExpression(ctx.getELContext(), "#{cfgbean}", CfgDbBean.class);)

How can avoid to cable that references and have a generic csiConverter for all Beans?

thanks

Body:
I have a converter where the getAsObject method optionally uses an attribute to pass the bean name. If the attribute is not set I use the component's value attribute to detect the type of object the value is bound to:

ValueExpression valueExpression = uiComponent.getValueExpression("value");
Class<?> type = valueExpression.getType(ctx.getELContext());

From the type I can determine the bean name. This might be an option for you as well.

In my case:

String beanName = type.getSimpleName() + "Bean";
beanName = beanName.substring(0, 1).toLowerCase() +
           beanName.substring(1);

If you are using the same type on different beans, you should be able to get the bean name from:

valueExpression.getExpressionString()

It returns the original string used to create the expression, unmodified. In your case:

#{cfgbean.csi}

Simply remove the .csi part from that string to get the bean. If your beans extends an abstract bean / implements an interface like CsiHolder (or whatever name you gave it), you can can get the bean like:

ctx.getApplication().evaluateExpressionGet(ctx, "#{cfgbean}", CsiHolder.class)


答:
You cannot use map on Object. But you can use Object.keys() and then map.

 let ObjVote = {
  '1':['EwaK','Jacek','Jacek'],
  '2':['Anna','Pawel','EwaK'],
  '3':['Anna','EwaK','Jacek'],
  '4':['Jas','Jas','Pawel'],
  '5':['Anna','Jas','Pawel']
}

let data = Object.keys(ObjVote).map(key => {
  return {
    vote: key,
    users: ObjVote[key]
  }
})

console.log(data)```

Title: React map on object then array


问:
How to create a list of conditions?
I am trying to create an if else code where there is about 20conditions for the elif, how do I create a list of conditions where i can just type something such as:

```<code>uno= <9
lol= >20
crad= =<3
list={uno,lol,crad}
if 13=list:
    print("yay")
elif 13!=list:
    print("nay")
</code>```

That's my current code
It should print "yay", instead there is syntax error

答:
Your "conditions" are functions mapping the input to booleans. Therefore, you can write them as functions:

```<code>def is_small(number):
    return number < 9
def is_large(number):
    return number > 20
conditions = (is_small, is_large)
</code>```

Then you can evaluate all of these functions on some input:

```<code>def check_all(input, conditions):
    return [condition(input) for condition in conditions]
check_all(10, conditions)
>>> [False, False]
</code>```

And if you want to know if all of these or any one of these are true, you can use the functions all and any:

```<code>any(check_all(10, conditions))
>>> False
any(check_all(21, conditions))
>>> True
</code>```

And not all(…) is True if one of the conditions is not fulfilled, not any is True if none is.

Edit: One thing to notice is that the list comprehension [… for … in …] in check_all always evaluates all functions. This is not necessary if you use any or all, which can use an iterator and stop evaluating it onces the result it fixed (at the first True for any and the first False for all). If you use them, you can just replace the list comprehension [… for … in …] by a generator expression (… for … in …).

Title: How to create a list of conditions?

Body:
I am trying to create an if else code where there is about 20conditions for the elif, how do I create a list of conditions where i can just type something such as:

uno= <9
lol= >20
crad= =<3
list={uno,lol,crad}
if 13=list:
    print("yay")
elif 13!=list:
    print("nay")

That's my current code
It should print "yay", instead there is syntax error

Body:
Your "conditions" are functions mapping the input to booleans. Therefore, you can write them as functions:

def is_small(number):
    return number < 9
def is_large(number):
    return number > 20
conditions = (is_small, is_large)

Then you can evaluate all of these functions on some input:

def check_all(input, conditions):
    return [condition(input) for condition in conditions]
check_all(10, conditions)
>>> [False, False]

And if you want to know if all of these or any one of these are true, you can use the functions all and any:

any(check_all(10, conditions))
>>> False
any(check_all(21, conditions))
>>> True

And not all(…) is True if one of the conditions is not fulfilled, not any is True if none is.

Edit: One thing to notice is that the list comprehension [… for … in …] in check_all always evaluates all functions. This is not necessary if you use any or all, which can use an iterator and stop evaluating it onces the result it fixed (at the first True for any and the first False for all). If you use them, you can just replace the list comprehension [… for … in …] by a generator expression (… for … in …).


问:
Backing up Minio to S3
I'm setting up distributed Minio servers locally to use in a solution but would like to back them up to S3 regularly in case the local file system fails/just for more durability or just to migrate to AWS. The use case being we need an S3 compatible storage locally for regular access but would like the option of having it backed up in the cloud.

Wanted to check if anyone has tried something similar before or knows of something similar? Like a simple way/tool to keep Minio buckets in sync with your S3 buckets?

答: you can simply use mc mirror between minio/ to s3/

Title: Backing up Minio to S3


问:
Stripe Java integration payment process using Spring MVC
I am completely new to Stripe API. I want to embedded a payment gateway in my java J2EE application using Spring MVC. I am using stripe for it.

What I have done so far is I have included checkout.js in my checkout page and hit the pay with card button. It then successfully opens a popup which contains the necessary card details.

When clicking on pay button it should go to the stripe and generate a token for me, then redirect to the success page. But I am unable to hold that token in my back-end and do the necessary stuff.

Can you please provide me the sample codes in Spring MVC which meet my entire requirements?

Thanks in advance.

答:
```<code>this is my controller to redirect to the checkout page
</code>```

@RequestMapping(value="/checkout", method = RequestMethod.GET)
    public String checkout(ModelMap map,HttpServletRequest request){

```<code>    //String stripePublicKey = "pk_test_vsp3nRQS4PqW0aqP6PG6cdef";
     String stripePublicKey = "pk_test_vsp3nRQS4PqW0aqP6PG6cdef";

    /*  String token = request.getParameter("stripeToken");
        System.out.println("print token @@@@@@@@@@@" + token);
</code>```

*/

```<code>    map.addAttribute("amount", 50 * 100); // in cents
    map.addAttribute("stripePublicKey", stripePublicKey);
    map.addAttribute("currency", ChargeRequest.Currency.EUR);
    //map.addAttribute("token", ChargeRequest.Currency.EUR);

        return "checkout";
</code>```

Body:
this is my controller to redirect to the checkout page

@RequestMapping(value="/checkout", method = RequestMethod.GET)
    public String checkout(ModelMap map,HttpServletRequest request){

    //String stripePublicKey = "pk_test_vsp3nRQS4PqW0aqP6PG6cdef";
     String stripePublicKey = "pk_test_vsp3nRQS4PqW0aqP6PG6cdef";

    /*  String token = request.getParameter("stripeToken");
        System.out.println("print token @@@@@@@@@@@" + token);

*/

    map.addAttribute("amount", 50 * 100); // in cents
    map.addAttribute("stripePublicKey", stripePublicKey);
    map.addAttribute("currency", ChargeRequest.Currency.EUR);
    //map.addAttribute("token", ChargeRequest.Currency.EUR);

        return "checkout";


答:
You could create a tuple of booleans and check it via all.

```<code>conditions = []

conditions.append(yourVar < 9)
conditions.append(yourVar > 20)
conditions.append(yourVar <= 3)

if all(conditions):
    print('All conditions are met')
else:
    print('At least one condition results in false)
</code>```

Title: How to create a list of conditions?

Body:
You could create a tuple of booleans and check it via all.

conditions = []

conditions.append(yourVar < 9)
conditions.append(yourVar > 20)
conditions.append(yourVar <= 3)

if all(conditions):
    print('All conditions are met')
else:
    print('At least one condition results in false)


问:
C# Winform ProgressBar and BackgroundWorker
I have the following problem:

I have a Form named MainForm. I have a long operation to be taken place on this form.

While this long operation is going on, I need to show another from named ProgressForm on top of the MainForm.

ProgressForm contains a progress bar which needs to be updated while the long operation is taking place.

After the long operation is completed, the ProgressForm should be closed automatically.

I have written the following code:

```<code>using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ClassLibrary
{
    public class MyClass
    {
        public static string LongOperation()
        {
            Thread.Sleep(new TimeSpan(0,0,30));

            return "HelloWorld";
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace BackgroungWorker__HelloWorld
{
    public partial class ProgressForm : Form
    {
        public ProgressForm()
        {
            InitializeComponent();
        }

        public ProgressBar ProgressBar
        {
            get { return this.progressBar1; }
            set { this.progressBar1 = value; }
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using ClassLibrary;

namespace BackgroungWorker__HelloWorld
{
    public partial class MainForm : Form
    {
        ProgressForm f = new ProgressForm();

        public MainForm()
        {
            InitializeComponent();
        }

        int count = 0;
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (f != null)
            {
                f.ProgressBar.Value = e.ProgressPercentage;
            }

            ++count;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                MessageBox.Show("The task has been cancelled");
            }
            else if (e.Error != null)
            {
                MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
            }
            else
            {
                MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (f == null)
            {
                f = new ProgressForm();
            }

            f.ShowDialog();

            //backgroundWorker1.ReportProgress(100);

            MyClass.LongOperation();

            f.Close();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();

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

I can't find a way to update the progressBar.

Where should I place backgroundWorker1.ReportProgress() and how should I call this?

I must not make any change in MyClass because I don't know what would happen or how long it takes to complete the operation in this layer of my application.

Can anyone help me?

答:
What is needed here is to not pass the entire main form to the class, but simply the instance of your BackgroundWorker! You need to cast the sender as Background worker like so:

```<code>private void bgWorker_DoWork(object sender DoWorkEventArgs e)
{
    // Get the BackgroundWorker that raised this event
    BackgroundWorker worker = sender as BackgroundWorker;

    // And now you just send worker to whatever class you need like so:
    bgArgs args = e.Argument as bgArgs;
    MyClass objMyClass = new MyClass();

    MyClass.MyMethod(strValue, args.Option, worker);

    // Do something based on return value.
}
</code>```

And then in your MyClass.MyMethod() you would do the progress calculations and simply raise the worker.ReportProgress(int percentage) event to update the progress bar or whatnot on your main UI form!

This should work perfectly!

Check out this MSDN article for more details, see their Fibonacci example, it's what they do since CalculateFibonacci is a custom class which sends updates to Main form's UI.

See MSDN BackgroundWorker Class for more details.

Body:
I have the following problem:

I have a Form named MainForm. I have a long operation to be taken place on this form.

While this long operation is going on, I need to show another from named ProgressForm on top of the MainForm.

ProgressForm contains a progress bar which needs to be updated while the long operation is taking place.

After the long operation is completed, the ProgressForm should be closed automatically.

I have written the following code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ClassLibrary
{
    public class MyClass
    {
        public static string LongOperation()
        {
            Thread.Sleep(new TimeSpan(0,0,30));

            return "HelloWorld";
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace BackgroungWorker__HelloWorld
{
    public partial class ProgressForm : Form
    {
        public ProgressForm()
        {
            InitializeComponent();
        }

        public ProgressBar ProgressBar
        {
            get { return this.progressBar1; }
            set { this.progressBar1 = value; }
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using ClassLibrary;

namespace BackgroungWorker__HelloWorld
{
    public partial class MainForm : Form
    {
        ProgressForm f = new ProgressForm();

        public MainForm()
        {
            InitializeComponent();
        }

        int count = 0;
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (f != null)
            {
                f.ProgressBar.Value = e.ProgressPercentage;
            }

            ++count;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                MessageBox.Show("The task has been cancelled");
            }
            else if (e.Error != null)
            {
                MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
            }
            else
            {
                MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (f == null)
            {
                f = new ProgressForm();
            }

            f.ShowDialog();

            //backgroundWorker1.ReportProgress(100);

            MyClass.LongOperation();

            f.Close();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();

            this.Close();
        }
    }
}

I can't find a way to update the progressBar.

Where should I place backgroundWorker1.ReportProgress() and how should I call this?

I must not make any change in MyClass because I don't know what would happen or how long it takes to complete the operation in this layer of my application.

Can anyone help me?

Body:
What is needed here is to not pass the entire main form to the class, but simply the instance of your BackgroundWorker! You need to cast the sender as Background worker like so:

private void bgWorker_DoWork(object sender DoWorkEventArgs e)
{
    // Get the BackgroundWorker that raised this event
    BackgroundWorker worker = sender as BackgroundWorker;

    // And now you just send worker to whatever class you need like so:
    bgArgs args = e.Argument as bgArgs;
    MyClass objMyClass = new MyClass();

    MyClass.MyMethod(strValue, args.Option, worker);

    // Do something based on return value.
}

And then in your MyClass.MyMethod() you would do the progress calculations and simply raise the worker.ReportProgress(int percentage) event to update the progress bar or whatnot on your main UI form!

This should work perfectly!

Check out this MSDN article for more details, see their Fibonacci example, it's what they do since CalculateFibonacci is a custom class which sends updates to Main form's UI.

See MSDN BackgroundWorker Class for more details.


问:
Is it possible to use vue-router without a component in vue 2?
I have a very simple page, just a few lines of code and I would like to use vue-router without a vue-component.

I would like to get the string "my-search-query" after the root:

```<code>www.example.com/my-search-query
</code>```

and use it in my main Vue() object. Is this possible?

Thank you!

答:
It is possible to use vue-router without a vue-component and still be notified about path changes in the main Vue() app object:

You can get the "my-search-query" string from www.example.com/#/my-search-query like this:

```<code>const router = new VueRouter({
  routes: [
    { path: '/:question' }
  ]
})

const app = new Vue({
  el: '#app',
  router,
  watch: {
    '$route.params.question': function(newVal, oldVal) {
      alert(newVal === 'my-search-query');
    }
 }
});
</code>```

Thanks to @samayo for pointing me in the right direction!

Body:
I have a very simple page, just a few lines of code and I would like to use vue-router without a vue-component.

I would like to get the string "my-search-query" after the root:

www.example.com/my-search-query

and use it in my main Vue() object. Is this possible?

Thank you!

Body:
It is possible to use vue-router without a vue-component and still be notified about path changes in the main Vue() app object:

You can get the "my-search-query" string from www.example.com/#/my-search-query like this:

const router = new VueRouter({
  routes: [
    { path: '/:question' }
  ]
})

const app = new Vue({
  el: '#app',
  router,
  watch: {
    '$route.params.question': function(newVal, oldVal) {
      alert(newVal === 'my-search-query');
    }
 }
});

Thanks to @samayo for pointing me in the right direction!


问:
What is meant by a transport independent/dependent protocol?
I am a beginner in web services and network protocols. I have come across a term called "transport independent" as in "SOAP is known as a transport-independent messaging protocol".

I googled a lot of sites, but I could not find an appropriate explanation for the same ? Could anyone explain me what the term means ?

Thanks in advance..

答: Would like to put my understanding as simple to the help the question. Web service is typically to provide the communication between two or more applications. Two or more systems means, they do have there own run time and those run times can be in any platform and built on different languages. In a scenario they communicate each other by exchanging data. REST and SOAP are the web services uses existing communication layers like HTTP, FTP, etc.. and REST work on HTTP and SOAP is uses any (transport independent) that available but most of the applications use HTTP. How we can configure communication protocol in case of SOAP? Each language has its own support in doing so. Would like hear more on this.</p>


问:
Laravel 5.5 Validation change format of response when validation fails
In Laravel 5.4, we created a class that all our requests for validation inherited because we needed to customize our response.

```<code>class APIRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Response on failure
     *
     * @param array $errors
     * @return Response
     */
    public function response(array $errors) {
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }
        return Response::json($response);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}
</code>```

A sample request that would extend this is shown below

```<code>class ResultsGetTermsRequest extends APIRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'school_id' => 'required|integer',
            'student_id' => 'required|integer',
        ];
    }
}
</code>```

And then our sample response on failure would be

```<code>{
    "status": "FAILED",
    "code": "400",
    "messages": [
        [
            "The school id field is required."
        ],
        [
            "The student id field is required."
        ]
    ],
    "result": []
}
</code>```

However, this doesn't work anymore with Laravel 5.5. I noticed they replaced with response method with failedValidation. This however isn't returning any response when the request isn't validated. If I un-comment the print_r, it is something is returned. It seems the only line that is never executed is the return statement. What am I missing?

```<code> public function failedValidation(Validator $validator) {

        $errors = (new ValidationException($validator))->errors();
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }
        //print_r($response);
        return Response::json($response);
    }
</code>```

答:
I guess as per laravel upgrade guide we should return HttpResponseException

```<code>protected function failedValidation(Validator $validator)
{
    $errors = $validator->errors();
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }

    throw new HttpResponseException(response()->json($response));
}
</code>```

Body:
In Laravel 5.4, we created a class that all our requests for validation inherited because we needed to customize our response.

class APIRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Response on failure
     *
     * @param array $errors
     * @return Response
     */
    public function response(array $errors) {
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }
        return Response::json($response);
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

A sample request that would extend this is shown below

class ResultsGetTermsRequest extends APIRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'school_id' => 'required|integer',
            'student_id' => 'required|integer',
        ];
    }
}

And then our sample response on failure would be

{
    "status": "FAILED",
    "code": "400",
    "messages": [
        [
            "The school id field is required."
        ],
        [
            "The student id field is required."
        ]
    ],
    "result": []
}

However, this doesn't work anymore with Laravel 5.5. I noticed they replaced with response method with failedValidation. This however isn't returning any response when the request isn't validated. If I un-comment the print_r, it is something is returned. It seems the only line that is never executed is the return statement. What am I missing?

 public function failedValidation(Validator $validator) {

        $errors = (new ValidationException($validator))->errors();
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }
        //print_r($response);
        return Response::json($response);
    }

Body:
I guess as per laravel upgrade guide we should return HttpResponseException

protected function failedValidation(Validator $validator)
{
    $errors = $validator->errors();
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }

    throw new HttpResponseException(response()->json($response));
}


问:
How to show two properties when filtering a list in Angular
I am trying to show two properties of an object. To do this, I am filtering from an array using another one of it's properties. I found a solution on here but it only works for a single property.

Here is a sample code

```<code>controller.js
$scope.people= [{name, last_name, code}, {name, last_name, code}];

view
<tr ng-repeat="item in transactions | filter:search">
  <td>{{(people| filter : {code:item.person_code}:true)[0].name}}</td>
</tr>
</code>```

I want to be able to show not only the name but also the last_name. Separated by comma if possible.

Right now it works but I am only displaying the name and I don't know how to display more than one property.

Is this even possible???

答:
Please try this.

Data:

```<code>$scope.people= [{name:"SUN", last_name:"SS", code:"101"},
 {name:"MOON", last_name:"MM", code:"103"},{name:"ION",
 last_name:"IO", code:"105"}];
$scope.transactions= [{person_code:"105"}, {person_code:"103"}];
</code>```

Filter:

```<code>filter('pFilter',function(){
return function(input,trans) {
var result =[];
angular.forEach(trans,function(item){
angular.forEach(input,function(p){
if(p.code == item.person_code)
result.push(p);
});
});
return result;
}
})
</code>```

HTML:

```<code>   <input ng-model="search"/>
   <table>
    <tr ng-repeat="p in people | filter:search|pFilter:transactions ">
    <td>{{$index +1}}. {{p.name}}: {{p.last_name}}</td>
   </tr>
   </table>
</code>```

Hope this works if data is big and you want to display more in table.

Body:
I am trying to show two properties of an object. To do this, I am filtering from an array using another one of it's properties. I found a solution on here but it only works for a single property.

Here is a sample code

controller.js
$scope.people= [{name, last_name, code}, {name, last_name, code}];

view

  {{(people| filter : {code:item.person_code}:true)[0].name}}

I want to be able to show not only the name but also the last_name. Separated by comma if possible.

Right now it works but I am only displaying the name and I don't know how to display more than one property.

Is this even possible???

Body:
Please try this.

Data:

$scope.people= [{name:"SUN", last_name:"SS", code:"101"},
 {name:"MOON", last_name:"MM", code:"103"},{name:"ION",
 last_name:"IO", code:"105"}];
$scope.transactions= [{person_code:"105"}, {person_code:"103"}];

Filter:

filter('pFilter',function(){
return function(input,trans) {
var result =[];
angular.forEach(trans,function(item){
angular.forEach(input,function(p){
if(p.code == item.person_code)
result.push(p);
});
});
return result;
}
})

HTML:

   <input ng-model="search"/>
   <table>
    <tr ng-repeat="p in people | filter:search|pFilter:transactions ">
    <td>{{$index +1}}. {{p.name}}: {{p.last_name}}</td>
   </tr>
   </table>

Hope this works if data is big and you want to display more in table.


问:
if-modified-since request header drupal 7
I want to add 'If-modified-since' header to all requests in Drupal 7.
Then I need to response with 304/200 status code dependancy on LastModiﬁed response header.

I tried implement it via hook_boot(). But this code doesn't work:
    function custom_views_hooks_boot() {
    //
}

I debugged with x debag, and it turned out that the code inside the function does not even run.

答:
1 - Create file into DRUPAL_ROOT/includes (by example : custom_bootstrap.inc)

2 - Edit DRUPAL_ROOT/index.php

```<code>require_once DRUPAL_ROOT . '/includes/custom_bootstrap.inc';
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();
</code>```

3 - Do your stuff into custom_bootstrap.inc

```<code>header('If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT');
</code>```

4 - Optionnaly if you need some drupal database function , include mini bootstrap :

```<code>require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
</code>```

Body:
1 - Create file into DRUPAL_ROOT/includes (by example : custom_bootstrap.inc)

2 - Edit DRUPAL_ROOT/index.php

require_once DRUPAL_ROOT . '/includes/custom_bootstrap.inc';
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

3 - Do your stuff into custom_bootstrap.inc

header('If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT');

4 - Optionnaly if you need some drupal database function , include mini bootstrap :

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);


问:
Using IN clause with PIG FILTER
Does PIG support IN clause?

```<code>filtered = FILTER bba BY reason not in ('a','b','c','d');
</code>```

or should i split it up into multiple OR's?

Thanks!

答:
you can do this likes:

```<code>X = FILTER bba BY NOT reason IN ('a','b','c','d');
</code>```

more info

Title: Using IN clause with PIG FILTER

Body:
Does PIG support IN clause?

filtered = FILTER bba BY reason not in ('a','b','c','d');

or should i split it up into multiple OR's?

Thanks!

Body:
you can do this likes:

X = FILTER bba BY NOT reason IN ('a','b','c','d');

more info


问:
Nextcloud notifications
I'm working in a project in which I need to record files information in the database whenever a file is added or modified so they remain synchronized. Those files are suposed to be stored in a Nextcloud server so, does Nextcloud have a way to notificate those changes (e.g. a webhook)? If it doesn't, could I achieve something similar using the webdav protocol?</p>

答: Yes, there is a hook mechanism, see postCreate (\OCP\Files\Node $node) on https://docs.nextcloud.com/server/12/developer_manual/app/hooks.html

Title: Nextcloud notifications


问:
Rest function fails before the start
Making API Rest testing, sometimes I meet with a situation, when a Rest function fails, but even the first breakpoint in it is not reached. Obviously, some preliminary settings fail. But what exactly?

Here is the header of the function:

```<code>@RequestMapping(value = { "/export" }, method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
public Object exportConfiguration(@RequestBody ConfigurationExport configurationExport) {
    try {
        // at return here stands the breakpoint that is never reached:
        return configurationExporterProvider.export(configurationExport);
</code>```

The body of request is:

```<code>{}
</code>```

As a response I am getting:

```<code>            <td>HTTP ERROR: 415 Unsupported Media Type
                <p>Problem accessing /cc/api/configuration/export
                    <pre id="message">Unsupported Media Type```
```

<p>OK, thought I - something happens when trying to load the body into configurationExport.  But there is no throwing errors in that class constructor:</p>

```private ConfigurationExport() {
    documentTypes = new ArrayList<>();
    valueSets = new ArrayList<>();
    configuration = new Configuration();
}
```

And setters and getters created by Lombok. And Lombok, surely, does not know anything about any Media Types.

I agree with application returning me the response with an error message. But where does it appear? Where and how should I look for it?

答: Before your method is called, Spring performs several Validations of the request, and the request headers. You can set a breakpoint in the Spring class method org.springframework.web.servlet.DispatcherServlet.doDispatch() to debug that, if you need.

Title: Rest function fails before the start

Body:
Making API Rest testing, sometimes I meet with a situation, when a Rest function fails, but even the first breakpoint in it is not reached. Obviously, some preliminary settings fail. But what exactly?

Here is the header of the function:

@RequestMapping(value = { "/export" }, method = RequestMethod.POST, produces = "text/plain;charset=UTF-8")
public Object exportConfiguration(@RequestBody ConfigurationExport configurationExport) {
    try {
        // at return here stands the breakpoint that is never reached:
        return configurationExporterProvider.export(configurationExport);

The body of request is:

{}

As a response I am getting:

            HTTP ERROR: 415 Unsupported Media Type

Problem accessing /cc/api/configuration/export

Unsupported Media Type

OK, thought I - something happens when trying to load the body into configurationExport.  But there is no throwing errors in that class constructor:

private ConfigurationExport() {
    documentTypes = new ArrayList<>();
    valueSets = new ArrayList<>();
    configuration = new Configuration();
}

And setters and getters created by Lombok. And Lombok, surely, does not know anything about any Media Types.

I agree with application returning me the response with an error message. But where does it appear? Where and how should I look for it?


问:
change FMI variable/function during simulation
I have a simple FMU file which contains a sine block that takes u as input and outputs y. In this case, u is set to equal to time. In my C++ code I have loaded the FMI library from FMILibrary and had done all the necessary steps up to a point where I want to give my input u a new value of pi(as 3.14). So I went:

```<code>fmistatus = fmi2_import_set_real(fmu, &uRef, 1, &pi);
while (timeCurrent < timeEnd){
    fmistatus = fmi2_import_do_step(fmu, timeCurrent , stepSize, fmi2_true);
    timeCurrent += stepSize;
}
</code>```

u was still set to time even though I tried to give it a new value. Did I miss something?

PS. Is there anywhere I can find a more detailed description on the FMI library functions? Currently I can only find input output descriptions or did I miss something again.

UPDATE: After a few trials, I think this issue might be because I was trying to redefine my equation u = time. In other words when I change my u variable into RealInput block in openmodelica everything goes fine. So what if I really wants to redefine a certain equation? what do I have to do?

答:
You shall not be able to set any variable in FMI - and especially not a variable with a binding equation - and I assume your Modelica model has "u=time;". Instead of having "u=time" you need to add a top-level input without any equation (so that the exported FMI has it as an input) - and then connect that to the sine-block.

Details:
For a co-simulation FMI the restriction on what you can set are in the state-diagram in section 4.2.4 of FMI2 specification.

Between fmi2DoStep you can only set Real variables that have causality="input" or causality="parameter" and variability="tunable" - and an input with an equation doesn't qualify.

Before starting the integration you could set it for other variables as well, but that is only guess-values for the initialization - and should not over-write the "u=time" equation.

Body:
I have a simple FMU file which contains a sine block that takes u as input and outputs y. In this case, u is set to equal to time. In my C++ code I have loaded the FMI library from FMILibrary and had done all the necessary steps up to a point where I want to give my input u a new value of pi(as 3.14). So I went:

fmistatus = fmi2_import_set_real(fmu, &uRef, 1, &pi);
while (timeCurrent < timeEnd){
    fmistatus = fmi2_import_do_step(fmu, timeCurrent , stepSize, fmi2_true);
    timeCurrent += stepSize;
}

u was still set to time even though I tried to give it a new value. Did I miss something?

PS. Is there anywhere I can find a more detailed description on the FMI library functions? Currently I can only find input output descriptions or did I miss something again.

UPDATE: After a few trials, I think this issue might be because I was trying to redefine my equation u = time. In other words when I change my u variable into RealInput block in openmodelica everything goes fine. So what if I really wants to redefine a certain equation? what do I have to do?


问:
Combinations with repetition of letters with weight from list
I have four letters with different weights as

```<code>letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]
</code>```

I want to get the combinations of letters which weight = 2. The letter can be repeatedly chose and order is not important. The result can be list or array or any forms but with this combinations

```<code>comb_w2 = ['CC','NN','NC','O','S']
</code>```

Here C and N has weight = 1 so combining two letters have weight = 2: The possible combinations are 'CC','NN','NC'

O and S has weight = 2 already so it cannot combine with other letters. Is there any libraries for calculating this? I saw itertools but it gives only the number of possibility, not the combinations.

答:
Try the following code:

```<code>def find_combinations(letter_list, weight_list, weignt_sum):
    output_list = []
    letter_weight_dict = dict(zip(letter_list,weight_list))
    for key, val in letter_weight_dict.items():
        for key1, val1 in letter_weight_dict.items():
            if val+val1 == weignt_sum:
                if (key + key1)[::-1] not in output_list:
                    output_list.append(key+key1)
            if val == weignt_sum:
                output_list.append(key)
    return set(output_list)

letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]
combinations = find_combinations(letters, weights_of_l, 2)
print combinations
</code>```

I got the following output:

['CC', 'S', 'NN', 'CN', 'O']

This may not be the best way to do this.

Body:
I have four letters with different weights as

letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]

I want to get the combinations of letters which weight = 2. The letter can be repeatedly chose and order is not important. The result can be list or array or any forms but with this combinations

comb_w2 = ['CC','NN','NC','O','S']

Here C and N has weight = 1 so combining two letters have weight = 2: The possible combinations are 'CC','NN','NC'

O and S has weight = 2 already so it cannot combine with other letters. Is there any libraries for calculating this? I saw itertools but it gives only the number of possibility, not the combinations.

Body:
Try the following code:

def find_combinations(letter_list, weight_list, weignt_sum):
    output_list = []
    letter_weight_dict = dict(zip(letter_list,weight_list))
    for key, val in letter_weight_dict.items():
        for key1, val1 in letter_weight_dict.items():
            if val+val1 == weignt_sum:
                if (key + key1)[::-1] not in output_list:
                    output_list.append(key+key1)
            if val == weignt_sum:
                output_list.append(key)
    return set(output_list)

letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]
combinations = find_combinations(letters, weights_of_l, 2)
print combinations

I got the following output:

['CC', 'S', 'NN', 'CN', 'O']

This may not be the best way to do this.


问:
How to set condition on UI route in angularjs
I'm new in angular and working on UI routing. My issue is how to set condition when user route to new state. What i want is, when user submit the form it should authenticate form data through Mobile OTP popup before going to next state. In my code everything works fine till form but when user submit form, otp popup open but its get hide when its route to new state. So i think i need to put some condition when user go to next state.
Here are my codes

//APP.JS FILE

```<code>.state('main.step4', {
        url: '/step2/step3/step4',
        templateUrl: 'pages/step4.html'
        }
</code>```

//Controller.js

```<code>$scope.getStep2Form = function($index, selectCarList) {
            $scope.selectCar.step2Form = selectCarList;
            $scope.step2Data = $scope.selectCar;
            console.log($scope.step2Data);
        }
        $scope.getStep3Form = function(step3FormData) {
            $scope.selectCar.step3Data = step3FormData;
            console.log($scope.selectCar);

        }
        $scope.showotp=function(){
            open_modal_menu()
        }
</code>```

//CUSTOM.js

```<code>function open_modal_menu() {
            $('.modal-menu').toggleClass('active-modal-menu');
            $('.modal-menu-overlay').addClass('active-overlay');
        }
</code>```

//SERVICES.js

```<code>angular.module('carmobApp.services', [])

.factory('carListDataFactry', function($http) {

var carListData = [];
return {
  all: function() {
    return $http.get("scripts/content.json").then(function(response) {
      carListData = response.data;
      //console.log(teamListData);
      return carListData;
    });

  },
  get: function(selectCarId) {
    for (var i = 0; i < carListData.length; i++) {
      if (carListData[i].id === parseInt(selectCarId)) {
        //console.log(carListData[i]);
        return carListData[i];
      }
    }
    return null;
  }

};
});
</code>```

//HTML

```<code><a ui-sref="main.step4" class="button button-green button-full button-icon submitBtn" ng-model="selectCar.step3Data" ng-click="showotp(); getStep3Form(step3FormData)" ng-disabled="selectCarform.$invalid">
    <i class="ion-arrow-right-c" style="color:#fff;"></i> PROCEED NEXT
</a>
</code>```

答:
You can use the $transition hooks to catch the page transition:

```<code>$transitions.onStart({to: 'main.step4' }, function(transition) {
    if(!user.isAuthenticated()) //if going to the last step and user is not authenticated
        return false; //abort the transition
});

}
</code>```

When the user authenticates you can use $state.go('main.step4') and continue the normal behaviuor.

Usually $transition is used to verify if the user has the right permissions for going to the next page, and if not redirect to a login (if not authenticated) or home page (if not authorized).

I understand that what you want to accomplish is a "login on the fly", I'm right? If that's the case you should reconsider your app flow and think of a login state which remembers where you were and knows where you want to go.

Body:
I'm new in angular and working on UI routing. My issue is how to set condition when user route to new state. What i want is, when user submit the form it should authenticate form data through Mobile OTP popup before going to next state. In my code everything works fine till form but when user submit form, otp popup open but its get hide when its route to new state. So i think i need to put some condition when user go to next state.
Here are my codes

//APP.JS FILE

.state('main.step4', {
        url: '/step2/step3/step4',
        templateUrl: 'pages/step4.html'
        }

//Controller.js

$scope.getStep2Form = function($index, selectCarList) {
            $scope.selectCar.step2Form = selectCarList;
            $scope.step2Data = $scope.selectCar;
            console.log($scope.step2Data);
        }
        $scope.getStep3Form = function(step3FormData) {
            $scope.selectCar.step3Data = step3FormData;
            console.log($scope.selectCar);

        }
        $scope.showotp=function(){
            open_modal_menu()
        }

//CUSTOM.js

function open_modal_menu() {
            $('.modal-menu').toggleClass('active-modal-menu');
            $('.modal-menu-overlay').addClass('active-overlay');
        }

//SERVICES.js

angular.module('carmobApp.services', [])

.factory('carListDataFactry', function($http) {

var carListData = [];
return {
  all: function() {
    return $http.get("scripts/content.json").then(function(response) {
      carListData = response.data;
      //console.log(teamListData);
      return carListData;
    });

  },
  get: function(selectCarId) {
    for (var i = 0; i < carListData.length; i++) {
      if (carListData[i].id === parseInt(selectCarId)) {
        //console.log(carListData[i]);
        return carListData[i];
      }
    }
    return null;
  }

};
});

//HTML

     PROCEED NEXT

Body:
You can use the $transition hooks to catch the page transition:

$transitions.onStart({to: 'main.step4' }, function(transition) {
    if(!user.isAuthenticated()) //if going to the last step and user is not authenticated
        return false; //abort the transition
});

}

When the user authenticates you can use $state.go('main.step4') and continue the normal behaviuor.

Usually $transition is used to verify if the user has the right permissions for going to the next page, and if not redirect to a login (if not authenticated) or home page (if not authorized).

I understand that what you want to accomplish is a "login on the fly", I'm right? If that's the case you should reconsider your app flow and think of a login state which remembers where you were and knows where you want to go.


问:
I need someone who explain me these lines of code
I need someone who explain me this code, line by line. I specially don't understand this line:

```<code>operator std::map<T, U>()
</code>```

Thank you very much.

```<code>template <typename T, typename U>
class create_map
{
    std::map<T, U> m_map;
public:
    create_map(const T& key, const U& val)
    {
        m_map[key] = val;
    }
    create_map<T, U>& operator()(const T& key, const U& val)
    {
        m_map[key] = val;
        return *this;
    }
    operator std::map<T, U>()
    {
        return m_map;
    }
};
</code>```

答:
Code:

```<code>template <typename T, typename U>
class create_map
{
    std::map<T, U> m_map;
public:
    create_map(const T& key, const U& val)
    {
        m_map[key] = val;
    }
    create_map<T, U>& operator()(const T& key, const U& val)
    {
        m_map[key] = val;
        return *this;
    }
    operator std::map<T, U>()
    {
        return m_map;
    }
};
</code>```

The purpose of this code is to be able to specify a map with specific key/value pairs, by chaining calls to operator(), like

```<code>create_map<int, std::string>( 1, "blah" )( 2, "hah" )( 3, "doh" )
</code>```

Since the class does not have a default constructor, there's no way to use it to create an empty map. That may be by design. Or it may be a design error.

The

```<code>operator std::map<T, U>()
{
    return m_map;
}
</code>```

defines a conversion to std::map<T, U>, which is the end result of it all.

It can be invoked implicitly wherever a create_map is specified and a std::map is expected, such as using a create_map expression as argument in a function call.

However, it can be pretty inefficient since it copies the map. The compiler may well optimize away the copying. But it’s ungood to needlessly rely on Quality Of Implementation (although sometimes that is the best that one can do).

So it should instead be

```<code>operator std::map<T, U> const& () const
{
    return m_map;
}
</code>```

The const at the end there allows a create_map to be declared as const and used.

With this conversion to reference there is the same problem as with using reference arguments, namely a theoretical possibility of aliasing, where code that retains a reference to const is not prepared to deal with changes of the referred object. But in practice it’s not a problem. For example, as formal argument one just writes std::string const& s (instead of just std::string s) as a matter of course, and very few if any errors result from that – I’ve never experienced any problem.

Cheers & hth.,

ContentLicense: CC BY-SA 2.5

Body:
I need someone who explain me this code, line by line. I specially don't understand this line:

operator std::map<T, U>()

Thank you very much.

template <typename T, typename U>
class create_map
{
    std::map<T, U> m_map;
public:
    create_map(const T& key, const U& val)
    {
        m_map[key] = val;
    }
    create_map<T, U>& operator()(const T& key, const U& val)
    {
        m_map[key] = val;
        return *this;
    }
    operator std::map<T, U>()
    {
        return m_map;
    }
};

Body:
Code:

template <typename T, typename U>
class create_map
{
    std::map<T, U> m_map;
public:
    create_map(const T& key, const U& val)
    {
        m_map[key] = val;
    }
    create_map<T, U>& operator()(const T& key, const U& val)
    {
        m_map[key] = val;
        return *this;
    }
    operator std::map<T, U>()
    {
        return m_map;
    }
};

The purpose of this code is to be able to specify a map with specific key/value pairs, by chaining calls to operator(), like

create_map<int, std::string>( 1, "blah" )( 2, "hah" )( 3, "doh" )

Since the class does not have a default constructor, there's no way to use it to create an empty map. That may be by design. Or it may be a design error.

The

operator std::map<T, U>()
{
    return m_map;
}

defines a conversion to std::map<T, U>, which is the end result of it all.

It can be invoked implicitly wherever a create_map is specified and a std::map is expected, such as using a create_map expression as argument in a function call.

However, it can be pretty inefficient since it copies the map. The compiler may well optimize away the copying. But it’s ungood to needlessly rely on Quality Of Implementation (although sometimes that is the best that one can do).

So it should instead be

operator std::map<T, U> const& () const
{
    return m_map;
}

The const at the end there allows a create_map to be declared as const and used.

With this conversion to reference there is the same problem as with using reference arguments, namely a theoretical possibility of aliasing, where code that retains a reference to const is not prepared to deal with changes of the referred object. But in practice it’s not a problem. For example, as formal argument one just writes std::string const& s (instead of just std::string s) as a matter of course, and very few if any errors result from that – I’ve never experienced any problem.

Cheers & hth.,


问:
Unable to get maxheight on resize
I have html and script like this. I want box1 box2 box display with the same height. But when I resize browser to check, the max height is not correct.

```<code><div class="pro_intro>"
   <div class="box box1">
     something 1
   </div>
   <div class="box box2">
     something 2
   </div>
   <div class="box box3">
     something 3
   </div>
</div>

$(window).on("resize", function () {
        var max = -1;
        $(".pro_intro .box").each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        $(".pro_intro .box").css("height",max);
        $(".pro_intro .box").css({'visibility':'visible'});
}).resize();
</code>```

Any suggestion for this. Thank you so much

答:
The problem with your current code is you are missing the closing double quote for
, which makes your code invalid, hence jQuery fails to work properly.

Also, there's a minor conceptual flaw with your script: you're not resetting the height of the divs. Which means .outerHeight() returns the current set height (by the previous iteration), not the height needed for your content if the element had height:auto. Here's the fix for it, using your (wrong, IMHO,) approach:

$(window).on("resize", function() {
  var max = -1;
  $(".pro_intro .box")
    .height('auto')
    .each(function() {
      max = Math.max(
        $(this).outerHeight(),
        max
      );
    });
  $(".pro_intro .box").css({
    height: max + 'px',
    visibility: 'visible'
  });
}).resize();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pro_intro .box {
  display: inline-block;
  float: left;
  width: 33.33%;
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.1);
  padding: 1rem;
}</code>```

    something 1

    something 2

    something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3
    something 3 something 3 something 3

```
</div>
</div>
</p>

<p>I said "wrong approach" because I advise you not to use JavaScript for this task. A bound listener on <code>resize</code> is really something you want to avoid for performance sake. You should at least throttle it.</p>

<hr>

<p>I would use flexbox for the task:</p>

<pre class="lang-css prettyprint-override"><code>.pro_intro {
  display: flex;
  align-items: stretch;
}
</code>```

Here's an example:

.pro_intro {
  display: flex;
  /* totally optional:
    min-height: 35vh;
  */
  justify-content: center;
  align-items: stretch;
}

.pro_intro>.box {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid rgba(0,0,0,.1);
  flex-direction: column;
  margin: 0 .5rem;
  padding: 0 .75rem;
}
@media (max-width: 767px) {
  .pro_intro {
    flex-wrap: wrap;
  }
  .pro_intro .box {
    flex: 1 0 51%;
    margin: .5rem;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pro_intro">
  <div class="box box1">
    <p>something 1
  </div>
  <div class="box box2">
    <p>something 2
  </div>
  <div class="box box3">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. In nibh mauris cursus mattis molestie a iaculis at. Morbi enim nunc faucibus a pellentesque sit amet porttitor eget. Donec pretium vulputate sapien nec. A pellentesque sit amet porttitor eget dolor morbi. Amet nisl suscipit adipiscing bibendum est ultricies integer quis auctor. Dui id ornare arcu odio ut sem nulla pharetra. Massa vitae tortor condimentum lacinia quis vel eros donec ac. Arcu bibendum at varius vel pharetra vel. Et odio pellentesque diam volutpat. Tempus egestas sed sed risus pretium quam vulputate. Sed velit dignissim sodales ut eu sem integer. Sit amet risus nullam eget felis eget nunc lobortis.
  </div>
</div></code>```

Title: Unable to get maxheight on resize

Body:
I have html and script like this. I want box1 box2 box display with the same height. But when I resize browser to check, the max height is not correct.

"

     something 1

     something 2

     something 3

$(window).on("resize", function () {
        var max = -1;
        $(".pro_intro .box").each(function() {
            var h = $(this).outerHeight();
            max = h > max ? h : max;
        });
        $(".pro_intro .box").css("height",max);
        $(".pro_intro .box").css({'visibility':'visible'});
}).resize();

Any suggestion for this. Thank you so much

Body:
The problem with your current code is you are missing the closing double quote for <div class="pro_intro>, which makes your code invalid, hence jQuery fails to work properly.

Also, there's a minor conceptual flaw with your script: you're not resetting the height of the divs. Which means .outerHeight() returns the current set height (by the previous iteration), not the height needed for your content if the element had height:auto. Here's the fix for it, using your (wrong, IMHO,) approach:

$(window).on("resize", function() {
  var max = -1;
  $(".pro_intro .box")
    .height('auto')
    .each(function() {
      max = Math.max(
        $(this).outerHeight(),
        max
      );
    });
  $(".pro_intro .box").css({
    height: max + 'px',
    visibility: 'visible'
  });
}).resize();

.pro_intro .box {
  display: inline-block;
  float: left;
  width: 33.33%;
  box-sizing: border-box;
  border: 1px solid rgba(0, 0, 0, 0.1);
  padding: 1rem;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pro_intro">
  <div class="box box1">
    something 1
  </div>
  <div class="box box2">
    something 2
  </div>
  <div class="box box3">
    something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3 something 3
    something 3 something 3 something 3
  </div>
</div>

I said "wrong approach" because I advise you not to use JavaScript for this task. A bound listener on resize is really something you want to avoid for performance sake. You should at least throttle it.

I would use flexbox for the task:

.pro_intro {
  display: flex;
  align-items: stretch;
}

Here's an example:

.pro_intro {
  display: flex;
  /* totally optional:
    min-height: 35vh;
  */
  justify-content: center;
  align-items: stretch;
}

.pro_intro>.box {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid rgba(0,0,0,.1);
  flex-direction: column;
  margin: 0 .5rem;
  padding: 0 .75rem;
}
@media (max-width: 767px) {
  .pro_intro {
    flex-wrap: wrap;
  }
  .pro_intro .box {
    flex: 1 0 51%;
    margin: .5rem;
  }
}

<div class="pro_intro">
  <div class="box box1">
    <p>something 1
  </div>
  <div class="box box2">
    <p>something 2
  </div>
  <div class="box box3">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. In nibh mauris cursus mattis molestie a iaculis at. Morbi enim nunc faucibus a pellentesque sit amet porttitor eget. Donec pretium vulputate sapien nec. A pellentesque sit amet porttitor eget dolor morbi. Amet nisl suscipit adipiscing bibendum est ultricies integer quis auctor. Dui id ornare arcu odio ut sem nulla pharetra. Massa vitae tortor condimentum lacinia quis vel eros donec ac. Arcu bibendum at varius vel pharetra vel. Et odio pellentesque diam volutpat. Tempus egestas sed sed risus pretium quam vulputate. Sed velit dignissim sodales ut eu sem integer. Sit amet risus nullam eget felis eget nunc lobortis.
  </div>
</div>


问:
split a column into multiple columns - tidyr - error
I am trying to split the first column based on . using separate function from tidyr.

However, I am unable to split as I wanted. I included a sample input and the code I tried.

I have also tried using extra parameter but I couldn't able to get the desired output.

Any suggestions would be appreciated.

input

```<code>var       name      tis      score
1       c.1.2.mi1.mi1_dup1.er.er2.er33.0..      t1      9.382828892992
2       c.2.2.mi1.mi1_dup1.er.er2.er33.0..      t2      99.382828892992
3       c.3.2.mi1.mi1_dup1.er.er2.er33.0..      t3      19.382828892992
</code>```

output

```<code>1       c       1       2       mi1     mi1_dup1        er      er2     er33    0      t1      9.382828892992
2       c       2       2       mi1     mi1_dup1        er      er2     er33    0      t2      99.382828892992
3       c       3       2       mi1     mi1_dup1        er      er2     er33    0      t3      19.382828892992
</code>```

code

```<code>input %>% separate("name", ".")
</code>```

error

```<code>Warning message:
Too many values at 6 locations: 1, 2, 3
</code>```

答:
You haven't named the 11 output columns:</p>

```<code>> input %>% separate(name,into=letters[1:11], sep="\\.")
  var a b c   d   e    f  g   h    i j k tis     score
1   1 c 1 2 mi1 mi1 dup1 er er2 er33 0    t1  9.382829
2   2 c 2 2 mi1 mi1 dup1 er er2 er33 0    t2 99.382829
3   3 c 3 2 mi1 mi1 dup1 er er2 er33 0    t3 19.382829
</code>```

Body:
I am trying to split the first column based on . using separate function from tidyr.

However, I am unable to split as I wanted. I included a sample input and the code I tried.

I have also tried using extra parameter but I couldn't able to get the desired output.

Any suggestions would be appreciated.

input

var       name      tis      score
1       c.1.2.mi1.mi1_dup1.er.er2.er33.0..      t1      9.382828892992
2       c.2.2.mi1.mi1_dup1.er.er2.er33.0..      t2      99.382828892992
3       c.3.2.mi1.mi1_dup1.er.er2.er33.0..      t3      19.382828892992

output

1       c       1       2       mi1     mi1_dup1        er      er2     er33    0      t1      9.382828892992
2       c       2       2       mi1     mi1_dup1        er      er2     er33    0      t2      99.382828892992
3       c       3       2       mi1     mi1_dup1        er      er2     er33    0      t3      19.382828892992

code

input %>% separate("name", ".")

error

Warning message:
Too many values at 6 locations: 1, 2, 3

Body:
You haven't named the 11 output columns:

> input %>% separate(name,into=letters[1:11], sep="\\.")
  var a b c   d   e    f  g   h    i j k tis     score
1   1 c 1 2 mi1 mi1 dup1 er er2 er33 0    t1  9.382829
2   2 c 2 2 mi1 mi1 dup1 er er2 er33 0    t2 99.382829
3   3 c 3 2 mi1 mi1 dup1 er er2 er33 0    t3 19.382829


问:
How do I make a Hazelcast client wait for the server to start up?
I have a Hazelcast client application which will sometimes be started before any server in the cluster. Before I start building this myself.

Is there any built in support in Hazelcast to make the client wait for the cluster to start up and then connect to it?

答:
I found this and it worked for me:
    <hz:network connection-attempt-limit="50"
      connection-attempt-period="5000"
      connection-timeout="1000"
      redo-operation="true">
   <hz:member>


问:
Force property to null
I assume the following would set the destination to null, but it doesn't. What's wrong?

```<code>.ForMember(m => m.prop1, opt => opt.MapFrom<MyType>(src => null))
</code>```

答:
To set a certain fixed value, use UseValue. Note that the fixed value will be set once on configuration.

```<code>.ForMember(m => m.prop1, opt => opt.UseValue(null))
</code>```

See also Understanding UseValue in AutoMapper.

Title: Force property to null

Body:
I assume the following would set the destination to null, but it doesn't. What's wrong?

.ForMember(m => m.prop1, opt => opt.MapFrom<MyType>(src => null))

Body:
To set a certain fixed value, use UseValue. Note that the fixed value will be set once on configuration.

.ForMember(m => m.prop1, opt => opt.UseValue(null))

See also Understanding UseValue in AutoMapper.


问:
How can i set global get variable in jsp
I make jsp pages and in that jsp page I have form with post method.

After form submission my get variable unset(naturally).Is there any way to keep get variable after form submission?

my code:

```<code><form method="POST" >
<input type="hidden" name="qty" value="10" />
                        <input type="text" name="eprice" value="3600" />
                        <input type="text" name="tprice" value="36000" />
                        <input type="text" name="type" value="request" />
<input type="submit" value="save" />
</form>
</code>```

After form submission I need url parameters too.

Here is my url before:

http://localhost:8080/q/product.jsp?page=2&saved=1

After form submission get variable unsets and url will changed to:

http://localhost:8080/q/product.jsp

How to keep get data after form submission and still access url parameters?

In php we simply do :

$_GET['page']=2;

How can we handle it in JSP?

答:
Java equivalent for PHP $_GET['page']=2; is

```<code>request.getParameter('page');
</code>```

request is an implicit object in jsp.

Body:
I make jsp pages and in that jsp page I have form with post method.

After form submission my get variable unset(naturally).Is there any way to keep get variable after form submission?

my code:

<form method="POST" >
<input type="hidden" name="qty" value="10" />
                        <input type="text" name="eprice" value="3600" />
                        <input type="text" name="tprice" value="36000" />
                        <input type="text" name="type" value="request" />
<input type="submit" value="save" />
</form>

After form submission I need url parameters too.

Here is my url before:

http://localhost:8080/q/product.jsp?page=2&saved=1

After form submission get variable unsets and url will changed to:

http://localhost:8080/q/product.jsp

How to keep get data after form submission and still access url parameters?

In php we simply do :

$_GET['page']=2;

How can we handle it in JSP?

Body:
Java equivalent for PHP $_GET['page']=2; is

request.getParameter('page');

request is an implicit object in jsp.


问:
Programmatically set the initial view controller using Storyboards
How do I programmatically set the InitialViewController for a Storyboard? I want to open my storyboard to a different view depending on some condition which may vary from launch to launch.

答:
```<code>let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewController(withIdentifier: "storyBoardid") as! ViewController
let navigationController = UINavigationController(rootViewController: vc)
UIApplication.shared.delegate.window?.rootViewController = navigationController
</code>```

Another way is to present viewController,

```<code>let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewController(withIdentifier: "storyBoardid") as! ViewController
self.present(vc,animated:true,completion:nil)
</code>```

First you need to create object of your storyboard then change root(if required) then you take reference of particular view controller which is pushed current view controller(if you change root) else it's just present new view controller which may you

Body:
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewController(withIdentifier: "storyBoardid") as! ViewController
let navigationController = UINavigationController(rootViewController: vc)
UIApplication.shared.delegate.window?.rootViewController = navigationController

Another way is to present viewController,

let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = mainStoryboard.instantiateViewController(withIdentifier: "storyBoardid") as! ViewController
self.present(vc,animated:true,completion:nil)

First you need to create object of your storyboard then change root(if required) then you take reference of particular view controller which is pushed current view controller(if you change root) else it's just present new view controller which may you


问:
Linux backup script won't run
I am using limux CentOS7 to run a backup script that will create a .tar file and then send the file to an S3 bucket.

However when the cornjob is executed, it only runs half of the script and creates the .tar file but does not upload it to S3.

The backup script;

```<code>TIME=`date +%b-%d-%y`            # This Command will add date in Backup File Nam            e.
FILENAME=backup-$TIME.tar.gz     #define Backup file name format.
SRCDIR=/opt                      # Location of Important Data Directory (Source of             backup).
DESDIR=/home/centos/backupfile   # Destination of backup file.
tar -cvf $DESDIR/$FILENAME $SRCDIR
aws s3 cp /home/centos/backupfile/$FILENAME s3://backup/
</code>```

The cronjob is;

```<code>30 7 * * * /home/centos/backupfile/runbackup
</code>```

When I run the back up file manually by running ./runbackup it works fine and sends the file to an s3 bucket.

I have checked permissions of the .tar file and it all looks fine, not too sure why it wont work. I have tried moving the file locations, changing the cronjob settings but no luck.

Any ideas?

答:
This was answered yesterday with the help of (smscstewart).

We added the below lines which worked fine.

source $HOME/.bash_profile
/usr/local/bin/aws s3 cp /home/centos/backupfile/$FILENAME s3://backup/

Title: Linux backup script won't run

Body:
I am using limux CentOS7 to run a backup script that will create a .tar file and then send the file to an S3 bucket.

However when the cornjob is executed, it only runs half of the script and creates the .tar file but does not upload it to S3.

The backup script;

TIME=`date +%b-%d-%y`            # This Command will add date in Backup File Nam            e.
FILENAME=backup-$TIME.tar.gz     #define Backup file name format.
SRCDIR=/opt                      # Location of Important Data Directory (Source of             backup).
DESDIR=/home/centos/backupfile   # Destination of backup file.
tar -cvf $DESDIR/$FILENAME $SRCDIR
aws s3 cp /home/centos/backupfile/$FILENAME s3://backup/

The cronjob is;

30 7 * * * /home/centos/backupfile/runbackup

When I run the back up file manually by running ./runbackup it works fine and sends the file to an s3 bucket.

I have checked permissions of the .tar file and it all looks fine, not too sure why it wont work. I have tried moving the file locations, changing the cronjob settings but no luck.

Any ideas?


问:
rails 3 custom mime type - default view format
I need to render some views without layout.
To skip line :render :layout=>false and if else logic from controller actions,
i have custom mime type like phtml (plain html).

```<code>Mime::Type.register "text/phtml", :phtml
</code>```

this format need to render the same html views, but only without layout. I complete this with this chunk of code in app. controller:

```<code> before_filter proc { |controller|
  if params[:format] && params[:format]=='phtml'
    controller.action_has_layout = false
    controller.request.format    = 'html'

  end
  }
</code>```

First, this is ugly, second i can't any more control this format from controller in the way:

```<code>respond_to :phtml,:only=>:index
</code>```

because it will always render view with requested format phtml.
is there a better solution? example? how can i alias view formats?

Thank a lot

答:
You can use the layout method in your controller directly:

```<code>class ProductsController < ApplicationController
  layout "product", :except => [:index, :rss]
end
</code>```

Or to use no layout at all:

```<code>class ProductsController < ApplicationController
  layout nil
end
</code>```

Check out the guide for more info.

Body:
I need to render some views without layout.
To skip line :render :layout=>false and if else logic from controller actions,
i have custom mime type like phtml (plain html).

Mime::Type.register "text/phtml", :phtml

this format need to render the same html views, but only without layout. I complete this with this chunk of code in app. controller:

 before_filter proc { |controller|
  if params[:format] && params[:format]=='phtml'
    controller.action_has_layout = false
    controller.request.format    = 'html'

  end
  }

First, this is ugly, second i can't any more control this format from controller in the way:

respond_to :phtml,:only=>:index

because it will always render view with requested format phtml.
is there a better solution? example? how can i alias view formats?

Thank a lot

Body:
You can use the layout method in your controller directly:

class ProductsController < ApplicationController
  layout "product", :except => [:index, :rss]
end

Or to use no layout at all:

class ProductsController < ApplicationController
  layout nil
end

Check out the guide for more info.


答:
Try this:

```<code>with tbl1(id ,cd1)  as (
    Select cd1.id , listagg(cd1.codes ,'#') within group (order by cd1.ID)
     from code1 cd1
     group by cd1.id
  )
  , tbl2(id,cd2) as (
    Select cd2.id as id, listagg(cd2.codes ,'#') within group (order by cd2.ID)
    from code2 cd2
    group by cd2.id
)
SELECT   CS.ID,
         CS.NAME,
         CS.DOB,
         TB1.CD1,
         TB2.CD2
FROM CUSTOMER CS
     INNER JOIN TBL1 TB1
         ON CS.ID = TB1.ID
     INNER JOIN TBL2 TB2
         ON CS.ID = TB2.ID
GROUP BY CS.ID,
         CS.NAME,
         CS.DOB,
         TB1.CD1,
         TB2.CD2 ;
</code>```

SQLFIDDLE

Title: Manipulating resultsets in sql

Body:
I'm trying to achieve the below result in the target table by querying data from three source tables.

Expected Target Table result:

ID  Name    DOB       Codes Table1   Codes Table2
=================================================
A1  Bob   29-8-1972     2#5#8#3       5#8#4#2
-----------------------------------------------
A2  Tim   10/2/1954     4#3#7          1#7#5
-------------------------------------------------

Sources Tables:

CustomerDetails Table

ID  Name    DOB
=========================
A1  Bob    29/08/1972
-------------------------
A2  Tim    10/2/1954
-------------------------

Customer Codes 1

ID  Codes Table1
=================
A1  2
-----------
A1  5
----------------
A1  8
-------------
A1  3
----------
A2  4
--------------
A2  3
-------------
A2  7
-------------

Customer Codes Table 2

ID  Codes Table2
===================
A1  5
--------------
A1  8
--------------
A1  4
-------------
A1  2
--------------
A2  1
--------------
A2  7
---------------
A2  5
----------------

What is the best way to code this over millions of records?

Body:
Try this:

with tbl1(id ,cd1)  as (
    Select cd1.id , listagg(cd1.codes ,'#') within group (order by cd1.ID)
     from code1 cd1
     group by cd1.id
  )
  , tbl2(id,cd2) as (
    Select cd2.id as id, listagg(cd2.codes ,'#') within group (order by cd2.ID)
    from code2 cd2
    group by cd2.id
)
SELECT   CS.ID,
         CS.NAME,
         CS.DOB,
         TB1.CD1,
         TB2.CD2
FROM CUSTOMER CS
     INNER JOIN TBL1 TB1
         ON CS.ID = TB1.ID
     INNER JOIN TBL2 TB2
         ON CS.ID = TB2.ID
GROUP BY CS.ID,
         CS.NAME,
         CS.DOB,
         TB1.CD1,
         TB2.CD2 ;

SQLFIDDLE


答:
@Sneha has a nice and succinct answer, but if you're going to have a lot of combinations then it might be better to to not go too far in creating combinations.  This solution is longer but will run faster for long lists of letters with large goal scores:

```<code>letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]

def get_combos(letters, weights, goal):
    weighted_letters = list(zip(letters, weights))
    combos = set()

    def get_combos(letters, weight):
        for letter, next_weight in weighted_letters:
            total = weight + next_weight
            if total == goal:
                combos.add(''.join(sorted(letters + letter)))
            elif total > goal:
                pass
            else:
                get_combos(letters + letter, weight+next_weight)

    get_combos('',0)
    return combos

print(get_combos(letters, weights_of_l, 3))
</code>```

EDIT: I think this one might be even faster:

```<code>letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]

def get_combos(letters, weights, goal):
    weighted_letters = sorted(zip(weights, letters))
    combos = []

    def get_combos(letters, weight, weighted_letters):
        for i, (next_weight, letter) in enumerate(weighted_letters):
            total = weight + next_weight
            if total == goal:
                combos.append(letters + letter)
            elif total > goal:
                return
            else:
                get_combos(letters+letter, weight+next_weight, weighted_letters[i:])

    get_combos('',0,weighted_letters)
    return combos

print(get_combos(letters, weights_of_l, 3))
</code>```

Title: Combinations with repetition of letters with weight from list

Body:
I have four letters with different weights as

letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]

I want to get the combinations of letters which weight = 2. The letter can be repeatedly chose and order is not important. The result can be list or array or any forms but with this combinations

comb_w2 = ['CC','NN','NC','O','S']

Here C and N has weight = 1 so combining two letters have weight = 2: The possible combinations are 'CC','NN','NC'

O and S has weight = 2 already so it cannot combine with other letters. Is there any libraries for calculating this? I saw itertools but it gives only the number of possibility, not the combinations.

Body:
@Sneha has a nice and succinct answer, but if you're going to have a lot of combinations then it might be better to to not go too far in creating combinations.  This solution is longer but will run faster for long lists of letters with large goal scores:

letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]

def get_combos(letters, weights, goal):
    weighted_letters = list(zip(letters, weights))
    combos = set()

    def get_combos(letters, weight):
        for letter, next_weight in weighted_letters:
            total = weight + next_weight
            if total == goal:
                combos.add(''.join(sorted(letters + letter)))
            elif total > goal:
                pass
            else:
                get_combos(letters + letter, weight+next_weight)

    get_combos('',0)
    return combos

print(get_combos(letters, weights_of_l, 3))

EDIT: I think this one might be even faster:

letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]

def get_combos(letters, weights, goal):
    weighted_letters = sorted(zip(weights, letters))
    combos = []

    def get_combos(letters, weight, weighted_letters):
        for i, (next_weight, letter) in enumerate(weighted_letters):
            total = weight + next_weight
            if total == goal:
                combos.append(letters + letter)
            elif total > goal:
                return
            else:
                get_combos(letters+letter, weight+next_weight, weighted_letters[i:])

    get_combos('',0,weighted_letters)
    return combos

print(get_combos(letters, weights_of_l, 3))


问:
Automatically restore breakpoint ignore count in Eclipse
Breakpoint ignore count in Eclipse breakpoint properties decreases with each pass over breakpoint until it reaches zero. On the next debug launch you have to manually restore ignore count if you wish to stop there again. Is it possible to restore the ignore count to the initial value automatically when the debugger is stopped?

Eclipse version: 4.7.1a

答:
This is a known issue of Eclipse CDT:

Eclipse bug 487053 - Breakpoint's "Ignore count" value changes when the breakpoint is hit

As workaround, you can import breakpoints (right-click in the Breakpoints view and choose Import Breakpoints...) that have been exported before the ignore counts have been decreased with the option Update existing breakpoints.


问:
Prestashop order products sql
Where I can find Prestashop SQL query where they display the products that were bought in order.

Like this:

I'm creating a custom page that shows 100 orders in table. and if clicked on order its shows the products that were ordered. I made an sql query:

```<code>SELECT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        LEFT JOIN ps_product_lang pl on o.product_id = pl.id_product
        LEFT JOIN ps_product p on p.id_product = pl.id_product
        LEFT JOIN ps_stock_available psa on p.id_product = psa.id_product
        LEFT JOIN ps_category_lang c on c.id_category = p.id_category_default
        LEFT JOIN ps_product_supplier ps on p.id_product = ps.id_product
        WHERE pl.id_lang=2 AND c.id_lang=2 AND id_order= '".$q."'
        GROUP BY product_id, kood,nimetus,nr,pl.link_rewrite, kogukogus,asukoht, link
</code>```

But when product has attributes it duplicates products.

In this case iButton has two colors black and red(attributes). In this order only one black iButton was bought with quantity of 20, but It shows three rows.

I tried to fix this, but that arised another problems with my sql query, that when it has no attribute it dosen't show anything.

```<code>SELECT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        JOIN ps_product_lang pl on o.product_id = pl.id_product
        JOIN ps_product p on p.id_product = pl.id_product
        JOIN ps_stock_available psa on p.id_product = psa.id_product
        JOIN ps_category_lang c on c.id_category = p.id_category_default
        JOIN ps_product_supplier ps on p.id_product = ps.id_product
        LEFT JOIN ps_product_attribute pa on p.id_product=pa.id_product
        WHERE pl.id_lang=2 AND pa.id_product_attribute = psa.id_product_attribute AND pa.id_product_attribute =o.product_attribute_id  AND c.id_lang=2 AND id_order= '".$q."'
        GROUP BY product_id, kood,nimetus,nr,pl.link_rewrite, kogukogus,asukoht, link
</code>```

How can I fix this problem?

答:
I think that you have to move 2 of your WHERE conditions to the JOIN conditions. Probably it is enough to move only the condition on the LEFT JOIN.
This should be the result:

```<code>SELECT DISTINCT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        JOIN ps_product_lang pl on o.product_id = pl.id_product
        JOIN ps_product p on p.id_product = pl.id_product
        JOIN ps_stock_available psa on p.id_product = psa.id_product
        JOIN ps_category_lang c on c.id_category = p.id_category_default
        JOIN ps_product_supplier ps on p.id_product = ps.id_product
        LEFT JOIN ps_product_attribute pa on p.id_product=pa.id_product
                   AND psa.id_product_attribute = pa.id_product_attribute

        WHERE pl.id_lang=2 AND c.id_lang=2 AND id_order= '".$q."'
</code>```

Title: Prestashop order products sql

Body:
Where I can find Prestashop SQL query where they display the products that were bought in order.

Like this:

I'm creating a custom page that shows 100 orders in table. and if clicked on order its shows the products that were ordered. I made an sql query:

SELECT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        LEFT JOIN ps_product_lang pl on o.product_id = pl.id_product
        LEFT JOIN ps_product p on p.id_product = pl.id_product
        LEFT JOIN ps_stock_available psa on p.id_product = psa.id_product
        LEFT JOIN ps_category_lang c on c.id_category = p.id_category_default
        LEFT JOIN ps_product_supplier ps on p.id_product = ps.id_product
        WHERE pl.id_lang=2 AND c.id_lang=2 AND id_order= '".$q."'
        GROUP BY product_id, kood,nimetus,nr,pl.link_rewrite, kogukogus,asukoht, link

But when product has attributes it duplicates products.

In this case iButton has two colors black and red(attributes). In this order only one black iButton was bought with quantity of 20, but It shows three rows.

I tried to fix this, but that arised another problems with my sql query, that when it has no attribute it dosen't show anything.

SELECT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        JOIN ps_product_lang pl on o.product_id = pl.id_product
        JOIN ps_product p on p.id_product = pl.id_product
        JOIN ps_stock_available psa on p.id_product = psa.id_product
        JOIN ps_category_lang c on c.id_category = p.id_category_default
        JOIN ps_product_supplier ps on p.id_product = ps.id_product
        LEFT JOIN ps_product_attribute pa on p.id_product=pa.id_product
        WHERE pl.id_lang=2 AND pa.id_product_attribute = psa.id_product_attribute AND pa.id_product_attribute =o.product_attribute_id  AND c.id_lang=2 AND id_order= '".$q."'
        GROUP BY product_id, kood,nimetus,nr,pl.link_rewrite, kogukogus,asukoht, link

How can I fix this problem?

Body:
I think that you have to move 2 of your WHERE conditions to the JOIN conditions. Probably it is enough to move only the condition on the LEFT JOIN.
This should be the result:

SELECT DISTINCT product_id, product_reference AS kood,product_name AS nimetus,product_quantity AS nr, pl.link_rewrite,psa.quantity as kogukogus,group_concat(ps.product_supplier_reference) as supp_ref, p.location AS asukoht,
         CONCAT(c.link_rewrite,'/',p.id_product,'-',pl.link_rewrite,'.html') link
        FROM ps_order_detail o
        JOIN ps_product_lang pl on o.product_id = pl.id_product
        JOIN ps_product p on p.id_product = pl.id_product
        JOIN ps_stock_available psa on p.id_product = psa.id_product
        JOIN ps_category_lang c on c.id_category = p.id_category_default
        JOIN ps_product_supplier ps on p.id_product = ps.id_product
        LEFT JOIN ps_product_attribute pa on p.id_product=pa.id_product
                   AND psa.id_product_attribute = pa.id_product_attribute

        WHERE pl.id_lang=2 AND c.id_lang=2 AND id_order= '".$q."'


问:
React map on object then array
This is my object and I want to map this in my component but I have problem, I cant use map on this object. First value is vote and next is array of users. How I cna use map on this in babel ? </p>

```<code>  var ObjVote = {
        '1':['EwaK','Jacek','Jacek'],
        '2':['Anna','Pawel','EwaK'],
        '3':['Anna','EwaK','Jacek'],
        '4':['Jas','Jas','Pawel'],
        '5':['Anna','Jas','Pawel']
        }
</code>```

答:
You can use:

```<code>Object.keys(ObjVote)
         .map(vote => ({ vote: vote, voters: ObjVote[vote]}))
         .map(data => <Vote {...data} key={data.vote} />)
</code>```

Or

```<code>Object.keys(ObjVote)
         .map(vote => ({ vote: vote, voters: ObjVote[vote]}))
         .map(data => <Vote data={data} key={data.vote} />)
</code>```

Now inside Vote component you can access votes by props.data.votes and voters array by props.data.voters.

Title: React map on object then array

Body:
This is my object and I want to map this in my component but I have problem, I cant use map on this object. First value is vote and next is array of users. How I cna use map on this in babel ?

  var ObjVote = {
        '1':['EwaK','Jacek','Jacek'],
        '2':['Anna','Pawel','EwaK'],
        '3':['Anna','EwaK','Jacek'],
        '4':['Jas','Jas','Pawel'],
        '5':['Anna','Jas','Pawel']
        }

Body:
You can use:

Object.keys(ObjVote)
         .map(vote => ({ vote: vote, voters: ObjVote[vote]}))
         .map(data => <Vote {...data} key={data.vote} />)

Or

Object.keys(ObjVote)
         .map(vote => ({ vote: vote, voters: ObjVote[vote]}))
         .map(data => <Vote data={data} key={data.vote} />)

Now inside Vote component you can access votes by props.data.votes and voters array by props.data.voters.


问:
Eclipse Jar-in-Jar fails to find a joda.time class
Eclipse has 3 runnable JAR export methods. One of them does not work in my case. I want to stop using the export method that makes a library sub-folder and switch to a single JAR.

In all cases my invocation is in a script, with a few script variables such as $MEMORYOPTIONS

java $MEMORYOPTIONS -enableassertions -classpath VARIOUS-SHOWN-BELOW topLevelDomain.domain.packageName.className $1 $2 $3

Firstly...

I have success with the following export method and the class path as shown.

export > runnable jar > extract required libraries

-classpath /home/user/workspace/project/project1.jar

I have a reason for not wanting to use this single JAR. (It is because unpackaged third party packages expose files with duplicate names so I get annoying warnings. Example: A file called License.txt is in several packages.)

Secondly...

As already mentioned I also have success with the following "library sub-folder" export method and class path as shown.

export > runnable jar > copy required libraries into a sub-folder

-classpath /home/user/workspace/project/project1.jar:/home/user/workspace/project/project1_lib/*

(Edit: As it turns out the JAR has a manifest that points to the project1_lib subfolder so the class path can be simplified to omit that. Just delete the part after the colon (:) separator from the class path.)

Thirdly...

I interpret "package required libraries" to mean a JAR-in-JAR export. Invoked with the class path shown, this export results in a failure to find the class.

export > runnable jar > package required libraries

-classpath /home/user/workspace/project/project1.jar

The error is:

Exception in thread "main" java.lang.NoClassDefFoundError: org/joda/time/ReadablePartial

How do I get this particular type of Eclipse export to work? I have already uninstalled Eclipse (Mars) and reinstalled. I have also
removed the org.joda.time package and added it back. The problem persists.

答:
You should launch your app using java's -jar option. Something like this:

```<code>java $MEMORYOPTIONS -enableassertions -jar /path/to/project1.jar $1 $2 $3
</code>```

Body:
You should launch your app using java's -jar option. Something like this:

java $MEMORYOPTIONS -enableassertions -jar /path/to/project1.jar $1 $2 $3