问:
What is purpose of Python build in `unittest.TestCase.assertEquals` field
Using Python 3.6, PyCharm Community 2017.2.4, Win 10

I can search so I know that unittest.TestCase.assertEquals() is deprecated method what is ok.

What I'm curious is the first field what is proposed to me in PyCharm IDE when I start typing assert part for unittest.TestCase.assert

First on the list of code completion I see field unittest.TestCase.assertEquals. Hmm

Docs by pressing Ctrl+Q shows

Class attribute assertEquals of class TestCase  External documentation: http://docs.python.org/3.6/library/unittest.html#unittest.case.assertEquals

Ok - link leads to main page about unittest framework

Lets print values:

```<code>Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
>>> import unittest
>>> unittest.TestCase.assertEquals
<function TestCase._deprecate.<locals>.deprecated_func at 0x03DAC348>
>>> help(unittest.TestCase.assertEquals)
Help on function deprecated_func in module unittest.case:
deprecated_func(*args, **kwargs)
</code>```

So this field is reference to function what is depricated - am I understanding that right?

答:
Here is a short example of how function decoration works in Python. Let's have a function that returns the answer to the ultimate question of life, the universe, and everything:

```<code>def get_answer():
   return 42
</code>```

If you examine the get_answer symbol, you'll see it's a function:

```<code>>>> get_answer
<function get_answer at 0x7f9c4f8bac08>
>>> get_answer()
42
</code>```

Now let's decide that returning a hardcoded answer is not really scientific or reusable in other universes and that the function should actually compute it based on the actual parameters of the universe. So a new function compute_answer is introduced and get_answer is deprecated in favour of the new one. To warn the user of the deprecation, several things could be done:

The source code could be modified to give out a warning:

```<code>def get_answer():
   print("WARNING: Function get_answer is deprecated")
   return 42
</code>```

This is ugly as it introduces changes in the source code of the function. A better way is to wrap the function:

```<code>def deprecated(func):
   def show_deprecated():
      print("WARNING: Function {} is deprecated".format(func.__name__))
      return func()
   return show_deprecated
</code>```

What happens here is that we pass a function to the deprecated function and the latter builds and returns a wrapper. The wrapper is an instance of the nested show_deprecated function that captures (remembers) the value of func argument at the time of call. This is called closure and is one of the cornerstones of functional programming.

We can now route the call to get_answer through deprecated to get an automatic deprecation message without changing anything in the source code of the function:

```<code>>>> get_answer_dep = deprecated(get_answer)
>>> get_answer_dep()
WARNING: Function get_answer is deprecated
42
</code>```

We can also override get_answer with its wrapped version so that all calls to it get routed through the wrapper:

```<code>>>> get_answer = deprecated(get_answer)
>>> get_answer()
WARNING: Function get_answer is deprecated
42
</code>```

At this point one no longer has access to the original non-wrapped code of get_answer. It still exists and gets called by the wrapper function, but there is no publicly visible symbol that allows us to simply call it directly (it is still possible to call the original code via introspection of the wrapper, but let's pretend we don't know how to do it). If you now examine the get_answer symbol, it is actually an instance of the show_deprecated function:

```<code>>>> get_answer
<function show_deprecated at 0x7f9c4218b140>
</code>```

Since help(something) displays the __doc__ property of the object itself, calling help(get_answer) actually shows the doc-string of show_deprecated:

```<code>>>> help(get_answer)
Help on function show_deprecated in module __main__:
show_deprecated()
</code>```

Writing name = deprecated(name) after each deprecated function is a bit tedious. That's why Python provides a short-cut syntax:

```<code>@deprecated
def get_answer()
   return 42
</code>```

The @deprecated syntax is called function decoration. It simply instructs the interpreter to insert a call to the decorator function, in this case deprecated(), after the definition of the function and assign the result to the symbol bearing the function name, i.e.:

```<code>@foo
def bar():
   ...
</code>```

is equivalent to:

```<code>>>> get_answer
<function get_answer at 0x7f9c4f8bac08>
>>> get_answer()
42
</code>```0

The unittest module is not making use of the decorator syntax as seen in the source code.

That help() shows the help of the wrapper function instead of the original one is a bummer while debugging. Fortunately, function names and doc strings are actually writeable properties and one can copy them from the original function onto the wrapper and thus preserve the name and documentation string shown by help(). Python comes with the functools module that provides the wraps decorator that does exactly that. The decorator is used on the nested (wrapper) function:

```<code>>>> get_answer
<function get_answer at 0x7f9c4f8bac08>
>>> get_answer()
42
</code>```1

If we now wrap the get_answer function, the name, the documentation, and the module properties are preserved:

```<code>>>> get_answer
<function get_answer at 0x7f9c4f8bac08>
>>> get_answer()
42
</code>```2

Body:
Using Python 3.6, PyCharm Community 2017.2.4, Win 10

I can search so I know that unittest.TestCase.assertEquals() is deprecated method what is ok.

What I'm curious is the first field what is proposed to me in PyCharm IDE when I start typing assert part for unittest.TestCase.assert

First on the list of code completion I see field unittest.TestCase.assertEquals. Hmm

Docs by pressing Ctrl+Q shows

Class attribute assertEquals of class TestCase  External documentation: http://docs.python.org/3.6/library/unittest.html#unittest.case.assertEquals

Ok - link leads to main page about unittest framework

Lets print values:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
>>> import unittest
>>> unittest.TestCase.assertEquals
<function TestCase._deprecate.<locals>.deprecated_func at 0x03DAC348>
>>> help(unittest.TestCase.assertEquals)
Help on function deprecated_func in module unittest.case:
deprecated_func(*args, **kwargs)

So this field is reference to function what is depricated - am I understanding that right?

Body:
Here is a short example of how function decoration works in Python. Let's have a function that returns the answer to the ultimate question of life, the universe, and everything:

def get_answer():
   return 42

If you examine the get_answer symbol, you'll see it's a function:

>>> get_answer
<function get_answer at 0x7f9c4f8bac08>
>>> get_answer()
42

Now let's decide that returning a hardcoded answer is not really scientific or reusable in other universes and that the function should actually compute it based on the actual parameters of the universe. So a new function compute_answer is introduced and get_answer is deprecated in favour of the new one. To warn the user of the deprecation, several things could be done:

The source code could be modified to give out a warning:

def get_answer():
   print("WARNING: Function get_answer is deprecated")
   return 42

This is ugly as it introduces changes in the source code of the function. A better way is to wrap the function:

def deprecated(func):
   def show_deprecated():
      print("WARNING: Function {} is deprecated".format(func.__name__))
      return func()
   return show_deprecated

What happens here is that we pass a function to the deprecated function and the latter builds and returns a wrapper. The wrapper is an instance of the nested show_deprecated function that captures (remembers) the value of func argument at the time of call. This is called closure and is one of the cornerstones of functional programming.

We can now route the call to get_answer through deprecated to get an automatic deprecation message without changing anything in the source code of the function:

>>> get_answer_dep = deprecated(get_answer)
>>> get_answer_dep()
WARNING: Function get_answer is deprecated
42

We can also override get_answer with its wrapped version so that all calls to it get routed through the wrapper:

>>> get_answer = deprecated(get_answer)
>>> get_answer()
WARNING: Function get_answer is deprecated
42

At this point one no longer has access to the original non-wrapped code of get_answer. It still exists and gets called by the wrapper function, but there is no publicly visible symbol that allows us to simply call it directly (it is still possible to call the original code via introspection of the wrapper, but let's pretend we don't know how to do it). If you now examine the get_answer symbol, it is actually an instance of the show_deprecated function:

>>> get_answer
<function show_deprecated at 0x7f9c4218b140>

Since help(something) displays the __doc__ property of the object itself, calling help(get_answer) actually shows the doc-string of show_deprecated:

>>> help(get_answer)
Help on function show_deprecated in module __main__:
show_deprecated()

Writing name = deprecated(name) after each deprecated function is a bit tedious. That's why Python provides a short-cut syntax:

@deprecated
def get_answer()
   return 42

The @deprecated syntax is called function decoration. It simply instructs the interpreter to insert a call to the decorator function, in this case deprecated(), after the definition of the function and assign the result to the symbol bearing the function name, i.e.:

@foo
def bar():
   ...

is equivalent to:

def bar():
   ...

bar = foo(bar)

The unittest module is not making use of the decorator syntax as seen in the source code.

That help() shows the help of the wrapper function instead of the original one is a bummer while debugging. Fortunately, function names and doc strings are actually writeable properties and one can copy them from the original function onto the wrapper and thus preserve the name and documentation string shown by help(). Python comes with the functools module that provides the wraps decorator that does exactly that. The decorator is used on the nested (wrapper) function:

from functools import wraps

def deprecated(func):
   @wraps(func)
   def show_deprecated():
      print("WARNING: Function {} is deprecated".format(func.__name__))
      return func()
   return show_deprecated

If we now wrap the get_answer function, the name, the documentation, and the module properties are preserved:

 >>> get_answer = deprecated(get_answer)
 >>> help(get_answer)
 Help on function get_answer in module __main__:
 get_answer()


来源: stackexchange

问:
Combine two different array in javascript
I have two array data that I want to combine into one array, the first array contain only data of date and id, the second array contain name and id.

```<code>    temp_data:[
      0:{
        id:"1"
        date:"2017-11-07"
      }
      1:{
        id:"1"
        date:"2017-11-08"
      }
      2:{
        id:"2"
        date:"2017-11-07"
      }
      3:{
        id:"2"
        date:"2017-11-08"
      }
]

name:[
      0:{
       id:"1"
       name:"Pervies, Peter"
      }
      1:{
       id:"2"
       name:"Ming, Edmund"
      }
]
</code>```

I want the data to be look like this:

```<code>    data:[
    0:{
     id:"1"
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
    1:{
     id:"2"
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
]
</code>```

I have try the code below to combine the two array,it works but not in the way I expect.

```<code>  let len = temp_data.length;
    let leng = name.length;
        for (let i = 0; i < leng; ++i) {
            for (let x = 0; x < len; ++x) {
                if (name[i].id == temp_data[x].id) {
                    let id = name[i].id;
                    let details = temp_data[x];
                    data.push({id,details})
                }
            }
        }

    // ------------------------------------------------------------------------

       let dat = temp_data,
       hash = Object.create(null),
       result = [];

   dat.forEach(function (o) {
        if (!hash[o.id]) {
         hash[o.id] = [];
         result.push(hash[o.id]);
        }
          hash[o.id].push(o);
    });

        data = result;
</code>```

can you help me with this?

答:
This is how you can do it:

First group your temp_data array items by id property:

```<code>temp_data.forEach(function(d) {
  if (!results.some(function(item) {
      return item.id == d.id;
    })) {
    let mixed = {};
    mixed.id = d.id;
    (mixed.details = mixed.details || []).push({
      "date": d.date
    });
    results.push(mixed);
  } else {
    results.find(function(r) {
      return r.id == d.id;
    }).details.push({
      "date": d.date
    });
  }
});
</code>```

Then add the name property to each relevant item in your results array, from names array:

```<code>results.forEach(function(r) {
  if (names.some(function(n) {
      return n.id == r.id;
    })) {
    r.name = names.find(function(name) {
      return name.id == r.id;
    }).name;
  }
});
</code>```

Explanation:

I used .forEach() to loop over the merged array elements, and for
each item:

I used .some()method to check over the existence of an item with
the same id in the array.

Then used .find()to get this object if it exists, and update it
with relevant data.

Demo:

const temp_data = [{
    id: "1",
    date: "2017-11-07"
  },
  {
    id: "1",
    date: "2017-11-08"
  },
  {
    id: "2",
    date: "2017-11-07"
  },
  {
    id: "2",
    date: "2017-11-08"
  }
];

const names = [{
  id: "1",
  name: "Pervies, Peter"
}, {
  id: "2",
  name: "Ming, Edmund"
}];

var results = [];

//First group your first array objects by id

temp_data.forEach(function(d) {
  if (!results.some(function(item) {
      return item.id == d.id;
    })) {
    let mixed = {};
    mixed.id = d.id;
    (mixed.details = mixed.details || []).push({
      "date": d.date
    });
    results.push(mixed);
  } else {
    results.find(function(r) {
      return r.id == d.id;
    }).details.push({
      "date": d.date
    });
  }
});

results.forEach(function(r) {
  if (names.some(function(n) {
      return n.id == r.id;
    })) {
    r.name = names.find(function(name) {
      return name.id == r.id;
    }).name;
  }
});
console.log(results);```

ContentLicense: CC BY-SA 3.0

Body:
I have two array data that I want to combine into one array, the first array contain only data of date and id, the second array contain name and id.

    temp_data:[
      0:{
        id:"1"
        date:"2017-11-07"
      }
      1:{
        id:"1"
        date:"2017-11-08"
      }
      2:{
        id:"2"
        date:"2017-11-07"
      }
      3:{
        id:"2"
        date:"2017-11-08"
      }
]

name:[
      0:{
       id:"1"
       name:"Pervies, Peter"
      }
      1:{
       id:"2"
       name:"Ming, Edmund"
      }
]

I want the data to be look like this:

    data:[
    0:{
     id:"1"
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
    1:{
     id:"2"
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
]

I have try the code below to combine the two array,it works but not in the way I expect.

  let len = temp_data.length;
    let leng = name.length;
        for (let i = 0; i < leng; ++i) {
            for (let x = 0; x < len; ++x) {
                if (name[i].id == temp_data[x].id) {
                    let id = name[i].id;
                    let details = temp_data[x];
                    data.push({id,details})
                }
            }
        }

    // ------------------------------------------------------------------------

       let dat = temp_data,
       hash = Object.create(null),
       result = [];

   dat.forEach(function (o) {
        if (!hash[o.id]) {
         hash[o.id] = [];
         result.push(hash[o.id]);
        }
          hash[o.id].push(o);
    });

        data = result;

can you help me with this?

Body:
This is how you can do it:

First group your temp_data array items by id property:

temp_data.forEach(function(d) {
  if (!results.some(function(item) {
      return item.id == d.id;
    })) {
    let mixed = {};
    mixed.id = d.id;
    (mixed.details = mixed.details || []).push({
      "date": d.date
    });
    results.push(mixed);
  } else {
    results.find(function(r) {
      return r.id == d.id;
    }).details.push({
      "date": d.date
    });
  }
});

Then add the name property to each relevant item in your results array, from names array:

results.forEach(function(r) {
  if (names.some(function(n) {
      return n.id == r.id;
    })) {
    r.name = names.find(function(name) {
      return name.id == r.id;
    }).name;
  }
});

Explanation:

I used .forEach() to loop over the merged array elements, and for
each item:

I used .some()method to check over the existence of an item with
the same id in the array.

Then used .find()to get this object if it exists, and update it
with relevant data.

Demo:

const temp_data = [{
    id: "1",
    date: "2017-11-07"
  },
  {
    id: "1",
    date: "2017-11-08"
  },
  {
    id: "2",
    date: "2017-11-07"
  },
  {
    id: "2",
    date: "2017-11-08"
  }
];

const names = [{
  id: "1",
  name: "Pervies, Peter"
}, {
  id: "2",
  name: "Ming, Edmund"
}];

var results = [];

//First group your first array objects by id

temp_data.forEach(function(d) {
  if (!results.some(function(item) {
      return item.id == d.id;
    })) {
    let mixed = {};
    mixed.id = d.id;
    (mixed.details = mixed.details || []).push({
      "date": d.date
    });
    results.push(mixed);
  } else {
    results.find(function(r) {
      return r.id == d.id;
    }).details.push({
      "date": d.date
    });
  }
});

results.forEach(function(r) {
  if (names.some(function(n) {
      return n.id == r.id;
    })) {
    r.name = names.find(function(name) {
      return name.id == r.id;
    }).name;
  }
});
console.log(results);


问:
Why can't a class member's name be the same as one of its nested classes?
Or why is the following impossible:

```<code>class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}
</code>```

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.

答:
"Anything that's not ambiguous should be legal" is absolutely NOT a design principle of the C# language. The C# language is designed to be a "pit of quality" language; that is, the rules of the language should throw you into a pit full of clearly correct code, and you have to work to climb out of the pit to turn it into incorrect code. The idea that "whatever is not ambiguous should be legal" works in most cases directly against the concept of a "pit of quality" language.

Furthermore, your idea that I need to provide you a justification for not doing a feature is backwards. We don't ever need to provide justification for not doing a feature. Rather, proposed features must be justified by demonstrating that their benefits outweigh their enormous costs. Features are very expensive and we have a limited budget; we must only do the very best features to yield their benefits to our customers.

Your proposed feature enables the easy production of code that is brittle and confusing; it helps make C# into a "pit of despair" language instead of a "pit of quality" language. Features which add brittleness and confusion to the language must add an enormous benefit to compensate for those costs. What is in your opinion the enormous benefit that this feature adds to the language that justifies its costs?

If the answer is "there is no such benefit" then now you know why the language doesn't have that feature: because it makes the language worse, net.

If there is a benefit, I'm happy to consider its merits for hypothetical future versions of the language.

ContentLicense: CC BY-SA 2.5

Body:
Or why is the following impossible:

class Material
{
    class Keys
    {
        ...
    }

    Material.Keys Keys { get; set; } // Illegal
}

I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?

I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.


问:
What is the advantage of "safe write" in JetBrains IntelliJ?
IntelliJ has a "safe write" option (quotes theirs, for some reason) which, on save, instead of simply updating the file, writes to a temporary file, then deletes the original, then renames the temporary file to the original's name. I hear that vim also does this.

I know this causes problems with programs that are watching the file. Sometimes such programs see the delete, but never see the update, for example.

But what advantages are there? IntelliJ's docs say that there are advantages that would be lost if you turned it off. There must be some reason this option is the default.

It took me a looong time to figure out this was how intellij operated and that it was causing some chronic issues I was facing, and took me even longer to figure out it was an option I could turn off. Now that I have that option, I'd like to know if the cure is worse than the disease, so to speak.

答: The safe write prevents you from data loss in case something goes wrong during the update. Just think of your computer or Intellij crashing while you are saving the file. You might lose the file completely then. But with safe write you would lose your recent changes only. After the updated version of your file is written to disk without errors, the old version can be replaced. This way you have a valid file version at any point of time during the update process, so no crash or whatever could make you lose all your work on that file. The worst thing which could happen is the loss of your recent changes.</p>


问:
how to solve this below runtime error 430?
I created one application (*.exe) it works fine in all systems but in one system it throws an error.

"class does not support automation or does support expected interface "

答:
Using a simple Google search:

Either the class you specified in the GetObject or CreateObject function call has not exposed a programmability interface, or you changed a project from .dll to .exe, or vice versa.

To correct this error Check the documentation of the application that created the object for limitations on the use of automation with this class of object.

If you changed a project from .dll to .exe or vice versa, you must manually unregister the old .dll or .exe.


问:
get the wanted objects from the array of objects
This is my first question in stackoverflow, So any kind of help is appreciated.

I have an array like this

```<code>var products = [{status:'available', ...},{status:'none', ...},{status:'available', ...},{status:'', ...},{status:'none', ...}]
</code>```

how can I get an array that contains only  products[i].status = 'available' .

I already did this with for loop but isn't there a better method? My code is practically full of loops now & it's not easy to read.

Thank you for you help.

答:
Try this

var products = [{
  status: 'available'
}, {
  status: 'none'
}, {
  status: 'available'
}, {
  status: ''
}, {
  status: 'none'
}]

var array = $.map(products, function(value, index) {

  if (value["status"] == "available") {
    return [value];
  }

});

console.log(array);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script></code>```

Body:
This is my first question in stackoverflow, So any kind of help is appreciated.

I have an array like this

var products = [{status:'available', ...},{status:'none', ...},{status:'available', ...},{status:'', ...},{status:'none', ...}]

how can I get an array that contains only  products[i].status = 'available' .

I already did this with for loop but isn't there a better method? My code is practically full of loops now & it's not easy to read.

Thank you for you help.

Body:
Try this

var products = [{
  status: 'available'
}, {
  status: 'none'
}, {
  status: 'available'
}, {
  status: ''
}, {
  status: 'none'
}]

var array = $.map(products, function(value, index) {

  if (value["status"] == "available") {
    return [value];
  }

});

console.log(array);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


答:
https://jsfiddle.net/dvwu75ja/

Try This one

```<code>var products = [{status:'available'},{status:'none'},{status:'available'},{status:''},{status:'none'}];
x = 0;
products.forEach(function(element) {

    if(element["status"] == "available"){
       //code here, x is just to represent what index you are in now
        console.log(x);
    }
    x++;
});
</code>```

Hopes this help

Title: get the wanted objects from the array of objects

Body:
https://jsfiddle.net/dvwu75ja/

Try This one

var products = [{status:'available'},{status:'none'},{status:'available'},{status:''},{status:'none'}];
x = 0;
products.forEach(function(element) {

    if(element["status"] == "available"){
       //code here, x is just to represent what index you are in now
        console.log(x);
    }
    x++;
});

Hopes this help


问:
How can I add a value in my list when a condition is true?
I have a dict with alot of items:

```<code>{'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',}
</code>```

I need to create a list with all three elements inside.
I'm expecting a list like this:

```<code><type 'list'>: [['60', u'1', u'on'], ['35', u'3', u'on'],]
</code>```

I have only 2 values above, but 2 times the same product-id. So it should add the quantity and the 'on off' together to the same product-id.

How can I do that? I tried it with something like this:

```<code>for key, value in request.params.items():
  if key[:12] == 'id-quantity-':
    if key[12:] in list:
      list.insert(key[12:], value)
    else:
      list.append([key[12:], value])

  if key[:11] == 'id-product-':
    if key[11:] in list:
      list.insert(key[11:], value)
    else:
      list.append([key[11:], value])
</code>```

The problem is I get this list all time splitet:

```<code><type 'list'>: [['60', u'1'], ['35', u'3'], ['35', u'on'], ['60', u'on'],]
</code>```

finally I should be able to fill the data in here (60, 1, True for example):

data = request.registry['website']._subscription_exclude_product(cr, uid, [{'product_id': int(60), 'qty': int(1), 'like': bool(True)}], context=context)

Thank you very much.

答:
Is it what you expect?</p>

```<code>products = {k.split('-')[-1]: v for k, v in x.items() if 'product' in k}
quantities = {k.split('-')[-1]: v for k, v in x.items() if 'quantity' in k}
all = [(k, v, 'on' if k in products else 'off') for k, v in quantities.items()]
</code>```

Body:
I have a dict with alot of items:

{'id-quantity-60': u'1', 'id-quantity-35': u'3','id-product-35': u'on', 'id-product-60': u'on',}

I need to create a list with all three elements inside.
I'm expecting a list like this:

<type 'list'>: [['60', u'1', u'on'], ['35', u'3', u'on'],]

I have only 2 values above, but 2 times the same product-id. So it should add the quantity and the 'on off' together to the same product-id.

How can I do that? I tried it with something like this:

for key, value in request.params.items():
  if key[:12] == 'id-quantity-':
    if key[12:] in list:
      list.insert(key[12:], value)
    else:
      list.append([key[12:], value])

  if key[:11] == 'id-product-':
    if key[11:] in list:
      list.insert(key[11:], value)
    else:
      list.append([key[11:], value])

The problem is I get this list all time splitet:

<type 'list'>: [['60', u'1'], ['35', u'3'], ['35', u'on'], ['60', u'on'],]

finally I should be able to fill the data in here (60, 1, True for example):

data = request.registry['website']._subscription_exclude_product(cr, uid, [{'product_id': int(60), 'qty': int(1), 'like': bool(True)}], context=context)

Thank you very much.

Body:
Is it what you expect?

products = {k.split('-')[-1]: v for k, v in x.items() if 'product' in k}
quantities = {k.split('-')[-1]: v for k, v in x.items() if 'quantity' in k}
all = [(k, v, 'on' if k in products else 'off') for k, v in quantities.items()]


问:
Using a REST web service how do you make a method that returns text passed to it?
I am currently using Eclipse and Tomcat for my servers and I am trying to make a method that passes an input string as output onto the HTML website.

I got some help from the question below, but how would I go about implementing the code from that link into a servlet file?

How to create a Restful web service with input parameters?

If anyone has any other solutions to taking text, passing it to the method and outputting it I'd appreciate it.

The code I'm using is a demo for Hello World (scroll to the very bottom):

https://www.ibm.com/developerworks/library/os-eclipse-tomcat/index.html

答: For your requirement you can develop a servlet which can accept any input as request parameters and in servlet you can manipulate that information as per your requirements. Then you can create the HTML inside servlet (although not preferred way, you can use jsp for this) to display anything.</p>


问:
Redmine - Extending context menu
I want to extend the functionality of the context menu of a Redmine plugin. I found the context menu view I want to modify. However I feel lost. I am new to Redmine api. I want to be able to select some items and make a function to only show these items. My question is how to get the selected items. Are they stored inthe session or..? Any documentation you can point me to regarding context menu will be of great help aswell. Thank you for your time!</p>

答:
You should use view hooks to extend view-related elements.

For your particular case, view hook is:

```<code>:view_issues_context_menu_start
</code>```

or

```<code>:view_issues_context_menu_end
</code>```

To see a full list of hooks, go to:
http://www.redmine.org/projects/redmine/wiki/Hooks_List#View-hooks

But sometimes that list is not updated, so the most reliable way to find hooks is to find call_hook in source files, so you can use grep from command console like this:

```<code>grep -r call_hook *    # list of source lines with hook calls
</code>```

Title: Redmine - Extending context menu

Body:
You should use view hooks to extend view-related elements.

For your particular case, view hook is:

:view_issues_context_menu_start

or

:view_issues_context_menu_end

To see a full list of hooks, go to:
http://www.redmine.org/projects/redmine/wiki/Hooks_List#View-hooks

But sometimes that list is not updated, so the most reliable way to find hooks is to find call_hook in source files, so you can use grep from command console like this:

grep -r call_hook *    # list of source lines with hook calls


问:
detect elements overflow using jquery
CSS:

```<code> .blue
    {
     width:200px;
     height:200px;
     background-color:blue;
     color:#000000;
     overflow:auto;
    }
</code>```

JavaScript:

```<code>function addChar() {
    $('.blue').append('some text  ');
}
</code>```

HTML:

```<code><div id='blue1' class="blue"></div><br />
<a href='javascript:void(0)' onclick='addChar()'>Add</a>
</code>```

div id='blue1' has overflow property set to auto. I want to detect overflow when it happens.

答:
Here's a plugin i wrote, which might come in handy if you want to find out if an element is overflown or not: https://github.com/ZetaSoftware/jquery-overflown-plugin.

With this plugin, in the original example, you could just do: $("#blue1").overflown() to find out of children of #blue1 are overflowing.

Title: detect elements overflow using jquery

Body:
CSS:

 .blue
    {
     width:200px;
     height:200px;
     background-color:blue;
     color:#000000;
     overflow:auto;
    }

JavaScript:

function addChar() {
    $('.blue').append('some text  ');
}

HTML:

Add

div id='blue1' has overflow property set to auto. I want to detect overflow when it happens.


问:
How to use typings for d3-tip in typescript 2.0
I want to use d3-tip library to add tooltips in my charts.

Using Typescript 2.0, I added the typings for d3-tip as follows:

```<code>npm install @types/d3-tip --save
</code>```

It shows up in my package.json:

```<code>"dependencies": {
  "@types/d3": "^4.7.0",
  "@types/d3-tip": "^3.5.4",
}
</code>```

index.d.ts for d3-tip looks like this:

```<code>import {Primitive} from "d3";

declare module "d3" {
    type TooltipDirection = ("n" | "s" | "e" | "w" | "nw" | "ne" | "sw" | "se");
    interface Tooltip {
        hide(): Tooltip;
        show(): Tooltip;
        destroy(): Tooltip;
        ....
    }
    export function tip(): Tooltip;
}
</code>```

My question is, how do I now use this/import in my code? I tried adding following:

```<code>import * as tip from 'd3-tip';   OR
import * from 'd3-tip';          OR
import { tip } from 'd3-tip';
</code>```

but none of them work, and I don't get any intellisense on d3.tip().

How do I make it work? Thanks.

答:
Import, which works for me:

```<code>import d3Tip from "d3-tip";
const tip = d3Tip();
</code>```

However, there is small discussion about this here.

Body:
I want to use d3-tip library to add tooltips in my charts.

Using Typescript 2.0, I added the typings for d3-tip as follows:

npm install @types/d3-tip --save

It shows up in my package.json:

"dependencies": {
  "@types/d3": "^4.7.0",
  "@types/d3-tip": "^3.5.4",
}

index.d.ts for d3-tip looks like this:

import {Primitive} from "d3";

declare module "d3" {
    type TooltipDirection = ("n" | "s" | "e" | "w" | "nw" | "ne" | "sw" | "se");
    interface Tooltip {
        hide(): Tooltip;
        show(): Tooltip;
        destroy(): Tooltip;
        ....
    }
    export function tip(): Tooltip;
}

My question is, how do I now use this/import in my code? I tried adding following:

import * as tip from 'd3-tip';   OR
import * from 'd3-tip';          OR
import { tip } from 'd3-tip';

but none of them work, and I don't get any intellisense on d3.tip().

How do I make it work? Thanks.

Body:
Import, which works for me:

import d3Tip from "d3-tip";
const tip = d3Tip();

However, there is small discussion about this here.


问:
Snapshot testing react component which depends on inject mobx store
I've been trying to figure out how to do simple snapshot testing for a few components that have mobx stores injected into them. Here's an example:

At the root i have a <Provider> wrapping the whole shebang at my final ReactDOM.render() in the entry point. (not shown here)

```<code>// component.js

...{imports}...
@inject('mystore')
@observer
export default class extends React.Component {
  render() {
    return (
      <div>Stuff</div>
    )
  }
}

// component.test.js

import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import Component from './'

it('renders a snapshot', () => {
  const tree = renderer.create(<Component/>).toJSON();
  expect(tree).toMatchSnapshot();
});
</code>```

I get a failed test because it's missing a store provided up the tree. I've tried exporting an "undecorated" component like so:

```<code>// in component.js
...{same as above}...

export const undecorated = Component
</code>```

and then importing the undecorated component in my snapshot test, however this doesn't work.

Ideas?

答:
You should be able to pass the store explicitly like so:

const tree = renderer.create(
          <Component.wrappedComponent myStore={store}/>).toJSON();
 )

Body:
I've been trying to figure out how to do simple snapshot testing for a few components that have mobx stores injected into them. Here's an example:

At the root i have a <Provider> wrapping the whole shebang at my final ReactDOM.render() in the entry point. (not shown here)

// component.js

...{imports}...
@inject('mystore')
@observer
export default class extends React.Component {
  render() {
    return (

Stuff

    )
  }
}

// component.test.js

import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import Component from './'

it('renders a snapshot', () => {
  const tree = renderer.create(<Component/>).toJSON();
  expect(tree).toMatchSnapshot();
});

I get a failed test because it's missing a store provided up the tree. I've tried exporting an "undecorated" component like so:

// in component.js
...{same as above}...

export const undecorated = Component

and then importing the undecorated component in my snapshot test, however this doesn't work.

Ideas?


问:
Java ME object persistence
I know that Serialization (Serializable) is not available in the Micro Edition of Java.
It's kinda straight forward to save primitives like int and java.lang.String objects with the RMS.
But if I want to save (make persistant) an arbitrary object? Is that possible?</p>

答: Unfortunately there's no way to save an arbitrary object without writing code for it, since reflection is severely limited in J2ME (you can look up classes, but can't look up their fields and methods).</p>

OwnerDisplayName: anon

LastEditorDisplayName: Roger

Title: Java ME object persistence

OwnerDisplayName: saua


问:
Capturing the text of the closest span element with a specific class
I'm trying to fetch the text of a span that has a given class -> closest to the click via Google Tag Manager. Is it possible via plain JS or JQuery?

The code looks like this:

```<code><a class="contenttile" href="/mypage" style="height: 193px;">
  <div class="imageContainer" style="height: 97px;">
    <img src="http://http:someadress.com/foto.jpg" class="blurr" alt="">
  </div>
  <div class="textContainer">
    <span class="text3">My text</span>
    <br>
  </div>
</a>
</code>```

What I want to return via a function is My text.

I was trying different snippets found here, but since im a JS lame I couldn't adjust it to work properly.

For example this one:

```<code>function(){
  var ec = {{Click Element}};
  var x = $(ec).closest('span');
  return x.innerText;
}
</code>```

答:
since you are using jQuery</p>

```<code>return ec.find('.text3').text();
</code>```

Body:
I'm trying to fetch the text of a span that has a given class -> closest to the click via Google Tag Manager. Is it possible via plain JS or JQuery?

The code looks like this:

    My text

What I want to return via a function is My text.

I was trying different snippets found here, but since im a JS lame I couldn't adjust it to work properly.

For example this one:

function(){
  var ec = {{Click Element}};
  var x = $(ec).closest('span');
  return x.innerText;
}

Body:
since you are using jQuery

return ec.find('.text3').text();


问:
Disable Submit button on selection from DropDownListFor
I am working on this code when the submit button will be enabled only when user selects values from a DropDownListFor.

```<code>      @Html.DropDownListFor(m => m.Year, Model.YearList, "--Select Year--", new { @class = "form-control",id = "Year" })
      @Html.ValidationMessageFor(m => m.Year)

 <input type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success" />
</code>```

js code:

```<code>   $("#Year").change(function () {
        if ($('#Year').val()!="--Select Year--")
            $('.submit').prop("disabled", false);
        else
            $('.submit').prop("disabled", true);
    });
</code>```

No error message just the submit button is always enabled. Any help?

答:
Using javascript you set the button as disabled and use an onchange function to check for value:

```<code><select id="Year" onchange = "enableButton()">
      <option value="">Select</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    <option value="4">4</option>
</select>
<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success" disabled/>
</code>```

JavaScript:

```<code>function enableButton(){
 var year =  document.getElementById("Year").value;
 if(year == ""){
    document.getElementById("submit").disabled = true;
 }
 else{
    document.getElementById("submit").disabled = false;
 }
}
</code>```

Body:
I am working on this code when the submit button will be enabled only when user selects values from a DropDownListFor.

      @Html.DropDownListFor(m => m.Year, Model.YearList, "--Select Year--", new { @class = "form-control",id = "Year" })
      @Html.ValidationMessageFor(m => m.Year)

 <input type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success" />

js code:

   $("#Year").change(function () {
        if ($('#Year').val()!="--Select Year--")
            $('.submit').prop("disabled", false);
        else
            $('.submit').prop("disabled", true);
    });

No error message just the submit button is always enabled. Any help?

Body:
Using javascript you set the button as disabled and use an onchange function to check for value:

<select id="Year" onchange = "enableButton()">
      <option value="">Select</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    <option value="4">4</option>
</select>
<input type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success" disabled/>

JavaScript:

function enableButton(){
 var year =  document.getElementById("Year").value;
 if(year == ""){
    document.getElementById("submit").disabled = true;
 }
 else{
    document.getElementById("submit").disabled = false;
 }
}


答:
```<code>var temp_date = [{"id": "1", "date": "2017-11-07"}, {"id": "1", "date": "2017-11-08"}, {"id": "2", "date": "2017-11-07"}, {"id": "2", "date": "2017-11-08"}];
var name = [{"id": "1", "name": "Pervies, Peter"}, {"id": "2", "name": "Ming, Edmund"}];
var data = []
for(var i = 0; i < name.length; i++ ){
  data.push({"id": name[i].id, "name": name[i].name, "details": []});
  for(var j = 0; j < temp_date.length; j++){
    if(name[i].id === temp_date[j].id){
      data[i].details.push({"date": temp_date[j].date});
    }
  }
}
</code>```

<p>Need to correct temp_date and name array and apply the above logic. </p>

Title: Combine two different array in javascript

Body:
I have two array data that I want to combine into one array, the first array contain only data of date and id, the second array contain name and id.

    temp_data:[
      0:{
        id:"1"
        date:"2017-11-07"
      }
      1:{
        id:"1"
        date:"2017-11-08"
      }
      2:{
        id:"2"
        date:"2017-11-07"
      }
      3:{
        id:"2"
        date:"2017-11-08"
      }
]

name:[
      0:{
       id:"1"
       name:"Pervies, Peter"
      }
      1:{
       id:"2"
       name:"Ming, Edmund"
      }
]

I want the data to be look like this:

    data:[
    0:{
     id:"1"
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
    1:{
     id:"2"
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-07"},
        {date:"2017-11-08"}
     ]
    }
]

I have try the code below to combine the two array,it works but not in the way I expect.

  let len = temp_data.length;
    let leng = name.length;
        for (let i = 0; i < leng; ++i) {
            for (let x = 0; x < len; ++x) {
                if (name[i].id == temp_data[x].id) {
                    let id = name[i].id;
                    let details = temp_data[x];
                    data.push({id,details})
                }
            }
        }

    // ------------------------------------------------------------------------

       let dat = temp_data,
       hash = Object.create(null),
       result = [];

   dat.forEach(function (o) {
        if (!hash[o.id]) {
         hash[o.id] = [];
         result.push(hash[o.id]);
        }
          hash[o.id].push(o);
    });

        data = result;

can you help me with this?

Body:
var temp_date = [{"id": "1", "date": "2017-11-07"}, {"id": "1", "date": "2017-11-08"}, {"id": "2", "date": "2017-11-07"}, {"id": "2", "date": "2017-11-08"}];
var name = [{"id": "1", "name": "Pervies, Peter"}, {"id": "2", "name": "Ming, Edmund"}];
var data = []
for(var i = 0; i < name.length; i++ ){
  data.push({"id": name[i].id, "name": name[i].name, "details": []});
  for(var j = 0; j < temp_date.length; j++){
    if(name[i].id === temp_date[j].id){
      data[i].details.push({"date": temp_date[j].date});
    }
  }
}

Need to correct temp_date and name array and apply the above logic.


问:
Trying to implement MUC Chat in Openfire and Android using Smack
Groups are created using MUC, but i cannot retrieve all group of user.  I have done research  and This is deprecated and REST API is recommended. The REST API is  not working as expected. I am not able to  connect to server. I have added REST API plugin. Now in my android code I have set the secret key but not able to connect to localhost openfire server.

Help needed

答: If you install the Rest API plugin, it is not enabled per default. You can enable the plugin on the same page where you saw the secret key (Server Settings tab). That's why you get 403 Forbidden and not 401 Unauthorized.</p>


答:
It will Occurs when launching an installation of FRx that resides in a different directory than the one that was specified when FRx was installed on the current workstation. For example, launching an FRx install that resides on the server, instead of the one that was installed locally. Register the FRXLICSYS.DLL and FRXSYSTEM.DLL files in the directory from which FRx is being launched. If the problem persists, uninstall and reinstall FRx Version 6.0

Note If you are running Microsoft FRx version 6.7, register the FRXLICSYS67.DLL file, instead of the FRXLICSYS.DLL file.

follow below steps to resolve your concern:
Manually register the required files.

Using Explorer, locate FRXLICSYS.DLLin the directory from which FRx is being run.

Note If you are running Microsoft FRx version 6.7, locate the FRXLICSYS67.DLL file, instead of the FRXLICSYS.DLL file.

Choose Open With from the menu.

Click the Other button at the bottom of the Open With window.

Browse to the local drive (most often C:), and select either REGSVR32.EXE in \WINNT\SYSTEM32 or REGSVR.EXE in \WINDOWS\SYSTEM.

Click Open.

Click OK. A message will display indicating whether the file was successfully registered.

Repeat steps 1 through6 for FRXSYSTEM.DLL.

Title: how to solve this below runtime error 430?

Body:
I created one application (*.exe) it works fine in all systems but in one system it throws an error.

"class does not support automation or does support expected interface "


问:
Replace multiple characters in one replace call
I need to replace every instance of '_' with a space, and every instance of '#' with nothing/empty.

```<code>var string = '#Please send_an_information_pack_to_the_following_address:';
</code>```

I've tried this:

```<code>string.replace('#','').replace('_', ' ');
</code>```

I don't really like chaining commands like this. Is there another way to do it in one?

答:
Please try:

replace multi string

var str = "http://www.abc.xyz.com";
str = str.replace(/http:|www|.com/g, ''); //str is "//.abc.xyz"

replace multi chars

var str = "a.b.c.d,e,f,g,h";
str = str.replace(/[.,]/g, '');  //str is "abcdefgh";

Good luck!

ContentLicense: CC BY-SA 4.0

Body:
I need to replace every instance of '_' with a space, and every instance of '#' with nothing/empty.

var string = '#Please send_an_information_pack_to_the_following_address:';

I've tried this:

string.replace('#','').replace('_', ' ');

I don't really like chaining commands like this. Is there another way to do it in one?


问:
react on datepicker click want to change toggle value
I'm developing Flight API. when user click on return journey field I want to toggle button from single trip to round trip ( false to true).

```<code><DatePicker
  hintText="Return Date"
  errorText={this.state.journeyDateErrorText}
  onChange={(event, value) => {
  this.setState({journeyDate: value})
  }}
  minDate={new Date()}
  onClick={this.enableReturnDate.bind(this)}
  />
</code>```

above is my datepicker field when user click on this field I want to toggle my toggle component from false (single trip) to true (round trip).

```<code><Toggle
 thumbSwitchedStyle={{backgroundColor: 'grey'}}
 onToggle={this.handleonToggle.bind(this)}
 label={this.state.tripType}
 defaultToggled={false}
 />
</code>```

to get result that I want I have added onClick event and change state of toggle that is show as lable this.state.tripType.

```<code>enableReturnDate(e){

    this.setState({
        tripType: 'Round Trip'
    })
}
</code>```

after add onClick event toggle state this.state.tripType is changed from single trip to round trip but I want to change toggle button too from false to true.

How can I do this ?

答:
You should control the toggle component through state,</p>

```<code><Toggle
     thumbSwitchedStyle={{backgroundColor: 'grey'}}
     onToggle={this.handleonToggle.bind(this)}
     label={this.state.tripType}
     defaultToggled={this.state.toggleState} // control toggle state by state
     />

    // keep the toggle state as false initially, and change it to true when datePicker has been clicked or changed

enableReturnDate(e){
        this.setState({
            tripType: 'Round Trip',
            toggleState: true  //dont forget the initialize the state as false in constructor
        })
    }
</code>```

Body:
I'm developing Flight API. when user click on return journey field I want to toggle button from single trip to round trip ( false to true).

<DatePicker
  hintText="Return Date"
  errorText={this.state.journeyDateErrorText}
  onChange={(event, value) => {
  this.setState({journeyDate: value})
  }}
  minDate={new Date()}
  onClick={this.enableReturnDate.bind(this)}
  />

above is my datepicker field when user click on this field I want to toggle my toggle component from false (single trip) to true (round trip).

<Toggle
 thumbSwitchedStyle={{backgroundColor: 'grey'}}
 onToggle={this.handleonToggle.bind(this)}
 label={this.state.tripType}
 defaultToggled={false}
 />

to get result that I want I have added onClick event and change state of toggle that is show as lable this.state.tripType.

enableReturnDate(e){

    this.setState({
        tripType: 'Round Trip'
    })
}

after add onClick event toggle state this.state.tripType is changed from single trip to round trip but I want to change toggle button too from false to true.

How can I do this ?

Body:
You should control the toggle component through state,

<Toggle
     thumbSwitchedStyle={{backgroundColor: 'grey'}}
     onToggle={this.handleonToggle.bind(this)}
     label={this.state.tripType}
     defaultToggled={this.state.toggleState} // control toggle state by state
     />

    // keep the toggle state as false initially, and change it to true when datePicker has been clicked or changed

enableReturnDate(e){
        this.setState({
            tripType: 'Round Trip',
            toggleState: true  //dont forget the initialize the state as false in constructor
        })
    }


问:
Find combinations of a two dimensional array
I need some help with generation of combinations, specifically in the store they're the variants of each product, e.g size and colour.

Let's say we have 3 customizable properties of the product:
Colour, Size, and Type.

For this specific product, the following are available of each property:
Color: [red, green], Size: [10, 11, 15], Type: [person]

Now according to the above data, I need to generate 6 combinations, however if we added another type it would increase even more.

I have been drawing on my board for 2 hours now trying to come up with a sane algorithm for this, something that's fast and can deal with thousands of combinations in a matter of seconds.

Take this example:

```<code>$options = ['Color' => ['Red', 'Green'], 'Size' => ['10', '11', '15'], 'Type' => ['person']];
$combinations = generateCombinations($options);
</code>```

genereateCombinations would then need to generate the following output:

```<code>[
    ['Color' => 'Red', 'Size' => '10', 'Type' => 'person'],
    ['Color' => 'Red', 'Size' => '11', 'Type' => 'person'],
    ['Color' => 'Red', 'Size' => '15', 'Type' => 'person'],
    ['Color' => 'Green', 'Size' => '10', 'Type' => 'person'],
    ['Color' => 'Green', 'Size' => '11', 'Type' => 'person'],
    ['Color' => 'Green', 'Size' => '15', 'Type' => 'person']
];
</code>```

What algorithm could do this efficiently and with unlimited input "titles"? (of course I'll enforce a limit earlier, but the algorithm should be able to do unlimited granted all the resources in the world)

Extending what I mean:
This function also needs to be able to take for example an array with 100 property rows, not just 3, it needs to be able to do this dynamically no matter the number of input rows.

答:
Three foreach loops are enough to generate all combinations, no matter how many entries are in $options:

```<code>function generateCombinations(array $options)
{
    // Start with one combination of length zero
    $all = array(array());

    // On each iteration append all possible values of the new key
    // to all items in $all; generate this way all the combinations
    // one item longer than before
    foreach ($options as $key => $values) {
        // Move all combinations of length N from $all to $current
        $current = $all;
        // Start with an empty list of combinations of length N+1
        $all = array();
        // Combine each combination of length N
        // with all possible values for the (N+1)th key
        foreach ($current as $one) {
           foreach ($values as $val) {
              // Put each new combination in $all (length N+1)
              $all[] = array_merge($one, array($key => $val));
           }
        }
    }

    return $all;
}

$options = [
    'Color' => ['Red', 'Green'],
    'Size' => ['10', '11', '15'],
    'Type' => ['person'],
    'Answer' => ['Yes', 'No'],
];

$combinations = generateCombinations($options);
echo(count($combinations));
# 12
</code>```

It can probably be slightly improved but, all in all, if you don't know in advance the length of $options it does a lot of duplicate iterations. If you know in advance the number of items in $options (let's say it is N) then N nested loops are the fast way to do it.

Body:
I need some help with generation of combinations, specifically in the store they're the variants of each product, e.g size and colour.

Let's say we have 3 customizable properties of the product:
Colour, Size, and Type.

For this specific product, the following are available of each property:
Color: [red, green], Size: [10, 11, 15], Type: [person]

Now according to the above data, I need to generate 6 combinations, however if we added another type it would increase even more.

I have been drawing on my board for 2 hours now trying to come up with a sane algorithm for this, something that's fast and can deal with thousands of combinations in a matter of seconds.

Take this example:

$options = ['Color' => ['Red', 'Green'], 'Size' => ['10', '11', '15'], 'Type' => ['person']];
$combinations = generateCombinations($options);

genereateCombinations would then need to generate the following output:

[
    ['Color' => 'Red', 'Size' => '10', 'Type' => 'person'],
    ['Color' => 'Red', 'Size' => '11', 'Type' => 'person'],
    ['Color' => 'Red', 'Size' => '15', 'Type' => 'person'],
    ['Color' => 'Green', 'Size' => '10', 'Type' => 'person'],
    ['Color' => 'Green', 'Size' => '11', 'Type' => 'person'],
    ['Color' => 'Green', 'Size' => '15', 'Type' => 'person']
];

What algorithm could do this efficiently and with unlimited input "titles"? (of course I'll enforce a limit earlier, but the algorithm should be able to do unlimited granted all the resources in the world)

Extending what I mean:
This function also needs to be able to take for example an array with 100 property rows, not just 3, it needs to be able to do this dynamically no matter the number of input rows.

Body:
Three foreach loops are enough to generate all combinations, no matter how many entries are in $options:

function generateCombinations(array $options)
{
    // Start with one combination of length zero
    $all = array(array());

    // On each iteration append all possible values of the new key
    // to all items in $all; generate this way all the combinations
    // one item longer than before
    foreach ($options as $key => $values) {
        // Move all combinations of length N from $all to $current
        $current = $all;
        // Start with an empty list of combinations of length N+1
        $all = array();
        // Combine each combination of length N
        // with all possible values for the (N+1)th key
        foreach ($current as $one) {
           foreach ($values as $val) {
              // Put each new combination in $all (length N+1)
              $all[] = array_merge($one, array($key => $val));
           }
        }
    }

    return $all;
}

$options = [
    'Color' => ['Red', 'Green'],
    'Size' => ['10', '11', '15'],
    'Type' => ['person'],
    'Answer' => ['Yes', 'No'],
];

$combinations = generateCombinations($options);
echo(count($combinations));
# 12

It can probably be slightly improved but, all in all, if you don't know in advance the length of $options it does a lot of duplicate iterations. If you know in advance the number of items in $options (let's say it is N) then N nested loops are the fast way to do it.


问:
Running a .NET core app (.dll) with cmd by using process.start
I'm new to .NET Core 2.0, so i might be doing this all wrong, if so let me know.

I have a .NET core 2.0 app that should be cross platform, hence the app is a .dll console application, and it does work fine on all platforms.

I'm trying to implement kind of a watchdog, that in case of necessary process will duplicate itself, and by the same way it was called

```<code>> $ dotnet process.dll
</code>```

My code is:

```<code>var process = new Process
{
   StartInfo = new ProcessStartInfo
   {
       FileName = "dotnet",
       Arguments = "path\release\PublishOutput\proces.dll"
       UseShellExecute = true,
       RedirectStandardOutput = false,
       RedirectStandardError = false,
       CreateNoWindow = true
     }

 };

 process.Start();
</code>```

The problem is that when the process runs this code, i'm getting the following exception

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.2.0.0, Culture=neutral, PublicKeyToken=sometoken' or one of its dependencies. The system cannot find the file specified.

I can't find any mention of ruining dotnet from code, and i don't know even if this is possible?

Is it possible? Is .NET core process able to duplicate itself?

Thanks

答: It seems you also need to set the WorkingDirectory to path\release\PublishOutput\ to be sure it is running in the same environment as calling dotnet process.dll directly in the console

Body:
I'm new to .NET Core 2.0, so i might be doing this all wrong, if so let me know.

I have a .NET core 2.0 app that should be cross platform, hence the app is a .dll console application, and it does work fine on all platforms.

I'm trying to implement kind of a watchdog, that in case of necessary process will duplicate itself, and by the same way it was called

> $ dotnet process.dll

My code is:

var process = new Process
{
   StartInfo = new ProcessStartInfo
   {
       FileName = "dotnet",
       Arguments = "path\release\PublishOutput\proces.dll"
       UseShellExecute = true,
       RedirectStandardOutput = false,
       RedirectStandardError = false,
       CreateNoWindow = true
     }

 };

 process.Start();

The problem is that when the process runs this code, i'm getting the following exception

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=4.2.0.0, Culture=neutral, PublicKeyToken=sometoken' or one of its dependencies. The system cannot find the file specified.

I can't find any mention of ruining dotnet from code, and i don't know even if this is possible?

Is it possible? Is .NET core process able to duplicate itself?

Thanks


问:
returning a boolean in one line for a ball that has crashed into another ball
I've just started learning java this quarter and on a sample quiz, this is a question. I have no idea where to begin save for the fact that it has to return a boolean type.

Fill in the blank so that this function returns true if the circle at x1, y1, with radius r1, has collided with the circle at x2, y2, with radius r2.

```<code>boolean collided(int x1, int y1, int r1, int x2, int y2, int r2) {
    return ___________________________________________________________;
}
</code>```

Appreciate the comments and kind help. Like I said above, if you had read it, I've just started learning java this quarter and on a sample quiz, this is a question I had no idea where to begin. If anyone is willing to direct me to another learning resource that is better suited for a complete beginner, that would be great.

答:
Balls are collided when distance between their centers is less than sum of their radiuses.

Distance is sqrt((x1-x2)^2 + (y1-y2)^2)

sqrt is square root, a^b is power (a^2 is a*a).

Body:
I've just started learning java this quarter and on a sample quiz, this is a question. I have no idea where to begin save for the fact that it has to return a boolean type.

Fill in the blank so that this function returns true if the circle at x1, y1, with radius r1, has collided with the circle at x2, y2, with radius r2.

boolean collided(int x1, int y1, int r1, int x2, int y2, int r2) {
    return ___________________________________________________________;
}

Appreciate the comments and kind help. Like I said above, if you had read it, I've just started learning java this quarter and on a sample quiz, this is a question I had no idea where to begin. If anyone is willing to direct me to another learning resource that is better suited for a complete beginner, that would be great.


问:
NoMethodError in Spree::Admin::Reviews#index
I am new to spree and ruby on rails.While clicking the 'reviews' in spree back-end, it's throwing an error.

Thanks in Advance.

NoMethodError in Spree::Admin::Reviews#index

Showing - var/lib/gems/2.3.0/ruby/2.3.0/bundler/gems/spree_reviews-e51cae9627f9/app/views/spree/admin/reviews/index.html.erb where line #25 raised:

index.html.erb:

```<code><% content_for :page_title do %>
<%= Spree.t('reviews') %>
<% end %>
<% render 'spree/admin/shared/product_sub_menu' %>
<% content_for :table_filter_title do %>
<%= Spree.t('search') %>
<% end %>
<% content_for :table_filter do %>
<div data-hook="admin_reviews_index_search">

<%= search_form_for [:admin, @search] do |f| %>
    <div class="alpha three columns">
        <div class="field">
            <%= label_tag nil, Spree.t(:user) %><br />
            <%= f.text_field :name_cont, :size => 25 %>
        </div>
    </div>

    <div class="seven columns">
        <div class="field">
            <%= label_tag nil, Spree.t(:title) -%><br/>
            <%= f.text_field :title_cont, :size => 25  -%>
        </div>
    </div>

    <div class="four columns">
        <div class="field">
            <%= label_tag nil, Spree.t(:review) -%><br/>
            <%= f.text_field :review_cont, :size => 25  -%>
        </div>
    </div>

    <div class="two columns omega">
        <div class="field">
            <%= label_tag nil, Spree.t(:approval_status)-%><br/>
            <%= f.select :approved_eq, [[Spree.t('all'), nil],
   [Spree.t('approved_reviews'), true],
   [Spree.t('unapproved_reviews'),false]]  -%>
     </div>
     </div>

     <div class="clear"></div>

     <div class="form-buttons actions filter-actions" data-
      hook="admin_reviews_index_search_buttons">
        <%= button Spree.t(:search), 'icon-search' %>
      </div>
      <%- end -%>
  </div>
  <%- end -%>

<% paginate @reviews %>

<% if @reviews.any? %>
<table class="index">
    <colgroup>
        <col style="width: 25%;">
        <col style="width: 10%;">
        <col style="width: 10%;">
        <col style="width: 20%;">
        <col style="width: 15%;">
        <col style="width: 17%;">
    </colgroup>
    <thead>
        <tr>
            <th><%= Spree.t('product') %></th>
            <th><%= Spree::Review.human_attribute_name(:rating) %></th>
            <th><%= Spree.t('feedback') %></th>
            <th><%= Spree::Review.human_attribute_name(:user) %></th>
            <th><%= Spree::Review.human_attribute_name(:created_at) %></th>
        </tr>
    </thead>
    <tbody>
    <%- @reviews.each do |review| -%>
        <tr id="<%= dom_id review %>">
            <td>
                <% if review.product %>
                    <%= link_to review.product.name, product_path(review.product) %>
                <% end %>
            </td>
            <td class="align-center">
                <%= txt_stars(review.rating) %>
            </td>
            <td class="align-center">
                <%= link_to "(#{review.feedback_stars}/#{review.feedback_reviews.size})", admin_review_feedback_reviews_path(review) %>
            </td>
            <td class="align-center">
                <%= review.user_id ? link_to(review.user.try(:email), [:admin, review.user]) : Spree.t(:anonymous) %></p>
                <p><%= Spree::Review.human_attribute_name(:ip_address) %>: <%= review.ip_address ? link_to(review.ip_address, "http://whois.domaintools.com/#{review.ip_address}") : '-' %></p>
            </td>
            <td class="align-center">
                <%= l review.created_at, :format => :short %>
            </td>
            <td class="actions">
                <%= link_to_with_icon 'check', Spree.t('approve'), approve_admin_review_url(review), :no_text => true, class: 'approve' unless review.approved %>

                <%= link_to_edit review, :no_text => true, :class => 'edit' %>

                <%= link_to_delete review, :no_text => true %>
            </td>
        </tr>
    <% end %>
    </tbody>
</table>
<% else %>
<div class="no-objects-found">
    <%= Spree.t(:no_results) %>
</div>
<% end %>

<%= paginate @reviews -%>
</code>```

reviews_controller

```<code>class Spree::Admin::ReviewsController <
 Spree::Admin::ResourceController
 helper Spree::ReviewsHelper
 def index
   @reviews = collection
   params[:q] ||= {}
   @search = Spree::Review.ransack(params[:q])
   @collection = @search.result.includes([:product, :user,
   :feedback_reviews]).page(params[:page]).per(params[:per_page])
 end
 def approve
 r = Spree::Review.find(params[:id])

 if r.update_attribute(:approved, true)
   flash[:notice] = Spree.t("info_approve_review")
 else
   flash[:error] = Spree.t("error_approve_review")
end
  redirect_to admin_reviews_path
end
def edit
if @review.product.nil?
  flash[:error] = Spree.t("error_no_product")
  redirect_to admin_reviews_path and return
end
end
 private
   def collection
   params[:q] ||= {}
   @search = Spree::Review.ransack(params[:q])
   @collection = @search.result.includes([:product, :user,
  :feedback_reviews]).page(params[:page]).per(params[:per_page])
  end
 end
</code>```

review.rb

```<code>class Spree::Review < ActiveRecord::Base

      belongs_to :product, touch: true
      belongs_to :user, :class_name => Spree.user_class.to_s
      has_many   :feedback_reviews

      after_save :recalculate_product_rating, :if => :approved?
      after_destroy :recalculate_product_rating

      validates :name, presence: true
      validates :review, presence: true

      validates :rating, numericality: { only_integer: true,
      greater_than_or_equal_to: 1,
      less_than_or_equal_to: 5,
      message: Spree.t('you_must_enter_value_for_rating') }

      default_scope { order("spree_reviews.created_at DESC") }

      scope :localized, ->(lc) { where('spree_reviews.locale = ?', lc) }
      scope :most_recent_first, -> { order('spree_reviews.created_at DESC') }
      scope :oldest_first, -> { reorder('spree_reviews.created_at ASC') }
      scope :preview, -> { limit(Spree::Reviews::Config[:preview_size]).oldest_first }
      scope :approved, -> { where(approved: true) }
      scope :not_approved, -> { where(approved: false) }
      scope :default_approval_filter, -> { Spree::Reviews::Config[:include_unapproved_reviews] ? all : approved }

      def feedback_stars
      return 0 if feedback_reviews.size <= 0
      ((feedback_reviews.sum(:rating) / feedback_reviews.size) + 0.5).floor
      end

      def set_search
      @search=Product.search(params[:q])
      end

      def recalculate_product_rating
      self.product.recalculate_rating if product.present?
      end
      end
</code>```

答:
Try to add result method after ransack:</p>

```<code>@search = Spree::Review.ransack(params[:q]).result
</code>```

Body:
I am new to spree and ruby on rails.While clicking the 'reviews' in spree back-end, it's throwing an error.

Thanks in Advance.

NoMethodError in Spree::Admin::Reviews#index

Showing - var/lib/gems/2.3.0/ruby/2.3.0/bundler/gems/spree_reviews-e51cae9627f9/app/views/spree/admin/reviews/index.html.erb where line #25 raised:

index.html.erb:

<% content_for :page_title do %>
<%= Spree.t('reviews') %>
<% end %>
<% render 'spree/admin/shared/product_sub_menu' %>
<% content_for :table_filter_title do %>
<%= Spree.t('search') %>
<% end %>
<% content_for :table_filter do %>

<%= search_form_for [:admin, @search] do |f| %>

            <%= label_tag nil, Spree.t(:user) %>

            <%= f.text_field :name_cont, :size => 25 %>

            <%= label_tag nil, Spree.t(:title) -%>

            <%= f.text_field :title_cont, :size => 25  -%>

            <%= label_tag nil, Spree.t(:review) -%>

            <%= f.text_field :review_cont, :size => 25  -%>

            <%= label_tag nil, Spree.t(:approval_status)-%>

            <%= f.select :approved_eq, [[Spree.t('all'), nil],
   [Spree.t('approved_reviews'), true],
   [Spree.t('unapproved_reviews'),false]]  -%>

        <%= button Spree.t(:search), 'icon-search' %>

      <%- end -%>

  <%- end -%>

<% paginate @reviews %>

<% if @reviews.any? %>

    <colgroup>
        <col style="width: 25%;">
        <col style="width: 10%;">
        <col style="width: 10%;">
        <col style="width: 20%;">
        <col style="width: 15%;">
        <col style="width: 17%;">
    </colgroup>

            <%= Spree.t('product') %>
            <%= Spree::Review.human_attribute_name(:rating) %>
            <%= Spree.t('feedback') %>
            <%= Spree::Review.human_attribute_name(:user) %>
            <%= Spree::Review.human_attribute_name(:created_at) %>

    <%- @reviews.each do |review| -%>
        <tr id="<%= dom_id review %>">

                <% if review.product %>
                    <%= link_to review.product.name, product_path(review.product) %>
                <% end %>

                <%= txt_stars(review.rating) %>

                <%= link_to "(#{review.feedback_stars}/#{review.feedback_reviews.size})", admin_review_feedback_reviews_path(review) %>

                <%= review.user_id ? link_to(review.user.try(:email), [:admin, review.user]) : Spree.t(:anonymous) %>

<%= Spree::Review.human_attribute_name(:ip_address) %>: <%= review.ip_address ? link_to(review.ip_address, "http://whois.domaintools.com/#{review.ip_address}") : '-' %>

                <%= l review.created_at, :format => :short %>

                <%= link_to_with_icon 'check', Spree.t('approve'), approve_admin_review_url(review), :no_text => true, class: 'approve' unless review.approved %>

                <%= link_to_edit review, :no_text => true, :class => 'edit' %>

                <%= link_to_delete review, :no_text => true %>

    <% end %>

<% else %>

    <%= Spree.t(:no_results) %>

<% end %>

<%= paginate @reviews -%>

reviews_controller

class Spree::Admin::ReviewsController <
 Spree::Admin::ResourceController
 helper Spree::ReviewsHelper
 def index
   @reviews = collection
   params[:q] ||= {}
   @search = Spree::Review.ransack(params[:q])
   @collection = @search.result.includes([:product, :user,
   :feedback_reviews]).page(params[:page]).per(params[:per_page])
 end
 def approve
 r = Spree::Review.find(params[:id])

 if r.update_attribute(:approved, true)
   flash[:notice] = Spree.t("info_approve_review")
 else
   flash[:error] = Spree.t("error_approve_review")
end
  redirect_to admin_reviews_path
end
def edit
if @review.product.nil?
  flash[:error] = Spree.t("error_no_product")
  redirect_to admin_reviews_path and return
end
end
 private
   def collection
   params[:q] ||= {}
   @search = Spree::Review.ransack(params[:q])
   @collection = @search.result.includes([:product, :user,
  :feedback_reviews]).page(params[:page]).per(params[:per_page])
  end
 end

review.rb

class Spree::Review < ActiveRecord::Base

      belongs_to :product, touch: true
      belongs_to :user, :class_name => Spree.user_class.to_s
      has_many   :feedback_reviews

      after_save :recalculate_product_rating, :if => :approved?
      after_destroy :recalculate_product_rating

      validates :name, presence: true
      validates :review, presence: true

      validates :rating, numericality: { only_integer: true,
      greater_than_or_equal_to: 1,
      less_than_or_equal_to: 5,
      message: Spree.t('you_must_enter_value_for_rating') }

      default_scope { order("spree_reviews.created_at DESC") }

      scope :localized, ->(lc) { where('spree_reviews.locale = ?', lc) }
      scope :most_recent_first, -> { order('spree_reviews.created_at DESC') }
      scope :oldest_first, -> { reorder('spree_reviews.created_at ASC') }
      scope :preview, -> { limit(Spree::Reviews::Config[:preview_size]).oldest_first }
      scope :approved, -> { where(approved: true) }
      scope :not_approved, -> { where(approved: false) }
      scope :default_approval_filter, -> { Spree::Reviews::Config[:include_unapproved_reviews] ? all : approved }

      def feedback_stars
      return 0 if feedback_reviews.size <= 0
      ((feedback_reviews.sum(:rating) / feedback_reviews.size) + 0.5).floor
      end

      def set_search
      @search=Product.search(params[:q])
      end

      def recalculate_product_rating
      self.product.recalculate_rating if product.present?
      end
      end

Body:
Try to add result method after ransack:

@search = Spree::Review.ransack(params[:q]).result


问:
when we need trim when we don't need in oracle
In Oracle I see, some time 'A  ' = 'A', but some time 'A  ' != 'A', Please see example below you will see detail. I has been try to short the code.

```<code>CREATE TABLE AAA (
    T1 CHAR(3),
    T2 VARCHAR(3),
    T3 VARCHAR(5)
);
insert into AAA
SELECT 'A','A  ', 'A    ' FROM DUAL;
COMMIT;
SELECT * FROM AAA WHERE T1 = 'A'
UNION ALL
SELECT  * FROM AAA WHERE T2 = 'A  '
UNION ALL
SELECT  * FROM AAA WHERE T2 = 'A    '
UNION ALL
SELECT  * FROM AAA WHERE TRIM(T2) = TRIM('A   ')
UNION ALL
SELECT CASE WHEN 'A' = 'A ' THEN '1' ELSE '0' END T1,
       CASE WHEN 'A       ' = 'A' THEN '1' ELSE '0' END T2,
       CASE WHEN 'A ' = 'A ' THEN '1' ELSE '0' END T2
FROM DUAL;
</code>```

I ask this question because in my db, When I join table A to table B some time we TRIM(A.ID) = TRIM(B.REFID) some time we don't need to do this. When we need TRIM(column)? When 'A  ' = 'A' ? and when 'A  ' != 'A'?

答:
Looking at the Oracle Documentation on literals:

Text literals have properties of both the CHAR and VARCHAR2 datatypes:

Within expressions and conditions, Oracle treats text literals as though they have the datatype CHAR by comparing them using blank-padded comparison semantics.

and the documentation of blank-padded comparison semantics states:

With blank-padded semantics, if the two values have different lengths, then Oracle first adds blanks to the end of the shorter one so their lengths are equal. Oracle then compares the values character by character up to the first character that differs. The value with the greater character in the first differing position is considered greater. If two values have no differing characters, then they are considered equal. This rule means that two values are equal if they differ only in the number of trailing blanks. Oracle uses blank-padded comparison semantics only when both values in the comparison are either expressions of datatype CHAR, NCHAR, text literals, or values returned by the USER function.

So, for your examples:

```<code>SELECT * FROM AAA WHERE T1 = 'A'
</code>```

Since the left-hand side of the comparison, T1 which equals 'A  ', is a CHAR(3) and the right-hand side is a text literal 'A' then blank-padded comparison semantics are used and 'A  ' = 'A' is true.

Then:

```<code>SELECT  * FROM AAA WHERE T2 = 'A  '
</code>```

The left-hand side of the comparison, T2 which equals 'A  ', is a VARCHAR2(3) and the right-hand side is a text literal 'A  ' then blank-padded comparison semantics are not used (both sides are not CHAR or text literals) but the values are equal ('A  ' = 'A  ') so the condition is true.

And:

```<code>SELECT  * FROM AAA WHERE T2 = 'A    '
</code>```

The LHS is a VARCHAR2 equal to 'A  ' and the RHS is a text literal equal to 'A     '; blank-padded comparison semantics will not be used and the values are not equal so the condition is not true and the row will not be returned.

Then:

```<code>SELECT  * FROM AAA WHERE TRIM(T2) = TRIM('A   ')
</code>```

The TRIM() function states that:

The string returned is of VARCHAR2 datatype if trim_source is a character datatype and a LOB if trim_source is a LOB datatype.

Both values are trimmed so you have the condition 'A' = 'A' where both sides are a VARCAHR2 data type so blank-padded comparison semantics will not be used but the values are equal so the condition is true and the row will be returned.

Finally:

```<code>SELECT CASE WHEN 'A' = 'A ' THEN '1' ELSE '0' END T1,
       CASE WHEN 'A       ' = 'A' THEN '1' ELSE '0' END T2,
       CASE WHEN 'A ' = 'A ' THEN '1' ELSE '0' END T2
FROM DUAL;
</code>```

In all cases both sides of the equality are text literals so blank-padded comparison semantics will be used so for

'A' = 'A ' the LHS will be padded so the strings are the same length;

'A       ' = 'A' the RHS will be padded;

'A ' = 'A ' both sides are equal length so no padding is needed.

And in each case the equalities are equal.

If you use CAST to change from text literals to a VARCHAR2 data type:

```<code>SELECT CASE WHEN 'A' = CAST( 'A ' AS VARCHAR2(5) ) THEN 1 ELSE 0 END AS T1
FROM   DUAL
</code>```

The LHS is a text literal but the RHS is a VARCHAR2 and blank-padded comparison semantics are not used and the equality is not true.

Body:
In Oracle I see, some time 'A  ' = 'A', but some time 'A  ' != 'A', Please see example below you will see detail. I has been try to short the code.

CREATE TABLE AAA (
    T1 CHAR(3),
    T2 VARCHAR(3),
    T3 VARCHAR(5)
);
insert into AAA
SELECT 'A','A  ', 'A    ' FROM DUAL;
COMMIT;
SELECT * FROM AAA WHERE T1 = 'A'
UNION ALL
SELECT  * FROM AAA WHERE T2 = 'A  '
UNION ALL
SELECT  * FROM AAA WHERE T2 = 'A    '
UNION ALL
SELECT  * FROM AAA WHERE TRIM(T2) = TRIM('A   ')
UNION ALL
SELECT CASE WHEN 'A' = 'A ' THEN '1' ELSE '0' END T1,
       CASE WHEN 'A       ' = 'A' THEN '1' ELSE '0' END T2,
       CASE WHEN 'A ' = 'A ' THEN '1' ELSE '0' END T2
FROM DUAL;

I ask this question because in my db, When I join table A to table B some time we TRIM(A.ID) = TRIM(B.REFID) some time we don't need to do this. When we need TRIM(column)? When 'A  ' = 'A' ? and when 'A  ' != 'A'?

Body:
Looking at the Oracle Documentation on literals:

Text literals have properties of both the CHAR and VARCHAR2 datatypes:

Within expressions and conditions, Oracle treats text literals as though they have the datatype CHAR by comparing them using blank-padded comparison semantics.

and the documentation of blank-padded comparison semantics states:

With blank-padded semantics, if the two values have different lengths, then Oracle first adds blanks to the end of the shorter one so their lengths are equal. Oracle then compares the values character by character up to the first character that differs. The value with the greater character in the first differing position is considered greater. If two values have no differing characters, then they are considered equal. This rule means that two values are equal if they differ only in the number of trailing blanks. Oracle uses blank-padded comparison semantics only when both values in the comparison are either expressions of datatype CHAR, NCHAR, text literals, or values returned by the USER function.

So, for your examples:

SELECT * FROM AAA WHERE T1 = 'A'

Since the left-hand side of the comparison, T1 which equals 'A  ', is a CHAR(3) and the right-hand side is a text literal 'A' then blank-padded comparison semantics are used and 'A  ' = 'A' is true.

Then:

SELECT  * FROM AAA WHERE T2 = 'A  '

The left-hand side of the comparison, T2 which equals 'A  ', is a VARCHAR2(3) and the right-hand side is a text literal 'A  ' then blank-padded comparison semantics are not used (both sides are not CHAR or text literals) but the values are equal ('A  ' = 'A  ') so the condition is true.

And:

SELECT  * FROM AAA WHERE T2 = 'A    '

The LHS is a VARCHAR2 equal to 'A  ' and the RHS is a text literal equal to 'A     '; blank-padded comparison semantics will not be used and the values are not equal so the condition is not true and the row will not be returned.

Then:

SELECT  * FROM AAA WHERE TRIM(T2) = TRIM('A   ')

The TRIM() function states that:

The string returned is of VARCHAR2 datatype if trim_source is a character datatype and a LOB if trim_source is a LOB datatype.

Both values are trimmed so you have the condition 'A' = 'A' where both sides are a VARCAHR2 data type so blank-padded comparison semantics will not be used but the values are equal so the condition is true and the row will be returned.

Finally:

SELECT CASE WHEN 'A' = 'A ' THEN '1' ELSE '0' END T1,
       CASE WHEN 'A       ' = 'A' THEN '1' ELSE '0' END T2,
       CASE WHEN 'A ' = 'A ' THEN '1' ELSE '0' END T2
FROM DUAL;

In all cases both sides of the equality are text literals so blank-padded comparison semantics will be used so for

'A' = 'A ' the LHS will be padded so the strings are the same length;

'A       ' = 'A' the RHS will be padded;

'A ' = 'A ' both sides are equal length so no padding is needed.

And in each case the equalities are equal.

If you use CAST to change from text literals to a VARCHAR2 data type:

SELECT CASE WHEN 'A' = CAST( 'A ' AS VARCHAR2(5) ) THEN 1 ELSE 0 END AS T1
FROM   DUAL

The LHS is a text literal but the RHS is a VARCHAR2 and blank-padded comparison semantics are not used and the equality is not true.


问:
Merge & display records from two different tables
I have to create a view using 2 tables

Table 1:

```<code>TokenNumber     Symbol      InstType    LotSize     TickSize   sin              ClosePrice
------------------------------------------------------------------------------------------
22              ACC         EQ          1           0.01       INE012A01025     0
25              ADANIENT    EQ          1           0.01       INE423A01024     0
</code>```

Table 2:

```<code>TokenNumber     InstType   Symbol     ExpiryDate    CMToken    sorted_index
---------------------------------------------------------------------------
46676           FUTSTK     ACC        25-Jan-18     22         12
48205           FUTSTK     ACC        28-Dec-17     22         8
4820546676      FUTSTK     ACC        28-Dec-17     22         3
5361748205      FUTSTK     ACC        30-Nov-17     22         1
53618           FUTSTK     ADANIENT   30-Nov-17     25         3
4820646677      FUTSTK     ADANIENT   28-Dec-17     25         3
48206           FUTSTK     ADANIENT   28-Dec-17     25         8
46677           FUTSTK     ADANIENT   25-Jan-18     25         12
</code>```

Thus to join both tables we have primary key of Table1(TokenNumber) in Table2(CMToken).

I have to show all the columns of both tables and records in a specific order(1st record from Table1  and next all records from Table2 where Table1.TokenNumber=Table2.CMToken).

New view with record order will be like:

```<code>TokenNumber  Symbol       InstType   LotSize    TickSize   Isin           ClosePrice    ExpiryDate      sorted_index
--------------------------------------------------------------------------------------------------------------------
22           ACC          EQ         1          0.01       INE012A01025   0             NULL            NULL
46676        ACC          FUTSTK     NULL       NULL       NULL           NULL          25-Jan-18       0
48205        ACC          FUTSTK     NULL       NULL       NULL           NULL          28-Dec-17       1
4820546676   ACC          FUTSTK     NULL       NULL       NULL           NULL          28-Dec-17       2
25           ADANIENT     EQ         1          0.01       INE423A01024   0             NULL            NULL
53618        ADANIENT     FUTSTK     NULL       NULL       NULL           NULL          30-Nov-17       0
4820646677   ADANIENT     FUTSTK     NULL       NULL       NULL           NULL          28-Dec-17       1
48206        ADANIENT     FUTSTK     NULL       NULL       NULL           NULL          28-Dec-17       3
46677        ADANIENT     FUTSTK     NULL       NULL       NULL           NULL          25-Jan-18       2
</code>```

Please suggest the query.

Thanks & Regards

答:
Looking in to your sample data and output, I think you actually want to assign sorted_index = NULL to values of table1 and sorted_index = row_number() partition by CMToken and order by TokenNumber starting from 0 to table2. After that you want to sort it by placing row of table1 on top of associated rows of table2 and among table2 rows, you want to sort it by row_number().

```<code>SELECT TokenNumber
    ,Symbol
    ,InstType
    ,LotSize
    ,TickSize
    ,Isin
    ,ClosePrice
    ,Expiry_Date
    ,sorted_index
FROM (
    SELECT TokenNumber
        ,Symbol
        ,InstType
        ,LotSize
        ,TickSize
        ,Isin
        ,ClosePrice
        ,NULL AS Expiry_Date
        ,NULL AS sorted_index
        ,TokenNumber AS CMToken
    FROM table1 t1

    UNION ALL

    SELECT TokenNumber
        ,InstType
        ,Symbol
        ,NULL
        ,NULL
        ,NULL
        ,NULL
        ,ExpiryDate
        ,row_number() OVER (
            PARTITION BY CMToken ORDER BY TokenNumber
            ) - 1 AS sorted_index
        ,CMToken
    FROM table2 t2
    ) t
ORDER BY CMToken
    ,sorted_index
</code>```

Result:

```<code> +-------------+----------+----------+---------+----------+--------------+------------+---------------------+--------------+
| TokenNumber |  Symbol  | InstType | LotSize | TickSize |     Isin     | ClosePrice |     Expiry_Date     | sorted_index |
+-------------+----------+----------+---------+----------+--------------+------------+---------------------+--------------+
|          22 | ACC      | EQ       | 1       | 0,01     | INE012A01025 | 0          | NULL                | NULL         |
|       46676 | FUTSTK   | ACC      | NULL    | NULL     | NULL         | NULL       | 25.01.2018 00:00:00 | 0            |
|       48205 | FUTSTK   | ACC      | NULL    | NULL     | NULL         | NULL       | 28.12.2017 00:00:00 | 1            |
|  4820546676 | FUTSTK   | ACC      | NULL    | NULL     | NULL         | NULL       | 28.12.2017 00:00:00 | 2            |
|  5361748205 | FUTSTK   | ACC      | NULL    | NULL     | NULL         | NULL       | 30.11.2017 00:00:00 | 3            |
|          25 | ADANIENT | EQ       | 1       | 0,01     | INE423A01024 | 0          | NULL                | NULL         |
|       46677 | FUTSTK   | ADANIENT | NULL    | NULL     | NULL         | NULL       | 25.01.2018 00:00:00 | 0            |
|       48206 | FUTSTK   | ADANIENT | NULL    | NULL     | NULL         | NULL       | 28.12.2017 00:00:00 | 1            |
|       53618 | FUTSTK   | ADANIENT | NULL    | NULL     | NULL         | NULL       | 30.11.2017 00:00:00 | 2            |
|  4820646677 | FUTSTK   | ADANIENT | NULL    | NULL     | NULL         | NULL       | 28.12.2017 00:00:00 | 3            |
+-------------+----------+----------+---------+----------+--------------+------------+---------------------+--------------+
</code>```

DEMO

Body:
I have to create a view using 2 tables

Table 1:

TokenNumber     Symbol      InstType    LotSize     TickSize   sin              ClosePrice
------------------------------------------------------------------------------------------
22              ACC         EQ          1           0.01       INE012A01025     0
25              ADANIENT    EQ          1           0.01       INE423A01024     0

Table 2:

TokenNumber     InstType   Symbol     ExpiryDate    CMToken    sorted_index
---------------------------------------------------------------------------
46676           FUTSTK     ACC        25-Jan-18     22         12
48205           FUTSTK     ACC        28-Dec-17     22         8
4820546676      FUTSTK     ACC        28-Dec-17     22         3
5361748205      FUTSTK     ACC        30-Nov-17     22         1
53618           FUTSTK     ADANIENT   30-Nov-17     25         3
4820646677      FUTSTK     ADANIENT   28-Dec-17     25         3
48206           FUTSTK     ADANIENT   28-Dec-17     25         8
46677           FUTSTK     ADANIENT   25-Jan-18     25         12

Thus to join both tables we have primary key of Table1(TokenNumber) in Table2(CMToken).

I have to show all the columns of both tables and records in a specific order(1st record from Table1  and next all records from Table2 where Table1.TokenNumber=Table2.CMToken).

New view with record order will be like:

TokenNumber  Symbol       InstType   LotSize    TickSize   Isin           ClosePrice    ExpiryDate      sorted_index
--------------------------------------------------------------------------------------------------------------------
22           ACC          EQ         1          0.01       INE012A01025   0             NULL            NULL
46676        ACC          FUTSTK     NULL       NULL       NULL           NULL          25-Jan-18       0
48205        ACC          FUTSTK     NULL       NULL       NULL           NULL          28-Dec-17       1
4820546676   ACC          FUTSTK     NULL       NULL       NULL           NULL          28-Dec-17       2
25           ADANIENT     EQ         1          0.01       INE423A01024   0             NULL            NULL
53618        ADANIENT     FUTSTK     NULL       NULL       NULL           NULL          30-Nov-17       0
4820646677   ADANIENT     FUTSTK     NULL       NULL       NULL           NULL          28-Dec-17       1
48206        ADANIENT     FUTSTK     NULL       NULL       NULL           NULL          28-Dec-17       3
46677        ADANIENT     FUTSTK     NULL       NULL       NULL           NULL          25-Jan-18       2

Please suggest the query.

Thanks & Regards

Body:
Looking in to your sample data and output, I think you actually want to assign sorted_index = NULL to values of table1 and sorted_index = row_number() partition by CMToken and order by TokenNumber starting from 0 to table2. After that you want to sort it by placing row of table1 on top of associated rows of table2 and among table2 rows, you want to sort it by row_number().

SELECT TokenNumber
    ,Symbol
    ,InstType
    ,LotSize
    ,TickSize
    ,Isin
    ,ClosePrice
    ,Expiry_Date
    ,sorted_index
FROM (
    SELECT TokenNumber
        ,Symbol
        ,InstType
        ,LotSize
        ,TickSize
        ,Isin
        ,ClosePrice
        ,NULL AS Expiry_Date
        ,NULL AS sorted_index
        ,TokenNumber AS CMToken
    FROM table1 t1

    UNION ALL

    SELECT TokenNumber
        ,InstType
        ,Symbol
        ,NULL
        ,NULL
        ,NULL
        ,NULL
        ,ExpiryDate
        ,row_number() OVER (
            PARTITION BY CMToken ORDER BY TokenNumber
            ) - 1 AS sorted_index
        ,CMToken
    FROM table2 t2
    ) t
ORDER BY CMToken
    ,sorted_index

Result:

 +-------------+----------+----------+---------+----------+--------------+------------+---------------------+--------------+
| TokenNumber |  Symbol  | InstType | LotSize | TickSize |     Isin     | ClosePrice |     Expiry_Date     | sorted_index |
+-------------+----------+----------+---------+----------+--------------+------------+---------------------+--------------+
|          22 | ACC      | EQ       | 1       | 0,01     | INE012A01025 | 0          | NULL                | NULL         |
|       46676 | FUTSTK   | ACC      | NULL    | NULL     | NULL         | NULL       | 25.01.2018 00:00:00 | 0            |
|       48205 | FUTSTK   | ACC      | NULL    | NULL     | NULL         | NULL       | 28.12.2017 00:00:00 | 1            |
|  4820546676 | FUTSTK   | ACC      | NULL    | NULL     | NULL         | NULL       | 28.12.2017 00:00:00 | 2            |
|  5361748205 | FUTSTK   | ACC      | NULL    | NULL     | NULL         | NULL       | 30.11.2017 00:00:00 | 3            |
|          25 | ADANIENT | EQ       | 1       | 0,01     | INE423A01024 | 0          | NULL                | NULL         |
|       46677 | FUTSTK   | ADANIENT | NULL    | NULL     | NULL         | NULL       | 25.01.2018 00:00:00 | 0            |
|       48206 | FUTSTK   | ADANIENT | NULL    | NULL     | NULL         | NULL       | 28.12.2017 00:00:00 | 1            |
|       53618 | FUTSTK   | ADANIENT | NULL    | NULL     | NULL         | NULL       | 30.11.2017 00:00:00 | 2            |
|  4820646677 | FUTSTK   | ADANIENT | NULL    | NULL     | NULL         | NULL       | 28.12.2017 00:00:00 | 3            |
+-------------+----------+----------+---------+----------+--------------+------------+---------------------+--------------+

DEMO


问:
Updating version in pom.xml (maven project)
My goal is to change version of a dependance , I modifiy the version in pom.xml  but when I check the effective pom , there are the two versions , in addition.
I clean install maven where it download the new version and when I build it , the new version doesn't appear
I can't unterstand why , help please.</p>

答:
The effective pom is not a good place to understand the dependencies.

If you want to use a specific version of a dependency, either set this version in your dependencyManagement or add it to your dependencies. Then you can use dependency:list to check whether your version is indeed drawn. If not, have a look at dependency:tree to find out where the wrong entry comes from. If unsure about the result, post it here.