问:
Why does my Ubuntu machine not have the /dev/cpu/0/cpuid directoy?
I try to run ./TurionPowerControl -spec as obtained from the following link (note that it had to be slightly modified to be compatible with a newer GCC):
https://github.com/turionpowercontrol/tpc/wiki

I get the following output:

```<code>Turion Power States Optimization and Control - by blackshard

ERROR: couldn't open /dev/cpu/0/cpuid (No such file or directory). Make sure that cpuid module is loaded.
</code>```

My question is simply: Why is there no such file or directory in my system? I am using Ubuntu Server 18.04.4 LTS on a Dell Inspiron 1501 Laptop. I looked through the code and I found the following snippet in sysdep-linux.cpp, which I think contains the line of code that outputs the error message:

```<code>#include <term.h>
#include <curses.h>
#include <unistd.h>

#include <fcntl.h>
#include <errno.h>
#include <string.h>

#include <signal.h>

#include "cpuPrimitives.h"

bool initializeCore()
{
        int fd;

        fd = open("/dev/cpu/0/cpuid", O_RDONLY);
        if (fd == -1) {
                printf("ERROR: couldn't open /dev/cpu/0/cpuid (%s).", strerror(errno));
                if (errno == ENXIO || errno == ENOENT) {
                        printf(" Make sure that cpuid module is loaded.\n");
                        return false;
                }
                if (errno == EACCES) {
                        printf(" Not root?.\n");
                        return false;
                }
                printf("\n");
                return false;
.
.
.
</code>```

答:
Probably because, as illustrated in this article, it uses the CPUID device driver, which is not installed by default:

```<code>sudo apt-get install -y cpuid
</code>```

See the driver description here.

The OP Nicholas confirms in the comments having to add a modules (modprob)

```<code>sudo modprobe cpuid
</code>```

Body:
I try to run ./TurionPowerControl -spec as obtained from the following link (note that it had to be slightly modified to be compatible with a newer GCC):
https://github.com/turionpowercontrol/tpc/wiki

I get the following output:

Turion Power States Optimization and Control - by blackshard

ERROR: couldn't open /dev/cpu/0/cpuid (No such file or directory). Make sure that cpuid module is loaded.

My question is simply: Why is there no such file or directory in my system? I am using Ubuntu Server 18.04.4 LTS on a Dell Inspiron 1501 Laptop. I looked through the code and I found the following snippet in sysdep-linux.cpp, which I think contains the line of code that outputs the error message:

#include <term.h>
#include <curses.h>
#include <unistd.h>

#include <fcntl.h>
#include <errno.h>
#include <string.h>

#include <signal.h>

#include "cpuPrimitives.h"

bool initializeCore()
{
        int fd;

        fd = open("/dev/cpu/0/cpuid", O_RDONLY);
        if (fd == -1) {
                printf("ERROR: couldn't open /dev/cpu/0/cpuid (%s).", strerror(errno));
                if (errno == ENXIO || errno == ENOENT) {
                        printf(" Make sure that cpuid module is loaded.\n");
                        return false;
                }
                if (errno == EACCES) {
                        printf(" Not root?.\n");
                        return false;
                }
                printf("\n");
                return false;
.
.
.

Body:
Probably because, as illustrated in this article, it uses the CPUID device driver, which is not installed by default:

sudo apt-get install -y cpuid

See the driver description here.

The OP Nicholas confirms in the comments having to add a modules (modprob)

sudo modprobe cpuid


来源: stackexchange

问:
How to prevent wrong values in an initializer list?
When you write a constructor, you have the opportunity to test the values of the arguments from out of range or other unwanted situations in its body.

```<code>class a
{
  int b;
public:
  a(int c)
  {
    if(c < MIN_ALLOWED || c > MAX_ALLOWED)
    {
      // Take some measure
    }
    else
    {
      b = c;
    }
  }
};
</code>```

But when you're dealing with const members, they should be initialized by means of an initializer list, so, in this case, how to prevent unwanted values?

```<code>class a
{
  const int b;
public:
  a(int c) : b(c)
  {
    // How to control "c" value?!...
  }
};
</code>```

答:
```<code>class a
{
    const int b;
public:
    a(int c) : b((c < MIN_ALLOWED || c > MAX_ALLOWED) ? throw std::logic_error("bad") : c)
    {
        // How to control "c" value?!...
    }
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When you write a constructor, you have the opportunity to test the values of the arguments from out of range or other unwanted situations in its body.

class a
{
  int b;
public:
  a(int c)
  {
    if(c < MIN_ALLOWED || c > MAX_ALLOWED)
    {
      // Take some measure
    }
    else
    {
      b = c;
    }
  }
};

But when you're dealing with const members, they should be initialized by means of an initializer list, so, in this case, how to prevent unwanted values?

class a
{
  const int b;
public:
  a(int c) : b(c)
  {
    // How to control "c" value?!...
  }
};


问:
What does this block of JS code mean?

Possible Duplicate:

  What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

```<code>   (function(window){
              // some codes here
                    })(window);
</code>```

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?

答:
As far your questions regarding window, the window in parentheses at the bottom is a reference to the global window object. The first window is just a name for a parameter. But in this instance it refers to the global window object since you're using an anonymous self-invoked function. You could call it monkeys and it wouldn't make a difference (of course, you'd have to use monkeys within the body of the anonymous function then, to refer to the parameter). So now, you now have a reference to the global window object within your function.

Yes, the function is invoked once and it is invoked as soon as it is defined. This is because it is a self-invoked anonymous function.

Title: What does this block of JS code mean?

Body:
Possible Duplicate:

  What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

   (function(window){
              // some codes here
                    })(window);

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?

ContentLicense: CC BY-SA 3.0


问:
Ensuring a NuGet package can only be installed from a specific feed
I have an Azure Pipelines job setup to authenticate to a private NuGet feed in Azure Artifacts, and then build my .NET project that relies on a NuGet package in the feed. However, my private package is a pretty common name. How can I ensure that it only installs that specific package from my private feed, and doesn't try to fallback to the NuGet general gallery? I do not want it to pull in an incorrect package that has the same name and version name as my private package.</p>

答: Once you configure multiple sources/feeds, NuGet will look for a package in all these sources together with no guarantee of where the package will be downloaded from. However, you could make the AzDo artifacts feed as the only configured feed and then upstream other sources from it. This way NuGet will get all packages from the configured AzDo artifacts source and AzDo artifacts will source other packages not available with it from the upstreamed sources in the order defined. More info can be found here: https://learn.microsoft.com/en-us/azure/devops/artifacts/concepts/upstream-sources?view=azure-devops</p>


问:
SERIAL for each value in another column
I want to have one column be an auto-incrementing sequence which counts up within values of other column(s).

e.g.

```<code>|  flav  | count|
| 'choc' |   1  |
| 'choc' |   2  |
|'banana'|   1  |
| 'choc' |   3  |
|'banana'|   2  |
| 'mint' |   1  |
|'banana'|   3  |
|   ...  |  ... |
</code>```

An individual row insert could of course be achieved with 2 separate queries, a SELECT COUNT followed by an INSERT, but this doesn't allow efficient batch inserts and I'm sure there's a better way.

I want to be able to just do INSERT INTO orders (flav) VALUES ('choc'); and have the schema handle the count column, like it would handle an auto-incrementing column.

I tried to define a DEFAULT expression for the count column in the schema which would be a SELECT COUNT query, but no dice: ERROR:  cannot use subquery in DEFAULT expression.

答:
Use the window function row_number.</p>

```<code>with flavor_list (flavor) as
 ( values
           ( 'choc' )
         , ( 'choc' )
         , ('banana')
         , ( 'choc' )
         , ('banana')
         , ( 'mint' )
         , ('banana')
  )
select flavor, row_number() over(partition by flavor)
 from flavor_list;
</code>```

Title: SERIAL for each value in another column

Body:
I want to have one column be an auto-incrementing sequence which counts up within values of other column(s).

e.g.

|  flav  | count|
| 'choc' |   1  |
| 'choc' |   2  |
|'banana'|   1  |
| 'choc' |   3  |
|'banana'|   2  |
| 'mint' |   1  |
|'banana'|   3  |
|   ...  |  ... |

An individual row insert could of course be achieved with 2 separate queries, a SELECT COUNT followed by an INSERT, but this doesn't allow efficient batch inserts and I'm sure there's a better way.

I want to be able to just do INSERT INTO orders (flav) VALUES ('choc'); and have the schema handle the count column, like it would handle an auto-incrementing column.

I tried to define a DEFAULT expression for the count column in the schema which would be a SELECT COUNT query, but no dice: ERROR:  cannot use subquery in DEFAULT expression.

Body:
Use the window function row_number.

with flavor_list (flavor) as
 ( values
           ( 'choc' )
         , ( 'choc' )
         , ('banana')
         , ( 'choc' )
         , ('banana')
         , ( 'mint' )
         , ('banana')
  )
select flavor, row_number() over(partition by flavor)
 from flavor_list;


问:
Sort a list by a given criteria
i have a list of strings i want to sort by only the numerical suffix of the string.
Below is what i have tried.
My desired output is ["ak-2","ss-12","aa-20","pp-90"]</p>

```<code>List<String> list1 = new ArrayList<>;
list1.add("aa-20");
list1.add("ss-12");
list1.add("ak-2");
list1.add("pp-90");
Collections.sort(list1);
</code>```

答:
Try this ::

```<code>
        List<String> list1 = new ArrayList<>();
        list1.add("aa-20");
        list1.add("ss-12");
        list1.add("ak-2");
        list1.add("pp-90");

        Comparator<String> comp=new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                o1=o1.substring(o1.indexOf("-")+1);
                o2=o2.substring(o2.indexOf("-")+1);
                if(Integer.parseInt(o1)>Integer.parseInt(o2)){
                    return 1;
                }
                return -1;
            }
        };

        Collections.sort(list1, comp);
        System.out.println(list1);

</code>```

Let me know if this helps.

Title: Sort a list by a given criteria

Body:
i have a list of strings i want to sort by only the numerical suffix of the string.
Below is what i have tried.
My desired output is ["ak-2","ss-12","aa-20","pp-90"]

List<String> list1 = new ArrayList<>;
list1.add("aa-20");
list1.add("ss-12");
list1.add("ak-2");
list1.add("pp-90");
Collections.sort(list1);

Body:
Try this ::

        List<String> list1 = new ArrayList<>();
        list1.add("aa-20");
        list1.add("ss-12");
        list1.add("ak-2");
        list1.add("pp-90");

        Comparator<String> comp=new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                o1=o1.substring(o1.indexOf("-")+1);
                o2=o2.substring(o2.indexOf("-")+1);
                if(Integer.parseInt(o1)>Integer.parseInt(o2)){
                    return 1;
                }
                return -1;
            }
        };

        Collections.sort(list1, comp);
        System.out.println(list1);

Let me know if this helps.


问:
Use list comprehension to find largest int value in kwargs that also contain a certain substring
Here's my code because I think it's easier to explain what I'm trying to do by showing what I'm doing first.

Let's say these are my kwargs passed to a function:

```<code>kwargs = {fastperiod=20, slowperiod=10, r=100}
</code>```

So I am trying to find the largest value of kwargs that also contain the substring period. In this case that would mean 20.

I am currently doing this with:

```<code>periods = []
    for kwarg in kwargs:
        if 'period' in kwarg:
            periods.append(kwargs.get(kwarg))
    max_ = max(periods)
</code>```

Which is not very terse. I feel like there has to be a way to achieve this with list comprehension.

The best I could come up with is:

```<code>max_ = max([i for i in kwargs.get(i) if 'period' in i])
</code>```

But I get an UnboundLocalError: local variable 'i' referenced before assignment

I am not sure how to check if kwarg contains period and then return the int value assigned to it at the same time.

答:
This will work friend </p>

```<code>kwargs = {'fastperiod':20, 'slowperiod':10, 'r':100}

max_ = max([kwargs[kwarg] for kwarg in kwargs if 'period' in kwarg])
</code>```

Body:
Here's my code because I think it's easier to explain what I'm trying to do by showing what I'm doing first.

Let's say these are my kwargs passed to a function:

kwargs = {fastperiod=20, slowperiod=10, r=100}

So I am trying to find the largest value of kwargs that also contain the substring period. In this case that would mean 20.

I am currently doing this with:

periods = []
    for kwarg in kwargs:
        if 'period' in kwarg:
            periods.append(kwargs.get(kwarg))
    max_ = max(periods)

Which is not very terse. I feel like there has to be a way to achieve this with list comprehension.

The best I could come up with is:

max_ = max([i for i in kwargs.get(i) if 'period' in i])

But I get an UnboundLocalError: local variable 'i' referenced before assignment

I am not sure how to check if kwarg contains period and then return the int value assigned to it at the same time.

Body:
This will work friend

kwargs = {'fastperiod':20, 'slowperiod':10, 'r':100}

max_ = max([kwargs[kwarg] for kwarg in kwargs if 'period' in kwarg])


问:
How to bypass python function definition with decorator?
I would like to know if its possible to control Python function definition based on global settings (e.g. OS). Example:

```<code>@linux
def my_callback(*args, **kwargs):
    print("Doing something @ Linux")
    return

@windows
def my_callback(*args, **kwargs):
    print("Doing something @ Windows")
    return
</code>```

Then, if someone is using Linux, the first definition of my_callback will be used and the second will be silently ignored.

Its not about determining the OS, its about function definition / decorators.

答:
If the goal is to have the same sort of effect in your code that #ifdef WINDOWS / #endif has.. here's a way to do it (I'm on a mac btw).

Simple Case, No Chaining

```<code>>>> def _ifdef_decorator_impl(plat, func, frame):
...     if platform.system() == plat:
...         return func
...     elif func.__name__ in frame.f_locals:
...         return frame.f_locals[func.__name__]
...     else:
...         def _not_implemented(*args, **kwargs):
...             raise NotImplementedError(
...                 f"Function {func.__name__} is not defined "
...                 f"for platform {platform.system()}.")
...         return _not_implemented
...
...
>>> def windows(func):
...     return _ifdef_decorator_impl('Windows', func, sys._getframe().f_back)
...
>>> def macos(func):
...     return _ifdef_decorator_impl('Darwin', func, sys._getframe().f_back)
</code>```

So with this implementation you get same syntax you have in your question.

```<code>>>> @macos
... def zulu():
...     print("world")
...
>>> @windows
... def zulu():
...     print("hello")
...
>>> zulu()
world
>>>
</code>```

What the code above is doing, essentially, is assigning zulu to zulu if the platform matches. If the platform doesn't match, it'll return zulu if it was previously defined. If it wasn't defined, it returns a placeholder function that raises an exception.

Decorators are conceptually easy to figure out if you keep in mind that

```<code>@mydecorator
def foo():
    pass
</code>```

is analogous to:

```<code>foo = mydecorator(foo)
</code>```

Here's an implementation using a parameterized decorator:

```<code>>>> def ifdef(plat):
...     frame = sys._getframe().f_back
...     def _ifdef(func):
...         return _ifdef_decorator_impl(plat, func, frame)
...     return _ifdef
...
>>> @ifdef('Darwin')
... def ice9():
...     print("nonsense")
</code>```

Parameterized decorators are analogous to foo = mydecorator(param)(foo).

I've updated the answer quite a bit. In response to comments, I've expanded its original scope to include application to class methods and to cover functions defined in other modules. In this last update, I've been able to greatly reduce the complexity involved in determining if a function has already been defined.

[A little update here... I just couldn't put this down - it's been a fun exercise] I've been doing some more testing of this, and found it works generally on callables - not just ordinary functions; you could also decorate class declarations whether callable or not. And it supports inner functions of functions, so things like this are possible (although probably not good style - this is just test code):

```<code>>>> @macos
... class CallableClass:
...
...     @macos
...     def __call__(self):
...         print("CallableClass.__call__() invoked.")
...
...     @macos
...     def func_with_inner(self):
...         print("Defining inner function.")
...
...         @macos
...         def inner():
...             print("Inner function defined for Darwin called.")
...
...         @windows
...         def inner():
...             print("Inner function for Windows called.")
...
...         inner()
...
...     @macos
...     class InnerClass:
...
...         @macos
...         def inner_class_function(self):
...             print("Called inner_class_function() Mac.")
...
...         @windows
...         def inner_class_function(self):
...             print("Called inner_class_function() for windows.")
</code>```

The above demonstrates the basic mechanism of decorators, how to access the caller's scope, and how to simplify multiple decorators that have similar behavior by having an internal function containing the common algorithm defined.

Chaining Support

To support chaining these decorators indicating whether a function applies to more than one platform, the decorator could be implemented like so:

```<code>>>> class IfDefDecoratorPlaceholder:
...     def __init__(self, func):
...         self.__name__ = func.__name__
...         self._func    = func
...
...     def __call__(self, *args, **kwargs):
...         raise NotImplementedError(
...             f"Function {self._func.__name__} is not defined for "
...             f"platform {platform.system()}.")
...
>>> def _ifdef_decorator_impl(plat, func, frame):
...     if platform.system() == plat:
...         if type(func) == IfDefDecoratorPlaceholder:
...             func = func._func
...         frame.f_locals[func.__name__] = func
...         return func
...     elif func.__name__ in frame.f_locals:
...         return frame.f_locals[func.__name__]
...     elif type(func) == IfDefDecoratorPlaceholder:
...         return func
...     else:
...         return IfDefDecoratorPlaceholder(func)
...
>>> def linux(func):
...     return _ifdef_decorator_impl('Linux', func, sys._getframe().f_back)
</code>```

That way you support chaining:

```<code>>>> @macos
... @linux
... def foo():
...     print("works!")
...
>>> foo()
works!
</code>```

The comments below don't really apply to this solution in its present state. They were made during the first iterations on finding a solution and no longer apply. For instance the statement, "Note that this only works if macos and windows are defined in the same module as zulu." (upvoted 4 times) applied to the earliest version, but has been addressed in the current version; which is the case for most of the statements below. It's curious that the comments that validated the current solution have been removed.

Body:
I would like to know if its possible to control Python function definition based on global settings (e.g. OS). Example:

@linux
def my_callback(*args, **kwargs):
    print("Doing something @ Linux")
    return

@windows
def my_callback(*args, **kwargs):
    print("Doing something @ Windows")
    return

Then, if someone is using Linux, the first definition of my_callback will be used and the second will be silently ignored.

Its not about determining the OS, its about function definition / decorators.

Body:
If the goal is to have the same sort of effect in your code that #ifdef WINDOWS / #endif has.. here's a way to do it (I'm on a mac btw).

Simple Case, No Chaining

>>> def _ifdef_decorator_impl(plat, func, frame):
...     if platform.system() == plat:
...         return func
...     elif func.__name__ in frame.f_locals:
...         return frame.f_locals[func.__name__]
...     else:
...         def _not_implemented(*args, **kwargs):
...             raise NotImplementedError(
...                 f"Function {func.__name__} is not defined "
...                 f"for platform {platform.system()}.")
...         return _not_implemented
...
...
>>> def windows(func):
...     return _ifdef_decorator_impl('Windows', func, sys._getframe().f_back)
...
>>> def macos(func):
...     return _ifdef_decorator_impl('Darwin', func, sys._getframe().f_back)

So with this implementation you get same syntax you have in your question.

>>> @macos
... def zulu():
...     print("world")
...
>>> @windows
... def zulu():
...     print("hello")
...
>>> zulu()
world
>>>

What the code above is doing, essentially, is assigning zulu to zulu if the platform matches. If the platform doesn't match, it'll return zulu if it was previously defined. If it wasn't defined, it returns a placeholder function that raises an exception.

Decorators are conceptually easy to figure out if you keep in mind that

@mydecorator
def foo():
    pass

is analogous to:

foo = mydecorator(foo)

Here's an implementation using a parameterized decorator:

>>> def ifdef(plat):
...     frame = sys._getframe().f_back
...     def _ifdef(func):
...         return _ifdef_decorator_impl(plat, func, frame)
...     return _ifdef
...
>>> @ifdef('Darwin')
... def ice9():
...     print("nonsense")

Parameterized decorators are analogous to foo = mydecorator(param)(foo).

I've updated the answer quite a bit. In response to comments, I've expanded its original scope to include application to class methods and to cover functions defined in other modules. In this last update, I've been able to greatly reduce the complexity involved in determining if a function has already been defined.

[A little update here... I just couldn't put this down - it's been a fun exercise] I've been doing some more testing of this, and found it works generally on callables - not just ordinary functions; you could also decorate class declarations whether callable or not. And it supports inner functions of functions, so things like this are possible (although probably not good style - this is just test code):

>>> @macos
... class CallableClass:
...
...     @macos
...     def __call__(self):
...         print("CallableClass.__call__() invoked.")
...
...     @macos
...     def func_with_inner(self):
...         print("Defining inner function.")
...
...         @macos
...         def inner():
...             print("Inner function defined for Darwin called.")
...
...         @windows
...         def inner():
...             print("Inner function for Windows called.")
...
...         inner()
...
...     @macos
...     class InnerClass:
...
...         @macos
...         def inner_class_function(self):
...             print("Called inner_class_function() Mac.")
...
...         @windows
...         def inner_class_function(self):
...             print("Called inner_class_function() for windows.")

The above demonstrates the basic mechanism of decorators, how to access the caller's scope, and how to simplify multiple decorators that have similar behavior by having an internal function containing the common algorithm defined.

Chaining Support

To support chaining these decorators indicating whether a function applies to more than one platform, the decorator could be implemented like so:

>>> class IfDefDecoratorPlaceholder:
...     def __init__(self, func):
...         self.__name__ = func.__name__
...         self._func    = func
...
...     def __call__(self, *args, **kwargs):
...         raise NotImplementedError(
...             f"Function {self._func.__name__} is not defined for "
...             f"platform {platform.system()}.")
...
>>> def _ifdef_decorator_impl(plat, func, frame):
...     if platform.system() == plat:
...         if type(func) == IfDefDecoratorPlaceholder:
...             func = func._func
...         frame.f_locals[func.__name__] = func
...         return func
...     elif func.__name__ in frame.f_locals:
...         return frame.f_locals[func.__name__]
...     elif type(func) == IfDefDecoratorPlaceholder:
...         return func
...     else:
...         return IfDefDecoratorPlaceholder(func)
...
>>> def linux(func):
...     return _ifdef_decorator_impl('Linux', func, sys._getframe().f_back)

That way you support chaining:

>>> @macos
... @linux
... def foo():
...     print("works!")
...
>>> foo()
works!

The comments below don't really apply to this solution in its present state. They were made during the first iterations on finding a solution and no longer apply. For instance the statement, "Note that this only works if macos and windows are defined in the same module as zulu." (upvoted 4 times) applied to the earliest version, but has been addressed in the current version; which is the case for most of the statements below. It's curious that the comments that validated the current solution have been removed.


问:
How to Pass JSON Data into Express REST API
I am creating a REST API using Node/Express and had a question regarding setting up the API and how to incorporate a JSON file into it. I have the following as an example of the JSON data I would like to look up and it includes an ID number, model and color:

{
    "1": {
        "car_model": "Ferrari",
        "color": "Silver"
    },
    "2": {
        "car_model": "Porsche",
        "color": "Green"
    },
    "3": {
        "car_model": "Camry",
        "color": "Blue"
    }
}

Now, I'd like to have the GET route return all the cars in the JSON list and return the ID, color and model. I'm not sure how to incorporate the JSON data into the requests (say it is located on my hard-drive at path/JSON)

I have the following code set up as the basics for the API:

```<code>// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/endpoint_get', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

router.post('/endpoint_post', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /endpoint.com
app.use('/endpoint.com/', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
</code>```

Not necessarily using this code, I would like some guidance or help from anyone or an example of how one would incorporate the JSON data (from some random file) into the HTTP requests. Thank you

答:
```<code>const jsonDoc = require('../Desktop/jsonDoc.json');// top of file...

router.get('/endpoint_get', function(req, res) {
try{
let jsonObj = JSON.parse(jsonDoc) /*{ "1": { "car_model": "Ferrari", "color": "Silver" }, "2": { "car_model": "Porsche", "color": "Green" }, "3": { "car_model": "Camry", "color": "Blue" } }*/
console.log(jsonObj)

    res.json({
        message: 'hooray! welcome to our api!',
        jsonDoc:JSON.stringify(jsonObj)
     });
/* returns {
  "message": "hooray! welcome to our api!",
  "jsonDoc": { "1": { "car_model": "Ferrari", "color": "Silver" }, "2": { "car_model": "Porsche", "color": "Green" }, "3": { "car_model": "Camry", "color": "Blue" } }
}*/

}catch(error){ /* now if anything above fails a error code can be returned to the caller and debug info can be sent to the developer*/
console.trace(error);// trace out the error.
res.sendStatus(500)// return error code to user.
}
    });
</code>```

Body:
I am creating a REST API using Node/Express and had a question regarding setting up the API and how to incorporate a JSON file into it. I have the following as an example of the JSON data I would like to look up and it includes an ID number, model and color:

{
    "1": {
        "car_model": "Ferrari",
        "color": "Silver"
    },
    "2": {
        "car_model": "Porsche",
        "color": "Green"
    },
    "3": {
        "car_model": "Camry",
        "color": "Blue"
    }
}

Now, I'd like to have the GET route return all the cars in the JSON list and return the ID, color and model. I'm not sure how to incorporate the JSON data into the requests (say it is located on my hard-drive at path/JSON)

I have the following code set up as the basics for the API:

// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/endpoint_get', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

router.post('/endpoint_post', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /endpoint.com
app.use('/endpoint.com/', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

Not necessarily using this code, I would like some guidance or help from anyone or an example of how one would incorporate the JSON data (from some random file) into the HTTP requests. Thank you


问:
MFC: What is guaranteed to be called after CWnd::OnCreate()?
Since WM_SHOWWINDOW (OnShowWindow) won't always be called per API docs, where do I process startup items that needs all CTreeView/CListView/etc.. of a CSplitterWnd() inside the CMainFrame populated?   I can't do in OnCreate() since the OnInitialUpdate() for the CTreeView/CListView come after that.

TIA!!

答: I ended up adding my own method CMainFrame::OnAfterCreate() which is called inside CWinApp::InitInstance() after the CSigneDocTemplate is created.


问:
how to updaload image twice with diffrent sizes
hello i have project i work on , it have some issues ,

the problem here i need to get file twice once to move it and one with resizing

this is my code , what should i do here

```<code> public function update_image(Request $request)
{
    $ad = Ad::where('id',$request->ad_id)->first();
    $photos= explode('||',$ad->photos);
    $thumbnails= explode('||',$ad->thumbnails);
    $number =  count($photos);
    $length = strlen($photos[$number-1]);
    $last_image_number = $photos[$number-1][$length - 5];
    // dd($photos[$number-1][$length - 5]);
    $last_image_number++;
    $image = $request->file('image');
    $image_name = 'preview_'.$last_image_number.'.'.$image->getClientOriginalExtension();
    $previews_path = public_path().'/uploads/images/'.$ad->ad_id.'/previews/';
    $thumbs_path = public_path().'/uploads/images/'.$ad->ad_id.'/thumbnails/';
    // $im = Image::make($image->getFullPath());
    chmod($previews_path,0777);
    $image->move($previews_path,$image_name);
    $photos[]= '/'.$ad->ad_id.'/previews/'.$image_name;
    $ad->photos = implode('||',$photos);
    $photo_path = basename($previews_path . $image_name);
    $ad->save();

    list($width, $heigh) = getimagesize($previews_path.$photo_path);
    $photo_path->move($thumbs_path,'ddd.jpg');
    dd($photo_path);
    // dd($width);
    $ratio = $width/ $heigh;
    $target_width = $width / $ratio;
    $target_height = $target_width / $ratio;
    $photo_path->resize($target_width,$target_height);

    $thumb_name= 'thumbnail_'.$last_image_number.'.'.$image->getClientOriginalExtension();
    $image->move($thumbs_path , $thumb_name);
    $thumbnails [] = '/'.$ad->ad_id.'/thumbnails/'.$thumb_name;
    $ad->thumbnails = implode('||',$thumbnails);
    $ad->save();

    // dd($image_name);
    return response()->json(['success'=>true]);
</code>```

答:
```<code>public function store(Request $request)
    {
        $this->validate($request,[
            'title' =>'required',
            'image' => 'mimes:jpeg,jpg,bmp,png',

        ]);

          $image = $request->file('image');
        $slug = str_slug($request->title);
        if (isset($image))
        {
            $currentDate = Carbon::now()->toDateString();
            $imagename = $slug.'-'.$currentDate.'-'. uniqid() .'.'. $image->getClientOriginalExtension();
            $image_resize = Image::make($image->getRealPath());

            if (!file_exists('storage/uploads/category'))
            {
                mkdir('storage/uploads/category',0777,true);
            }
            $image_resize->resize(1600,1066);
            $image_resize->save('storage/uploads/category/'.$imagename);

            if (!file_exists('storage/uploads/post'))
            {
                mkdir('storage/uploads/post',0777,true);
            }
            $image_resize->resize(550,600);
            $image_resize->save('storage/uploads/post/'.$imagename);
        }else{
            $imagename = "default.png";
        }

         $post = new Post();
        $post->user_id = Auth::id();
        $post->title = $request->title;
        $post->slug = str_slug($request->title);
        $post->image = $imagename;
        $post->save();
        Toastr::success('Post Successfully Save:)','Success');
        return redirect()->route('admin.post.index');

    }
</code>```

Body:
hello i have project i work on , it have some issues ,

the problem here i need to get file twice once to move it and one with resizing

this is my code , what should i do here

 public function update_image(Request $request)
{
    $ad = Ad::where('id',$request->ad_id)->first();
    $photos= explode('||',$ad->photos);
    $thumbnails= explode('||',$ad->thumbnails);
    $number =  count($photos);
    $length = strlen($photos[$number-1]);
    $last_image_number = $photos[$number-1][$length - 5];
    // dd($photos[$number-1][$length - 5]);
    $last_image_number++;
    $image = $request->file('image');
    $image_name = 'preview_'.$last_image_number.'.'.$image->getClientOriginalExtension();
    $previews_path = public_path().'/uploads/images/'.$ad->ad_id.'/previews/';
    $thumbs_path = public_path().'/uploads/images/'.$ad->ad_id.'/thumbnails/';
    // $im = Image::make($image->getFullPath());
    chmod($previews_path,0777);
    $image->move($previews_path,$image_name);
    $photos[]= '/'.$ad->ad_id.'/previews/'.$image_name;
    $ad->photos = implode('||',$photos);
    $photo_path = basename($previews_path . $image_name);
    $ad->save();

    list($width, $heigh) = getimagesize($previews_path.$photo_path);
    $photo_path->move($thumbs_path,'ddd.jpg');
    dd($photo_path);
    // dd($width);
    $ratio = $width/ $heigh;
    $target_width = $width / $ratio;
    $target_height = $target_width / $ratio;
    $photo_path->resize($target_width,$target_height);

    $thumb_name= 'thumbnail_'.$last_image_number.'.'.$image->getClientOriginalExtension();
    $image->move($thumbs_path , $thumb_name);
    $thumbnails [] = '/'.$ad->ad_id.'/thumbnails/'.$thumb_name;
    $ad->thumbnails = implode('||',$thumbnails);
    $ad->save();

    // dd($image_name);
    return response()->json(['success'=>true]);


问:
Importing from directory gives ImportError
I have the following directory structure, in Ubuntu:

```<code>/Test/Foo
/Test/Foo/foo.py
</code>```

If I am in /Test, and I run python from the command line, followed by from Foo import foo, I get the following error: ImportError: No module named Foo.

But this is very confusing, since according to here, one of the directories used to search when importing is the directory from which the script was invoked. If I print out sys.path though, it does not include /Test, it just includes other standard Python directories.

Any idea what is going on?

答:
If you just need a function try this (python 2.7):

sys.path.insert() inserts the directory specified in the path python uses to find files.

commify.py is a file in subdirectory xyz that contains a function commify(value)

```<code>import os
import sys
sys.path.insert(0, os.getcwd() + r'\xyz')
from commify import commify

print commify(12345678)
</code>```

output: 12,345,678

Body:
I have the following directory structure, in Ubuntu:

/Test/Foo
/Test/Foo/foo.py

If I am in /Test, and I run python from the command line, followed by from Foo import foo, I get the following error: ImportError: No module named Foo.

But this is very confusing, since according to here, one of the directories used to search when importing is the directory from which the script was invoked. If I print out sys.path though, it does not include /Test, it just includes other standard Python directories.

Any idea what is going on?

Body:
If you just need a function try this (python 2.7):

sys.path.insert() inserts the directory specified in the path python uses to find files.

commify.py is a file in subdirectory xyz that contains a function commify(value)

import os
import sys
sys.path.insert(0, os.getcwd() + r'\xyz')
from commify import commify

print commify(12345678)

output: 12,345,678


问:
What are the use cases for selecting CHAR over VARCHAR in SQL?
I realize that CHAR is recommended if all my values are fixed-width. But, so what? Why not just pick VARCHAR for all text fields just to be safe.</p>

答:
There are performance benefits, but here is one that has not been mentioned: row migration.

With CHAR, you reserve the entire space in advance.So let's says you have a CHAR(1000), and you store 10 characters, you will use up all 1000 characters of space. In a VARCHAR2(1000), you will only use 10 characters.

The problem comes when you modify the data. Let's say you update the column to now contain 900 characters. It is possible that the space to expand the varchar is not available in the current block. In that case, the DB engine must migrate the row to another block, and make a pointer in the original block to the new row in the new block. To read this data, the DB engine will now have to read 2 blocks.

No one can equivocally say that varchar or char are better. There is a space for time tradeoff, and consideration of whether the data will be updated, especially if there is a good chance that it will grow.

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Tony BenBrahim


问:
CSS won't dynamically change with .addClass() or .css()
I have a table that has rows with different classes depending on what color it should be.  On the click of a button I want the background color of the row to change instantly.  I tried both .addClass() and .css() but they both fail. On click, I have a function that checks whether the row is colored or not, that works fine.

Here are the pieces of code I'm using and the css classes that go along with the rows.

If a row is white:

$("#"+table+"_row_"+id).addClass("table-1").removeClass("table-0");

or

$("#"+table+"_row_"+id).css("background-color","orange");

If a row is orange:

$("#"+table+"_row_"+id).addClass("table-0").removeClass("table-1");

or

$("#"+table+"_row_"+id).css("background-color","white");

css:

```<code>table.tablesorter .table-1{
background-color:orange;
}
table.tablesorter .table-0{
background-color:white;
}
</code>```

答: Check out this fiddle. It is a stripped down version of what I believe you're trying to make work. http://jsfiddle.net/edelman/ntPGb/1/</p>

Body:
I have a table that has rows with different classes depending on what color it should be.  On the click of a button I want the background color of the row to change instantly.  I tried both .addClass() and .css() but they both fail. On click, I have a function that checks whether the row is colored or not, that works fine.

Here are the pieces of code I'm using and the css classes that go along with the rows.

If a row is white:

$("#"+table+"_row_"+id).addClass("table-1").removeClass("table-0");

or

$("#"+table+"_row_"+id).css("background-color","orange");

If a row is orange:

$("#"+table+"_row_"+id).addClass("table-0").removeClass("table-1");

or

$("#"+table+"_row_"+id).css("background-color","white");

css:

table.tablesorter .table-1{
background-color:orange;
}
table.tablesorter .table-0{
background-color:white;
}


问:
Filter string to array char - 'IEnumerable<char>' does not contain a definition for 'ToCharArray'
Say I have this string $$A121B and I want to create an array char of all the digit and letter only.

```<code>'IEnumerable<char>' does not contain a definition for 'ToCharArray' and no accessible extension method 'ToCharArray' accepting a first argument of type 'IEnumerable<char>'
</code>```

I have this code but it has syntax error at ToCharArray

```<code>var testData = "$$A121B";
var testDataFiltered = (from c in testData
                        where char.IsLetterOrDigit(c)
                        select c).ToCharArray();
</code>```

答:
Your code is effectively converted into this:

var testData = "$$A121B";
var testDataFiltered = testData.Where(c => char.IsLetterOrDigit(c)).ToCharArray();
```

<p>In other words, you're trying to call <code>ToCharArray</code> on the result of the <code>Where</code> call, which is an <code>IEnumerable<char></code>, not a <code>string</code>.</p>

<p>Fortunately, this is easy to fix as LINQ provides a <code>ToArray</code> method:</p>

<pre class="lang-cs prettyprint-override"><code>var testData = "$$A121B";
var testDataFiltered = testData.Where(c => char.IsLetterOrDigit(c)).ToArray();
</code>```

The same code would work with the query expression form as well, but I typically find that when you're just using a Select and/or Where like this, the "method syntax" is simpler, particularly if you're calling a method on the result, as you are here. (It's definitely worth being comfortable with both forms.)

Body:
Say I have this string $$A121B and I want to create an array char of all the digit and letter only.

'IEnumerable<char>' does not contain a definition for 'ToCharArray' and no accessible extension method 'ToCharArray' accepting a first argument of type 'IEnumerable<char>'

I have this code but it has syntax error at ToCharArray

var testData = "$$A121B";
var testDataFiltered = (from c in testData
                        where char.IsLetterOrDigit(c)
                        select c).ToCharArray();

Body:
Your code is effectively converted into this:

var testData = "$$A121B";
var testDataFiltered = testData.Where(c => char.IsLetterOrDigit(c)).ToCharArray();

In other words, you're trying to call ToCharArray on the result of the Where call, which is an IEnumerable<char>, not a string.

Fortunately, this is easy to fix as LINQ provides a ToArray method:

var testData = "$$A121B";
var testDataFiltered = testData.Where(c => char.IsLetterOrDigit(c)).ToArray();

The same code would work with the query expression form as well, but I typically find that when you're just using a Select and/or Where like this, the "method syntax" is simpler, particularly if you're calling a method on the result, as you are here. (It's definitely worth being comfortable with both forms.)


问:
Typescript alias for builtin type
How can i make alias for built in type such as from utility-types, i have definition which have the same name as builtin types, and happen to use type with the same name from builtin types, example :

```<code>interface Record { // <-- my definition

   toObject() : Record<string, object> // <-- built in definition
}
</code>```

does not work

```<code>type TsRecord<K,V> = Record<K, V>
</code>```

if there is an import method, i cant find the reference

```<code>import {Record as TsRecord} from ?
</code>```

答:
If you're using TypeScript 3.4 or above, you can use the globalThis namespace to access global types whose names have been shadowed by local declarations:

```<code>interface Record { // <-- my definition
  toObject(): globalThis.Record<string, object> // <-- built in definition
}
</code>```

Okay, hope that helps; good luck!

Playground link to code

Title: Typescript alias for builtin type

Body:
How can i make alias for built in type such as from utility-types, i have definition which have the same name as builtin types, and happen to use type with the same name from builtin types, example :

interface Record { // <-- my definition

   toObject() : Record<string, object> // <-- built in definition
}

does not work

type TsRecord<K,V> = Record<K, V>

if there is an import method, i cant find the reference

import {Record as TsRecord} from ?

Body:
If you're using TypeScript 3.4 or above, you can use the globalThis namespace to access global types whose names have been shadowed by local declarations:

interface Record { // <-- my definition
  toObject(): globalThis.Record<string, object> // <-- built in definition
}

Okay, hope that helps; good luck!

Playground link to code


问:
Unable to access DynamoDB from Lambda
I have created a lambda java project to get items from dynamoDB.But I am getting error while accessing.

Code that I wrote:

```<code>dbClient = AmazonDynamoDBClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
DynamoDB dynamoDB = new DynamoDB(dbClient);
Table table = dynamoDB.getTable("TokenSystem");
Item item = table.getItem("TokenId", 123456);
return item.toJSON();
</code>```

Error getting in lambda console:

```<code>com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException: The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: 9OJVLPJHV011KLGKI20Q8QN2FNVV4KQNSO5AEMVJF66Q9ASUAAJG)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1658)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1322)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1072)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:745)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:719)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:701)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:669)
at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:651)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:515)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:3609)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3578)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3567)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.executeGetItem(AmazonDynamoDBClient.java:1869)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.getItem(AmazonDynamoDBClient.java:1840)
at com.amazonaws.services.dynamodbv2.document.internal.GetItemImpl.doLoadItem(GetItemImpl.java:77)
at com.amazonaws.services.dynamodbv2.document.internal.GetItemImpl.getItemOutcome(GetItemImpl.java:40)
at com.amazonaws.services.dynamodbv2.document.internal.GetItemImpl.getItemOutcome(GetItemImpl.java:99)
at com.amazonaws.services.dynamodbv2.document.internal.GetItemImpl.getItem(GetItemImpl.java:111)
at com.amazonaws.services.dynamodbv2.document.Table.getItem(Table.java:624)
at com.amazonaws.lambda.service.TokenValidatorService.retrieveItemFromDB(TokenValidatorService.java:82)
at com.amazonaws.lambda.service.TokenValidatorService.checkToken(TokenValidatorService.java:42)
</code>```

In DynamoDB I have a table with the SAME NAME and REGION.I am using the AWS package com.amazonaws.services.dynamodbv2 to do all the operations.Can anyone help me to solve the issue.

答:
The provided key element does not match the schema

Make sure you provide the right key Name

Title: Unable to access DynamoDB from Lambda

Body:
I have created a lambda java project to get items from dynamoDB.But I am getting error while accessing.

Code that I wrote:

dbClient = AmazonDynamoDBClientBuilder.standard().withRegion(Regions.US_EAST_1).build();
DynamoDB dynamoDB = new DynamoDB(dbClient);
Table table = dynamoDB.getTable("TokenSystem");
Item item = table.getItem("TokenId", 123456);
return item.toJSON();

Error getting in lambda console:

com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException: The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: 9OJVLPJHV011KLGKI20Q8QN2FNVV4KQNSO5AEMVJF66Q9ASUAAJG)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1658)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1322)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1072)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:745)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:719)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:701)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:669)
at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:651)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:515)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.doInvoke(AmazonDynamoDBClient.java:3609)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3578)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3567)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.executeGetItem(AmazonDynamoDBClient.java:1869)
at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.getItem(AmazonDynamoDBClient.java:1840)
at com.amazonaws.services.dynamodbv2.document.internal.GetItemImpl.doLoadItem(GetItemImpl.java:77)
at com.amazonaws.services.dynamodbv2.document.internal.GetItemImpl.getItemOutcome(GetItemImpl.java:40)
at com.amazonaws.services.dynamodbv2.document.internal.GetItemImpl.getItemOutcome(GetItemImpl.java:99)
at com.amazonaws.services.dynamodbv2.document.internal.GetItemImpl.getItem(GetItemImpl.java:111)
at com.amazonaws.services.dynamodbv2.document.Table.getItem(Table.java:624)
at com.amazonaws.lambda.service.TokenValidatorService.retrieveItemFromDB(TokenValidatorService.java:82)
at com.amazonaws.lambda.service.TokenValidatorService.checkToken(TokenValidatorService.java:42)

In DynamoDB I have a table with the SAME NAME and REGION.I am using the AWS package com.amazonaws.services.dynamodbv2 to do all the operations.Can anyone help me to solve the issue.


问:
Can't retrieve application rules with HNetCfg.FwMgr + AuthorizedApplications
I'm trying to retrieve all authorized applications with C#:

```<code>ArrayList result = new ArrayList();
INetFwMgr firewallManager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
foreach (INetFwAuthorizedApplication app in firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications)
{
    Console.WriteLine(app.Name);
}
</code>```

The AuthorizedApplications is empty, but in Control Panel I can see many rules, enabled or not:

What was wrong? I tried other profiles, e.g DOMAIN/STANDARD, same result.

答:
```<code>          console.write(result);                                                            check if forEach method brings you all aplications authorized with C#                          should be a loop instead
            foreach (INetFwAuthorizedApplication app in
           firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications)
            {
                 Console.WriteLine(app.Name);
            }e.g                      for(INetFwAuthorizedApplication app in
            firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications){console.log(app.Name);}  Are you sure Name is the correct value?, shouldn't be app.name?
</code>```

It seems you can iterate the app list, but you are not finding the correct name for app. Use name instead Name. Try console.WriteLine(app.name) or console.WriteLine(app.GetName)

Maybe try this:

```<code>       public List<Object>(String name){

           ArrayList result = new ArrayList();
           INetFwMgr firewallManager =

                           (INetFwMgr)Activator.CreateInstance
                           (Type.GetTypeFromProgID("HNetCfg.FwMgr"));
                           foreach (INetFwAuthorizedApplication app in
                            firewallManager.LocalPolicy
                           .CurrentProfile.AuthorizedApplications)
                         {
                          if(app.Name == _name){
                             app.Name = name;
                            Console.WriteLine(app.Name);
                               }
                                   }
                             return result;
                                }
</code>```

Body:
I'm trying to retrieve all authorized applications with C#:

ArrayList result = new ArrayList();
INetFwMgr firewallManager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
foreach (INetFwAuthorizedApplication app in firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications)
{
    Console.WriteLine(app.Name);
}

The AuthorizedApplications is empty, but in Control Panel I can see many rules, enabled or not:

What was wrong? I tried other profiles, e.g DOMAIN/STANDARD, same result.

Body:
          console.write(result);                                                            check if forEach method brings you all aplications authorized with C#                          should be a loop instead
            foreach (INetFwAuthorizedApplication app in
           firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications)
            {
                 Console.WriteLine(app.Name);
            }e.g                      for(INetFwAuthorizedApplication app in
            firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications){console.log(app.Name);}  Are you sure Name is the correct value?, shouldn't be app.name?

It seems you can iterate the app list, but you are not finding the correct name for app. Use name instead Name. Try console.WriteLine(app.name) or console.WriteLine(app.GetName)

Maybe try this:

       public List<Object>(String name){

           ArrayList result = new ArrayList();
           INetFwMgr firewallManager =

                           (INetFwMgr)Activator.CreateInstance
                           (Type.GetTypeFromProgID("HNetCfg.FwMgr"));
                           foreach (INetFwAuthorizedApplication app in
                            firewallManager.LocalPolicy
                           .CurrentProfile.AuthorizedApplications)
                         {
                          if(app.Name == _name){
                             app.Name = name;
                            Console.WriteLine(app.Name);
                               }
                                   }
                             return result;
                                }


问:
Determining Filetype with PHP. What is Magic Database?
I'm trying to determine if some files are actually images (using PHP).
I've been advised to use finfo and i'm trying to understand how it works.

What I don't get is - what is a magic numbers database and how does it work? I'm a bit puzzled - does each file have certain "magic number" that you compare against that database?

Also - I have it on my debian squeeze - but will it also be available on WIN platform? or would one have to attach that database along with the app?

```<code><?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>
</code>```

答: On my Ubuntu, it's in /usr/share/file/magic.mime. I don't know about Windows. And yes, typically various file formats have a specific prefix just for this purpose (even if there is no extension, you can recognise a GIF, for instance, by the fact that it always starts with the string "GIF").

Body:
I'm trying to determine if some files are actually images (using PHP).
I've been advised to use finfo and i'm trying to understand how it works.

What I don't get is - what is a magic numbers database and how does it work? I'm a bit puzzled - does each file have certain "magic number" that you compare against that database?

Also - I have it on my debian squeeze - but will it also be available on WIN platform? or would one have to attach that database along with the app?

<?php
$finfo = new finfo(FILEINFO_MIME, "/usr/share/misc/magic.mgc");
if (!$finfo) {
    echo "Opening fileinfo database failed";
    exit();
}

/* get mime-type for a specific file */
$filename = "/usr/local/something.txt";
echo $finfo->file($filename);

?>


问:
Using count in in query with left join
I am currently trying to count how many dislikes and likes users have given to an image on my website, underneath you will see the database setup I did for exactly that. Vote_type keeps the like and dislike information where 1 is equal to a like, 0 is equal to a dislike.

this table is called projects
Project table

This table is called projects_votes

Now I want to include that when I make a query to drag information from my database for a blog post. This is currently the query I am making to get the necessary information to display a list of blogs on the frontpage. Here I am getting the uploader, project ID for links and so on.

```<code>    $query = "
SELECT * FROM projects
LEFT JOIN users
ON fk_usr_id = usr_id
LEFT JOIN projects_maps
ON fk_project_id = project_id
ORDER BY RAND()
";
</code>```

So what I have a hard time understanding is how to count my Likes and Dislikes on a specific blog, so I can display this information on my website.

答:
maybe something like this?</p>

```<code>SELECT project_id,
       sum(case when vote_type = 1 then 1 else 0 end) likeCount,
       sum(case when vote_type = 0 then 1 else 0 end) dislikeCount
FROM projects
LEFT JOIN users ON fk_usr_id = usr_id
LEFT JOIN projects_maps ON fk_project_id = project_id
GROUP BY  project_id
</code>```

Title: Using count in in query with left join

Body:
I am currently trying to count how many dislikes and likes users have given to an image on my website, underneath you will see the database setup I did for exactly that. Vote_type keeps the like and dislike information where 1 is equal to a like, 0 is equal to a dislike.

this table is called projects
Project table

This table is called projects_votes

Now I want to include that when I make a query to drag information from my database for a blog post. This is currently the query I am making to get the necessary information to display a list of blogs on the frontpage. Here I am getting the uploader, project ID for links and so on.

    $query = "
SELECT * FROM projects
LEFT JOIN users
ON fk_usr_id = usr_id
LEFT JOIN projects_maps
ON fk_project_id = project_id
ORDER BY RAND()
";

So what I have a hard time understanding is how to count my Likes and Dislikes on a specific blog, so I can display this information on my website.

Body:
maybe something like this?

SELECT project_id,
       sum(case when vote_type = 1 then 1 else 0 end) likeCount,
       sum(case when vote_type = 0 then 1 else 0 end) dislikeCount
FROM projects
LEFT JOIN users ON fk_usr_id = usr_id
LEFT JOIN projects_maps ON fk_project_id = project_id
GROUP BY  project_id


问:
React state not updating onclick
im a noob in react.js and am trying to learn state and set state  by writing a simple addition ap.  im trying to get the 2 values of inputs using state   but am not getting anything when i click on the add button for some reason.
Can someone please explain how i can add the 2 values and what im doing wrong ? thanks ! </p>

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
class Grade extends React.Component {
 constructor(props) {
    super(props);
    this.state = {
      result: 0,
      num1: 0,
      num2: 0
    };

       this.handlenum1Change = this.handlenum1Change.bind(this);
    this.handlenum2Change = this.handlenum2Change.bind(this);
  }

  handlenum1Change (evt) {
    this.setState({ num1: evt.target.value });
  }

handlenum2Change(evt) {

    this.setState({ num2: evt.target.value });

}

   addAction (event) {

  var num1=this.setState({ num1: event.target.value });
  var num2=this.setState({ num2: event.target.value });

   this.setState({result: num1 + num2 })

            }

  render() {

     return (

      <form>
        <label>
          Name:
          <input type="number" onChange={this.handlenum1Change} />
           <input type="number" ref="term" placeholder="Length of loan"  onChange={this.handlenum2Change}/>

            <input type="button" onClick={this.addAction} value="Add"/>
    <input type='text' value={this.state.result} readonly/>

        </label>

      </form>
    );
  }
}

export default Grade;
</code>```

答:
```<code>function Sum(props) {
    return (
       <h1>
        {props.a} + {props.b} = {props.a + props.b}
       </h1>
    );
}

ReactDOM.render(<Sum a={4} b={2}/>,document.getElementById('root'));
</code>```

Title: React state not updating onclick

Body:
im a noob in react.js and am trying to learn state and set state  by writing a simple addition ap.  im trying to get the 2 values of inputs using state   but am not getting anything when i click on the add button for some reason.
Can someone please explain how i can add the 2 values and what im doing wrong ? thanks !

import React from 'react';
import ReactDOM from 'react-dom';
import { Button } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
class Grade extends React.Component {
 constructor(props) {
    super(props);
    this.state = {
      result: 0,
      num1: 0,
      num2: 0
    };

       this.handlenum1Change = this.handlenum1Change.bind(this);
    this.handlenum2Change = this.handlenum2Change.bind(this);
  }

  handlenum1Change (evt) {
    this.setState({ num1: evt.target.value });
  }

handlenum2Change(evt) {

    this.setState({ num2: evt.target.value });

}

   addAction (event) {

  var num1=this.setState({ num1: event.target.value });
  var num2=this.setState({ num2: event.target.value });

   this.setState({result: num1 + num2 })

            }

  render() {

     return (

      <form>

          Name:
          <input type="number" onChange={this.handlenum1Change} />
           <input type="number" ref="term" placeholder="Length of loan"  onChange={this.handlenum2Change}/>

            <input type="button" onClick={this.addAction} value="Add"/>
    <input type='text' value={this.state.result} readonly/>

      </form>
    );
  }
}

export default Grade;


答:
The only thing I can think of is that "#"+table+"_row_"+id won't give you the element you want. Check if that selector gives you any elements at all, and verify they are the right one.

I prefer to use classes only for this, because else you're still embedding style in code while you just got it out of your html. You can use hasClass to do this.

Speed things up by storing the reference:

```<code>var x = $('#'+table+'_row_'+id);
if (x.hasClass('table-0'))
{
  x.addClass('table-1').removeClass('table-0');
}
else
{
  x.addClass('table-0').removeClass('table-1');
}
</code>```

It makes debugging and updating easier too, since you know that if x is right once, it will always be right. And you can inspect it easier too.

Title: CSS won't dynamically change with .addClass() or .css()

Body:
The only thing I can think of is that "#"+table+"_row_"+id won't give you the element you want. Check if that selector gives you any elements at all, and verify they are the right one.

I prefer to use classes only for this, because else you're still embedding style in code while you just got it out of your html. You can use hasClass to do this.

Speed things up by storing the reference:

var x = $('#'+table+'_row_'+id);
if (x.hasClass('table-0'))
{
  x.addClass('table-1').removeClass('table-0');
}
else
{
  x.addClass('table-0').removeClass('table-1');
}

It makes debugging and updating easier too, since you know that if x is right once, it will always be right. And you can inspect it easier too.


问:
Retrieving data from Firebase Realtime Database in Android - recyclerview
I'm trying to retrieve data from Firebase Realtime Database and display this data inside recyclerview but I can't do it and I can't understand why because I tried everything(Google / StackOverflow etc) and nothing works.

The code seems to be ok but when I run the app it gives me these messages: No setter/field for Surname found on class com.example.ipill.Users

I checked how to solve the problem and nothing works, I deleted and create a couple of times the database and nothing.

I'm new to Android Studio and I can't understand what I'm doing wrong.

Below I will attach the code and the database. The thing that I don't understand is that when I add a new Object to the database with Name = Alex I can see the new recycler view containing a new item inside, that means that the apps understand that there are more objects with Name = Alex but can't I retrieve the of that object from the database.

Thank you in advance.

CODE ACTIVITY

```<code>package com.example.ipill;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;

private RecyclerView mResultList;

private DatabaseReference mUserDatabase;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_firebasesearch);

    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = (EditText) findViewById(R.id.search_field);

    mSearchBtn = findViewById(R.id.search_btn);
    mResultList = (RecyclerView)findViewById(R.id.result_list);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String searchText = mSearchField.getText().toString();

            firebaseUserSearch(searchText);

        }
    });

}

private void firebaseUserSearch(String searchText) {

    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();

    Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");

    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(

            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery

    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
            viewHolder.setDetails(model.getName(), model.getSurname());

        }
    };

    mResultList.setAdapter(firebaseRecyclerAdapter);

}

// View Holder Class

public static class UsersViewHolder extends RecyclerView.ViewHolder {

    View mView;

    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;

    }

    public void setDetails(String name, String surname) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView) mView.findViewById(R.id.status_text);

        user_name.setText(name);
        user_surname.setText(surname);

    }

}

}
</code>```

DATABASE:

The problem that I have:

```<code>W/PersistentConnection: pc_0 - Using an unspecified index. Your data will be downloaded and filtered
on the client. Consider adding '".indexOn": "Name"' at Users to your security and Firebase Database
rules for better performance
W/ClassMapper: No setter/field for Surname found on class com.example.ipill.Users (fields/setters are
case sensitive!)
W/ClassMapper: No setter/field for Name found on class com.example.ipill.Users (fields/setters are
case sensitive!)
W/m.example.ipil: Accessing hidden field Landroid/view/View;-
>mAccessibilityDelegate:Landroid/view/View$AccessibilityDelegate; (greylist, reflection, allowed)
</code>```

Model CLASS

```<code>package com.example.ipill;

public class Users {

public String name, surname;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public Users(String name, String surname, String status) {
    this.name = name;
    this.surname = surname;

}

public Users(){

}

}
</code>```

答:
The error message is quite explicit on what you need to do:

Consider adding '".indexOn": "Name"' at Users

So you need to add ".indexOn": "Name" at the Users node in your rules.

So:

```<code>{
  "rules": {
    "Users": {
      ".indexOn": "Name"
    }
  }
}
</code>```

The square brackets are fine ["Name"], but right now  you're defining the index on the wrong level.

Body:
I'm trying to retrieve data from Firebase Realtime Database and display this data inside recyclerview but I can't do it and I can't understand why because I tried everything(Google / StackOverflow etc) and nothing works.

The code seems to be ok but when I run the app it gives me these messages: No setter/field for Surname found on class com.example.ipill.Users

I checked how to solve the problem and nothing works, I deleted and create a couple of times the database and nothing.

I'm new to Android Studio and I can't understand what I'm doing wrong.

Below I will attach the code and the database. The thing that I don't understand is that when I add a new Object to the database with Name = Alex I can see the new recycler view containing a new item inside, that means that the apps understand that there are more objects with Name = Alex but can't I retrieve the of that object from the database.

Thank you in advance.

CODE ACTIVITY

package com.example.ipill;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerAdapter;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;

private RecyclerView mResultList;

private DatabaseReference mUserDatabase;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_firebasesearch);

    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = (EditText) findViewById(R.id.search_field);

    mSearchBtn = findViewById(R.id.search_btn);
    mResultList = (RecyclerView)findViewById(R.id.result_list);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String searchText = mSearchField.getText().toString();

            firebaseUserSearch(searchText);

        }
    });

}

private void firebaseUserSearch(String searchText) {

    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();

    Query firebaseSearchQuery = mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");

    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(

            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery

    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
            viewHolder.setDetails(model.getName(), model.getSurname());

        }
    };

    mResultList.setAdapter(firebaseRecyclerAdapter);

}

// View Holder Class

public static class UsersViewHolder extends RecyclerView.ViewHolder {

    View mView;

    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;

    }

    public void setDetails(String name, String surname) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView) mView.findViewById(R.id.status_text);

        user_name.setText(name);
        user_surname.setText(surname);

    }

}

}

DATABASE:

The problem that I have:

W/PersistentConnection: pc_0 - Using an unspecified index. Your data will be downloaded and filtered
on the client. Consider adding '".indexOn": "Name"' at Users to your security and Firebase Database
rules for better performance
W/ClassMapper: No setter/field for Surname found on class com.example.ipill.Users (fields/setters are
case sensitive!)
W/ClassMapper: No setter/field for Name found on class com.example.ipill.Users (fields/setters are
case sensitive!)
W/m.example.ipil: Accessing hidden field Landroid/view/View;-
>mAccessibilityDelegate:Landroid/view/View$AccessibilityDelegate; (greylist, reflection, allowed)

Model CLASS

package com.example.ipill;

public class Users {

public String name, surname;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public Users(String name, String surname, String status) {
    this.name = name;
    this.surname = surname;

}

public Users(){

}

}

Body:
The error message is quite explicit on what you need to do:

Consider adding '".indexOn": "Name"' at Users

So you need to add ".indexOn": "Name" at the Users node in your rules.

So:

{
  "rules": {
    "Users": {
      ".indexOn": "Name"
    }
  }
}

The square brackets are fine ["Name"], but right now  you're defining the index on the wrong level.


问:
How to use name range in VBA code for a new chart series' values and X-Values?
I am enhancing a work template that requires users to create a new file each week to be able to track progress from week to week, so the file will change name each week.

This file has about 3 charts in a "Summary" worksheet.

In this "Summary" worksheet, bar chart #2 currently has 5 series. I am writing a script to be able to add a 6th series.... this I have no problem.

I would like the new Series values to use the values from a Name Range of cells the template currently has defined ("software") in a different worksheet.

I would also like the Horizontal Axis Labels to use a different Name Range of cells that template also has defined ("dates") in a different worksheet.

Here is the code I have so far:

```<code>Sub add_software()
'Update software Trend in Summary

Sheets("Summary").SelectActiveSheet.ChartObjects("Chart 2").Activate
ActiveChart.SeriesCollection.NewSeriesActiveChart.FullSeriesCollection(6).Name = "='Summary'!$C$44"

'MY PROBLEM IS HERE

ActiveChart.FullSeriesCollection(6).Value = ActiveWorkbook.Sheets("Summary").Range("Software")
ActiveChart.FullSeriesCollection(6).XValues = ActiveWorkbook.Sheets("Summary").Range("dates")

End sub
</code>```

I would expect that the script will use the values in these Name Ranges (which are the same values used in the other 5 series) and populate with the values from the name range.

This is the error I get is:

Run-Time error '438':
 Object doesn't support this property or method
  error

答:
The accepted solution by @RicardoA works fine, but it assumes a static definition of the names, and places the current address of each name into the SERIES formula of the series. If the names are dynamic, the SERIES formula will not keep up with the changes. The following puts the names not addresses of the names into the series formula:</p>

```<code>ActiveChart.SeriesCollection(6).XValues = "='" & ThisWorkbook.Name & "'!dates"
ActiveChart.SeriesCollection(6).Values = "='" & ThisWorkbook.Name & "'!software"
</code>```

Body:
I am enhancing a work template that requires users to create a new file each week to be able to track progress from week to week, so the file will change name each week.

This file has about 3 charts in a "Summary" worksheet.

In this "Summary" worksheet, bar chart #2 currently has 5 series. I am writing a script to be able to add a 6th series.... this I have no problem.

I would like the new Series values to use the values from a Name Range of cells the template currently has defined ("software") in a different worksheet.

I would also like the Horizontal Axis Labels to use a different Name Range of cells that template also has defined ("dates") in a different worksheet.

Here is the code I have so far:

Sub add_software()
'Update software Trend in Summary

Sheets("Summary").SelectActiveSheet.ChartObjects("Chart 2").Activate
ActiveChart.SeriesCollection.NewSeriesActiveChart.FullSeriesCollection(6).Name = "='Summary'!$C$44"

'MY PROBLEM IS HERE

ActiveChart.FullSeriesCollection(6).Value = ActiveWorkbook.Sheets("Summary").Range("Software")
ActiveChart.FullSeriesCollection(6).XValues = ActiveWorkbook.Sheets("Summary").Range("dates")

End sub

I would expect that the script will use the values in these Name Ranges (which are the same values used in the other 5 series) and populate with the values from the name range.

This is the error I get is:

Run-Time error '438':
 Object doesn't support this property or method
  error

Body:
The accepted solution by @RicardoA works fine, but it assumes a static definition of the names, and places the current address of each name into the SERIES formula of the series. If the names are dynamic, the SERIES formula will not keep up with the changes. The following puts the names not addresses of the names into the series formula:

ActiveChart.SeriesCollection(6).XValues = "='" & ThisWorkbook.Name & "'!dates"
ActiveChart.SeriesCollection(6).Values = "='" & ThisWorkbook.Name & "'!software"


问:
Aws lambda vs aws batch
I am currently working on a project where I need to merge two significantly large csv files into one(both are a few hundred MBs). I am fairly new to aws. I am aware of memory allocation and execution time limitations of lambda. Other than that are there any advantages of using batch jobs over lambda for this project? Is there any other aws component which more suitable for this task? Either lambda or batch job will be triggered inside a step function using a sns notification.</p>

答:
Lambda function has some limitations:

Execute time: 15 mins

RAM: 3G

disk space /tmp only 500mb <= difficult to store any file large than this number on lambda

The good point is cheap and fast boot up

I suggest you use the ECS (Both Fargate and Container are good)

Title: Aws lambda vs aws batch


问:
Manual creation of TFS document libraries
In TFS 2010,  if you create a project with an associated Sharepoint site, or even create and link a sharepoint site afterwords you'll see a 'Documents' Node in the project in the Visual Studio 2010 Team Explorer, and Visual Studio will give you the ability to right click on that node, create document libraryes and add a document.

If you just create a TFS project with no associated sharepoint site, you won't see the 'Documents' node, but is there a way to create one through Visual Studio without having a Sharepoint site?

答: No, I believe that function will always use SharePoint.</p>


问:
ORA-24381 finding root cause
I faced this error Error message: ORA-24381: error(s) in array DML in doing insert operation. There is no exception handling involved in the sql. Can I know now the root cause for this through any view ?

My database is oracle 12c

答:
Check if this is similar to this article

I figured that my problem had to do Oracle’s bad estimation of the string length (that led to the issue).

  So, I forced a CAST to limit the string to 30 characters and the issue went away!

```<code>SELECT NVL(MAX(USERNAME),
           CAST('NOT_THERE' AS VARCHAR2(30))
          ) as usr1
FROM DBA_USERS
WHERE USERNAME = 'AN_USER_ID'
</code>```

In your case, the problem might be a similar data length issue and you might be able to resolve it too with a simple cast.

Title: ORA-24381 finding root cause

Body:
Check if this is similar to this article

I figured that my problem had to do Oracle’s bad estimation of the string length (that led to the issue).

  So, I forced a CAST to limit the string to 30 characters and the issue went away!

SELECT NVL(MAX(USERNAME),
           CAST('NOT_THERE' AS VARCHAR2(30))
          ) as usr1
FROM DBA_USERS
WHERE USERNAME = 'AN_USER_ID'

In your case, the problem might be a similar data length issue and you might be able to resolve it too with a simple cast.


问:
benchmark for using base64 string instead of image reducing http requests
I am looking at replacing source of my images currently set to a image file in my css to a base64 string.  Instead of the browser needing to make several calls, one for the CSS file and then one for each image, base64 embedding means that all of the images are embedded within the CSS file itself.

So I am currently investigating introducing this. However I have an issue I would like some advice on, a known problem with this approach. That is in my tests a base64 encoded string image is somewhere around 150% the size of a regular image. This means it’s unusable for large images. While I am not too concerned regarding larger images, I am not sure when I should and shouldn't use it.

Is there a benchmark I should use, as in if the base64 more than 150% larger I should not use it etc?

What are others views on this and what from your own experiences may help with the decision of when to and not to use it?

答: Base64 encoding always uses 4 output bytes for every 3 input bytes. It works by using essentially 6 bits of each output byte, mapped to characters that are safe to use. So you'll always see a consist 133% increase for anything you base64 encode, rounded up for the last chunk of 4 bytes. You can use gzip compression of your responses to gain some of this loss back.</p>


问:
Rx Java, what's the difference between subscribe({}) vs subscribe { }?
```<code>Observable.just(10,20,30,40,50)
            .subscribe { Consumer<Int>{
                Log.d(TAG, "Where I'm I" + Thread.currentThread())
                System.out.println("Hello boss")
                Toast.makeText(baseContext.applicationContext, "Hellloo",Toast.LENGTH_SHORT).show()
            } }
</code>```

vs

```<code> Observable.just(10,20,30,40,50)
            .subscribe( { Consumer<Int>{
                Log.d(TAG, "Where I'm I" + Thread.currentThread())
                System.out.println("Hello boss")
                Toast.makeText(baseContext.applicationContext, "Hellloo",Toast.LENGTH_SHORT).show()
            } })
</code>```

What's the difference between calling subscribe({}) vs subscribe { }

答:
With respect to RxJava there is no difference. Calling and execution stays the same. Its just a special syntax in kotlin known as trailing lambda.

In kotlin if you have a function with a lambda as last parameter then you can move that lambda out of parentheses. If the lambda is the only parameter then you can also remove the parentheses.

From the kotlin docs

Passing trailing lambdas

In Kotlin, there is a convention: if the last parameter of a function
  is a function, then a lambda expression passed as the corresponding
  argument can be placed outside the parentheses:

```<code>// Second argument of fold is of function type,
// hence we have moved the lambda out of parentheses.
val product = items.fold(1) { acc, e -> acc * e }
</code>```

Such syntax is also known as trailing lambda.

If the lambda is the only argument to that call, the parentheses can
  be omitted entirely:

```<code>// run only takes a single argument of function type,
// hence we have omitted the parentheses.
run { println("...") }
</code>```

Body:
Observable.just(10,20,30,40,50)
            .subscribe { Consumer<Int>{
                Log.d(TAG, "Where I'm I" + Thread.currentThread())
                System.out.println("Hello boss")
                Toast.makeText(baseContext.applicationContext, "Hellloo",Toast.LENGTH_SHORT).show()
            } }

vs

 Observable.just(10,20,30,40,50)
            .subscribe( { Consumer<Int>{
                Log.d(TAG, "Where I'm I" + Thread.currentThread())
                System.out.println("Hello boss")
                Toast.makeText(baseContext.applicationContext, "Hellloo",Toast.LENGTH_SHORT).show()
            } })

What's the difference between calling subscribe({}) vs subscribe { }

Body:
With respect to RxJava there is no difference. Calling and execution stays the same. Its just a special syntax in kotlin known as trailing lambda.

In kotlin if you have a function with a lambda as last parameter then you can move that lambda out of parentheses. If the lambda is the only parameter then you can also remove the parentheses.

From the kotlin docs

Passing trailing lambdas

In Kotlin, there is a convention: if the last parameter of a function
  is a function, then a lambda expression passed as the corresponding
  argument can be placed outside the parentheses:

// Second argument of fold is of function type,
// hence we have moved the lambda out of parentheses.
val product = items.fold(1) { acc, e -> acc * e }

Such syntax is also known as trailing lambda.

If the lambda is the only argument to that call, the parentheses can
  be omitted entirely:

// run only takes a single argument of function type,
// hence we have omitted the parentheses.
run { println("...") }


问:
How to Create a New Dataframe from Missing Values Between Two Dataframes
I have two dataframes:

df1

```<code>  Person     Date Company Name Symbol   ID
0   Dale  2019 Q4       A Corp    AAA   10
1   Bill  2019 Q4       B Corp    NaN   20
2   Hank  2019 Q4       C Corp    NaN   30
3  Rusty  2019 Q4       C Corp    CCC   30
4  Peggy  2019 Q4       X Corp    NaN  100
5   John  2019 Q4       Y Corp    NaN  200
6   Kahn  2019 Q4       Z Corp    NaN  300
7   Mihn  2019 Q4       Z Corp    NaN  300
</code>```

df2

```<code>  Company Name Symbol  ID
0       A Corp    AAA  10
1       B Corp    BBB  20
2       C Corp    CCC  30
3       D Corp    DDD  40
4       E Corp    EEE  50
5       F Corp    FFF  60
6       G Corp    GGG  70
7       H Corp    HHH  80
8       I Corp    III  90
</code>```

And I want to create a new df3 which is made up of IDs that are in df1, but not in df2,so that the output would look like:

df3

```<code>  Company Name Symbol  ID
1       X Corp        100
2       Y Corp        200
3       Z Corp        300

</code>```

How would I achieve this?

答:
Index based on 'ID' of both dataframes

```<code>df1[~df1['ID'].isin(df2['ID'])]
</code>```

Body:
I have two dataframes:

df1

  Person     Date Company Name Symbol   ID
0   Dale  2019 Q4       A Corp    AAA   10
1   Bill  2019 Q4       B Corp    NaN   20
2   Hank  2019 Q4       C Corp    NaN   30
3  Rusty  2019 Q4       C Corp    CCC   30
4  Peggy  2019 Q4       X Corp    NaN  100
5   John  2019 Q4       Y Corp    NaN  200
6   Kahn  2019 Q4       Z Corp    NaN  300
7   Mihn  2019 Q4       Z Corp    NaN  300

df2

  Company Name Symbol  ID
0       A Corp    AAA  10
1       B Corp    BBB  20
2       C Corp    CCC  30
3       D Corp    DDD  40
4       E Corp    EEE  50
5       F Corp    FFF  60
6       G Corp    GGG  70
7       H Corp    HHH  80
8       I Corp    III  90

And I want to create a new df3 which is made up of IDs that are in df1, but not in df2,so that the output would look like:

df3

  Company Name Symbol  ID
1       X Corp        100
2       Y Corp        200
3       Z Corp        300

How would I achieve this?

Body:
Index based on 'ID' of both dataframes

df1[~df1['ID'].isin(df2['ID'])]


问:
iFrame Changes window.innerHeight / window.innerWidth on Android + PhoneGap
I'm creating an App using PhoneGap for Android. One of the pages in the App contains an iFrame (with local content) that is larger than the rest of the pages (this is a single-page App).

The problem I've run into is that once the iFrame page is viewed, the window.innerHeight and window.innerWidth JavaScript objects change their values to match the iFrame's width/height which is causing the rest of the 'pages' to display incorrectly as they are not the same size.

This persists even after I remove the iFrame from the DOM.

Has anyone run into this or has an idea of a workaround?

答:
I just was in the same situation and also I removed the iframe, the solution (that worked for me) is to put the next in your html head:

<meta name="viewport" content="width=device-width, initial-scale=1">

I always though that this part was unnecessary because the innerWidth and innerHeight don't complicate on the desktop, but it cost me 6 hours.

I would like to know if it worked for you, bye.


问:
How to match different groups in regex
I have the following string:

```<code>"Josua de Grave* (1643-1712)"
</code>```

Everything before the * is the person's name, the first date 1634 is his birth date, 1712 is the date of his death.

Following this logic I'd like to have 3 match groups for each one of the item. I tried

```<code>([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})
</code>```

```<code>"Josua de Grave* (1643-1712)".match(/([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})/)
</code>```

but that returns nil.

Why is my logic wrong, and what should I do to get the 3 intended match groups.

答:
```<code>r = /\*\s+\(|(?<=\d)\s*-\s*|\)/

"Josua de Grave* (1643-1712)".split r
  #=> ["Josua de Grave", "1643", "1712"]

"Sir Winston Leonard Spencer-Churchill* (1874 - 1965)".split r
  #=> ["Sir Winston Leonard Spencer-Churchill", "1874", "1965"]
</code>```

The regular expression can be made self-documenting by writing it in free-spacing mode:

```<code>r = /
    \*\s+\(  # match '*' then >= 1 whitespaces then '('
    |        # or
    (?<=\d)  # match is preceded by a digit (positive lookbehind)
    \s*-\s*  # match >= 0 whitespaces then '-' then >= 0 whitespaces
    |        # or
    \)       # match ')'
    /x       # free-spacing regex definition mode
</code>```

The positive lookbehind is needed to avoid splitting hyphenated names on hyphens. (The positive lookahead (?=\d), placed after \s*-\s*, could be used instead.)

Title: How to match different groups in regex

Body:
I have the following string:

"Josua de Grave* (1643-1712)"

Everything before the * is the person's name, the first date 1634 is his birth date, 1712 is the date of his death.

Following this logic I'd like to have 3 match groups for each one of the item. I tried

([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})

"Josua de Grave* (1643-1712)".match(/([a-zA-Z|\s]*)\* (\d{3,4})-(\d{3,4})/)

but that returns nil.

Why is my logic wrong, and what should I do to get the 3 intended match groups.

Body:
r = /\*\s+\(|(?<=\d)\s*-\s*|\)/

"Josua de Grave* (1643-1712)".split r
  #=> ["Josua de Grave", "1643", "1712"]

"Sir Winston Leonard Spencer-Churchill* (1874 - 1965)".split r
  #=> ["Sir Winston Leonard Spencer-Churchill", "1874", "1965"]

The regular expression can be made self-documenting by writing it in free-spacing mode:

r = /
    \*\s+\(  # match '*' then >= 1 whitespaces then '('
    |        # or
    (?<=\d)  # match is preceded by a digit (positive lookbehind)
    \s*-\s*  # match >= 0 whitespaces then '-' then >= 0 whitespaces
    |        # or
    \)       # match ')'
    /x       # free-spacing regex definition mode

The positive lookbehind is needed to avoid splitting hyphenated names on hyphens. (The positive lookahead (?=\d), placed after \s*-\s*, could be used instead.)