问:
Combining object destructuring with parameter properties in TypeScript
I've read about how typescript provides a shorthand where you can prefix constructor parameter with an access modifier and it is automatically declared on the class and copied from the constructor

```<code>class Foo {
    x: number;
    constructor(x:number) {
        this.x = x;
    }
}
</code>```

So the previous example can be re-written as (notice public x:number):

```<code>class Foo {
    constructor(public x:number) {
    }
}
</code>```

But I can't do it with a parameter with object literal:

```<code>export class Hero {
  constructor( {public id = 0   , public name = 'noname'}: {id?: number, name?: string }  = {}) {
  }
}
</code>```

I get double error: error TS1005: '=' expected.

Is it possible to do it in typescript ?

答:
Your specific requirement with combination of object destruction and parameter properties is not yet supported in TypeScript. See https://github.com/Microsoft/TypeScript/issues/5326 for details.
But you can implement a workaround and define an interface (or class, it's not significant in TypeScript) for this puprose like this:

```<code>interface TestInterface {
    id: number;
    name: string;
}

class Greeter {
    constructor(public greeting: string, public objectField: TestInterface) {
    }

    greet() {
        return "Hello, " + this.greeting + " " + this.objectField.name;
    }
}

let greeter = new Greeter("world", { id: 0, name: 'no name' });

alert(greeter.greet());
</code>```

But if you define TestInterface as class, then corresponding construcor function will be in complied JS.

```<code>var TestInterface = (function () {
    function TestInterface() {
    }
    return TestInterface;
}());
</code>```

Body:
I've read about how typescript provides a shorthand where you can prefix constructor parameter with an access modifier and it is automatically declared on the class and copied from the constructor

class Foo {
    x: number;
    constructor(x:number) {
        this.x = x;
    }
}

So the previous example can be re-written as (notice public x:number):

class Foo {
    constructor(public x:number) {
    }
}

But I can't do it with a parameter with object literal:

export class Hero {
  constructor( {public id = 0   , public name = 'noname'}: {id?: number, name?: string }  = {}) {
  }
}

I get double error: error TS1005: '=' expected.

Is it possible to do it in typescript ?

Body:
Your specific requirement with combination of object destruction and parameter properties is not yet supported in TypeScript. See https://github.com/Microsoft/TypeScript/issues/5326 for details.
But you can implement a workaround and define an interface (or class, it's not significant in TypeScript) for this puprose like this:

interface TestInterface {
    id: number;
    name: string;
}

class Greeter {
    constructor(public greeting: string, public objectField: TestInterface) {
    }

    greet() {
        return "Hello, " + this.greeting + " " + this.objectField.name;
    }
}

let greeter = new Greeter("world", { id: 0, name: 'no name' });

alert(greeter.greet());

But if you define TestInterface as class, then corresponding construcor function will be in complied JS.

var TestInterface = (function () {
    function TestInterface() {
    }
    return TestInterface;
}());


来源: stackexchange

问:
Crontab php fail
My cron file says:
* * * * * root /usr/bin/php /var/www/html/cron.php

And cron.php is executable and located at /var/www/html/cron.php, still it doesn't work at all. My cron.php file:

```<code><?php
include('Includes/top.php');

$Cron->closeServer();
?>
</code>```

答:
The problem is the include() is relative and you're probably not in the right working dir.

Change your command to cd /var/www/html && /usr/bin/php cron.php

ContentLicense: CC BY-SA 3.0

Title: Crontab php fail

Body:
My cron file says:
* * * * * root /usr/bin/php /var/www/html/cron.php

And cron.php is executable and located at /var/www/html/cron.php, still it doesn't work at all. My cron.php file:

<?php
include('Includes/top.php');

$Cron->closeServer();
?>


问:
A program interpretation in C
I am new to c and sometimes I get confused by things I see.
I have the following code:

```<code>int
sstmm_()

{time_t ourtime;
 time(&ourtime);
 return (int)(ourtime&0x00000fff);
}
</code>```

I do not understand what the meaning of ourtime&0x00000fff is?
Is it a pointer yet? What is the rule of 0x00000fff?
Thank you so much.

答:
ourtime is of type time_t which is normally a typedef of __time_t

__time_t type is in itself not the first thing I would explore if I was new to ANSI C, the standard says it represents the system time since unix epoch, on linux like environment it is usually signed integer, which could be 32 bit or 64 bit long.

In visual c++ it has traditionally been a 64bit unsigned integer.

So, no it is not a pointer, now with the usage of &, if you see integers on both sides then it implies it is being used as a binary operator, if you just see it being used with one variable it is used as a unary operator. You should check out what are the different types of operators in ANSI C many programming languages use them in a similar fashion, use of &as a unary operator is typical to C/C++ though.

&ourtime is evaluating to address of ourtime.
  ourtime&0x00000fff is asking for last 3 nibbles of integer ourtime.

Title: A program interpretation in C

Body:
I am new to c and sometimes I get confused by things I see.
I have the following code:

int
sstmm_()

{time_t ourtime;
 time(&ourtime);
 return (int)(ourtime&0x00000fff);
}

I do not understand what the meaning of ourtime&0x00000fff is?
Is it a pointer yet? What is the rule of 0x00000fff?
Thank you so much.


问:
JavaScript - compare two arrays with limited values/elements
I have an array of a few numbers or strings, eg.

```<code>[4.3, 1.2, 4.5, 3.9]

['I', 'the', 'sheriff', 'shot']
</code>```

The users re-arrange the elements in a specific order. For example, in an ascending order:

```<code>[1.2, 3.9, 4.3, 4.5]
</code>```

and to create a valid sentence:

```<code>['I', 'shot', 'the', 'sheriff']
</code>```

I have those predefined answers stored in an object. How do I compare the arrays with user generated order with the ones with correct order of elements. I have seen other answers on how to compare arrays but my question does not require a wide range of 'what if....' that other answers had. The elements are generated by the app so no unexpected input would be there, no undefined values, no empty elements, etc. Users do not input anything. They just rearrange tiles with those elements.

What's the best way to compare the arrays to determine if the users have rearranged the boxes in the right way.

My first attempt is incorrect as it always seems to be outputing 'BINGO' even if the order is incorrect:

```<code>if (this.props.squares === correctOrder) {
      console.log("BINGO");
    }
</code>```

答:
The easiest way would be to iterate through all the elements and compare:

```<code>function arraysEqual(array1, array2) {
    for(var i = array1.length; i--;) {
        if(array1[i] !== array2[i])
            return false;
    }

    return true;
}
</code>```

Ex:

```<code>arraysEqual(["I", "am", "well"], ["I", "am", "not", "well"])  // returns false
arraysEqual(["I", "am", "well"], ["I", "am", "well"])  // returns true
</code>```

Hope it helps.

Body:
I have an array of a few numbers or strings, eg.

[4.3, 1.2, 4.5, 3.9]

['I', 'the', 'sheriff', 'shot']

The users re-arrange the elements in a specific order. For example, in an ascending order:

[1.2, 3.9, 4.3, 4.5]

and to create a valid sentence:

['I', 'shot', 'the', 'sheriff']

I have those predefined answers stored in an object. How do I compare the arrays with user generated order with the ones with correct order of elements. I have seen other answers on how to compare arrays but my question does not require a wide range of 'what if....' that other answers had. The elements are generated by the app so no unexpected input would be there, no undefined values, no empty elements, etc. Users do not input anything. They just rearrange tiles with those elements.

What's the best way to compare the arrays to determine if the users have rearranged the boxes in the right way.

My first attempt is incorrect as it always seems to be outputing 'BINGO' even if the order is incorrect:

if (this.props.squares === correctOrder) {
      console.log("BINGO");
    }

Body:
The easiest way would be to iterate through all the elements and compare:

function arraysEqual(array1, array2) {
    for(var i = array1.length; i--;) {
        if(array1[i] !== array2[i])
            return false;
    }

    return true;
}

Ex:

arraysEqual(["I", "am", "well"], ["I", "am", "not", "well"])  // returns false
arraysEqual(["I", "am", "well"], ["I", "am", "well"])  // returns true

Hope it helps.


问:
Formatting the way a string is entered into my database
I am wanting to format data entered into a string column (confusingly named time) of my database in a certain way. Because of legacy data issues on this project I can't simply change the column type from string to time because I would lose the old entries.

I simply want to require that the format of the information entered into the form and then submitted to the database is as follows:

00:00 where a 0 can by any integer 0-9.

How would I do that within a form_for.

I am using Rails 2.3.8.

答: Your regex would be /\d\d:\d\d/, but I'm not sure how to use regular expressions in Ruby.

ContentLicense: CC BY-SA 2.5


问:
How to make tornado execute concurrent code?
I'm trying to write a simple workload generator for a Tornado server, here's its simplified version:

```<code>class EventsLoader(object):

    generate_num_requests = 1000
    generate_concurrency = 32
    server_port = 8001

    def __init__(self, conf_file):
        self.parse_config(conf_file)
        self.client = AsyncHTTPClient()

    def generate(self):
        IOLoop.current().run_sync(self.generate_work)

    @gen.coroutine
    def generate_work(self):
        self.queue = queues.Queue()
        IOLoop.current().spawn_callback(self.fetch_requests)
        for i in range(self.generate_concurrency):
            yield self.generate_requests(i)
        print 'before join queue size: %s' % self.queue.qsize()
        yield self.queue.join()

    @gen.coroutine
    def generate_requests(self, i):
        load = self.generate_num_requests / self.generate_concurrency
        for j in range(load):
            request = self.generate_request(i * 1000 + j)
            self.queue.put(request)

    @gen.coroutine
    def fetch_requests(self):
        while True:
            try:
                request = yield self.queue.get()
                yield self.client.fetch(request)
            except Exception as e:
                print 'failed fetching: %s: %s' % (request.body, e)
            finally:
                print 'fetched: %s' % json.loads(request.body)['seq']
                self.queue.task_done()

    def generate_request(self, seq):
        event = {
            'seq': seq,
            # ... more fields here ...
        }
        return HTTPRequest(
            'http://localhost:%s/events' % self.server_port,
            method='POST',
            body=json.dumps(event),
        )
</code>```

What I see happen is that all messages fetched: xxxx appear in sequential order, which is absolutely improbable, if the generator was indeed working concurrently.

How do I make it run concurrently? There must be something huge missing in my understanding of what I/O loop is for, and what @gen.coroutine does.  I.e. regardless of my generate_concurrency setting, the performance is unchanged.

答:
No matter how you're generating the requests, you've only got on task fetching them. It's the fetching, not the generating, that you need to parallelize:

```<code>for i in range(self.fetch_concurrency):
    IOLoop.current().spawn_callback(self.fetch_requests)
</code>```

This will give you multiple fetch_requests workers that can pull work from the shared queue.

Also, the generation part of this code isn't running in parallel either. Instead of

```<code>   for i in range(self.generate_concurrency):
        yield self.generate_requests(i)
</code>```

which waits for one generate_requests call to finish before starting the next, you can run them in parallel with

```<code>yield [self.generate_requests(i) for i in range(self.generate_concurrency)]
</code>```

Body:
I'm trying to write a simple workload generator for a Tornado server, here's its simplified version:

class EventsLoader(object):

    generate_num_requests = 1000
    generate_concurrency = 32
    server_port = 8001

    def __init__(self, conf_file):
        self.parse_config(conf_file)
        self.client = AsyncHTTPClient()

    def generate(self):
        IOLoop.current().run_sync(self.generate_work)

    @gen.coroutine
    def generate_work(self):
        self.queue = queues.Queue()
        IOLoop.current().spawn_callback(self.fetch_requests)
        for i in range(self.generate_concurrency):
            yield self.generate_requests(i)
        print 'before join queue size: %s' % self.queue.qsize()
        yield self.queue.join()

    @gen.coroutine
    def generate_requests(self, i):
        load = self.generate_num_requests / self.generate_concurrency
        for j in range(load):
            request = self.generate_request(i * 1000 + j)
            self.queue.put(request)

    @gen.coroutine
    def fetch_requests(self):
        while True:
            try:
                request = yield self.queue.get()
                yield self.client.fetch(request)
            except Exception as e:
                print 'failed fetching: %s: %s' % (request.body, e)
            finally:
                print 'fetched: %s' % json.loads(request.body)['seq']
                self.queue.task_done()

    def generate_request(self, seq):
        event = {
            'seq': seq,
            # ... more fields here ...
        }
        return HTTPRequest(
            'http://localhost:%s/events' % self.server_port,
            method='POST',
            body=json.dumps(event),
        )

What I see happen is that all messages fetched: xxxx appear in sequential order, which is absolutely improbable, if the generator was indeed working concurrently.

How do I make it run concurrently? There must be something huge missing in my understanding of what I/O loop is for, and what @gen.coroutine does.  I.e. regardless of my generate_concurrency setting, the performance is unchanged.

Body:
No matter how you're generating the requests, you've only got on task fetching them. It's the fetching, not the generating, that you need to parallelize:

for i in range(self.fetch_concurrency):
    IOLoop.current().spawn_callback(self.fetch_requests)

This will give you multiple fetch_requests workers that can pull work from the shared queue.

Also, the generation part of this code isn't running in parallel either. Instead of

   for i in range(self.generate_concurrency):
        yield self.generate_requests(i)

which waits for one generate_requests call to finish before starting the next, you can run them in parallel with

yield [self.generate_requests(i) for i in range(self.generate_concurrency)]


问:
How does this strange I/O method work?
While taking input output in C++ I have only used scanf/printf and cin/cout. Now I recently came across this code taking I/O in a strange fashion.

Also note that this I/O method is causing the code to run extremely fast, as this code uses almost the same algorithm as most of the other codes but it executes in a much smaller time. Why is this I/O so fast and how does this work in general?

edit: code

```<code> #include <bits/stdtr1c++.h>

 #define MAXN 200010
 #define MAXQ 200010
 #define MAXV 1000010
 #define clr(ar) memset(ar, 0, sizeof(ar))
 #define read() freopen("lol.txt", "r", stdin)

 using namespace std;

 const int block_size = 633;

 long long res, out[MAXQ]; int n, q, ar[MAXN], val[MAXN], freq[MAXV];

 namespace fastio{
     int ptr, ye;
     char temp[25], str[8333667], out[8333669];

     void init(){
         ptr = 0, ye = 0;
         fread(str, 1, 8333667, stdin);
     }

     inline int number(){
         int i, j, val = 0;

         while (str[ptr] < 45 || str[ptr] > 57) ptr++;
         while (str[ptr] > 47 && str[ptr] < 58) val = (val * 10) + (str[ptr++] - 48);
         return val;
     }

     inline void convert(long long x){
         int i, d = 0;

         for (; ;){
             temp[++d] = (x % 10) + 48;
             x /= 10;
             if (!x) break;
         }
         for (i = d; i; i--) out[ye++] = temp[i];
         out[ye++] = 10;
     }

     inline void print(){
         fwrite(out, 1, ye, stdout);
     } }

 struct query{
     int l, r, d, i;

     inline query() {}
     inline query(int a, int b, int c){
         i = c;
         l = a, r = b, d = l / block_size;
     }

     inline bool operator < (const query& other) const{
         if (d != other.d) return (d < other.d);
         return ((d & 1) ? (r < other.r) : (r > other.r));
     } } Q[MAXQ];

 void compress(int n, int* in, int* out){
     unordered_map <int, int> mp;
     for (int i = 0; i < n; i++) out[i] = mp.emplace(in[i], mp.size()).first->second; }

 inline void insert(int i){
     res += (long long)val[i] * (1 + 2 * freq[ar[i]]++); }

 inline void erase(int i){
     res -= (long long)val[i] * (1 + 2 * --freq[ar[i]]); }

 inline void run(){
     sort(Q, Q + q);
     int i, l, r, a = 0, b = 0;

     for (res = 0, i = 0; i < q; i++){
         l = Q[i].l, r = Q[i].r;
         while (a > l) insert(--a);
         while (b <= r) insert(b++);
         while (a < l) erase(a++);
         while (b > (r + 1)) erase(--b);
         out[Q[i].i] = res;
     }
     for (i = 0; i < q; i++) fastio::convert(out[i]); }

 int main(){
     fastio::init();
     int n, i, j, k, a, b;

     n = fastio::number();
     q = fastio::number();
     for (i = 0; i < n; i++) val[i] = fastio::number();
     compress(n, val, ar);

     for (i = 0; i < q; i++){
         a = fastio::number();
         b = fastio::number();
         Q[i] = query(a - 1, b - 1, i);
     }

     run();
     fastio::print();
     return 0; }
</code>```

答:
This solution, http://codeforces.com/contest/86/submission/22526466 (624 ms, 32 MB RAM uses) uses single fread and manual parsing of numbers from memory (so it uses more memory); many other solutions are slower and uses scanf (http://codeforces.com/contest/86/submission/27561563 1620 ms 9MB) or C++ iostream cin (http://codeforces.com/contest/86/submission/27558562 3118 ms, 15 MB). Not all difference of solutions comes from input-output and parsing (solutions methods have differences too), but some is.

```<code> fread(str, 1, 8333667, stdin);
</code>```

This code uses single fread libcall to read up to 8MB, which is full file. The file may have up to 2 (n,t) + 200000 (a_i) + 2*200000 (l,r) 6/7-digit numbers with or without line breaks or separated by one (?) space, so around 8 chars max for number (6 or 7 for number, as 1000000 is allowed too, and 1 space or \n); max input file size is like 0.6 M * 8 bytes =~ 5 MB.

```<code> inline int number(){
     int i, j, val = 0;

     while (str[ptr] < 45 || str[ptr] > 57) ptr++;
     while (str[ptr] > 47 && str[ptr] < 58) val = (val * 10) + (str[ptr++] - 48);
     return val;
 }
</code>```

Then code uses manual code of parsing decimal int numbers. According to ascii table, http://www.asciitable.com/ decimal codes of 48...57 are decimal digits (second while loop): '0'...'9', and we can just subtract 48 from the letter code to get the digit; multiply partially read val by 10 and add current digit. And chr<45 || chr > 57 in the first while loops sound like skipping non-digits from input. This is incorrect, as this code will not parse codes 45, 46, 47 = '-', '.', '/', and no any number after these chars will be read.

```<code> n = fastio::number();
 q = fastio::number();
 for (i = 0; i < n; i++) val[i] = fastio::number();

 for (i = 0; i < q; i++){
     a = fastio::number();
     b = fastio::number();
</code>```

Actual reading uses this fastio::number() method; and other solutions uses calling of scanf or iostream operator << in loop:

```<code>for (int i = 0; i < N; i++) {
    scanf("%d", &(arr[i]));
    add(arr[i]);
}
</code>```

or

```<code>for (int i = 1; i <= n; ++i)
    cin >> a[i];
</code>```

Both methods are more universal, but they do library call, which will read some chars from internal buffer (like 4KB) or call OS syscall for buffer refill, and every function does many checks and has error reporting: For every number of input scanf will reparse the same format string of first argument, and will do all the logic described in POSIX http://pubs.opengroup.org/onlinepubs/7908799/xsh/fscanf.html and all error-checking. C++ iostream has no format string, but it is still more universal: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/istream.tcc#L156 'operator>>(int& __n)'.

So, standard library functions have more logic inside, more calls, more branching; and they are more universal and much safer, and should be used in real-world programming. And this "sport programming" contest allow users to solve the task with standard library functions which are fast enough, if you can imagine the algorithm. Authors or task are required to write several solutions with standard i/o functions to check that timelimit of the task is correct and task can be solved. (The TopCoder system is better with i/o, you will not implement i/o, the data is already passed into your function in some language structs/collections).

Sometimes tasks in sport programming have tight limits on memory: input files several times bigger than allowed memory usage, and programmer can't read whole file into memory. For example: get 20 mln of digits of single verylong number from input file and add 1 to it, with memory limit of 2 MB; you can't read full input number from file in forward direction; it is very hard to do correct reading in chunks in backward direction; and you just need to forget standard method of addition  (Columnar addition) and build FSM (Finite-state machine) with state, counting sequences of 9s.

Title: How does this strange I/O method work?

Body:
While taking input output in C++ I have only used scanf/printf and cin/cout. Now I recently came across this code taking I/O in a strange fashion.

Also note that this I/O method is causing the code to run extremely fast, as this code uses almost the same algorithm as most of the other codes but it executes in a much smaller time. Why is this I/O so fast and how does this work in general?

edit: code

 #include <bits/stdtr1c++.h>

 #define MAXN 200010
 #define MAXQ 200010
 #define MAXV 1000010
 #define clr(ar) memset(ar, 0, sizeof(ar))
 #define read() freopen("lol.txt", "r", stdin)

 using namespace std;

 const int block_size = 633;

 long long res, out[MAXQ]; int n, q, ar[MAXN], val[MAXN], freq[MAXV];

 namespace fastio{
     int ptr, ye;
     char temp[25], str[8333667], out[8333669];

     void init(){
         ptr = 0, ye = 0;
         fread(str, 1, 8333667, stdin);
     }

     inline int number(){
         int i, j, val = 0;

         while (str[ptr] < 45 || str[ptr] > 57) ptr++;
         while (str[ptr] > 47 && str[ptr] < 58) val = (val * 10) + (str[ptr++] - 48);
         return val;
     }

     inline void convert(long long x){
         int i, d = 0;

         for (; ;){
             temp[++d] = (x % 10) + 48;
             x /= 10;
             if (!x) break;
         }
         for (i = d; i; i--) out[ye++] = temp[i];
         out[ye++] = 10;
     }

     inline void print(){
         fwrite(out, 1, ye, stdout);
     } }

 struct query{
     int l, r, d, i;

     inline query() {}
     inline query(int a, int b, int c){
         i = c;
         l = a, r = b, d = l / block_size;
     }

     inline bool operator < (const query& other) const{
         if (d != other.d) return (d < other.d);
         return ((d & 1) ? (r < other.r) : (r > other.r));
     } } Q[MAXQ];

 void compress(int n, int* in, int* out){
     unordered_map <int, int> mp;
     for (int i = 0; i < n; i++) out[i] = mp.emplace(in[i], mp.size()).first->second; }

 inline void insert(int i){
     res += (long long)val[i] * (1 + 2 * freq[ar[i]]++); }

 inline void erase(int i){
     res -= (long long)val[i] * (1 + 2 * --freq[ar[i]]); }

 inline void run(){
     sort(Q, Q + q);
     int i, l, r, a = 0, b = 0;

     for (res = 0, i = 0; i < q; i++){
         l = Q[i].l, r = Q[i].r;
         while (a > l) insert(--a);
         while (b <= r) insert(b++);
         while (a < l) erase(a++);
         while (b > (r + 1)) erase(--b);
         out[Q[i].i] = res;
     }
     for (i = 0; i < q; i++) fastio::convert(out[i]); }

 int main(){
     fastio::init();
     int n, i, j, k, a, b;

     n = fastio::number();
     q = fastio::number();
     for (i = 0; i < n; i++) val[i] = fastio::number();
     compress(n, val, ar);

     for (i = 0; i < q; i++){
         a = fastio::number();
         b = fastio::number();
         Q[i] = query(a - 1, b - 1, i);
     }

     run();
     fastio::print();
     return 0; }

Body:
This solution, http://codeforces.com/contest/86/submission/22526466 (624 ms, 32 MB RAM uses) uses single fread and manual parsing of numbers from memory (so it uses more memory); many other solutions are slower and uses scanf (http://codeforces.com/contest/86/submission/27561563 1620 ms 9MB) or C++ iostream cin (http://codeforces.com/contest/86/submission/27558562 3118 ms, 15 MB). Not all difference of solutions comes from input-output and parsing (solutions methods have differences too), but some is.

 fread(str, 1, 8333667, stdin);

This code uses single fread libcall to read up to 8MB, which is full file. The file may have up to 2 (n,t) + 200000 (a_i) + 2*200000 (l,r) 6/7-digit numbers with or without line breaks or separated by one (?) space, so around 8 chars max for number (6 or 7 for number, as 1000000 is allowed too, and 1 space or \n); max input file size is like 0.6 M * 8 bytes =~ 5 MB.

 inline int number(){
     int i, j, val = 0;

     while (str[ptr] < 45 || str[ptr] > 57) ptr++;
     while (str[ptr] > 47 && str[ptr] < 58) val = (val * 10) + (str[ptr++] - 48);
     return val;
 }

Then code uses manual code of parsing decimal int numbers. According to ascii table, http://www.asciitable.com/ decimal codes of 48...57 are decimal digits (second while loop): '0'...'9', and we can just subtract 48 from the letter code to get the digit; multiply partially read val by 10 and add current digit. And chr<45 || chr > 57 in the first while loops sound like skipping non-digits from input. This is incorrect, as this code will not parse codes 45, 46, 47 = '-', '.', '/', and no any number after these chars will be read.

 n = fastio::number();
 q = fastio::number();
 for (i = 0; i < n; i++) val[i] = fastio::number();

 for (i = 0; i < q; i++){
     a = fastio::number();
     b = fastio::number();

Actual reading uses this fastio::number() method; and other solutions uses calling of scanf or iostream operator << in loop:

for (int i = 0; i < N; i++) {
    scanf("%d", &(arr[i]));
    add(arr[i]);
}

or

for (int i = 1; i <= n; ++i)
    cin >> a[i];

Both methods are more universal, but they do library call, which will read some chars from internal buffer (like 4KB) or call OS syscall for buffer refill, and every function does many checks and has error reporting: For every number of input scanf will reparse the same format string of first argument, and will do all the logic described in POSIX http://pubs.opengroup.org/onlinepubs/7908799/xsh/fscanf.html and all error-checking. C++ iostream has no format string, but it is still more universal: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/istream.tcc#L156 'operator>>(int& __n)'.

So, standard library functions have more logic inside, more calls, more branching; and they are more universal and much safer, and should be used in real-world programming. And this "sport programming" contest allow users to solve the task with standard library functions which are fast enough, if you can imagine the algorithm. Authors or task are required to write several solutions with standard i/o functions to check that timelimit of the task is correct and task can be solved. (The TopCoder system is better with i/o, you will not implement i/o, the data is already passed into your function in some language structs/collections).

Sometimes tasks in sport programming have tight limits on memory: input files several times bigger than allowed memory usage, and programmer can't read whole file into memory. For example: get 20 mln of digits of single verylong number from input file and add 1 to it, with memory limit of 2 MB; you can't read full input number from file in forward direction; it is very hard to do correct reading in chunks in backward direction; and you just need to forget standard method of addition  (Columnar addition) and build FSM (Finite-state machine) with state, counting sequences of 9s.


问:
PHP: problems with inheritance
I try to do class tree  where each class in tree check own directory for template and use it, but when I call function in inherited class then called parent. How can i do it ?

My code in example below output:

D

  C

  b/1.phtml

but i need to d/1.phtml

```<code><?php

class A {
    private $templates_dir = 'a';
}

class B extends A {

    private $templates_dir = 'b';

    public function templates_dir()
    {
        return $this->templates_dir;
    }

    public function check_template($tpl)
    {
        $dir = $this->templates_dir();
        $file = $dir. '/'. $tpl;
        echo (get_class($this)). "\r\n";
        echo (get_parent_class($this)). "\r\n";
        echo $file . "\r\n";
// idea  - if (!file_exists($file)) return parent::check_template($file);
// method call each class while template will be found
// how do it?

    }

}

class C extends B {

    private $templates_dir = 'c';

}

class D extends C {

    private $templates_dir = 'd';

}

$obj = new D();
$obj->check_template('1.phtml');
</code>```

答:
Another approach will be placing the functions in a abstract class, and each of class A,B,C,D extends this, This is a neater way of doing things.

Below is the code --

```<code>    abstract class WW {

    protected function templates_dir()
    {
        return $this->templates_dir;
    }

    public function check_template($tpl)
    {
        $dir = $this->templates_dir();
        $file = $dir. '/'. $tpl;
        echo (get_class($this)). "\r\n";
        echo (get_parent_class($this)). "\r\n";
        echo $file . "\r\n";
    // idea  - if (!file_exists($file)) return parent::check_template($file);
    // method call each class while template will be found
    // how do it?

    }
}

class A extends WW {
    protected $templates_dir = 'a';
}

class B extends WW {

    protected $templates_dir = 'b';

}

class C extends WW {

    protected $templates_dir = 'c';

}

class D extends WW {

    protected $templates_dir = 'd';

}

$obj = new D();
$obj->check_template('1.phtml');
</code>```

Title: PHP: problems with inheritance

Body:
I try to do class tree  where each class in tree check own directory for template and use it, but when I call function in inherited class then called parent. How can i do it ?

My code in example below output:

D

  C

  b/1.phtml

but i need to d/1.phtml

<?php

class A {
    private $templates_dir = 'a';
}

class B extends A {

    private $templates_dir = 'b';

    public function templates_dir()
    {
        return $this->templates_dir;
    }

    public function check_template($tpl)
    {
        $dir = $this->templates_dir();
        $file = $dir. '/'. $tpl;
        echo (get_class($this)). "\r\n";
        echo (get_parent_class($this)). "\r\n";
        echo $file . "\r\n";
// idea  - if (!file_exists($file)) return parent::check_template($file);
// method call each class while template will be found
// how do it?

    }

}

class C extends B {

    private $templates_dir = 'c';

}

class D extends C {

    private $templates_dir = 'd';

}

$obj = new D();
$obj->check_template('1.phtml');

Body:
Another approach will be placing the functions in a abstract class, and each of class A,B,C,D extends this, This is a neater way of doing things.

Below is the code --

    abstract class WW {

    protected function templates_dir()
    {
        return $this->templates_dir;
    }

    public function check_template($tpl)
    {
        $dir = $this->templates_dir();
        $file = $dir. '/'. $tpl;
        echo (get_class($this)). "\r\n";
        echo (get_parent_class($this)). "\r\n";
        echo $file . "\r\n";
    // idea  - if (!file_exists($file)) return parent::check_template($file);
    // method call each class while template will be found
    // how do it?

    }
}

class A extends WW {
    protected $templates_dir = 'a';
}

class B extends WW {

    protected $templates_dir = 'b';

}

class C extends WW {

    protected $templates_dir = 'c';

}

class D extends WW {

    protected $templates_dir = 'd';

}

$obj = new D();
$obj->check_template('1.phtml');


问:
Singletons factory using generics and reflection
OrderDBManager, UserDBManager, ProductDBManager extend DBManager.
I'm trying to create a singletons DBManager Factory
to get instances of different DBManager type classes.

But I have a problem using generics to return an instance of exact DBManager type class user wants. Right now it only works for DBManager itself.
I would appreciate your help!

```<code>public class DBManagerFactory {

     private static final Map<String, DBManager> instances = new HashMap<>();

     private static final String DB_MANAGER_PACKAGE_NAME = "ua.Test.db.";

     public static DBManager getInstance(Class<? extends DBManager> dbManagerClass) {
            String dbManagerClassName = dbManagerClass.getSimpleName();
            DBManager dbManager = instances.get(dbManagerClassName);

            if(dbManager == null){
                Class clazz = Class.forName(DB_MANAGER_PACKAGE_NAME + dbManagerClassName);
                dbManager = (DBManager)clazz.newInstance();
                instances.put(dbManagerClassName, dbManager);
            }
            return dbManager;
     }}
</code>```

答:
If you need to get explicit return type, then you could use generic factory method, as follows:

```<code>class Base {}

class A extends Base {}

class B extends Base {}

class InitializationFailedException extends RuntimeException {
    public InitializationFailedException(Throwable cause) {
        super(cause);
    }
}

class Factory {

    private static Logger log = LoggerFactory.getLogger(Factory.class);

    private static final ConcurrentHashMap<Class<? extends Base>, Base> instances = new ConcurrentHashMap<>();

    public static  <T extends Base> T getInstance(Class<T> tClass) {
        if (tClass == null) {
            throw new NullPointerException();
        }
        return (T) instances.computeIfAbsent(tClass, (tClass1) -> {
            try {
                return tClass1.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                log.error("Unable to create singleton value for " + tClass1.getCanonicalName(), e);
                throw new InitializationFailedException(e);
            }
        });
    }

}
</code>```

With this approach you can get you sub type references created:

```<code>A aInstance = Factory.getInstance(A.class);
B bInstance = Factory.getInstance(B.class);
</code>```

for your problem method signature can look like:

```<code>public static <T extends DBManager> T getInstance(Class<T> dbManagerClass);
</code>```

instances Map should look like:

```<code>private static final Map<Class<? extends DBManager>, DBManager> instances = new HashMap<>();
</code>```

Body:
OrderDBManager, UserDBManager, ProductDBManager extend DBManager.
I'm trying to create a singletons DBManager Factory
to get instances of different DBManager type classes.

But I have a problem using generics to return an instance of exact DBManager type class user wants. Right now it only works for DBManager itself.
I would appreciate your help!

public class DBManagerFactory {

     private static final Map<String, DBManager> instances = new HashMap<>();

     private static final String DB_MANAGER_PACKAGE_NAME = "ua.Test.db.";

     public static DBManager getInstance(Class<? extends DBManager> dbManagerClass) {
            String dbManagerClassName = dbManagerClass.getSimpleName();
            DBManager dbManager = instances.get(dbManagerClassName);

            if(dbManager == null){
                Class clazz = Class.forName(DB_MANAGER_PACKAGE_NAME + dbManagerClassName);
                dbManager = (DBManager)clazz.newInstance();
                instances.put(dbManagerClassName, dbManager);
            }
            return dbManager;
     }}

Body:
If you need to get explicit return type, then you could use generic factory method, as follows:

class Base {}

class A extends Base {}

class B extends Base {}

class InitializationFailedException extends RuntimeException {
    public InitializationFailedException(Throwable cause) {
        super(cause);
    }
}

class Factory {

    private static Logger log = LoggerFactory.getLogger(Factory.class);

    private static final ConcurrentHashMap<Class<? extends Base>, Base> instances = new ConcurrentHashMap<>();

    public static  <T extends Base> T getInstance(Class<T> tClass) {
        if (tClass == null) {
            throw new NullPointerException();
        }
        return (T) instances.computeIfAbsent(tClass, (tClass1) -> {
            try {
                return tClass1.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                log.error("Unable to create singleton value for " + tClass1.getCanonicalName(), e);
                throw new InitializationFailedException(e);
            }
        });
    }

}

With this approach you can get you sub type references created:

A aInstance = Factory.getInstance(A.class);
B bInstance = Factory.getInstance(B.class);

for your problem method signature can look like:

public static <T extends DBManager> T getInstance(Class<T> dbManagerClass);

instances Map should look like:

private static final Map<Class<? extends DBManager>, DBManager> instances = new HashMap<>();


问:
Class 'FIRDynamicLinkComponents' not found while integrating FirebaseDynamicLink in iOS
I am integrating FirebaseDynamicLink in my cocos2dx-ios project, I have successfully integrated firebase into my iOS project, but while integrating FirebaseDynamicLink, I could not find class FIRDynamicLinkComponents into framewok, I also tried using Firebase dynamiclink sample, but found same error there also. Plz help me with this issue.
Here is my podfile content:

```<code># Uncomment the next line to define a global platform for your project
platform :ios, '8.0'

target 'test-mobile' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!

# Pods for test-mobile
pod 'Firebase/Core'
pod 'Firebase/AdMob'
pod 'Google/Analytics'
pod 'Firebase/DynamicLinks'
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'
pod 'AppsFlyerFramework'
pod 'Firebase/Messaging'

end
</code>```

Waiting for response!

答:
Open terminal, use pod update at the directory of PodFile of your project then you should see something like:

Installing FirebaseDynamicLinks 2.0.0 (was 1.3.4)

Build again and your problem should be resolved.

Body:
I am integrating FirebaseDynamicLink in my cocos2dx-ios project, I have successfully integrated firebase into my iOS project, but while integrating FirebaseDynamicLink, I could not find class FIRDynamicLinkComponents into framewok, I also tried using Firebase dynamiclink sample, but found same error there also. Plz help me with this issue.
Here is my podfile content:

# Uncomment the next line to define a global platform for your project
platform :ios, '8.0'

target 'test-mobile' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!

# Pods for test-mobile
pod 'Firebase/Core'
pod 'Firebase/AdMob'
pod 'Google/Analytics'
pod 'Firebase/DynamicLinks'
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'
pod 'AppsFlyerFramework'
pod 'Firebase/Messaging'

end

Waiting for response!


问:
C# Access Database Update Syntax Error
Is there something wrong with this query?

```<code>"UPDATE tb_EmployeeMasterList SET [EmployeeID] = " + txt_EmpId.Text +", [LastName] = '" + txt_LN.Text + "', [FirstName] = '" + txt_FN.Text + "', [MiddleName] = '" + txt_MN.Text + "', [PositionOrSkill] = '" + txt_PorS.Text + "', [BasicSalary] = " + txt_Basic.Text + ", [Allowance] = " + txt_Allow.Text + ", [Total] = " + total + ", [EPAproposedBonus] = " + txt_Bonus.Text + ", [Remarks] = '" + txt_Remarks.Text + "' WHERE ([LastName] = '" + LN + "' AND [FirstName] = '" + FN + "');"
</code>```

I keep on Getting syntax error on that query alone.

答:
Try to fire the WHERE statement without brackets </p>

```<code>"UPDATE tb_EmployeeMasterList SET [EmployeeID] = " + txt_EmpId.Text +", [LastName] = '" + txt_LN.Text + "', [FirstName] = '" + txt_FN.Text + "', [MiddleName] = '" + txt_MN.Text + "', [PositionOrSkill] = '" + txt_PorS.Text + "', [BasicSalary] = " + txt_Basic.Text + ", [Allowance] = " + txt_Allow.Text + ", [Total] = " + total + ", [EPAproposedBonus] = " + txt_Bonus.Text + ", [Remarks] = '" + txt_Remarks.Text + "' WHERE [LastName] = '" + LN + "' AND [FirstName] = '" + FN + "';"
</code>```

Title: C# Access Database Update Syntax Error

Body:
Is there something wrong with this query?

"UPDATE tb_EmployeeMasterList SET [EmployeeID] = " + txt_EmpId.Text +", [LastName] = '" + txt_LN.Text + "', [FirstName] = '" + txt_FN.Text + "', [MiddleName] = '" + txt_MN.Text + "', [PositionOrSkill] = '" + txt_PorS.Text + "', [BasicSalary] = " + txt_Basic.Text + ", [Allowance] = " + txt_Allow.Text + ", [Total] = " + total + ", [EPAproposedBonus] = " + txt_Bonus.Text + ", [Remarks] = '" + txt_Remarks.Text + "' WHERE ([LastName] = '" + LN + "' AND [FirstName] = '" + FN + "');"

I keep on Getting syntax error on that query alone.

Body:
Try to fire the WHERE statement without brackets

"UPDATE tb_EmployeeMasterList SET [EmployeeID] = " + txt_EmpId.Text +", [LastName] = '" + txt_LN.Text + "', [FirstName] = '" + txt_FN.Text + "', [MiddleName] = '" + txt_MN.Text + "', [PositionOrSkill] = '" + txt_PorS.Text + "', [BasicSalary] = " + txt_Basic.Text + ", [Allowance] = " + txt_Allow.Text + ", [Total] = " + total + ", [EPAproposedBonus] = " + txt_Bonus.Text + ", [Remarks] = '" + txt_Remarks.Text + "' WHERE [LastName] = '" + LN + "' AND [FirstName] = '" + FN + "';"


问:
If rows exists before adding it to datagridview
I'm having trouble getting this code to work, I'm adding rows to a datagridview from an SQL (WHILE) query, but while doing that I need to run a foreach inside to check if a row.Cells[0].Value exists before adding it, but i'm getting the following errors:

Error   1   foreach statement cannot operate on variables of type 'System.Windows.Forms.DataGridView' because 'System.Windows.Forms.DataGridView' does not contain a public definition for 'GetEnumerator'  C:\Users................project1.cs

Error   2   A local variable named 'row' cannot be declared in this scope because it would give a different meaning to 'row', which is already used in a 'parent or current' scope to denote something else C:\Users................project1.cs

Here is my code:

```<code>//dgData is a datagridview with columns created programmatically, this works already by the way.
dgData.ColumnCount = 3;
dgData.Columns[0].Name = "ColumnA";
dgData.Columns[0].Name = "ColumnB";
dgData.Columns[0].Name = "ColumnC";

string query1 = " SELECT * FROM ....... ";

SqlCommand cmd1 = new SqlCommand(query1, connection);
            //Create a data reader and Execute the command
            SqlDataReader dataReader1 = cmd1.ExecuteReader();

Application.DoEvents();
while (dataReader1.Read())
{

    string[] row = new string[] { dataReader1["columnA"].ToString(),     dataReader1["columnB"].ToString(), dataReader1["columnC"].ToString() };
    Boolean found = false;

    // this foreach is what doesn't work.
    foreach (DataGridViewRow row in dgData)
    {
         if (row.Cells[0].Value == dataReader1["columnA"].ToString())
         {
                 // row exists
                 found = true;
                 MessageBox.Show("Row already exists");
         }
    }

    if (!found)
    {
         dgData.Rows.Add(row);
    }

}
</code>```

答:
row is a name for string[] and for loop variable. rename one of them

DataGridView dgData isn't enumerable, iterate over dgData.Rows in foreach

```<code>while (dataReader1.Read())
{
    string[] newRow = new string[]
    {
      dataReader1["columnA"].ToString(),
      dataReader1["columnB"].ToString(),
      dataReader1["columnC"].ToString()
    };
    Boolean found = false;
    foreach (DataGridViewRow row in dgData.Rows)
    {
         if (row.Cells[0].Value == dataReader1["columnA"].ToString())
         {
              // row exists
              found = true;
              MessageBox.Show("Row already exists");
              break;
         }
    }

    if (!found)
    {
         dgData.Rows.Add(newRow);
    }
}
</code>```

Body:
I'm having trouble getting this code to work, I'm adding rows to a datagridview from an SQL (WHILE) query, but while doing that I need to run a foreach inside to check if a row.Cells[0].Value exists before adding it, but i'm getting the following errors:

Error   1   foreach statement cannot operate on variables of type 'System.Windows.Forms.DataGridView' because 'System.Windows.Forms.DataGridView' does not contain a public definition for 'GetEnumerator'  C:\Users................project1.cs

Error   2   A local variable named 'row' cannot be declared in this scope because it would give a different meaning to 'row', which is already used in a 'parent or current' scope to denote something else C:\Users................project1.cs

Here is my code:

//dgData is a datagridview with columns created programmatically, this works already by the way.
dgData.ColumnCount = 3;
dgData.Columns[0].Name = "ColumnA";
dgData.Columns[0].Name = "ColumnB";
dgData.Columns[0].Name = "ColumnC";

string query1 = " SELECT * FROM ....... ";

SqlCommand cmd1 = new SqlCommand(query1, connection);
            //Create a data reader and Execute the command
            SqlDataReader dataReader1 = cmd1.ExecuteReader();

Application.DoEvents();
while (dataReader1.Read())
{

    string[] row = new string[] { dataReader1["columnA"].ToString(),     dataReader1["columnB"].ToString(), dataReader1["columnC"].ToString() };
    Boolean found = false;

    // this foreach is what doesn't work.
    foreach (DataGridViewRow row in dgData)
    {
         if (row.Cells[0].Value == dataReader1["columnA"].ToString())
         {
                 // row exists
                 found = true;
                 MessageBox.Show("Row already exists");
         }
    }

    if (!found)
    {
         dgData.Rows.Add(row);
    }

}

Body:
row is a name for string[] and for loop variable. rename one of them

DataGridView dgData isn't enumerable, iterate over dgData.Rows in foreach

while (dataReader1.Read())
{
    string[] newRow = new string[]
    {
      dataReader1["columnA"].ToString(),
      dataReader1["columnB"].ToString(),
      dataReader1["columnC"].ToString()
    };
    Boolean found = false;
    foreach (DataGridViewRow row in dgData.Rows)
    {
         if (row.Cells[0].Value == dataReader1["columnA"].ToString())
         {
              // row exists
              found = true;
              MessageBox.Show("Row already exists");
              break;
         }
    }

    if (!found)
    {
         dgData.Rows.Add(newRow);
    }
}


问:
Regex for everything *after* the first complete sentence (period and space) *after* N characters
I'd like to get smarter excerpts of sections of text. As I'll be using Movable Type's regex_replace function, I'm gonna be trying to grab everything after the first few sentences.

While \..* gets everything after the first period, that often leaves a too-short excerpt. How might I do the same thing (everything after the first period) but skipping the first 100 characters?

Alternatively, how would I just grab everything after, say, the second or third period?

答:
Not familiar with regex_replace, I'll use the PHP preg_replace function and you can adapt accordingly:

```<code>$truncated = preg_replace('/^(.{100}.*?\.).*$/s', '$1', $long);
</code>```

Edit: I don't know what's up with the syntax highlighting on output treating the entire thing as a string, it looks fine in the preview.

And another version, which will try to be smart about not breaking up numbers with a decimal point (or other places a period might occur somewhere other than the end of a sentence):

```<code>$truncated = preg_replace('/^(.{100}.*?\.(?![a-z0-9])).*$/s', '$1', $long);
</code>```

Explanation:

The part you want to keep is grouped with parentheses.

You'll keep at least 100 characters: .{100}

You'll then keep any following characters up to the first decimal point: .*?\.

In the second version, I used a negative lookahead—(?![a-z0-9])—which will cause the last part to continue on to the next decimal place if the period character is followed by either a number or letter.

Dot matches new-line (the s modifier at the end of the pattern). If Movable Type's regex_replace function takes a pattern without delimiters (the leading slash and the trailing /s in my pattern), you can use (?s) at the beginning of the pattern instead.

Use $1 in the replacement to keep the first captured group.

Body:
Not familiar with regex_replace, I'll use the PHP preg_replace function and you can adapt accordingly:

$truncated = preg_replace('/^(.{100}.*?\.).*$/s', '$1', $long);

Edit: I don't know what's up with the syntax highlighting on output treating the entire thing as a string, it looks fine in the preview.

And another version, which will try to be smart about not breaking up numbers with a decimal point (or other places a period might occur somewhere other than the end of a sentence):

$truncated = preg_replace('/^(.{100}.*?\.(?![a-z0-9])).*$/s', '$1', $long);

Explanation:

The part you want to keep is grouped with parentheses.

You'll keep at least 100 characters: .{100}

You'll then keep any following characters up to the first decimal point: .*?\.

In the second version, I used a negative lookahead—(?![a-z0-9])—which will cause the last part to continue on to the next decimal place if the period character is followed by either a number or letter.

Dot matches new-line (the s modifier at the end of the pattern). If Movable Type's regex_replace function takes a pattern without delimiters (the leading slash and the trailing /s in my pattern), you can use (?s) at the beginning of the pattern instead.

Use $1 in the replacement to keep the first captured group.


问:
Group totals conditionally based on field values
I am trying to query different documents from MongoDB via pymongo and group them by specific fields. The grouping part works really well, but I have a field that has a boolean value (True, False), but currnently it is keeping documents with True and documents with False in a separate grouping.

For example:

```<code>doc1{boolean : True, ... ... ..., count = 20}
doc2{boolean : False, ... ... ..., count = 10}
</code>```

But I need it to group it like that:

```<code>doc{boolTrue : 20, boolFalse, 10, ... ... ..., count = 30}
</code>```

So that it would not separate the documents by the boolean field.

I tried to do something like that, but neither of the proposed (see below) solutions didn't work:

```<code>"$group": {
    "_id": {
       "succTrue": {"$sum": {"$cond": [{"$client.succeeded": "True"}, 1, 0]}},
       "succFalse": {"$cond": [{"$client.succeeded": "False"}, 1, 0]},
    }
}
</code>```

PS: There are other fields as well, but they are not relevant for the question.

E: Actual documents look something like that:

```<code>{
    "sType" : "Client",
    "succeeded" : false,
    "sVer" : "v1"
}
</code>```

Expected output:

```<code>{
    countSucceededTrue: 15,
    countSucceededFalse: 5,
    "sType" : "Client",
    "sVer" : "v1"
},
{
    countSucceededTrue: 5,
    countSucceededFalse: 13,
    "sType" : "Client",
    "sVer" : "v2"
}
{
    countSucceededTrue: 3,
    countSucceededFalse: 2,
    "sType" : "Client",
    "sVer" : "v3"
}
</code>```

答:
You want your "grouping keys" in the _id field, and the other conditions under $sum accumulators:

```<code>collection.aggregate([
  { "$group": {
    "_id": { "sType": "$sType", "sVer": "$sVer" },
    "countSucceededTrue": { "$sum": { "$cond": [ "$succeeded", 1, 0 ] } },
    "countSucceededFalse": { "$sum": { "$cond": [ "$succeeded", 0, 1 ] } }
  }}
])
</code>```

The "grouping key" is of course nested, but you should get used to the that concept. It is possible to do another pass to rename fields with $project, but the cost is running through all results rather than just accepting that these are nested within _id:

```<code>collection.aggregate([
  { "$group": {
    "_id": { "sType": "$sType", "sVer": "$sVer" },
    "countSucceededTrue": { "$sum": { "$cond": [ "$succeeded", 1, 0 ] } },
    "countSucceededFalse": { "$sum": { "$cond": [ "$succeeded", 0, 1 ] } }
  }},
  { "$project": {
     "sType": "$_id.sType",
     "sVer": "$_id.sVer",
     "countSucceededTrue": 1,
     "countSucceededFalse": 1
  }}
])
</code>```

The $cond is a "ternary", so where the first condition "if" is logically true ( and it's already a boolean ) "then" use the second argument "else" use the value of the third. This supplies the "count" to the $sum accumulator.

Body:
I am trying to query different documents from MongoDB via pymongo and group them by specific fields. The grouping part works really well, but I have a field that has a boolean value (True, False), but currnently it is keeping documents with True and documents with False in a separate grouping.

For example:

doc1{boolean : True, ... ... ..., count = 20}
doc2{boolean : False, ... ... ..., count = 10}

But I need it to group it like that:

doc{boolTrue : 20, boolFalse, 10, ... ... ..., count = 30}

So that it would not separate the documents by the boolean field.

I tried to do something like that, but neither of the proposed (see below) solutions didn't work:

"$group": {
    "_id": {
       "succTrue": {"$sum": {"$cond": [{"$client.succeeded": "True"}, 1, 0]}},
       "succFalse": {"$cond": [{"$client.succeeded": "False"}, 1, 0]},
    }
}

PS: There are other fields as well, but they are not relevant for the question.

E: Actual documents look something like that:

{
    "sType" : "Client",
    "succeeded" : false,
    "sVer" : "v1"
}

Expected output:

{
    countSucceededTrue: 15,
    countSucceededFalse: 5,
    "sType" : "Client",
    "sVer" : "v1"
},
{
    countSucceededTrue: 5,
    countSucceededFalse: 13,
    "sType" : "Client",
    "sVer" : "v2"
}
{
    countSucceededTrue: 3,
    countSucceededFalse: 2,
    "sType" : "Client",
    "sVer" : "v3"
}

Body:
You want your "grouping keys" in the _id field, and the other conditions under $sum accumulators:

collection.aggregate([
  { "$group": {
    "_id": { "sType": "$sType", "sVer": "$sVer" },
    "countSucceededTrue": { "$sum": { "$cond": [ "$succeeded", 1, 0 ] } },
    "countSucceededFalse": { "$sum": { "$cond": [ "$succeeded", 0, 1 ] } }
  }}
])

The "grouping key" is of course nested, but you should get used to the that concept. It is possible to do another pass to rename fields with $project, but the cost is running through all results rather than just accepting that these are nested within _id:

collection.aggregate([
  { "$group": {
    "_id": { "sType": "$sType", "sVer": "$sVer" },
    "countSucceededTrue": { "$sum": { "$cond": [ "$succeeded", 1, 0 ] } },
    "countSucceededFalse": { "$sum": { "$cond": [ "$succeeded", 0, 1 ] } }
  }},
  { "$project": {
     "sType": "$_id.sType",
     "sVer": "$_id.sVer",
     "countSucceededTrue": 1,
     "countSucceededFalse": 1
  }}
])

The $cond is a "ternary", so where the first condition "if" is logically true ( and it's already a boolean ) "then" use the second argument "else" use the value of the third. This supplies the "count" to the $sum accumulator.


问:
EF Core Migrations doesn't pick up all properties
When using EF Core Migrations the tooling isn't picking up all my properties, only the "Id" and some (not all) of the FK's (navigation properties). It also seems to understand the "Table Per Hierarchy" very well - as it has set up a discriminator where I wanted it to, but the migration file itself doesn't reflect the properties I have in my Model namespace (see github code).

My DbContext are located here: https://github.com/aredfox/TheConference/blob/master/InfoBooth/TheConference.InfoBooth.Data/InfoBoothContext.cs
My Model classes here: https://github.com/aredfox/TheConference/tree/master/InfoBooth/TheConference.InfoBooth.Core/Model

You can look at the generated "Initial Migration" at [ https://github.com/aredfox/TheConference/blob/master/InfoBooth/TheConference.InfoBooth.Data/Migrations/20170604125116_Initial.cs ]. There you'll see that it detected all the Id properties (defined in the base class [Entity][1]), but none of the other properties I of my Model classes.

I used the approach of adding a Console App to run migrations (otherwise it won't work - see Julie Lerman's tips on getting started with EF Core). Thus when running migrations I do it this way: dotnet ef --startup-project ../../TheConference.Infrastructure.ConsoleApp migrations add Initial.

Do I have to use annotations or modelBuilder or a form of EntityTypeConfiguration in EFCore to let EF know what I want to take?.

答:
All of your class properties are like this

```<code>public string Title { get; }
</code>```

i.e. read only auto properties.

EF Core does not support (map) such properties. In order to get them mapped, you need to provide property setters

```<code>public string Title { get; set; }
</code>```

The access level does not really matter - private, protected or internal will work. The only requirement is to have a setter.

EF Core also allows mapping properties and using backing fields, but all that requires fluent API configuration and also most likely will not work with get only auto properties because they are backed with readonly fields.

Body:
All of your class properties are like this

public string Title { get; }

i.e. read only auto properties.

EF Core does not support (map) such properties. In order to get them mapped, you need to provide property setters

public string Title { get; set; }

The access level does not really matter - private, protected or internal will work. The only requirement is to have a setter.

EF Core also allows mapping properties and using backing fields, but all that requires fluent API configuration and also most likely will not work with get only auto properties because they are backed with readonly fields.


问:
PHP - array_diff all similar values are compared and removed
I would appreciate a little help . I have tried array_diff(), intersect combos but not able to get my expected return.

Here is an example what i want to do.

First array.

```<code>Array
(
    [0] => 21
    [1] => 2
    [2] => 1
    [3] => 2
)
</code>```

Second array

```<code>Array
(
    [0] => 21
    [1] => 2
)
</code>```

using array_diff(firstarray, secondarray) i get following.

```<code>Array
(
    [2] => 1
)
</code>```

But what i want

```<code>Array
(
    [2] => 1
    [3] => 2
)
</code>```

keys from firstarray and secondarray wont necessarily be same.

答:
This little snippet should help you achieve what you want. Here we'll loop the second array, and remove the first occurrence of each value it finds from the first array.

```<code>$first = array(0 => 21, 1 => 2, 2 => 1, 3 => 2);
$second = array(0 => 21, 1 => 2);

foreach ($second as $v) {
    unset($first[array_search($v, $first)]);
}
</code>```

Output from $first after looping:

```<code>Array
(
    [2] => 1
    [3] => 2
)
</code>```

If you wish to keep the $first array intact, copy it into an other variable, and loop that, i.e. $new = $first; and unset from $new instead of $first.

Live demo

http://php.net/manual/en/function.array-search.php

Body:
I would appreciate a little help . I have tried array_diff(), intersect combos but not able to get my expected return.

Here is an example what i want to do.

First array.

Array
(
    [0] => 21
    [1] => 2
    [2] => 1
    [3] => 2
)

Second array

Array
(
    [0] => 21
    [1] => 2
)

using array_diff(firstarray, secondarray) i get following.

Array
(
    [2] => 1
)

But what i want

Array
(
    [2] => 1
    [3] => 2
)

keys from firstarray and secondarray wont necessarily be same.

Body:
This little snippet should help you achieve what you want. Here we'll loop the second array, and remove the first occurrence of each value it finds from the first array.

$first = array(0 => 21, 1 => 2, 2 => 1, 3 => 2);
$second = array(0 => 21, 1 => 2);

foreach ($second as $v) {
    unset($first[array_search($v, $first)]);
}

Output from $first after looping:

Array
(
    [2] => 1
    [3] => 2
)

If you wish to keep the $first array intact, copy it into an other variable, and loop that, i.e. $new = $first; and unset from $new instead of $first.

Live demo

http://php.net/manual/en/function.array-search.php


问:
How to unittest setup.py
I have a class named ConfigInstantiator which has some logic in setup.py.

I want to test this class.

I assume that when setup.py is called, my package is not ready yet, so moving this class into one of the module of my package doesn't work. (Am I right?)

I tried to:

```<code>import setup
</code>```

in unit test, but it conflicts with PyCharm's setup.py.

Do you know if there is a way to unittest this class?

答:
As @SmartManoj suggested, use technology suggested in How to import a module given the full path?

Put setup function inside block:

```<code>if __name__ == '__main__':
</code>```

Title: How to unittest setup.py

Body:
I have a class named ConfigInstantiator which has some logic in setup.py.

I want to test this class.

I assume that when setup.py is called, my package is not ready yet, so moving this class into one of the module of my package doesn't work. (Am I right?)

I tried to:

import setup

in unit test, but it conflicts with PyCharm's setup.py.

Do you know if there is a way to unittest this class?

Body:
As @SmartManoj suggested, use technology suggested in How to import a module given the full path?

Put setup function inside block:

if __name__ == '__main__':


问:
function wrapping exercise (decorators)
I have issue with following exercise:https://pythonprogramming.net/decorators-intermediate-python-tutorial/
Here is code I wanted to write:

```<code>def add_wrapping(item):
    def wrapped_item():
        return 'a wrapped up box of {}'.format(str(item()))
    return wrapped_item

@add_wrapping
def new_gpu():
    return 'a new Tesla P100 GPU!'
print(new_gpu())
</code>```

Here is my code:

```<code>def add_wrapping(item):
    def wrapped_item():
        return "a wrapped up box of {}".format(str(item()))
    return wrapped_item()
@add_wrapping
def new_gpu():
    return "new car!"
print(new_gpu())
</code>```

I work in PyCharm, here is error that it gives me:

line 17, in <module>
    print(new_gpu())
TypeError: 'str' object is not callable
```

I am stuck at this point, can't figure what went wrong, any help is appreciated!

答:
First you need to return wrapped_item object instead of return wrapped_item()

for example you can call func argument inside your decorator.

```<code>def add_wrapping(func):
    def wrapped_item():
        return "a wrapped up box of " + func()
    return wrapped_item

@add_wrapping
def new_gpu():
    return "new car!"
print(new_gpu())
</code>```

but it's will work if you returned str argument in new_gpu function.

Title: function wrapping exercise (decorators)

Body:
I have issue with following exercise:https://pythonprogramming.net/decorators-intermediate-python-tutorial/
Here is code I wanted to write:

def add_wrapping(item):
    def wrapped_item():
        return 'a wrapped up box of {}'.format(str(item()))
    return wrapped_item

@add_wrapping
def new_gpu():
    return 'a new Tesla P100 GPU!'
print(new_gpu())

Here is my code:

def add_wrapping(item):
    def wrapped_item():
        return "a wrapped up box of {}".format(str(item()))
    return wrapped_item()
@add_wrapping
def new_gpu():
    return "new car!"
print(new_gpu())

I work in PyCharm, here is error that it gives me:

line 17, in <module>
    print(new_gpu())
TypeError: 'str' object is not callable

I am stuck at this point, can't figure what went wrong, any help is appreciated!

Body:
First you need to return wrapped_item object instead of return wrapped_item()

for example you can call func argument inside your decorator.

def add_wrapping(func):
    def wrapped_item():
        return "a wrapped up box of " + func()
    return wrapped_item

@add_wrapping
def new_gpu():
    return "new car!"
print(new_gpu())

but it's will work if you returned str argument in new_gpu function.


问:
Why do different versions of Silverlight assemblies have the same version number?
Why do different versions of Silverlight assemblies have the same version number?

```<code>Location: ...\Silverlight\v3.0\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

Location: ...\Silverlight\v4.0\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

Location: ...\Silverlight\v4.0\Profile\WindowsPhone\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e
</code>```

While standard .net has different version numbers

```<code>Location: ...\Framework\v4.0.30319\System.dll
Name: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Location: ...\Framework\v2.0.50727\System.dll
Name: System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
</code>```

答: There's nothing stopping the Silverlight 4 framework from using the 2.0.5.0 version of System.Core. The .NET 3.5 framework shipped with version 2.0 of System.Web. However, the .NET 4 framework ships with a newer version of System.Core.</p>

Body:
Why do different versions of Silverlight assemblies have the same version number?

Location: ...\Silverlight\v3.0\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

Location: ...\Silverlight\v4.0\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

Location: ...\Silverlight\v4.0\Profile\WindowsPhone\System.Core.dll
Name: System.Core, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e

While standard .net has different version numbers

Location: ...\Framework\v4.0.30319\System.dll
Name: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Location: ...\Framework\v2.0.50727\System.dll
Name: System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089


问:
as.date recieved NA in R data.frame
Please help me to transform characters to date format

as.date and strptime don't work...

```<code>c <- data.frame(id = c('1', '2', '3', '4'), Date = c("01-Feb-16","03-May-15","24-Oct-14","20-Oct-12"))
c$Date <- as.character(c$Date)
str(c)
</code>```

then I'm trying use code:

```<code>c$Date <- as.Date(c$Date, format = "%d-%b-%y")
</code>```

or

```<code>c$Date <- strptime(c$Date, '%d-%b-%y')
</code>```

And I have received NA

答:
Your date is in the german format with english monthnames. Try this prior to your code:</p>

```<code>c <- data.frame(lapply(c, function(y) {
y <- gsub("May", "Mai", y); y
y <- gsub("Oct", "Okt", y); y
}))

c$Date1 <- as.Date(c$Date, format = "%d-%b-%y")
c$Date2 <- strptime(c$Date, '%d-%b-%y')
c

# id      Date      Date1      Date2
# 1  1 01-Feb-16 2016-02-01 2016-02-01
# 2  2 03-Mai-15 2015-05-03 2015-05-03
# 3  3 24-Okt-14 2014-10-24 2014-10-24
# 4  4 20-Okt-12 2012-10-20 2012-10-20
</code>```

Title: as.date recieved NA in R data.frame

Body:
Please help me to transform characters to date format

as.date and strptime don't work...

c <- data.frame(id = c('1', '2', '3', '4'), Date = c("01-Feb-16","03-May-15","24-Oct-14","20-Oct-12"))
c$Date <- as.character(c$Date)
str(c)

then I'm trying use code:

c$Date <- as.Date(c$Date, format = "%d-%b-%y")

or

c$Date <- strptime(c$Date, '%d-%b-%y')

And I have received NA

Body:
Your date is in the german format with english monthnames. Try this prior to your code:

c <- data.frame(lapply(c, function(y) {
y <- gsub("May", "Mai", y); y
y <- gsub("Oct", "Okt", y); y
}))

c$Date1 <- as.Date(c$Date, format = "%d-%b-%y")
c$Date2 <- strptime(c$Date, '%d-%b-%y')
c

# id      Date      Date1      Date2
# 1  1 01-Feb-16 2016-02-01 2016-02-01
# 2  2 03-Mai-15 2015-05-03 2015-05-03
# 3  3 24-Okt-14 2014-10-24 2014-10-24
# 4  4 20-Okt-12 2012-10-20 2012-10-20


问:
Angular Router nested Resolve(s)
I have a route:

```<code>const routes: Routes = [
    {
        path: ':id',
        component: MoyComponent,
        resolve: {
            first: MyFirstResolver
            second: mySecondResolver(first)
        }
    }
</code>```

I have a Resolver:

```<code>@Injectable()
export class MyFirstResolver implements Resolve<any> {
    constructor(private ms: MyService, private router: Router) {}
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
        let id = route.params['id'];
        return this.ms.get(id).map(res => {
            if (res) {
                return res;
            } else {
                this.router.navigate(['/']);
                return null;
            }
        });
    }
}
</code>```

MyFirstResolver returns an object obj which I would like to pass obj['price'] to mySecondResolver as mySecondResolver depends on the price property of obj. How can I pass the result(s) from myFirstResolver to mySecondResolver ?

答: You could consolidate both resolvers into a single resolver and chain them: so create ThirdResolver, and import the other two resolvers and chain their resolve methods together.

Title: Angular Router nested Resolve(s)

Body:
I have a route:

const routes: Routes = [
    {
        path: ':id',
        component: MoyComponent,
        resolve: {
            first: MyFirstResolver
            second: mySecondResolver(first)
        }
    }

I have a Resolver:

@Injectable()
export class MyFirstResolver implements Resolve<any> {
    constructor(private ms: MyService, private router: Router) {}
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> {
        let id = route.params['id'];
        return this.ms.get(id).map(res => {
            if (res) {
                return res;
            } else {
                this.router.navigate(['/']);
                return null;
            }
        });
    }
}

MyFirstResolver returns an object obj which I would like to pass obj['price'] to mySecondResolver as mySecondResolver depends on the price property of obj. How can I pass the result(s) from myFirstResolver to mySecondResolver ?


问:
You have to be inside an angular-cli project in order to use the build command after reinstall of angular-cli
I had the latest angular-cli installed globally and my project was building successfully.

While reading a suggested solution for another issue, (https://github.com/angular/angular-cli/issues/917) I uninstalled the  global angular-cli and installed it as a dev-dependency.

That other issue wasn't solved so I uninstalled the dev-dependency and reinstalled angular-cli globally once again.
Now when I try to do an ng build I'm getting the error:

You have to be inside an angular-cli project in order to use the build command

My angular-cli version did not change. Why isn't my project being recognised as an angular-cli project??

答:
In my case (Mac OS X and previously used Angular 1.5 environment)

npm -g cache clean --force

npm cache clean --force

worked. (npm install -g @angular/cli@latest afterwards)


问:
Is it possible to increment a PowerShell pipe variable?
I'm trying to count a record as it passes through a pipe. My expression looks like:

```<code>$x=28
gci | Select-Object basename, fullname, @{name='x'; Expression={($x--)}}
</code>```

I get:

```<code>BaseName FullName                x
-------- --------                -
aaoeu    C:\Users\m\x\aaoeu.txt 28
aue      C:\Users\m\x\aue.txt   28
xx       C:\Users\m\x\xx.txt    28
</code>```

I've tried Add-Member instead of the @ expression as above and that did the same thing - x doesn't alter value per object.

My end-goal is to generate a CSV file so I could use Write-Host to iterate through the Get-ChildItem (gci) output if it's not possible to get my variables to change value as gci emits records.

Am I missing the correct syntax to increment a variable in Select-Object or Add-Member or is it just not possible to do that?

答:
Solution 1 (foreach can found variable):</p>

```<code>$x=28
gci | %{ $x++; [pscustomobject]@{BaseName=$_.BaseName; FullName=$_.FullName; x=$x}}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to count a record as it passes through a pipe. My expression looks like:

$x=28
gci | Select-Object basename, fullname, @{name='x'; Expression={($x--)}}

I get:

BaseName FullName                x
-------- --------                -
aaoeu    C:\Users\m\x\aaoeu.txt 28
aue      C:\Users\m\x\aue.txt   28
xx       C:\Users\m\x\xx.txt    28

I've tried Add-Member instead of the @ expression as above and that did the same thing - x doesn't alter value per object.

My end-goal is to generate a CSV file so I could use Write-Host to iterate through the Get-ChildItem (gci) output if it's not possible to get my variables to change value as gci emits records.

Am I missing the correct syntax to increment a variable in Select-Object or Add-Member or is it just not possible to do that?

Body:
Solution 1 (foreach can found variable):

$x=28
gci | %{ $x++; [pscustomobject]@{BaseName=$_.BaseName; FullName=$_.FullName; x=$x}}


问:
NetLogo: How do I use random-gamma and division for the same calculation formula without any error?
I am using random-gamma with NetLogo. When I add division to the syntax of random-gamma, NetLogo gets an error. The following is an example of calculation syntax using random-gamma. (In addition, these variables "number-dead, S, T" are registered in global variables.) In my simulation it is necessary to add division after random-gamma calculation result. What should I do? Please give some advice to this. We thank you for your cooperation.

```<code>set sim precision((number-dead * random-gamma(1 / (S * S))(1 / (T * (S * S)))) / number-dead)3
</code>```

The following is a popup message when an error occurs.

It is divided by 0.
 error while observer running /
 called by procedure GOPARALLEL
 called by button 'goparallel'

答:
I don't think the problem has anything to do with random-gamma. Either S, T, or number-dead are likely to be 0.

If S is 0, then both (1 / (S * S)) and (1 / (T * (S * S))) will result in division by 0.

If T is 0, then (1 / (T * (S * S))) will result in a division by 0.

If number-dead is 0, then (number-dead * random-gamma (1 / (S * S)) (1 / (T * (S * S)))) / number-dead) will result in a division by 0.

Also,  I think that code is wrong. It's essentially doing:

```<code>let rand random-gamma (1 / (S * S)) (1 / (T * (S * S)))
let raw-num number-dead * rand / number-dead
set sim precision raw-num 3
</code>```

That is, you're multiplying the result of random-gamma by number-dead, and then immediately dividing the result of that by number-dead, which just leaves you with the result of random-gamma. So I think you may have misplaced some parentheses or something.

Body:
I am using random-gamma with NetLogo. When I add division to the syntax of random-gamma, NetLogo gets an error. The following is an example of calculation syntax using random-gamma. (In addition, these variables "number-dead, S, T" are registered in global variables.) In my simulation it is necessary to add division after random-gamma calculation result. What should I do? Please give some advice to this. We thank you for your cooperation.

set sim precision((number-dead * random-gamma(1 / (S * S))(1 / (T * (S * S)))) / number-dead)3

The following is a popup message when an error occurs.

It is divided by 0.
 error while observer running /
 called by procedure GOPARALLEL
 called by button 'goparallel'

Body:
I don't think the problem has anything to do with random-gamma. Either S, T, or number-dead are likely to be 0.

If S is 0, then both (1 / (S * S)) and (1 / (T * (S * S))) will result in division by 0.

If T is 0, then (1 / (T * (S * S))) will result in a division by 0.

If number-dead is 0, then (number-dead * random-gamma (1 / (S * S)) (1 / (T * (S * S)))) / number-dead) will result in a division by 0.

Also,  I think that code is wrong. It's essentially doing:

let rand random-gamma (1 / (S * S)) (1 / (T * (S * S)))
let raw-num number-dead * rand / number-dead
set sim precision raw-num 3

That is, you're multiplying the result of random-gamma by number-dead, and then immediately dividing the result of that by number-dead, which just leaves you with the result of random-gamma. So I think you may have misplaced some parentheses or something.


问:
Creating temp column upon logic
How can I create a temp (empty) column in which values will be inserted upon logic:

```<code>SELECT ..., *temp_col*

FROM *table*

IF *table.column_1* is not null, THEN *temp_col=table.column_1*

else temp_col=table.column_2
</code>```

Note: Colume_1 is a CLOB field which will be transformed to TEXT.
someone advised me to use the EXIST condition.

答:
Using Case :

```<code>SELECT ...,
       temp_col= CASE WHEN table.column_1 is not nul THEN table.column_1
       ELSE
       table.column_2 END
FROM table;
</code>```

Title: Creating temp column upon logic

Body:
How can I create a temp (empty) column in which values will be inserted upon logic:

SELECT ..., *temp_col*

FROM *table*

IF *table.column_1* is not null, THEN *temp_col=table.column_1*

else temp_col=table.column_2

Note: Colume_1 is a CLOB field which will be transformed to TEXT.
someone advised me to use the EXIST condition.

Body:
Using Case :

SELECT ...,
       temp_col= CASE WHEN table.column_1 is not nul THEN table.column_1
       ELSE
       table.column_2 END
FROM table;


问:
Singletons factory using generics and reflection
OrderDBManager, UserDBManager, ProductDBManager extend DBManager.
I'm trying to create a singletons DBManager Factory
to get instances of different DBManager type classes.

But I have a problem using generics to return an instance of exact DBManager type class user wants. Right now it only works for DBManager itself.
I would appreciate your help!

```<code>public class DBManagerFactory {

     private static final Map<String, DBManager> instances = new HashMap<>();

     private static final String DB_MANAGER_PACKAGE_NAME = "ua.Test.db.";

     public static DBManager getInstance(Class<? extends DBManager> dbManagerClass) {
            String dbManagerClassName = dbManagerClass.getSimpleName();
            DBManager dbManager = instances.get(dbManagerClassName);

            if(dbManager == null){
                Class clazz = Class.forName(DB_MANAGER_PACKAGE_NAME + dbManagerClassName);
                dbManager = (DBManager)clazz.newInstance();
                instances.put(dbManagerClassName, dbManager);
            }
            return dbManager;
     }}
</code>```

答:
But I have a problem using generics to return an instance of exact
  DBManager type class user wants.

To return a specific class in the method, you should specify a scoped method parameterized type that allows the client of the class to specify which type the method should return.

You could declare the method in this way :

```<code>public static <T extends DBManager> T getInstance(Class<T> dbManagerClass)  {
</code>```

To avoid unsafe casts, you could cast the DBManager instance retrieved from the Map<String, DBManager> to a T extends DBManager type by using the Class#cast(Object ) method that performs for you the type check before casting the DBManager instance :

```<code>T dbManager = dbManagerClass.cast(instances.get(dbManagerClassName));
</code>```

At last, the way to retrieve the class :

```<code>Class clazz = Class.forName(DB_MANAGER_PACKAGE_NAME + dbManagerClassName);
</code>```

is not required as you have already the class as parameter of the method.

Just directly use it.

Here is sample code that implements this solution :

```<code>public class DBManagerFactory {

    private static final Map<String, DBManager> instances = new HashMap<>();

    public static <T extends DBManager> T getInstance(Class<T> dbManagerClass)  {

      final String dbManagerClassName = dbManagerClass.getSimpleName();

      T dbManager = dbManagerClass.cast(instances.get(dbManagerClassName));

      if (dbManager == null) {
        try {
          dbManager =  dbManagerClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          e.printStackTrace(); // or better log it
          throw new RuntimeException("faillure during reflection instantiation for class " + dbManagerClass.getName(), e);
        }
        instances.put(dbManagerClassName, dbManager);
      }

      return dbManager;
    }

}
</code>```

With these modifications, the client classes could invoke the method in this way :

```<code>DBManager instance = DBManagerFactory.getInstance(DBManager.class);
DBManagerChild child = DBManagerFactory.getInstance(DBManagerChild.class);
</code>```

Body:
OrderDBManager, UserDBManager, ProductDBManager extend DBManager.
I'm trying to create a singletons DBManager Factory
to get instances of different DBManager type classes.

But I have a problem using generics to return an instance of exact DBManager type class user wants. Right now it only works for DBManager itself.
I would appreciate your help!

public class DBManagerFactory {

     private static final Map<String, DBManager> instances = new HashMap<>();

     private static final String DB_MANAGER_PACKAGE_NAME = "ua.Test.db.";

     public static DBManager getInstance(Class<? extends DBManager> dbManagerClass) {
            String dbManagerClassName = dbManagerClass.getSimpleName();
            DBManager dbManager = instances.get(dbManagerClassName);

            if(dbManager == null){
                Class clazz = Class.forName(DB_MANAGER_PACKAGE_NAME + dbManagerClassName);
                dbManager = (DBManager)clazz.newInstance();
                instances.put(dbManagerClassName, dbManager);
            }
            return dbManager;
     }}

Body:
But I have a problem using generics to return an instance of exact
  DBManager type class user wants.

To return a specific class in the method, you should specify a scoped method parameterized type that allows the client of the class to specify which type the method should return.

You could declare the method in this way :

public static <T extends DBManager> T getInstance(Class<T> dbManagerClass)  {

To avoid unsafe casts, you could cast the DBManager instance retrieved from the Map<String, DBManager> to a T extends DBManager type by using the Class#cast(Object ) method that performs for you the type check before casting the DBManager instance :

T dbManager = dbManagerClass.cast(instances.get(dbManagerClassName));

At last, the way to retrieve the class :

Class clazz = Class.forName(DB_MANAGER_PACKAGE_NAME + dbManagerClassName);

is not required as you have already the class as parameter of the method.

Just directly use it.

Here is sample code that implements this solution :

public class DBManagerFactory {

    private static final Map<String, DBManager> instances = new HashMap<>();

    public static <T extends DBManager> T getInstance(Class<T> dbManagerClass)  {

      final String dbManagerClassName = dbManagerClass.getSimpleName();

      T dbManager = dbManagerClass.cast(instances.get(dbManagerClassName));

      if (dbManager == null) {
        try {
          dbManager =  dbManagerClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          e.printStackTrace(); // or better log it
          throw new RuntimeException("faillure during reflection instantiation for class " + dbManagerClass.getName(), e);
        }
        instances.put(dbManagerClassName, dbManager);
      }

      return dbManager;
    }

}

With these modifications, the client classes could invoke the method in this way :

DBManager instance = DBManagerFactory.getInstance(DBManager.class);
DBManagerChild child = DBManagerFactory.getInstance(DBManagerChild.class);


问:
Code skipping run
```<code>public class A{
public static void main(String[] args) {
    int a;
    int b;int c=0;
    for(a=100;a<=999;a++){
        for(b=100;b<=999;b++){
            int n=a*b;
            int temp=n;
            while(n>0){
                int r=n%10;
                c=(c*10)+r;
                n=n/10;
            }
            if(temp==c){
                System.out.println(c);
            }
        }
    }
    }
}
</code>```

The code compiles well but while running it just skips off everything and exits. Help please.
P.S. Problem 4 ProjectEuler

答:
First of all lets format the code to read it easily:

```<code>public class A {
    public static void main(String[] args) {
        int a;
        int b;
        int c = 0;
        for (a = 100; a <= 999; a++) {
            for (b = 100; b <= 999; b++) {
                int n = a * b;
                int temp = n;
                while (n > 0) {
                    int r = n % 10;
                    c = (c * 10) + r;
                    n = n / 10;
                }
                if (temp == c) {
                    System.out.println(c);
                }
            }
        }
    }
}
</code>```

Now we notice that the only blocks keeping us away from the print statement inside the main method are the two for loops, and an if statemet.
Examining the two loops, there is nothing obviously wrong with them, so we rule them out and what is left is the if statement. At this point we can asume that temp never equals c.
If you can't trace why this conition is not satisfied just by looking at the code you can do some simple debuging using print statements (I.e. printing the variables c and temp before the if to visually examine their values for instance) or use some more advanced debuging tools that you can find on IDEs for instance.

Guides on debuging:

How to debug a Java program without using an IDE?

http://www.vogella.com/tutorials/EclipseDebugging/article.html

Title: Code skipping run

Body:
public class A{
public static void main(String[] args) {
    int a;
    int b;int c=0;
    for(a=100;a<=999;a++){
        for(b=100;b<=999;b++){
            int n=a*b;
            int temp=n;
            while(n>0){
                int r=n%10;
                c=(c*10)+r;
                n=n/10;
            }
            if(temp==c){
                System.out.println(c);
            }
        }
    }
    }
}

The code compiles well but while running it just skips off everything and exits. Help please.
P.S. Problem 4 ProjectEuler

Body:
First of all lets format the code to read it easily:

public class A {
    public static void main(String[] args) {
        int a;
        int b;
        int c = 0;
        for (a = 100; a <= 999; a++) {
            for (b = 100; b <= 999; b++) {
                int n = a * b;
                int temp = n;
                while (n > 0) {
                    int r = n % 10;
                    c = (c * 10) + r;
                    n = n / 10;
                }
                if (temp == c) {
                    System.out.println(c);
                }
            }
        }
    }
}

Now we notice that the only blocks keeping us away from the print statement inside the main method are the two for loops, and an if statemet.
Examining the two loops, there is nothing obviously wrong with them, so we rule them out and what is left is the if statement. At this point we can asume that temp never equals c.
If you can't trace why this conition is not satisfied just by looking at the code you can do some simple debuging using print statements (I.e. printing the variables c and temp before the if to visually examine their values for instance) or use some more advanced debuging tools that you can find on IDEs for instance.

Guides on debuging:

How to debug a Java program without using an IDE?

http://www.vogella.com/tutorials/EclipseDebugging/article.html


答:
Solution 2 (with a global variable):

```<code>$global:x=28
Get-ChildItem | select-object basename,fullname,@{name='x'; Expression={($global:x--)}}
</code>```

Short version:

```<code>$global:x=28
gci | select basename,fullname,@{N='x'; E={($global:x--)}}
</code>```

Title: Is it possible to increment a PowerShell pipe variable?

Body:
Solution 2 (with a global variable):

$global:x=28
Get-ChildItem | select-object basename,fullname,@{name='x'; Expression={($global:x--)}}

Short version:

$global:x=28
gci | select basename,fullname,@{N='x'; E={($global:x--)}}


问:
DRYing Views in Rails (number_to_currency)
I have code similar to:

number_to_currency(line_item.price, :unit => "£")

littering my views in various models. Since my application deals only in GBP (£), should I not move this into each of my models so that line_item.price returns the string as it should be (i.e. number_to_currency(line_item.price, :unit => "£") and line_item.price are the same. I'm thinking that to do this I should:

```<code>def price
 number_to_currency(self.price, :unit => "£")
end
</code>```

but this doesn't work. If price is already defined in the model, then Rails reports 'stack level too deep', when I change def price to def amount, then it complains that number_to_currency is not defined?

答:
If you want to change the default for your whole application, you can edit config/locales/en.yml

Mine looks like this:

```<code># Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
"en":
  number:
    currency:
        format:
            format: "%u%n"
            unit: "£"
            # These three are to override number.format and are optional
            separator: "."
            delimiter: ","
            precision: 2
</code>```

Everything except the unit is optional and will fall back to the default, but I put it in so I know what values I can change.  you could also use the £ sign instead of £.

Body:
I have code similar to:

number_to_currency(line_item.price, :unit => "£")

littering my views in various models. Since my application deals only in GBP (£), should I not move this into each of my models so that line_item.price returns the string as it should be (i.e. number_to_currency(line_item.price, :unit => "£") and line_item.price are the same. I'm thinking that to do this I should:

def price
 number_to_currency(self.price, :unit => "£")
end

but this doesn't work. If price is already defined in the model, then Rails reports 'stack level too deep', when I change def price to def amount, then it complains that number_to_currency is not defined?

Body:
If you want to change the default for your whole application, you can edit config/locales/en.yml

Mine looks like this:

# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
"en":
  number:
    currency:
        format:
            format: "%u%n"
            unit: "&pound;"
            # These three are to override number.format and are optional
            separator: "."
            delimiter: ","
            precision: 2

Everything except the unit is optional and will fall back to the default, but I put it in so I know what values I can change.  you could also use the £ sign instead of &pound;.


问:
how replace self.navigationItem.leftBarButtonItem = self.editButtonItem() } with button action
I replace BarButtonItem's self.editButtonItem() with button @IBAction..

```<code>override func viewDidLoad() {
    super.viewDidLoad()

   ....
    self.navigationItem.leftBarButtonItem = self.editButtonItem()
}
</code>```

I delete self.navigationItem.leftBarButtonItem = self.editButtonItem()
above code

I wanna replace @IBAction button () { code }...

what's code?

答:
My Solution is this. Connect the nav button outlet action to this function</p>

```<code>@IBAction func startEditBtnAct(_ sender: Any) {
        tableview.isEditing = !tableview.isEditing

    }
</code>```

Body:
I replace BarButtonItem's self.editButtonItem() with button @IBAction..

override func viewDidLoad() {
    super.viewDidLoad()

   ....
    self.navigationItem.leftBarButtonItem = self.editButtonItem()
}

I delete self.navigationItem.leftBarButtonItem = self.editButtonItem()
above code

I wanna replace @IBAction button () { code }...

what's code?

Body:
My Solution is this. Connect the nav button outlet action to this function

@IBAction func startEditBtnAct(_ sender: Any) {
        tableview.isEditing = !tableview.isEditing

    }


问:
State not working properly in ReactJS
What I'm trying to do is, store a input field value to a state and then, If a user click on save button or store button then input field will be vanished so editing will be false.I'm trying to check the state length when user click on the save button. The problem is there. it's say's this error: Uncaught TypeError: Cannot read property 'state' of null, But I've already stored  data on editData state why is that please can you tell me?

Here is Codes to understand better

```<code>class EditData extends Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.state = {
            editData: ''
        }
    }
    handleChange(e) {
        this.setState({editData: e.target.value})
    }

    save() {
        if (this.state.editData.length !== 0) {
            this.setState({isEditing: false});
            console.log(this.state.editData + 'Added on your database')
        } else {
            alert('Hahah Are you')
        }
        // console.log(this.refs.valTo.value);
    }
    render() {
        return (
            <div>
                <input onChange={this.handleChange} type="text" defaultValue={this.props.data}  /> <button onClick={this.save}>Save</button> <button>cancel</button>
            </div>
            );
    }
}
</code>```

答:
You need to bind handleChange and save.
Check also that you initialized state in the constructor.

In the constructor do:

```<code>this.handleChange = this.handleChange.bind(this);
this.save= this.save.bind(this);
this.state = {};
</code>```

Title: State not working properly in ReactJS

Body:
What I'm trying to do is, store a input field value to a state and then, If a user click on save button or store button then input field will be vanished so editing will be false.I'm trying to check the state length when user click on the save button. The problem is there. it's say's this error: Uncaught TypeError: Cannot read property 'state' of null, But I've already stored  data on editData state why is that please can you tell me?

Here is Codes to understand better

class EditData extends Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.state = {
            editData: ''
        }
    }
    handleChange(e) {
        this.setState({editData: e.target.value})
    }

    save() {
        if (this.state.editData.length !== 0) {
            this.setState({isEditing: false});
            console.log(this.state.editData + 'Added on your database')
        } else {
            alert('Hahah Are you')
        }
        // console.log(this.refs.valTo.value);
    }
    render() {
        return (

                <input onChange={this.handleChange} type="text" defaultValue={this.props.data}  /> <button onClick={this.save}>Save</button> <button>cancel</button>

            );
    }
}

Body:
You need to bind handleChange and save.
Check also that you initialized state in the constructor.

In the constructor do:

this.handleChange = this.handleChange.bind(this);
this.save= this.save.bind(this);
this.state = {};


问:
PHP/HTML - Trying to make image appear using localhost
I am using XAMPP for APACHE server on localhost:8080 (I had to change the default port for it to work). Assume that I have the rest of the html needed to run.
Here is the current code:

home.html

```<code><body>
<script src="main/profile.php"></script>
</body>
</code>```

profile.php

```<code><?php
$imagepath ="omj/logo.jpg";
$image = imagecreatefromjpeg( $imagepath);
header('Content-Type: image/jpeg');
imagejpeg($image);
?>
</code>```

I tried referencing the following articles to no avail:

http://www.configure-all.com/howto_display_image.php

How to display images from a folder using php - PHP

Edit
I got the image to work using HTML by simply moving the image folder inside the html folder. Now the question remains, why isn't the php code running to show the image?

The image path is within the directory of the html file. Like this: /htmlfolder/imagefolder/image.jpg while html file is /htmlfolder/file.html

答:
So simple, " PHP optimally used single quotes '. Use standard html within string!</p>

```<code>echo ' <img src="php.gif" /> ';
</code>```

Body:
I am using XAMPP for APACHE server on localhost:8080 (I had to change the default port for it to work). Assume that I have the rest of the html needed to run.
Here is the current code:

home.html

profile.php

<?php
$imagepath ="omj/logo.jpg";
$image = imagecreatefromjpeg( $imagepath);
header('Content-Type: image/jpeg');
imagejpeg($image);
?>

I tried referencing the following articles to no avail:

http://www.configure-all.com/howto_display_image.php

How to display images from a folder using php - PHP

Edit
I got the image to work using HTML by simply moving the image folder inside the html folder. Now the question remains, why isn't the php code running to show the image?

The image path is within the directory of the html file. Like this: /htmlfolder/imagefolder/image.jpg while html file is /htmlfolder/file.html

Body:
So simple, " PHP optimally used single quotes '. Use standard html within string!

echo ' <img src="php.gif" /> ';